new platform global constant

This commit is contained in:
The MMGen Project 2026-05-17 18:03:32 +00:00
commit ab41b78863
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
43 changed files with 154 additions and 129 deletions

View file

@ -17,7 +17,7 @@ from stat import S_IWUSR, S_IRUSR
from pathlib import Path
from subprocess import run, PIPE, DEVNULL
from ..cfg import Config
from ..cfg import Config, gc
from ..util import msg, msg_r, ymsg, rmsg, gmsg, bmsg, die, suf, fmt, fmt_list, is_int, cached_property
from ..color import yellow, brown, gray
from ..wallet import Wallet, get_wallet_cls
@ -79,7 +79,7 @@ class Autosign:
cfg.mnemonic_fmt,
fmt_list(self.mn_fmts, fmt='no_spc')))
match sys.platform:
match gc.platform:
case 'linux':
self.dfl_mountpoint = f'/mnt/{self.linux_mount_subdir}'
self.dfl_shm_dir = '/dev/shm'
@ -107,7 +107,7 @@ class Autosign:
self.shm_dir = Path(self.dfl_shm_dir)
self.wallet_dir = Path(cfg.wallet_dir or self.dfl_wallet_dir)
match sys.platform:
match gc.platform:
case 'linux':
self.mount_cmd = f'mount {self.mountpoint}'
self.umount_cmd = f'umount {self.mountpoint}'
@ -215,7 +215,7 @@ class Autosign:
msg(f'Creating ‘{path}')
path.mkdir(parents=True)
if sys.platform == 'linux' and not self.mountpoint.is_dir():
if gc.platform == 'linux' and not self.mountpoint.is_dir():
def do_die(m):
die(1, '\n' + yellow(fmt(m.strip(), indent=' ')))
if Path(self.old_dfl_mountpoint).is_dir():
@ -383,7 +383,7 @@ class Autosign:
from .swap_mgr import SwapMgr
SwapMgr(self.cfg, ignore_zram=True).disable()
if sys.platform == 'darwin':
if gc.platform == 'darwin':
self.macos_ramdisk.create()
remove_wallet_dir()
@ -486,7 +486,7 @@ class Autosign:
def device_inserted(self):
if self.cfg.no_insert_check:
return True
match sys.platform:
match gc.platform:
case 'linux':
cp = run(self.linux_blkid_cmd.split(), stdout=PIPE, text=True)
if cp.returncode not in (0, 2):

View file

@ -12,14 +12,14 @@
autosign.swap_mgr: swap management for MMGen Wallet autosigning
"""
import sys
from subprocess import run, PIPE, DEVNULL
from ..cfg import gc
from ..util import msg, ymsg, suf, fmt_list, have_sudo, capfirst
from ..color import orange, blue
def SwapMgr(*args, **kwargs):
match sys.platform:
match gc.platform:
case 'linux':
return SwapMgrLinux(*args, **kwargs)
case 'darwin':
@ -70,6 +70,7 @@ class SwapMgrBase:
d = fmt_list(cmds, indent=' ', fmt='col')) + '\n' + post
msg(m)
if not self.cfg.test_suite:
import sys
sys.exit(1)
class SwapMgrLinux(SwapMgrBase):

View file

@ -92,12 +92,14 @@ class GlobalConstants(Lockable):
prog_id = prog_name.removeprefix(f'{proj_id}-')
cmd_caps = cmd_caps_data.get(prog_id)
if sys.platform not in ('linux', 'win32', 'darwin'):
die2(1, f'{sys.platform!r}: platform not supported by {proj_name}')
platform = sys.platform # linux, darwin, win32 (MSYS2)
if platform not in ('linux', 'win32', 'darwin'):
die2(1, f'{platform!r}: platform not supported by {proj_name}')
if os.getenv('HOME'): # Linux, MSYS2, or macOS
home_dir = os.getenv('HOME')
elif sys.platform == 'win32': # Windows without MSYS2 - not supported
elif platform == 'win32': # Windows without MSYS2 - not supported
die2(1, f'$HOME not set! {proj_name} for Windows must be run in MSYS2 environment')
else:
die2(2, '$HOME is not set! Unable to determine home directory')

View file

@ -20,6 +20,8 @@
color: color handling for the MMGen suite
"""
from .cfg import gc
_colors = {
'black': (232, (30, 0)),
'red': (210, (31, 1)),
@ -49,8 +51,7 @@ def nocolor(s):
def set_vt100():
'hack to put term into VT100 mode under MSWin'
import sys
if sys.platform == 'win32':
if gc.platform == 'win32':
from subprocess import run
run([], shell=True)
@ -84,7 +85,7 @@ def init_color(num_colors='auto'):
if num_colors == 'auto':
import os
if sys.platform == 'win32':
if gc.platform == 'win32':
# Force 256-color for MSYS2: terminal supports it, however infocmp reports 8-color.
# We also avoid spawning a subprocess, leading to a subsequent OSError 22 when testing
# with pexpect spawn.

View file

@ -20,10 +20,11 @@
daemon: Daemon control interface for the MMGen suite
"""
import sys, os, time, importlib
import os, time, importlib
from subprocess import run, PIPE, CompletedProcess
from collections import namedtuple
from .cfg import gc
from .base_obj import Lockable
from .color import set_vt100
from .util import msg, Msg_r, die, remove_dups, oneshot_warning, fmt_list
@ -53,8 +54,7 @@ class Daemon(Lockable):
def __init__(self, cfg, *, opts=None, flags=None):
self.cfg = cfg
self.platform = sys.platform
if self.platform == 'win32':
if gc.platform == 'win32':
self.use_pidfile = False
self.use_threads = True
@ -64,11 +64,11 @@ class Daemon(Lockable):
def exec_cmd_thread(self, cmd):
import threading
tname = ('exec_cmd', 'exec_cmd_win_console')[self.platform == 'win32' and self.new_console_mswin]
tname = ('exec_cmd', 'exec_cmd_win_console')[gc.platform == 'win32' and self.new_console_mswin]
t = threading.Thread(target=getattr(self, tname), args=(cmd,))
t.daemon = True
t.start()
if self.platform == 'win32':
if gc.platform == 'win32':
Msg_r(' \b') # blocks w/o this...crazy
return True
@ -121,7 +121,7 @@ class Daemon(Lockable):
with open(self.pidfile) as fp:
return fp.read().strip()
match self.platform:
match gc.platform:
case 'win32':
# Assumes only one running instance of given daemon. If multiple daemons are running,
# the first PID in the list is returned and self.pids is set to the PID list.
@ -159,7 +159,7 @@ class Daemon(Lockable):
@property
def stop_cmd(self):
return (
['kill', '-Wf', self.pid] if self.platform == 'win32' else
['kill', '-Wf', self.pid] if gc.platform == 'win32' else
['kill', '-9', self.pid] if self.force_kill else
['kill', self.pid])
@ -448,7 +448,7 @@ class CoinDaemon(Daemon):
if self.test_suite:
return os.path.join('test', 'daemons', self.network_id)
else:
return os.path.join(*self.datadirs[self.platform])
return os.path.join(*self.datadirs[gc.platform])
@property
def network_datadir(self):

View file

@ -20,7 +20,9 @@
filename: File and MMGenFile classes and methods for the MMGen suite
"""
import sys, os
import os
from .cfg import gc
from .util import die, get_extension
class File:
@ -42,8 +44,8 @@ class File:
import stat
if stat.S_ISBLK(st.st_mode):
if sys.platform == 'win32':
die(2, 'Access to raw block devices not supported on platform {sys.platform!r}')
if gc.platform == 'win32':
die(2, 'Access to raw block devices not supported on platform {gc.platform!r}')
mode = (os.O_RDONLY, os.O_RDWR)[bool(write)]
try:
fd = os.open(fn, mode)
@ -52,7 +54,7 @@ class File:
die(2, f'{fn!r}: permission denied')
# if e.errno != 17: raise
else:
match sys.platform:
match gc.platform:
case 'linux':
self.size = os.lseek(fd, 0, os.SEEK_END)
case 'darwin':

View file

@ -24,6 +24,7 @@ fileutil: Routines that read, write, execute or stat files
import sys, os
from .cfg import gc
from .color import set_vt100
from .util import (
msg,
@ -83,7 +84,7 @@ def _check_file_type_and_access(fname, ftype, *, blkdev_ok=False):
(stat.S_ISLNK, 'symbolic link')
]
if blkdev_ok:
if not sys.platform in ('win32',):
if not gc.platform in ('win32',):
ok_types.append((stat.S_ISBLK, 'block device'))
try:
@ -217,7 +218,7 @@ def write_data_to_file(
else:
msg('Redirecting output to file')
if binary and sys.platform == 'win32':
if binary and gc.platform == 'win32':
import msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

View file

@ -20,8 +20,7 @@
autosign: Auto-sign MMGen transactions, message files and XMR wallet output files
"""
import sys
from .cfg import gc
from .util import msg, ymsg, gmsg, die, fmt_list, exit_if_mswin, async_run
exit_if_mswin('autosigning')
@ -130,6 +129,7 @@ if cmd in ('enable_swap', 'disable_swap', 'list_led', 'test_led'):
ymsg('No LED signaling support for this platform')
else:
gmsg('LED signaling is supported by this platform!')
import sys
sys.exit(0)
if cmd not in Autosign.cmds + Autosign.util_cmds:
@ -185,6 +185,6 @@ match cmd:
asi.wipe_encryption_key()
asi.do_umount()
case 'macos_ramdisk_setup' | 'macos_ramdisk_delete':
if sys.platform != 'darwin':
if gc.platform != 'darwin':
die(1, f'The ‘{cmd}’ operation is for the macOS platform only')
asi.macos_ramdisk.create() if cmd == 'macos_ramdisk_setup' else asi.macos_ramdisk.destroy()

View file

@ -21,7 +21,7 @@ mmgen-passgen: Generate a series or range of passwords from an MMGen
deterministic wallet
"""
import sys, time
import time
from .cfg import gc, Config
from .addrlist import AddrIdxList
@ -177,6 +177,6 @@ if keypress_confirm(cfg, 'Encrypt password list?'):
af.encrypt()
af.write(binary=True, desc='encrypted password list')
else:
if cfg.test_suite_popen_spawn and sys.platform == 'win32':
if cfg.test_suite_popen_spawn and gc.platform == 'win32':
time.sleep(0.1)
af.write(desc='password list')

View file

@ -280,7 +280,7 @@ def process_args(cmd, cmd_args, cls):
die(1, "'Binary input data must be supplied via STDIN")
if have_stdin_input and arg_type == 'str' and isinstance(arg, bytes):
NL = '\r\n' if sys.platform == 'win32' else '\n'
NL = '\r\n' if gc.platform == 'win32' else '\n'
arg = arg.decode()
if arg[-len(NL):] == NL: # rstrip one newline
arg = arg[:-len(NL)]

View file

@ -76,7 +76,7 @@ class bitcoin_core_daemon(CoinDaemon):
['--rpcallowip=127.0.0.1'],
[f'--rpcbind=127.0.0.1:{self.rpc_port}'],
['--pid='+self.pidfile, self.use_pidfile],
['--daemon', self.platform in ('linux', 'darwin') and not self.opt.no_daemonize],
['--daemon', gc.platform in ('linux', 'darwin') and not self.opt.no_daemonize],
['--fallbackfee=0.0002', self.coin == 'BTC' and self.network == 'regtest'],
['--deprecatedrpc=create_bdb', self.coin == 'BTC' and self.opt.bdb_wallet],
['--mempoolreplacement=1', self.coin == 'LTC'],

View file

@ -68,8 +68,8 @@ class openethereum_daemon(ethereum_daemon):
def init_subclass(self):
self.use_pidfile = self.platform == 'linux' and not self.opt.no_daemonize
self.use_threads = self.platform in ('win32', 'darwin')
self.use_pidfile = gc.platform == 'linux' and not self.opt.no_daemonize
self.use_threads = gc.platform in ('win32', 'darwin')
self.coind_args = list_gen(
['--no-ws'],

View file

@ -12,7 +12,7 @@
proto.xmr.daemon: Monero base protocol daemon classes
"""
import sys, os
import os
from ...cfg import gc
from ...util import list_gen, die, contains_any
@ -53,7 +53,7 @@ class monero_daemon(CoinDaemon):
test_connection = False,
daemon = self)
self.use_pidfile = sys.platform == 'linux'
self.use_pidfile = gc.platform == 'linux'
self.shared_args = list_gen(
['--no-zmq'],
@ -67,13 +67,13 @@ class monero_daemon(CoinDaemon):
['--no-igd'],
[f'--data-dir={self.datadir}', self.non_dfl_datadir],
[f'--pidfile={self.pidfile}', self.use_pidfile],
['--detach', not (self.opt.no_daemonize or self.platform=='win32')],
['--detach', not (self.opt.no_daemonize or gc.platform=='win32')],
['--offline', not self.opt.online],
)
@property
def stop_cmd(self):
if self.platform == 'win32':
if gc.platform == 'win32':
return ['kill', '-Wf', self.pid]
elif contains_any(self.start_cmd, ['--restricted-rpc', '--public-node']):
return ['kill', self.pid]
@ -135,7 +135,7 @@ class MoneroWalletDaemon(RPCDaemon):
self.pidfile = os.path.join(self.datadir, id_str+'.pid')
self.logfile = os.path.join(self.datadir, id_str+'.log')
self.use_pidfile = sys.platform == 'linux'
self.use_pidfile = gc.platform == 'linux'
self.proxy = proxy
self.monerod_addr = monerod_addr
@ -175,8 +175,8 @@ class MoneroWalletDaemon(RPCDaemon):
[f'--daemon-address={self.monerod_addr}', self.monerod_addr],
[f'--daemon-port={self.monerod_port}', not self.monerod_addr],
[f'--proxy={self.proxy}', self.proxy],
[f'--pidfile={self.pidfile}', self.platform == 'linux'],
['--detach', not (self.opt.no_daemonize or self.platform=='win32')],
[f'--pidfile={self.pidfile}', gc.platform == 'linux'],
['--detach', not (self.opt.no_daemonize or gc.platform=='win32')],
['--stagenet', self.network == 'testnet'],
['--allow-mismatched-daemon-version', test_suite],
)

View file

@ -12,8 +12,9 @@
rpc.local: local RPC client class for the MMGen Project
"""
import sys, json, asyncio, importlib
import json, asyncio, importlib
from ..cfg import gc
from ..util import msg, die, fmt, oneshot_warning, isAsync
from . import util
@ -32,7 +33,7 @@ class RPCClient:
self.name = type(self).__name__
# aiohttp workaround, and may speed up RPC performance overall on some systems:
if sys.platform == 'win32' and host == 'localhost':
if gc.platform == 'win32' and host == 'localhost':
host = '127.0.0.1'
if not self.cfg.debug_rpc:
@ -63,7 +64,7 @@ class RPCClient:
def get_cls(backend_id):
return getattr(importlib.import_module(f'mmgen.rpc.backends.{backend_id}'), backend_id)
backend_id = backend or self.cfg.rpc_backend
return get_cls(dfl_backends[sys.platform] if backend_id == 'auto' else backend_id)
return get_cls(dfl_backends[gc.platform] if backend_id == 'auto' else backend_id)
def set_backend(self, backend=None):
self.backend = self._get_backend_cls(backend)(self)

View file

@ -25,13 +25,14 @@ term: Terminal classes for the MMGen suite
import sys, os, time
from collections import namedtuple
from .cfg import gc
from .util import msg, msg_r, die
match sys.platform:
match gc.platform:
case 'linux' | 'darwin':
import tty, termios
from select import select
hold_protect_timeout = 2 if sys.platform == 'darwin' else 0.3
hold_protect_timeout = 2 if gc.platform == 'darwin' else 0.3
case 'win32':
try:
import msvcrt
@ -288,7 +289,7 @@ def get_term():
'linux': (MMGenTermLinux if sys.stdin.isatty() else MMGenTermLinuxStub),
'darwin': (MMGenTermLinux if sys.stdin.isatty() else MMGenTermLinuxStub),
'win32': (MMGenTermMSWin if sys.stdin.isatty() else MMGenTermMSWinStub),
}[sys.platform]
}[gc.platform]
def init_term(cfg, *, noecho=False):

View file

@ -20,9 +20,10 @@
tool.fileutil: File routines for the 'mmgen-tool' utility
"""
import sys, os
import os
from .common import tool_cmd_base
from ..cfg import gc
from ..util import msg, msg_r, die, suf, make_full_path
from ..crypto import Crypto
@ -40,7 +41,7 @@ class tool_cmd(tool_cmd_base):
ivsize, bsize, mod = (Crypto.aesctr_iv_len, 4096, 4096*8)
n, carry = 0, b' '*ivsize
flgs = os.O_RDONLY|os.O_BINARY if sys.platform == 'win32' else os.O_RDONLY
flgs = os.O_RDONLY|os.O_BINARY if gc.platform == 'win32' else os.O_RDONLY
f = os.open(filename, flgs)
for ch in incog_id:
if ch not in '0123456789ABCDEF':
@ -56,6 +57,7 @@ class tool_cmd(tool_cmd_base):
continue
msg(f'\rIncog data for ID {incog_id} found at offset {n+i-ivsize}')
if not keep_searching:
import sys
sys.exit(0)
carry = d[len(d)-ivsize:]
n += bsize

View file

@ -20,7 +20,9 @@
tool.util: Utility commands for the 'mmgen-tool' utility
"""
import sys, os
import os
from ..cfg import gc
from .common import tool_cmd_base
@ -125,8 +127,8 @@ class tool_cmd(tool_cmd_base):
def unhexdump(self, infile: str):
"decode hexdump from file (use '-' for stdin) (warning: outputs binary data)"
if sys.platform == 'win32':
import msvcrt
if gc.platform == 'win32':
import sys, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
from ..fileutil import get_data_from_file
from ..util2 import decode_pretty_hexdump

View file

@ -12,9 +12,10 @@
tw.json: export and import tracking wallet to JSON format
"""
import sys, os, json
import os, json
from collections import namedtuple
from ..cfg import gc
from ..util import msg, ymsg, fmt, suf, die, make_timestamp, make_chksum_8
from ..base_obj import AsyncInit
from ..objmethods import MMGenObject
@ -55,7 +56,7 @@ class TwJSON:
from ..addrlist import AddrIdxList
prune_id = AddrIdxList(idx_list=self.pruned).id_str
fn = get_fn(prune_id)
mf = 255 if sys.platform == 'win32' else os.statvfs(self.cfg.outdir or os.curdir).f_namemax
mf = 255 if gc.platform == 'win32' else os.statvfs(self.cfg.outdir or os.curdir).f_namemax
if len(fn) > mf:
fn = get_fn(f'idhash={make_chksum_8(prune_id.encode()).lower()}')
else:

View file

@ -23,7 +23,7 @@ tw.view: base class for tracking wallet view classes
import sys, time, asyncio
from collections import namedtuple
from ..cfg import gv
from ..cfg import gv, gc
from ..objmethods import MMGenObject
from ..obj import get_obj, MMGenIdx, MMGenList
from ..color import nocolor, yellow, orange, green, red, blue
@ -586,7 +586,7 @@ class TwView(MMGenObject, metaclass=AsyncInit):
if scroll:
for k in self.scroll_keys['vi']:
assert k not in self.key_mappings, f'{k!r} is in key_mappings'
self.key_mappings.update(self.scroll_keys['vi'] | self.scroll_keys[sys.platform])
self.key_mappings.update(self.scroll_keys['vi'] | self.scroll_keys[gc.platform])
return self.key_mappings
def cleanup(add_nl=False):

View file

@ -23,7 +23,7 @@ util: Frequently-used variables, classes and utility functions for the MMGen sui
import sys, os, time, re
from .color import red, yellow, green, blue, purple
from .cfg import gv
from .cfg import gv, gc
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
@ -96,7 +96,7 @@ class Util:
msg(f'{capfirst(desc2)} OK ({val2})')
return True
if sys.platform == 'win32':
if gc.platform == 'win32':
def msg_r(s):
try:
gv.stderr.write(s)
@ -468,7 +468,7 @@ def wrap_ripemd160(called=[]):
called.append(True)
def exit_if_mswin(feature):
if sys.platform == 'win32':
if gc.platform == 'win32':
die(2, capfirst(feature) + ' not supported on the MSWin / MSYS2 platform')
def have_sudo(*, silent=False):

View file

@ -12,8 +12,9 @@
wallet.incog_hidden: hidden incognito wallet class
"""
import sys, os
import os
from ..cfg import gc
from ..seed import Seed
from ..util import msg, die, capfirst
from ..util2 import parse_bytespec
@ -72,7 +73,7 @@ class wallet(wallet):
d.target_data_len = self._get_incog_data_len(self.cfg.seed_len or Seed.dfl_len)
self._check_valid_offset(self.infile, 'read')
flgs = os.O_RDONLY|os.O_BINARY if sys.platform == 'win32' else os.O_RDONLY
flgs = os.O_RDONLY|os.O_BINARY if gc.platform == 'win32' else os.O_RDONLY
fh = os.open(self.infile.name, flgs)
os.lseek(fh, int(d.hincog_offset), os.SEEK_SET)
self.fmt_data = os.read(fh, d.target_data_len)
@ -135,7 +136,7 @@ class wallet(wallet):
message = '',
action = f'alter file {f.name!r}')
flgs = os.O_RDWR|os.O_BINARY if sys.platform == 'win32' else os.O_RDWR
flgs = os.O_RDWR|os.O_BINARY if gc.platform == 'win32' else os.O_RDWR
fh = os.open(f.name, flgs)
os.lseek(fh, int(d.hincog_offset), os.SEEK_SET)
os.write(fh, self.fmt_data)

View file

@ -30,7 +30,7 @@ def create_shm_dir(data_dir, trash_dir):
# under '/dev/shm' and put datadir and tmpdirs here.
import shutil
from subprocess import run
if sys.platform in ('win32', 'darwin'):
if gc.platform in ('win32', 'darwin'):
for tdir in (data_dir, trash_dir):
try:
os.listdir(tdir)
@ -81,7 +81,7 @@ try:
except ImportError:
from test.include.test_init import repo_root
from mmgen.cfg import Config
from mmgen.cfg import Config, gc
from mmgen.color import red, yellow, green, blue, init_color
from mmgen.util import msg, Msg, rmsg, die
@ -203,7 +203,7 @@ cfg.skipping_deps = cfg.resuming or 'skip_deps' in po.user_opts
cmd_args = cfg._args
if cfg.pexpect_spawn and sys.platform == 'win32':
if cfg.pexpect_spawn and gc.platform == 'win32':
die(1, '--pexpect-spawn option not supported on Windows platform, exiting')
if cfg.daemon_id and cfg.daemon_id in cfg.blacklisted_daemons.split():
@ -240,7 +240,7 @@ if cfg.skipping_deps:
from test.cmdtest_d.include.cfg import cfgs
def create_tmp_dirs(shm_dir):
if sys.platform in ('win32', 'darwin'):
if gc.platform in ('win32', 'darwin'):
for cfg in sorted(cfgs):
mk_tmpdir(cfgs[cfg]['tmpdir'])
else:

View file

@ -24,7 +24,7 @@ import sys, os, time, shutil, atexit
from subprocess import run, DEVNULL
from pathlib import Path
from mmgen.cfg import Config
from mmgen.cfg import Config, gc
from mmgen.color import red, blue, yellow, cyan, orange, purple, gray
from mmgen.util import msg, suf, die, indent, fmt
from mmgen.led import LEDControl
@ -71,13 +71,13 @@ class CmdTestAutosignBase(CmdTestBase):
self._create_autosign_instances(create_dirs=not cfg.skipping_deps)
self.fs_image_path = Path(self.tmpdir).absolute() / 'removable_device_image'
if sys.platform == 'linux':
if gc.platform == 'linux':
self.txdev = VirtBlockDevice(self.fs_image_path, '10M')
if not (cfg.skipping_deps or self.live):
self._create_removable_device()
if sys.platform == 'darwin' and not cfg.no_daemon_stop:
if gc.platform == 'darwin' and not cfg.no_daemon_stop:
atexit.register(self._macOS_eject_disk, self.asi.dev_label)
self.opts = ['--coins='+','.join(self.coins)]
@ -99,7 +99,7 @@ class CmdTestAutosignBase(CmdTestBase):
del self.txdev
if not self.cfg.no_daemon_stop:
if sys.platform == 'darwin':
if gc.platform == 'darwin':
for label in (self.asi.dev_label, self.asi.macos_ramdisk.label):
self._macOS_eject_disk(label)
@ -123,10 +123,10 @@ class CmdTestAutosignBase(CmdTestBase):
for k in ('mountpoint', 'shm_dir', 'wallet_dir'):
if subdir == 'online' and k in ('shm_dir', 'wallet_dir'):
continue
if sys.platform == 'darwin' and k != 'mountpoint':
if gc.platform == 'darwin' and k != 'mountpoint':
continue
getattr(asi, k).mkdir(parents=True, exist_ok=True)
if sys.platform == 'darwin' and k == 'mountpoint':
if gc.platform == 'darwin' and k == 'mountpoint':
asi.mountpoint.rmdir()
continue
@ -143,7 +143,7 @@ class CmdTestAutosignBase(CmdTestBase):
raise
def _create_removable_device(self):
match sys.platform:
match gc.platform:
case 'linux':
self.txdev.create()
self.txdev.attach(silent=True)
@ -211,7 +211,7 @@ class CmdTestAutosignBase(CmdTestBase):
mn_desc = mn_type or 'default'
mn_type = mn_type or 'mmgen'
if sys.platform == 'darwin' and not self.cfg.no_daemon_stop:
if gc.platform == 'darwin' and not self.cfg.no_daemon_stop:
self._macOS_eject_disk(self.asi.macos_ramdisk.label)
self.insert_device()
@ -257,7 +257,7 @@ class CmdTestAutosignBase(CmdTestBase):
t.read()
self.remove_device()
if sys.platform == 'darwin' and not self.cfg.no_daemon_stop:
if gc.platform == 'darwin' and not self.cfg.no_daemon_stop:
atexit.register(self._macOS_eject_disk, self.asi.macos_ramdisk.label)
return t
@ -267,7 +267,7 @@ class CmdTestAutosignBase(CmdTestBase):
return
loc = getattr(self, asi)
match sys.platform:
match gc.platform:
case 'linux':
self._set_e2label(loc.dev_label)
self.txdev.attach()
@ -284,7 +284,7 @@ class CmdTestAutosignBase(CmdTestBase):
if self.live:
return
loc = getattr(self, asi)
match sys.platform:
match gc.platform:
case 'linux':
self.txdev.detach()
for _ in range(20):
@ -407,7 +407,7 @@ class CmdTestAutosignClean(CmdTestAutosignBase):
t = self.spawn('mmgen-autosign', [f'--coins={coins}', 'clean'], no_msg=True)
out = t.read()
if sys.platform == 'darwin':
if gc.platform == 'darwin':
self.insert_device()
silence()
@ -718,7 +718,7 @@ class CmdTestAutosign(CmdTestAutosignBase):
for fn in (db.control, db.trigger):
run(f'sudo rm -f {fn}'.split(), check=True)
LEDControl.create_dummy_control_files()
usrgrp = {'linux': 'root:root', 'darwin': 'root:wheel'}[sys.platform]
usrgrp = {'linux': 'root:root', 'darwin': 'root:wheel'}[gc.platform]
for fn in (db.control, db.trigger): # trigger the auto-chmod feature
run(f'sudo chmod 644 {fn}'.split(), check=True)
run(f'sudo chown {usrgrp} {fn}'.split(), check=True)

View file

@ -20,8 +20,9 @@
test.cmdtest_d.base: Base class for the cmdtest.py test suite
"""
import sys, os
import os
from mmgen.cfg import gc
from mmgen.util import msg
from mmgen.color import gray, purple, yellow
@ -95,7 +96,7 @@ class CmdTestBase:
msg(f'{fn}: file does not exist or could not be deleted')
def skip_for_platform(self, name, extra_msg=None):
if sys.platform == name:
if gc.platform == name:
msg(gray('Skipping test {!r} for {} platform{}'.format(
self.test_name,
name,

View file

@ -10,8 +10,9 @@
test.cmdtest_d.cfgfile: CfgFile tests for the MMGen cmdtest.py test suite
"""
import sys, os, time, shutil
import os, time, shutil
from mmgen.cfg import gc
from mmgen.color import yellow
from mmgen.cfgfile import CfgFileSampleSys, CfgFileSampleUsr, cfg_file_sample
@ -180,7 +181,7 @@ class CmdTestCfgFile(CmdTestBase):
self.write_to_cfgfile('usr', ['foo true', 'bar false'])
t = self.old_sample_common(
old_set = True,
pexpect_spawn = not sys.platform == 'win32')
pexpect_spawn = not gc.platform == 'win32')
t.expect('unrecognized option')
return t

View file

@ -20,12 +20,13 @@
test.cmdtest_d.ethdev: Ethdev tests for the cmdtest.py test suite
"""
import sys, time, os, re, shutil, asyncio, json
import time, os, re, shutil, asyncio, json
from decimal import Decimal
from collections import namedtuple
from subprocess import run, PIPE, DEVNULL
from pathlib import Path
from mmgen.cfg import gc
from mmgen.color import red, yellow, blue, cyan, orange, set_vt100
from mmgen.util import msg, msg_r, rmsg, die
from mmgen.proto.eth.util import compute_contract_addr
@ -1701,7 +1702,7 @@ class CmdTestEthdev(CmdTestEthdevMethods, CmdTestBase, CmdTestShared):
def edit_comment1(self):
return self.edit_comment(out_num=del_addrs[0], comment_text=tw_comment_zh[:3])
def edit_comment2(self):
spawn = not sys.platform == 'win32'
spawn = not gc.platform == 'win32'
return self.edit_comment(
out_num = del_addrs[0],
comment_text = tw_comment_zh[3:],

View file

@ -12,7 +12,7 @@
test.cmdtest_d.help: helpscreen test group for the cmdtest.py test suite
"""
import sys, os, time
import os, time
from mmgen.util import ymsg
from mmgen.cfg import gc
@ -103,7 +103,7 @@ class CmdTestHelp(CmdTestBase):
scripts = [scripts]
for script in scripts:
d = gc.cmd_caps_data[script]
if sys.platform == 'win32' and 'w' not in d.platforms:
if gc.platform == 'win32' and 'w' not in d.platforms:
yield script
elif not (d.use_coin_opt or self.proto.coin.lower() == 'btc'):
yield script

View file

@ -22,6 +22,7 @@ test.cmdtest_d.include.common: Shared routines and data for the cmdtest.py test
import sys, os
from mmgen.cfg import gc
from mmgen.color import green, blue, gray
from mmgen.util import msg
@ -55,7 +56,7 @@ from mmgen.obj import MMGenTxComment, TwComment
tx_comment_jp = text_jp
tx_comment_zh = text_zh
lcg = ascii_cyr_gr if sys.platform == 'win32' else lat_cyr_gr # MSYS2 popen_spawn issue
lcg = ascii_cyr_gr if gc.platform == 'win32' else lat_cyr_gr # MSYS2 popen_spawn issue
tx_comment_lat_cyr_gr = lcg[:MMGenTxComment.max_len] # 72 chars
tw_comment_zh = text_zh[:TwComment.max_screen_width // 2]

View file

@ -12,9 +12,10 @@
test.cmdtest_d.include.proxy: SSH SOCKS proxy runner for the cmdtest.py test suite
"""
import sys, atexit
import atexit
from subprocess import run, PIPE
from mmgen.cfg import gc
from mmgen.util import msg, die, fmt
from mmgen.util2 import port_in_use
@ -54,7 +55,7 @@ class TestProxy:
"""
def kill_proxy(self, args):
if sys.platform in ('linux', 'darwin'):
if gc.platform in ('linux', 'darwin'):
omsg(f'Stopping SSH SOCKS server at localhost:{self.port}')
cmd = ['pkill', '-f', ' '.join(args)]
run(cmd)

View file

@ -88,7 +88,7 @@ class CmdTestRunner:
omsg(f'INFO → Writing coverage files to {coverdir!r}')
self.pre_args = ['python3', '-m', 'trace', '--count', '--coverdir='+coverdir, '--file='+accfile]
else:
self.pre_args = ['python3'] if sys.platform == 'win32' else []
self.pre_args = ['python3'] if gc.platform == 'win32' else []
if self.cfg.pexpect_spawn:
omsg('INFO → Using pexpect.spawn() for real terminal emulation')
@ -190,7 +190,7 @@ class CmdTestRunner:
clr1, clr2 = (nocolor, nocolor) if self.cfg.print_cmdline else (green, cyan)
omsg(
clr1('Executing: ') +
clr2(repr(cmd_disp) if sys.platform == 'win32' else cmd_disp)
clr2(repr(cmd_disp) if gc.platform == 'win32' else cmd_disp)
)
else:
omsg_r('{a}Testing {b}: {c}'.format(
@ -242,8 +242,8 @@ class CmdTestRunner:
ct_cls = self.gm.load_mod(gname)
if sys.platform in ct_cls.platform_skip:
omsg(gray(f'INFO → skipping test {gname!r} for platform {sys.platform!r}'))
if gc.platform in ct_cls.platform_skip:
omsg(gray(f'INFO → skipping test {gname!r} for platform {gc.platform!r}'))
return None
for k in ('segwit', 'segwit_random', 'bech32'):

View file

@ -10,7 +10,7 @@
test.cmdtest_d.input: user input tests for the MMGen cmdtest.py test suite
"""
import sys, os
import os
from mmgen.cfg import gc
from mmgen.util import fmt, capfirst, remove_whitespace
@ -28,7 +28,7 @@ from .include.common import Ctrl_U, ref_dir
from .base import CmdTestBase
from .include.input import stealth_mnemonic_entry, user_dieroll_entry
hold_protect_delay = 2 if sys.platform == 'darwin' else None
hold_protect_delay = 2 if gc.platform == 'darwin' else None
class CmdTestInput(CmdTestBase):
'user input'
@ -236,7 +236,7 @@ class CmdTestInput(CmdTestBase):
return t
def _input_func(self, func_name, arg_dfls, func_args, text, expect, term, delay=None):
if term and sys.platform == 'win32':
if term and gc.platform == 'win32':
return ('skip_warn', 'pexpect_spawn not supported on Windows platform')
func_args = dict(zip(arg_dfls.keys(), func_args))
t = self.spawn(
@ -285,7 +285,7 @@ class CmdTestInput(CmdTestBase):
return self._get_char(['prompt> ', '', True, 5], 'x', 'x', False)
def get_char2(self):
expect = 'x' if sys.platform == 'win32' else 'xxxxx'
expect = 'x' if gc.platform == 'win32' else 'xxxxx'
return self._get_char(['prompt> ', '', True, 5], 'xxxxx', expect, False)
def get_char3(self):
@ -383,7 +383,7 @@ class CmdTestInput(CmdTestBase):
hold_protect_delay)
def _password_entry(self, prompt, opts=[], term=False):
if term and sys.platform == 'win32':
if term and gc.platform == 'win32':
return ('skip_warn', 'pexpect_spawn not supported on Windows platform')
t = self.spawn('test/misc/input_func.py', opts + ['passphrase'], cmd_dir='.', pexpect_spawn=term)
imsg(f'Terminal: {term}')

View file

@ -22,6 +22,7 @@ test.cmdtest_d.misc: Miscellaneous test groups for the cmdtest.py test suite
import sys, re
from mmgen.cfg import gc
from mmgen.util import die
from ..include.common import start_test_daemons, stop_test_daemons, imsg
@ -208,7 +209,7 @@ class CmdTestOutput(CmdTestBase):
def oneshot_warning(self, pexpect_spawn=None):
t = self.spawn('test/misc/oneshot_warning.py', cmd_dir='.', pexpect_spawn=pexpect_spawn)
nl = '\r\n' if sys.platform == 'win32' or t.pexpect_spawn else '\n'
nl = '\r\n' if gc.platform == 'win32' or t.pexpect_spawn else '\n'
for s in (
f'pw{nl}wg1',
'foo is experimental',

View file

@ -10,8 +10,9 @@
test.cmdtest_d.tool: tool tests for the MMGen cmdtest.py test suite
"""
import sys, os
import os
from mmgen.cfg import gc
from mmgen.util import suf
from mmgen.color import cyan
@ -101,7 +102,7 @@ class CmdTestTool(CmdTestMain, CmdTestBase):
vmsg(f'Incog ID: {cyan(i_id)}')
t = self.spawn('mmgen-tool', ['-d', self.tmpdir, 'find_incog_data', f1, i_id])
o = t.expect_getend(f'Incog data for ID {i_id} found at offset ')
if not sys.platform == 'win32':
if not gc.platform == 'win32':
os.unlink(f1) # causes problems with MSYS2
cmp_or_die(hincog_offset, int(o))
return t

View file

@ -20,8 +20,9 @@
test.cmdtest_d.wallet: Wallet conversion tests for the cmdtest.py test suite
"""
import sys, os
import os
from mmgen.cfg import gc
from mmgen.util import msg, capfirst, get_extension
from mmgen.wallet import get_wallet_cls
@ -174,7 +175,7 @@ class CmdTestWalletConv(CmdTestBase, CmdTestShared):
b = VirtBlockDevice(os.path.join(self.tmpdir, 'hincog_blkdev_img'), '1K')
b.create()
b.attach(dev_mode='0666' if sys.platform == 'linux' else None)
b.attach(dev_mode='0666' if gc.platform == 'linux' else None)
self.ref_hincog_conv_out(ic_f=b.dev)
b.detach()

View file

@ -20,10 +20,11 @@
test.cmdtest_d.xmrwallet: xmrwallet tests for the cmdtest.py test suite
"""
import sys, os, time, re, atexit, asyncio, shutil
import os, time, re, atexit, asyncio, shutil
from subprocess import run, PIPE
from collections import namedtuple
from mmgen.cfg import gc
from mmgen.util import capfirst, is_int, die, suf, list_gen
from mmgen.obj import MMGenRange
from mmgen.amt import XMRAmt
@ -798,7 +799,7 @@ class CmdTestXMRWallet(CmdTestBase):
h = await self._get_height()
imsg_r(f'Chain height: {h} ')
max_iterations, min_height = (300, 64) if sys.platform == 'win32' else (50, 300)
max_iterations, min_height = (300, 64) if gc.platform == 'win32' else (50, 300)
verbose = False
for count in range(max_iterations):

View file

@ -4,9 +4,9 @@
test.daemontest_d.rpc: RPC unit test for the MMGen suite
"""
import sys, os, asyncio
import os, asyncio
from mmgen.cfg import Config
from mmgen.cfg import Config, gc
from mmgen.color import yellow, cyan
from mmgen.util import msg, gmsg, make_timestr, pp_fmt, die, async_run
from mmgen.protocol import init_proto
@ -149,7 +149,7 @@ def run_test(network_ids, test_cf_auth=False, daemon_ids=None, cfg_override=None
d.stop()
d.remove_datadir()
if test_cf_auth and sys.platform != 'win32':
if test_cf_auth and gc.platform != 'win32':
asyncio.run(cfg_file_auth_test(cfg, d))
asyncio.run(cfg_file_auth_test(cfg, d, bad_auth=True))
@ -267,7 +267,7 @@ class unit_tests:
password = 'foo',
seed = xmrseed().fromhex('beadface'*8, tostr=True))
if sys.platform == 'win32':
if gc.platform == 'win32':
wd.stop()
wd.start()

View file

@ -25,7 +25,7 @@ from subprocess import run, PIPE, DEVNULL
from pathlib import Path
from collections import namedtuple
from mmgen.cfg import gv
from mmgen.cfg import gv, gc
from mmgen.color import yellow, green, orange
from mmgen.util import msg, msg_r, Msg, Msg_r, gmsg, die, suf, fmt_list
from mmgen.fileutil import write_data_to_file, get_data_from_file
@ -383,7 +383,7 @@ def create_addrpairs(proto, mmtype, num):
for m in range(num)]
def VirtBlockDevice(img_path, size):
match sys.platform:
match gc.platform:
case 'linux':
return VirtBlockDeviceLinux(img_path, size)
case 'darwin':

View file

@ -243,10 +243,10 @@ def run_test(test, subtest=None):
if cfg.fast and _subtest in fast_skip:
subtest_skip_msg(_subtest, '[--fast]')
continue
if sys.platform == 'win32' and _subtest in win_skip:
if gc.platform == 'win32' and _subtest in win_skip:
subtest_skip_msg(_subtest, 'for Windows platform')
continue
if sys.platform == 'darwin' and _subtest in mac_skip:
if gc.platform == 'darwin' and _subtest in mac_skip:
subtest_skip_msg(_subtest, 'for macOS platform')
continue
if platform.machine() == 'aarch64' and _subtest in arm_skip:

View file

@ -22,7 +22,7 @@ commands = [
'get_char_one_raw',
]
match sys.platform:
match gc.platform:
case 'linux' | 'darwin':
commands.extend([
'get_char',
@ -42,7 +42,7 @@ opts_data = {
-h, --help Print this help message
""",
'notes': f"""
available commands for platform {sys.platform!r}:
available commands for platform {gc.platform!r}:
{fmt_list(commands, fmt='col', indent=' ')}
"""
}
@ -122,7 +122,7 @@ def _tt_get_char(raw=False, one_char=False, immed_chars=''):
if one_char else
'echoed as a FULL CONTROL SEQUENCE.'
)
if sys.platform == 'win32':
if gc.platform == 'win32':
if raw:
m3 = 'The Escape and F1-F12 keys will be returned as two-character strings.'
else:

View file

@ -21,7 +21,7 @@ test/scrambletest.py: seed scrambling and addrlist data generation tests for all
supported coins + passwords
"""
import sys, os, time
import os, time
from subprocess import run, PIPE
from collections import namedtuple
@ -31,7 +31,7 @@ except ImportError:
from test.include import test_init
from mmgen.main import launch
from mmgen.cfg import Config
from mmgen.cfg import Config, gc
from mmgen.util import msg, msg_r, bmsg, die, list_gen
from mmgen.color import gray, green
from test.include.common import set_globals, init_coverage, end_msg
@ -136,7 +136,7 @@ def make_coin_test_data():
bmsg('Testing address scramble strings and list IDs')
coin_data = bitcoin_data | ({} if cfg.no_altcoin else altcoin_data)
for id_str, test_data in coin_data.items():
if id_str == 'zec_zcash_z' and sys.platform == 'win32':
if id_str == 'zec_zcash_z' and gc.platform == 'win32':
msg(gray("Skipping 'zec_zcash_z' test for Windows platform"))
continue
coin, mmtype = id_str.split('_', 1) if '_' in id_str else (id_str, None)

View file

@ -28,7 +28,7 @@ try:
except ImportError:
from test.include.test_init import repo_root
from mmgen.cfg import Config
from mmgen.cfg import Config, gc
from mmgen.color import red, yellow, green, blue, cyan
from mmgen.util import msg, msg_r, Msg, die
@ -155,7 +155,7 @@ spawn_cmd = [
if cfg.coverage:
d, f = init_coverage()
spawn_cmd = ['python3', '-m', 'trace', '--count', '--coverdir='+d, '--file='+f] + spawn_cmd
elif sys.platform == 'win32':
elif gc.platform == 'win32':
spawn_cmd = ['python3'] + spawn_cmd
add_spawn_args = ['--data-dir='+tcfg['tmpdir']] + ['--{}{}'.format(

View file

@ -34,7 +34,7 @@ except ImportError:
from test.include.common import set_globals, end_msg, init_coverage
from mmgen import main_tool
from mmgen.cfg import Config
from mmgen.cfg import Config, gc
from mmgen.color import green, blue, purple, cyan, gray
from mmgen.util import msg, msg_r, Msg, die, isAsync
@ -234,7 +234,7 @@ def run_test(cls, gid, cmd_name):
elif cfg.fork:
cmd_out = fork_cmd(cmd_name, args, opts, stdin_input)
else:
if stdin_input and sys.platform == 'win32':
if stdin_input and gc.platform == 'win32':
msg(gray('Skipping for MSWin - no os.fork()'))
continue
method = getattr(cls(cfg, cmdname=cmd_name, proto=proto, mmtype=mmtype), cmd_name)

View file

@ -12,9 +12,10 @@
test.tooltest2_d.data: Test vectors for the mmgen-tool utility
"""
import sys
from decimal import Decimal
from mmgen.cfg import gc
from mmgen.key import is_wif
from mmgen.addr import is_coin_addr
from mmgen.util import is_hex_str
@ -47,7 +48,7 @@ def md5_hash_strip(s):
s = s.replace(NL, '\n') # fix DOS newlines
return md5_hash(s.strip())
NL = ('\n', '\r\n')[sys.platform=='win32']
NL = ('\n', '\r\n')[gc.platform=='win32']
sample_text_hexdump = (
'000000: 5468 6520 5469 6d65 7320 3033 2f4a 616e{n}' +