main_*: use match statement where practicable (6 files)

This commit is contained in:
The MMGen Project 2025-09-23 09:20:55 +00:00
commit df49bc851c
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
6 changed files with 131 additions and 128 deletions

View file

@ -86,28 +86,27 @@ def parse_cmd_args(cmd_args):
def import_mmgen_list(infile):
return (AddrList, KeyAddrList)[bool(cfg.keyaddr_file)](cfg, proto, infile=infile)
if len(cmd_args) == 1:
infile = cmd_args[0]
from .fileutil import check_infile, get_lines_from_file
check_infile(infile)
if cfg.addrlist:
al = AddrList(
cfg = cfg,
proto = proto,
addrlist = get_lines_from_file(
cfg,
infile,
desc = f'non-{gc.proj_name} addresses',
trim_comments = True))
else:
al = import_mmgen_list(infile)
elif len(cmd_args) == 0 and cfg.address:
al = AddrList(cfg, proto=proto, addrlist=[cfg.address])
infile = 'command line'
else:
die(1, addrimport_msgs['bad_args'])
return al, infile
match cmd_args:
case [infile]:
from .fileutil import check_infile, get_lines_from_file
check_infile(infile)
if cfg.addrlist:
return (
AddrList(
cfg = cfg,
proto = proto,
addrlist = get_lines_from_file(
cfg,
infile,
desc = f'non-{gc.proj_name} addresses',
trim_comments = True)),
infile)
else:
return (import_mmgen_list(infile), infile)
case [] if cfg.address:
return (AddrList(cfg, proto=proto, addrlist=[cfg.address]), 'command line')
case _:
die(1, addrimport_msgs['bad_args'])
def check_opts(twctl):
batch = bool(cfg.batch)

View file

@ -221,38 +221,39 @@ asi = Autosign(cfg, cmd=cmd)
cfg._post_init()
if cmd == 'gen_key':
asi.gen_key()
elif cmd == 'setup':
asi.setup()
from .ui import keypress_confirm
if cfg.xmrwallets and keypress_confirm(cfg, '\nContinue with Monero setup?', default_yes=True):
msg('')
match cmd:
case 'gen_key':
asi.gen_key()
case 'setup':
asi.setup()
from .ui import keypress_confirm
if cfg.xmrwallets and keypress_confirm(cfg, '\nContinue with Monero setup?', default_yes=True):
msg('')
asi.xmr_setup()
asi.do_umount()
case 'xmr_setup':
if not cfg.xmrwallets:
die(1, 'Please specify a wallet or range of wallets with the --xmrwallets option')
asi.do_mount()
asi.xmr_setup()
asi.do_umount()
elif cmd == 'xmr_setup':
if not cfg.xmrwallets:
die(1, 'Please specify a wallet or range of wallets with the --xmrwallets option')
asi.do_mount()
asi.xmr_setup()
asi.do_umount()
elif cmd.startswith('macos_ramdisk'):
if sys.platform != 'darwin':
die(1, f'The ‘{cmd}’ operation is for the macOS platform only')
getattr(asi, cmd)()
elif cmd == 'enable_swap':
asi.swap.enable()
elif cmd == 'disable_swap':
asi.swap.disable()
elif cmd == 'sign':
main(do_loop=False)
elif cmd == 'wait':
main(do_loop=True)
elif cmd == 'clean':
asi.do_mount()
asi.clean_old_files()
asi.do_umount()
elif cmd == 'wipe_key':
asi.do_mount()
asi.wipe_encryption_key()
asi.do_umount()
asi.do_umount()
case 'macos_ramdisk_setup' | 'macos_ramdisk_delete':
if sys.platform != 'darwin':
die(1, f'The ‘{cmd}’ operation is for the macOS platform only')
getattr(asi, cmd)()
case 'enable_swap':
asi.swap.enable()
case 'disable_swap':
asi.swap.disable()
case 'sign':
main(do_loop=False)
case 'wait':
main(do_loop=True)
case 'clean':
asi.do_mount()
asi.clean_old_files()
asi.do_umount()
case 'wipe_key':
asi.do_mount()
asi.wipe_encryption_key()
asi.do_umount()

View file

@ -213,17 +213,18 @@ if cfg.msghash_type and op != 'create':
die(1, '--msghash-type option may only be used with the "create" command')
async def main():
if op == 'create':
if not cmd_args:
cfg._usage()
MsgOps.create(arg1, ' '.join(cmd_args))
elif op == 'sign':
await MsgOps.sign(arg1, cmd_args[:])
elif op in ('verify', 'export'):
if len(cmd_args) not in (0, 1):
cfg._usage()
await getattr(MsgOps, op)(arg1, addr=cmd_args[0] if cmd_args else None)
else:
die(1, f'{op!r}: unrecognized operation')
match op:
case 'create':
if not cmd_args:
cfg._usage()
MsgOps.create(arg1, ' '.join(cmd_args))
case 'sign':
await MsgOps.sign(arg1, cmd_args[:])
case 'verify' | 'export':
if len(cmd_args) not in (0, 1):
cfg._usage()
await getattr(MsgOps, op)(arg1, addr=cmd_args[0] if cmd_args else None)
case _:
die(1, f'{op!r}: unrecognized operation')
async_run(main())

View file

@ -321,24 +321,25 @@ def process_result(ret, *, pager=False, print_result=False):
else:
return o
if ret is True:
return True
elif ret in (False, None):
die(2, f'tool command returned {ret!r}')
elif isinstance(ret, str):
return triage_result(ret)
elif isinstance(ret, int):
return triage_result(str(ret))
elif isinstance(ret, tuple):
return triage_result('\n'.join([r.decode() if isinstance(r, bytes) else r for r in ret]))
elif isinstance(ret, bytes):
try:
return triage_result(ret.decode())
except:
# don't add NL to binary data if it can't be converted to utf8
return os.write(1, ret) if print_result else ret
else:
die(2, f'tool.py: can’t handle return value of type {type(ret).__name__!r}')
match ret:
case True:
return True
case False | None:
die(2, f'tool command returned {ret!r}')
case str():
return triage_result(ret)
case int():
return triage_result(str(ret))
case tuple():
return triage_result('\n'.join([r.decode() if isinstance(r, bytes) else r for r in ret]))
case bytes():
try:
return triage_result(ret.decode())
except:
# don't add NL to binary data if it can't be converted to utf8
return os.write(1, ret) if print_result else ret
case _:
die(2, f'tool.py: can’t handle return value of type {type(ret).__name__!r}')
def get_cmd_cls(cmd):
for modname, cmdlist in mods.items():

View file

@ -90,27 +90,27 @@ if cfg.dump_hex and cfg.dump_hex != '-':
asi = None
if len(cfg._args) == 1:
infile = cfg._args[0]
from .fileutil import check_infile
check_infile(infile)
elif not cfg._args and cfg.autosign:
from .tx.util import mount_removable_device
from .autosign import Signable
asi = mount_removable_device(cfg)
si = Signable.automount_transaction(asi)
if cfg.abort:
si.shred_abortable() # prompts user, then raises exception or exits
elif cfg.status or cfg.receipt:
if si.unsent:
die(1, 'Transaction is unsent')
if si.unsigned:
die(1, 'Transaction is unsigned')
else:
infile = si.get_unsent()
cfg._util.qmsg(f'Got signed transaction file ‘{infile}')
else:
cfg._usage()
match cfg._args:
case [infile]:
from .fileutil import check_infile
check_infile(infile)
case [] if cfg.autosign:
from .tx.util import mount_removable_device
from .autosign import Signable
asi = mount_removable_device(cfg)
si = Signable.automount_transaction(asi)
if cfg.abort:
si.shred_abortable() # prompts user, then raises exception or exits
elif cfg.status or cfg.receipt:
if si.unsent:
die(1, 'Transaction is unsent')
if si.unsigned:
die(1, 'Transaction is unsigned')
else:
infile = si.get_unsent()
cfg._util.qmsg(f'Got signed transaction file ‘{infile}')
case _:
cfg._usage()
if not cfg.status:
from .ui import do_license_msg

View file

@ -121,27 +121,28 @@ op = cmd_args.pop(0)
infile = cmd_args.pop(0)
wallets = spec = None
if op in ('relay', 'submit', 'resubmit', 'abort'):
if len(cmd_args) != 0:
cfg._usage()
elif op in ('txview', 'txlist'):
infile = [infile] + cmd_args
elif op in ('create', 'sync', 'list', 'view', 'listview', 'dump', 'restore'): # kafile_arg_ops
if len(cmd_args) > 1:
cfg._usage()
wallets = cmd_args.pop(0) if cmd_args else None
elif op in ('new', 'transfer', 'sweep', 'sweep_all', 'label'):
if len(cmd_args) != 1:
cfg._usage()
spec = cmd_args[0]
elif op in ('export-outputs', 'export-outputs-sign', 'import-key-images'):
if not cfg.autosign:
die(1, f'--autosign must be used with command {op!r}')
if len(cmd_args) > 1:
cfg._usage()
wallets = cmd_args.pop(0) if cmd_args else None
else:
die(1, f'{op!r}: unrecognized operation')
match op:
case 'relay' | 'submit' | 'resubmit' | 'abort':
if len(cmd_args) != 0:
cfg._usage()
case 'txview' | 'txlist':
infile = [infile] + cmd_args
case 'create' | 'sync' | 'list' | 'view' | 'listview' | 'dump' | 'restore': # kafile_arg_ops
if len(cmd_args) > 1:
cfg._usage()
wallets = cmd_args.pop(0) if cmd_args else None
case 'new' | 'transfer' | 'sweep' | 'sweep_all' | 'label':
if len(cmd_args) != 1:
cfg._usage()
spec = cmd_args[0]
case 'export-outputs' | 'export-outputs-sign' | 'import-key-images':
if not cfg.autosign:
die(1, f'--autosign must be used with command {op!r}')
if len(cmd_args) > 1:
cfg._usage()
wallets = cmd_args.pop(0) if cmd_args else None
case _:
die(1, f'{op!r}: unrecognized operation')
m = xmrwallet.op(op, cfg, infile, wallets, spec=spec)