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):

Some files were not shown because too many files have changed in this diff Show more