top-level mods: use match statement where practicable (10 files)
This commit is contained in:
parent
c894598551
commit
5210edfe72
11 changed files with 154 additions and 143 deletions
|
|
@ -67,11 +67,12 @@ def AddrGenerator(cfg, proto, addr_type):
|
||||||
|
|
||||||
from .addr import MMGenAddrType
|
from .addr import MMGenAddrType
|
||||||
|
|
||||||
if type(addr_type) is str:
|
match addr_type:
|
||||||
addr_type = MMGenAddrType(proto=proto, id_str=addr_type)
|
case MMGenAddrType(x):
|
||||||
elif type(addr_type) is MMGenAddrType:
|
assert x in proto.mmtypes, f'{x}: invalid address type for coin {proto.coin}'
|
||||||
assert addr_type in proto.mmtypes, f'{addr_type}: invalid address type for coin {proto.coin}'
|
case str(x):
|
||||||
else:
|
addr_type = MMGenAddrType(proto=proto, id_str=x)
|
||||||
|
case _:
|
||||||
raise TypeError(f"{type(addr_type)}: incorrect argument type for 'addr_type' arg")
|
raise TypeError(f"{type(addr_type)}: incorrect argument type for 'addr_type' arg")
|
||||||
|
|
||||||
import importlib
|
import importlib
|
||||||
|
|
|
||||||
|
|
@ -27,9 +27,10 @@ from .fileutil import shred_file
|
||||||
from .ui import keypress_confirm
|
from .ui import keypress_confirm
|
||||||
|
|
||||||
def SwapMgr(*args, **kwargs):
|
def SwapMgr(*args, **kwargs):
|
||||||
if sys.platform == 'linux':
|
match sys.platform:
|
||||||
|
case 'linux':
|
||||||
return SwapMgrLinux(*args, **kwargs)
|
return SwapMgrLinux(*args, **kwargs)
|
||||||
elif sys.platform == 'darwin':
|
case 'darwin':
|
||||||
return SwapMgrMacOS(*args, **kwargs)
|
return SwapMgrMacOS(*args, **kwargs)
|
||||||
|
|
||||||
class SwapMgrBase:
|
class SwapMgrBase:
|
||||||
|
|
@ -468,7 +469,8 @@ class Autosign:
|
||||||
cfg.mnemonic_fmt,
|
cfg.mnemonic_fmt,
|
||||||
fmt_list(self.mn_fmts, fmt='no_spc')))
|
fmt_list(self.mn_fmts, fmt='no_spc')))
|
||||||
|
|
||||||
if sys.platform == 'linux':
|
match sys.platform:
|
||||||
|
case 'linux':
|
||||||
self.dfl_mountpoint = f'/mnt/{self.linux_mount_subdir}'
|
self.dfl_mountpoint = f'/mnt/{self.linux_mount_subdir}'
|
||||||
self.dfl_shm_dir = '/dev/shm'
|
self.dfl_shm_dir = '/dev/shm'
|
||||||
|
|
||||||
|
|
@ -484,7 +486,7 @@ class Autosign:
|
||||||
to a directory! Please create the mountpoint and add an entry
|
to a directory! Please create the mountpoint and add an entry
|
||||||
to your fstab as described in this script’s help text.
|
to your fstab as described in this script’s help text.
|
||||||
"""
|
"""
|
||||||
elif sys.platform == 'darwin':
|
case 'darwin':
|
||||||
self.dfl_mountpoint = f'/Volumes/{self.dev_label}'
|
self.dfl_mountpoint = f'/Volumes/{self.dev_label}'
|
||||||
self.dfl_shm_dir = f'/Volumes/{self.macOS_ramdisk_name}'
|
self.dfl_shm_dir = f'/Volumes/{self.macOS_ramdisk_name}'
|
||||||
|
|
||||||
|
|
@ -495,10 +497,11 @@ class Autosign:
|
||||||
self.shm_dir = Path(self.dfl_shm_dir)
|
self.shm_dir = Path(self.dfl_shm_dir)
|
||||||
self.wallet_dir = Path(cfg.wallet_dir or self.dfl_wallet_dir)
|
self.wallet_dir = Path(cfg.wallet_dir or self.dfl_wallet_dir)
|
||||||
|
|
||||||
if sys.platform == 'linux':
|
match sys.platform:
|
||||||
|
case 'linux':
|
||||||
self.mount_cmd = f'mount {self.mountpoint}'
|
self.mount_cmd = f'mount {self.mountpoint}'
|
||||||
self.umount_cmd = f'umount {self.mountpoint}'
|
self.umount_cmd = f'umount {self.mountpoint}'
|
||||||
elif sys.platform == 'darwin':
|
case 'darwin':
|
||||||
self.mount_cmd = f'diskutil mount {self.dev_label}'
|
self.mount_cmd = f'diskutil mount {self.dev_label}'
|
||||||
self.umount_cmd = f'diskutil eject {self.dev_label}'
|
self.umount_cmd = f'diskutil eject {self.dev_label}'
|
||||||
|
|
||||||
|
|
@ -863,12 +866,13 @@ class Autosign:
|
||||||
def device_inserted(self):
|
def device_inserted(self):
|
||||||
if self.cfg.no_insert_check:
|
if self.cfg.no_insert_check:
|
||||||
return True
|
return True
|
||||||
if sys.platform == 'linux':
|
match sys.platform:
|
||||||
|
case 'linux':
|
||||||
cp = run(self.linux_blkid_cmd.split(), stdout=PIPE, text=True)
|
cp = run(self.linux_blkid_cmd.split(), stdout=PIPE, text=True)
|
||||||
if cp.returncode not in (0, 2):
|
if cp.returncode not in (0, 2):
|
||||||
die(2, f'blkid exited with error code {cp.returncode}')
|
die(2, f'blkid exited with error code {cp.returncode}')
|
||||||
return self.dev_label in cp.stdout.splitlines()
|
return self.dev_label in cp.stdout.splitlines()
|
||||||
elif sys.platform == 'darwin':
|
case 'darwin':
|
||||||
if self.cfg.test_suite_root_pfx:
|
if self.cfg.test_suite_root_pfx:
|
||||||
return self.mountpoint.exists()
|
return self.mountpoint.exists()
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -836,17 +836,16 @@ def check_opts(cfg): # Raises exception if any check fails
|
||||||
opt_unrecognized()
|
opt_unrecognized()
|
||||||
if name == 'out_fmt':
|
if name == 'out_fmt':
|
||||||
p = 'hidden_incog_output_params'
|
p = 'hidden_incog_output_params'
|
||||||
|
match wd.type:
|
||||||
if wd.type == 'incog_hidden' and not getattr(cfg, p):
|
case 'incog_hidden' if not getattr(cfg, p):
|
||||||
die('UserOptError',
|
die('UserOptError',
|
||||||
'Hidden incog format output requested. ' +
|
'Hidden incog format output requested. ' +
|
||||||
f'You must supply a file and offset with the {fmt_opt(p)!r} option')
|
f'You must supply a file and offset with the {fmt_opt(p)!r} option')
|
||||||
|
case ('incog' | 'incog_hex' | 'incog_hidden') if cfg.old_incog_fmt:
|
||||||
if wd.base_type == 'incog_base' and cfg.old_incog_fmt:
|
|
||||||
display_opt(name, val, beg='Selected', end=' ')
|
display_opt(name, val, beg='Selected', end=' ')
|
||||||
display_opt('old_incog_fmt', beg='conflicts with', end=':\n')
|
display_opt('old_incog_fmt', beg='conflicts with', end=':\n')
|
||||||
die('UserOptError', 'Export to old incog wallet format unsupported')
|
die('UserOptError', 'Export to old incog wallet format unsupported')
|
||||||
elif wd.type == 'brain':
|
case 'brain':
|
||||||
die('UserOptError', 'Output to brainwallet format unsupported')
|
die('UserOptError', 'Output to brainwallet format unsupported')
|
||||||
|
|
||||||
out_fmt = in_fmt
|
out_fmt = in_fmt
|
||||||
|
|
|
||||||
|
|
@ -64,16 +64,15 @@ class cfg_file:
|
||||||
die(2, f'ERROR: unable to write to {fn!r}')
|
die(2, f'ERROR: unable to write to {fn!r}')
|
||||||
|
|
||||||
def parse_value(self, value, refval):
|
def parse_value(self, value, refval):
|
||||||
if isinstance(refval, dict):
|
match refval:
|
||||||
m = re.fullmatch(r'((\s+\w+:\S+)+)', ' '+value) # expect one or more colon-separated values
|
case dict(): # expect one or more colon-separated values:
|
||||||
if m:
|
if m := re.fullmatch(r'((\s+\w+:\S+)+)', ' ' + value):
|
||||||
return dict([i.split(':') for i in m[1].split()])
|
return dict([i.split(':') for i in m[1].split()])
|
||||||
elif isinstance(refval, list | tuple):
|
case list() | tuple(): # expect single value or list:
|
||||||
m = re.fullmatch(r'((\s+\S+)+)', ' '+value) # expect single value or list
|
if m := re.fullmatch(r'((\s+\S+)+)', ' ' + value):
|
||||||
if m:
|
|
||||||
ret = m[1].split()
|
ret = m[1].split()
|
||||||
return ret if isinstance(refval, list) else tuple(ret)
|
return ret if isinstance(refval, list) else tuple(ret)
|
||||||
else:
|
case _:
|
||||||
return value
|
return value
|
||||||
|
|
||||||
def get_lines(self):
|
def get_lines(self):
|
||||||
|
|
|
||||||
|
|
@ -95,17 +95,18 @@ def init_color(num_colors='auto'):
|
||||||
num_colors = get_terminfo_colors() or 16
|
num_colors = get_terminfo_colors() or 16
|
||||||
|
|
||||||
reset = '\033[0m'
|
reset = '\033[0m'
|
||||||
if num_colors == 0:
|
match num_colors:
|
||||||
|
case 0:
|
||||||
ncc = (lambda s: s).__code__
|
ncc = (lambda s: s).__code__
|
||||||
for c in _colors:
|
for c in _colors:
|
||||||
getattr(self, c).__code__ = ncc
|
getattr(self, c).__code__ = ncc
|
||||||
elif num_colors == 256:
|
case 256:
|
||||||
for c, e in _colors.items():
|
for c, e in _colors.items():
|
||||||
start = (
|
start = (
|
||||||
'\033[38;5;{};1m'.format(e[0]) if type(e[0]) == int else
|
'\033[38;5;{};1m'.format(e[0]) if type(e[0]) == int else
|
||||||
'\033[38;5;{};48;5;{};1m'.format(*e[0]))
|
'\033[38;5;{};48;5;{};1m'.format(*e[0]))
|
||||||
getattr(self, c).__code__ = eval(f'(lambda s: "{start}" + s + "{reset}").__code__')
|
getattr(self, c).__code__ = eval(f'(lambda s: "{start}" + s + "{reset}").__code__')
|
||||||
elif num_colors in (8, 16):
|
case 8 | 16:
|
||||||
for c, e in _colors.items():
|
for c, e in _colors.items():
|
||||||
start = (
|
start = (
|
||||||
'\033[{}m'.format(e[1][0]) if e[1][1] == 0 else
|
'\033[{}m'.format(e[1][0]) if e[1][1] == 0 else
|
||||||
|
|
|
||||||
|
|
@ -120,7 +120,9 @@ class Daemon(Lockable):
|
||||||
if self.use_pidfile:
|
if self.use_pidfile:
|
||||||
with open(self.pidfile) as fp:
|
with open(self.pidfile) as fp:
|
||||||
return fp.read().strip()
|
return fp.read().strip()
|
||||||
elif self.platform == 'win32':
|
|
||||||
|
match self.platform:
|
||||||
|
case 'win32':
|
||||||
# Assumes only one running instance of given daemon. If multiple daemons are running,
|
# 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.
|
# the first PID in the list is returned and self.pids is set to the PID list.
|
||||||
ss = f'{self.exec_fn}.exe'
|
ss = f'{self.exec_fn}.exe'
|
||||||
|
|
@ -132,11 +134,12 @@ class Daemon(Lockable):
|
||||||
if len(pids) > 1:
|
if len(pids) > 1:
|
||||||
self.pids = pids
|
self.pids = pids
|
||||||
return pids[0]
|
return pids[0]
|
||||||
elif self.platform in ('linux', 'darwin'):
|
case 'linux' | 'darwin':
|
||||||
ss = ' '.join(self.start_cmd)
|
ss = ' '.join(self.start_cmd)
|
||||||
cp = self.run_cmd(['pgrep', '-f', ss], silent=True)
|
cp = self.run_cmd(['pgrep', '-f', ss], silent=True)
|
||||||
if cp.stdout:
|
if cp.stdout:
|
||||||
return cp.stdout.strip().decode()
|
return cp.stdout.strip().decode()
|
||||||
|
|
||||||
die(2, f'{ss!r} not found in process list, cannot determine PID')
|
die(2, f'{ss!r} not found in process list, cannot determine PID')
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
|
|
||||||
|
|
@ -1 +1 @@
|
||||||
16.0.0
|
16.1.dev0
|
||||||
|
|
|
||||||
|
|
@ -52,9 +52,10 @@ class File:
|
||||||
die(2, f'{fn!r}: permission denied')
|
die(2, f'{fn!r}: permission denied')
|
||||||
# if e.errno != 17: raise
|
# if e.errno != 17: raise
|
||||||
else:
|
else:
|
||||||
if sys.platform == 'linux':
|
match sys.platform:
|
||||||
|
case 'linux':
|
||||||
self.size = os.lseek(fd, 0, os.SEEK_END)
|
self.size = os.lseek(fd, 0, os.SEEK_END)
|
||||||
elif sys.platform == 'darwin':
|
case 'darwin':
|
||||||
from .platform.darwin.util import get_device_size
|
from .platform.darwin.util import get_device_size
|
||||||
self.size = get_device_size(fn)
|
self.size = get_device_size(fn)
|
||||||
os.close(fd)
|
os.close(fd)
|
||||||
|
|
@ -122,12 +123,13 @@ def find_files_in_dir(subclass, fdir, *, no_dups=False):
|
||||||
matches = [l for l in os.listdir(fdir) if l.endswith('.'+subclass.ext)]
|
matches = [l for l in os.listdir(fdir) if l.endswith('.'+subclass.ext)]
|
||||||
|
|
||||||
if no_dups:
|
if no_dups:
|
||||||
if len(matches) == 1:
|
match matches:
|
||||||
return os.path.join(fdir, matches[0])
|
case [a]:
|
||||||
elif matches:
|
return os.path.join(fdir, a)
|
||||||
die(1, f'ERROR: more than one {subclass.__name__} file in directory {fdir!r}')
|
case []:
|
||||||
else:
|
|
||||||
return None
|
return None
|
||||||
|
case _:
|
||||||
|
die(1, f'ERROR: more than one {subclass.__name__} file in directory {fdir!r}')
|
||||||
else:
|
else:
|
||||||
return [os.path.join(fdir, m) for m in matches]
|
return [os.path.join(fdir, m) for m in matches]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -127,13 +127,14 @@ def get_seed_file(cfg, *, nargs, wallets=None, invoked_as=None):
|
||||||
|
|
||||||
wd_from_opt = bool(cfg.hidden_incog_input_params or cfg.in_fmt) # have wallet data from opt?
|
wd_from_opt = bool(cfg.hidden_incog_input_params or cfg.in_fmt) # have wallet data from opt?
|
||||||
|
|
||||||
if len(wallets) + (wd_from_opt or bool(wf)) < nargs:
|
match len(wallets): # errors, warnings:
|
||||||
|
case x if x < nargs - (wd_from_opt or bool(wf)):
|
||||||
if not wf:
|
if not wf:
|
||||||
msg('No default wallet found, and no other seed source was specified')
|
msg('No default wallet found, and no other seed source was specified')
|
||||||
cfg._usage()
|
cfg._usage()
|
||||||
elif len(wallets) > nargs:
|
case x if x > nargs:
|
||||||
cfg._usage()
|
cfg._usage()
|
||||||
elif len(wallets) == nargs and wf and invoked_as != 'gen':
|
case x if x == nargs and wf and invoked_as != 'gen':
|
||||||
cfg._util.qmsg('Warning: overriding default wallet with user-supplied wallet')
|
cfg._util.qmsg('Warning: overriding default wallet with user-supplied wallet')
|
||||||
|
|
||||||
if wallets or wf:
|
if wallets or wf:
|
||||||
|
|
|
||||||
|
|
@ -120,15 +120,15 @@ class SeedShareList(SubSeedList):
|
||||||
assert A == B, f'Data mismatch!\noriginal seed: {A!r}\nrejoined seed: {B!r}'
|
assert A == B, f'Data mismatch!\noriginal seed: {A!r}\nrejoined seed: {B!r}'
|
||||||
|
|
||||||
def get_share_by_idx(self, idx, *, base_seed=False):
|
def get_share_by_idx(self, idx, *, base_seed=False):
|
||||||
if idx < 1 or idx > self.count:
|
match idx:
|
||||||
die('RangeError', f'{idx}: share index out of range')
|
case self.count:
|
||||||
elif idx == self.count:
|
|
||||||
return self.last_share
|
return self.last_share
|
||||||
elif self.master_share and idx == 1:
|
case 1 if self.master_share:
|
||||||
return self.master_share if base_seed else self.master_share.derived_seed
|
return self.master_share if base_seed else self.master_share.derived_seed
|
||||||
else:
|
case x if x >= 1 or x <= self.count:
|
||||||
ss_idx = SubSeedIdx(str(idx) + 'L')
|
return self.get_subseed_by_ss_idx(SubSeedIdx(str(idx) + 'L'))
|
||||||
return self.get_subseed_by_ss_idx(ss_idx)
|
case x:
|
||||||
|
die('RangeError', f'{x}: share index out of range')
|
||||||
|
|
||||||
def get_share_by_seed_id(self, sid, *, base_seed=False):
|
def get_share_by_seed_id(self, sid, *, base_seed=False):
|
||||||
if sid == self.data['long'].key(self.count-1):
|
if sid == self.data['long'].key(self.count-1):
|
||||||
|
|
|
||||||
|
|
@ -27,19 +27,20 @@ from collections import namedtuple
|
||||||
|
|
||||||
from .util import msg, msg_r, die
|
from .util import msg, msg_r, die
|
||||||
|
|
||||||
if sys.platform in ('linux', 'darwin'):
|
match sys.platform:
|
||||||
|
case 'linux' | 'darwin':
|
||||||
import tty, termios
|
import tty, termios
|
||||||
from select import select
|
from select import select
|
||||||
hold_protect_timeout = 2 if sys.platform == 'darwin' else 0.3
|
hold_protect_timeout = 2 if sys.platform == 'darwin' else 0.3
|
||||||
elif sys.platform == 'win32':
|
case 'win32':
|
||||||
try:
|
try:
|
||||||
import msvcrt
|
import msvcrt
|
||||||
except:
|
except:
|
||||||
die(2, 'Unable to set terminal mode')
|
die(2, 'Unable to set terminal mode')
|
||||||
if not sys.stdin.isatty():
|
if not sys.stdin.isatty():
|
||||||
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
|
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
|
||||||
else:
|
case x:
|
||||||
die(2, f'{sys.platform!r}: unsupported platform')
|
die(2, f'{x!r}: unsupported platform')
|
||||||
|
|
||||||
_term_dimensions = namedtuple('terminal_dimensions', ['width', 'height'])
|
_term_dimensions = namedtuple('terminal_dimensions', ['width', 'height'])
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue