cfg.py: prefix internally used attrs with underscore

This commit is contained in:
The MMGen Project 2023-04-04 16:04:11 +00:00
commit d81d82fe35
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
10 changed files with 54 additions and 51 deletions

View file

@ -24,9 +24,12 @@ import sys,os
from collections import namedtuple
from .base_obj import Lockable
def die(exit_val,s=''):
if s:
sys.stderr.write(s+'\n')
def die(*args,**kwargs):
from .util import die
die(*args,**kwargs)
def die2(exit_val,s):
sys.stderr.write(s+'\n')
sys.exit(exit_val)
class GlobalConstants(Lockable):
@ -57,14 +60,14 @@ class GlobalConstants(Lockable):
platform = { 'linux':'linux', 'win':'win', 'msys':'win' }[k]
break
else:
die(1,f'{sys.platform!r}: platform not supported by {proj_name}')
die2(1,f'{sys.platform!r}: platform not supported by {proj_name}')
if os.getenv('HOME'): # Linux or MSYS2
home_dir = os.getenv('HOME')
elif platform == 'win': # Windows without MSYS2 - not supported
die(1,f'$HOME not set! {proj_name} for Windows must be run in MSYS2 environment')
die2(1,f'$HOME not set! {proj_name} for Windows must be run in MSYS2 environment')
else:
die(2,'$HOME is not set! Unable to determine home directory')
die2(2,'$HOME is not set! Unable to determine home directory')
def get_mmgen_data_file(self,filename,package='mmgen'):
"""
@ -218,7 +221,7 @@ class Config(Lockable):
pager = False
# 'long' opts (subset of common_opts_data):
common_opts = (
_common_opts = (
'accept_defaults',
'aiohttp_rpc_queue_len',
'bob',
@ -242,10 +245,10 @@ class Config(Lockable):
'testnet',
'token' )
# opts not in common_opts but required to be set during opts initialization
init_opts = ('show_hash_presets','yes','verbose')
# opts not in _common_opts but required to be set during opts initialization
_init_opts = ('show_hash_presets','yes','verbose')
incompatible_opts = (
_incompatible_opts = (
('help','longhelp'),
('bob','alice','carol'),
('label','keep_label'),
@ -253,7 +256,7 @@ class Config(Lockable):
('tx_id','terse_info'),
)
cfg_file_opts = (
_cfg_file_opts = (
'autochg_ignore_labels',
'color',
'daemon_data_dir',
@ -295,7 +298,7 @@ class Config(Lockable):
# Supported environmental vars
# The corresponding attributes (lowercase, without 'mmgen_') must exist in the class.
# The 'MMGEN_DISABLE_' prefix sets the corresponding attribute to False.
env_opts = (
_env_opts = (
'MMGEN_DEBUG_ALL', # special: there is no `debug_all` attribute
'MMGEN_COLUMNS',
@ -331,7 +334,7 @@ class Config(Lockable):
'MMGEN_ENABLE_ERIGON',
'MMGEN_DISABLE_COLOR',
)
infile_opts = (
_infile_opts = (
'keys_from_file',
'mmgen_keys_from_file',
'passwd_file',
@ -341,12 +344,12 @@ class Config(Lockable):
)
# Auto-typechecked and auto-set opts - first value in list is the default
_ov = namedtuple('autoset_opt_info',['type','choices'])
autoset_opts = {
_autoset_opts = {
'fee_estimate_mode': _ov('nocase_pfx', ['conservative','economical']),
'rpc_backend': _ov('nocase_pfx', ['auto','httplib','curl','aiohttp','requests']),
}
auto_typeset_opts = {
_auto_typeset_opts = {
'seed_len': int,
'subseeds': int,
'vsize_adj': float,
@ -367,7 +370,7 @@ class Config(Lockable):
_reset_ok += ('force_standalone_scrypt_module',)
if os.getenv('MMGEN_DEBUG_ALL'):
for name in env_opts:
for name in _env_opts:
if name[:11] == 'MMGEN_DEBUG':
os.environ[name] = '1'
@ -379,8 +382,8 @@ class Config(Lockable):
if hasattr(self,'_data_dir_root'):
return self._data_dir_root
else:
if self.data_dir_root_override:
self._data_dir_root = os.path.normpath(os.path.abspath(self.data_dir_root_override))
if self._data_dir_root_override:
self._data_dir_root = os.path.normpath(os.path.abspath(self._data_dir_root_override))
elif self.test_suite:
from test.include.common import get_test_data_dir
self._data_dir_root = get_test_data_dir()

View file

@ -68,8 +68,8 @@ opts_data = {
'options': lambda cfg,proto,help_notes,s: s.format(
fu=help_notes('rel_fee_desc'),
fl=help_notes('fee_spec_letters'),
fe_all=fmt_list(cfg.autoset_opts['fee_estimate_mode'].choices,fmt='no_spc'),
fe_dfl=cfg.autoset_opts['fee_estimate_mode'].choices[0],
fe_all=fmt_list(cfg._autoset_opts['fee_estimate_mode'].choices,fmt='no_spc'),
fe_dfl=cfg._autoset_opts['fee_estimate_mode'].choices[0],
cu=proto.coin,
cfg=cfg),
'notes': lambda cfg,help_notes,s: s.format(

View file

@ -110,8 +110,8 @@ FMT CODES:
fl=help_notes('fee_spec_letters'),
ss=help_notes('dfl_subseeds'),
ss_max=SubSeedIdxRange.max_idx,
fe_all=fmt_list(cfg.autoset_opts['fee_estimate_mode'].choices,fmt='no_spc'),
fe_dfl=cfg.autoset_opts['fee_estimate_mode'].choices[0],
fe_all=fmt_list(cfg._autoset_opts['fee_estimate_mode'].choices,fmt='no_spc'),
fe_dfl=cfg._autoset_opts['fee_estimate_mode'].choices[0],
dsl=help_notes('dfl_seed_len'),
cu=proto.coin),
'notes': lambda cfg,help_notes,s: s.format(

View file

@ -83,7 +83,7 @@ def fmt_opt(o):
return '--' + o.replace('_','-')
def die_on_incompatible_opts(cfg):
for group in cfg.incompatible_opts:
for group in cfg._incompatible_opts:
bad = [k for k in cfg.__dict__ if k in group and getattr(cfg,k) != None]
if len(bad) > 1:
from .util import die
@ -161,7 +161,7 @@ def set_cfg_from_cfg_file(
from .protocol import init_proto
for d in ucfg.get_lines():
if d.name in cfg.cfg_file_opts:
if d.name in cfg._cfg_file_opts:
ns = d.name.split('_')
if ns[0] in gc.core_coins:
if not need_proto:
@ -183,9 +183,9 @@ def set_cfg_from_cfg_file(
val_conv = set_for_type(val,refval,attr,src=ucfg.fn)
if attr not in env_cfg:
setattr(cls,attr,val_conv)
elif d.name in cfg.autoset_opts:
elif d.name in cfg._autoset_opts:
cfgfile_autoset_opts[d.name] = d.value
elif d.name in cfg.auto_typeset_opts:
elif d.name in cfg._auto_typeset_opts:
cfgfile_auto_typeset_opts[d.name] = d.value
else:
from .util import die
@ -195,7 +195,7 @@ def set_cfg_from_env(cfg):
for name,val in ((k,v) for k,v in os.environ.items() if k.startswith('MMGEN_')):
if name == 'MMGEN_DEBUG_ALL':
continue
elif name in cfg.env_opts:
elif name in cfg._env_opts:
if val: # ignore empty string values; string value of '0' or 'false' sets variable to False
disable = name.startswith('MMGEN_DISABLE_')
gname = name[(6,14)[disable]:].lower()
@ -218,16 +218,16 @@ def show_common_opts_diff(cfg):
from .util import fmt_list
return fmt_list(['--'+s.replace('_','-') for s in set_data],fmt='col',indent=' ')
a = cfg.common_opts
a = cfg._common_opts
b = list(common_opts_data_to_list())
a_minus_b = [e for e in a if e not in b]
b_minus_a = [e for e in b if e not in a]
a_and_b = [e for e in a if e in b]
from .util import msg
msg(f'cfg.common_opts - common_opts_data:\n {do_fmt(a_minus_b) if a_minus_b else "None"}\n')
msg(f'common_opts_data - cfg.common_opts (these do not set global var):\n{do_fmt(b_minus_a)}\n')
msg(f'common_opts_data ^ cfg.common_opts (these set global var):\n{do_fmt(a_and_b)}\n')
msg(f'cfg._common_opts - common_opts_data:\n {do_fmt(a_minus_b) if a_minus_b else "None"}\n')
msg(f'common_opts_data - cfg._common_opts (these do not set global var):\n{do_fmt(b_minus_a)}\n')
msg(f'common_opts_data ^ cfg._common_opts (these set global var):\n{do_fmt(a_and_b)}\n')
sys.exit(0)
@ -323,8 +323,8 @@ def init(
+ po.filtered_opts
+ tuple(add_opts or [])
+ tuple(init_opts or [])
+ cfg.init_opts
+ cfg.common_opts ):
+ cfg._init_opts
+ cfg._common_opts ):
setattr(opt,o,po.user_opts[o] if o in po.user_opts else None)
if opt.version:
@ -345,7 +345,7 @@ def init(
init_term(cfg)
# --data-dir overrides computed value of data_dir_root
cfg.data_dir_root_override = opt.data_dir
cfg._data_dir_root_override = opt.data_dir
if opt.data_dir:
del opt.data_dir
@ -368,7 +368,7 @@ def init(
need_proto )
# Set cfg from opts, setting type from original class attr in Config if it exists:
auto_keys = tuple(cfg.autoset_opts.keys()) + tuple(cfg.auto_typeset_opts.keys())
auto_keys = tuple(cfg._autoset_opts.keys()) + tuple(cfg._auto_typeset_opts.keys())
for key,val in opt.__dict__.items():
if val is not None and key not in auto_keys:
setattr(cfg, key, set_for_type(val,getattr(cfg,key),'--'+key) if hasattr(cfg,key) else val)
@ -396,7 +396,7 @@ def init(
check_or_create_dir(cfg.data_dir)
# Set globals from opts, setting type from original global value if it exists:
for key in cfg.autoset_opts:
for key in cfg._autoset_opts:
if hasattr(opt,key):
assert not hasattr(cfg,key), f'{key!r} is in cfg!'
if getattr(opt,key) is not None:
@ -404,7 +404,7 @@ def init(
elif key in cfgfile_autoset_opts:
setattr(cfg, key, get_autoset_opt(cfg,key,cfgfile_autoset_opts[key],src='cfgfile'))
else:
setattr(cfg, key, cfg.autoset_opts[key].choices[0])
setattr(cfg, key, cfg._autoset_opts[key].choices[0])
set_auto_typeset_opts(cfg,cfgfile_auto_typeset_opts)
@ -637,7 +637,7 @@ def check_usr_opts(cfg,usr_opts): # Raises an exception if any check fails
val = getattr(cfg,key)
desc = f'parameter for {fmt_opt(key)!r} option'
if key in cfg.infile_opts:
if key in cfg._infile_opts:
from .fileutil import check_infile
check_infile(val) # file exists and is readable - dies on error
elif key == 'outdir':
@ -654,7 +654,7 @@ def set_auto_typeset_opts(cfg,cfgfile_auto_typeset_opts):
assert not hasattr(cfg,key), f'{key!r} is in cfg!'
setattr(cfg,key,None if val is None else ref_type(val))
for key,ref_type in cfg.auto_typeset_opts.items():
for key,ref_type in cfg._auto_typeset_opts.items():
if hasattr(opt,key):
do_set(key, getattr(opt,key), ref_type)
elif key in cfgfile_auto_typeset_opts:
@ -690,6 +690,6 @@ def get_autoset_opt(cfg,key,val,src):
else:
die_on_err('unique substring of')
data = cfg.autoset_opts[key]
data = cfg._autoset_opts[key]
return getattr(opt_type,data.type)()

View file

@ -55,8 +55,8 @@ if cfg._args == ['show_common_opts_diff']:
for k in (
'foo', # added opt
'print_checksum', # sets 'quiet'
'quiet','verbose', # init_opts, incompatible_opts
'passwd_file', # infile_opts - check_infile()
'quiet','verbose', # _incompatible_opts
'passwd_file', # _infile_opts - check_infile()
'outdir', # check_outdir()
'cached_balances', # opt_sets_global
'minconf', # global_sets_opt
@ -73,6 +73,6 @@ for k in (
msg('')
for k in (
'fee_estimate_mode', # autoset_opts
'fee_estimate_mode', # _autoset_opts
):
msg('{:30} {}'.format( f'cfg.{k}:', getattr(cfg,k) ))

View file

@ -341,7 +341,7 @@ def set_environ_for_spawned_scripts():
os.environ['MMGEN_COLUMNS'] = str(get_terminal_size().width)
if os.getenv('MMGEN_DEBUG_ALL'):
for name in cfg.env_opts:
for name in cfg._env_opts:
if name[:11] == 'MMGEN_DEBUG':
os.environ[name] = '1'

View file

@ -97,7 +97,7 @@ def randbool():
def disable_debug():
global save_debug
save_debug = {}
for k in cfg.env_opts:
for k in cfg._env_opts:
if k[:11] == 'MMGEN_DEBUG':
save_debug[k] = os.getenv(k)
os.environ[k] = ''

View file

@ -41,7 +41,7 @@ class TestSuiteMisc(TestSuiteBase):
color = True
def rpc_backends(self):
backends = cfg.autoset_opts['rpc_backend'][1]
backends = cfg._autoset_opts['rpc_backend'][1]
for b in backends:
t = self.spawn_chk('mmgen-tool',[f'--rpc-backend={b}','daemon_version'],extra_desc=f'({b})')
return t

View file

@ -59,13 +59,13 @@ class TestSuiteOpts(TestSuiteBase):
(
('cfg.foo', 'None'), # added opt
('cfg.print_checksum', 'None'), # sets 'quiet'
('cfg.quiet', 'False'), # init_opts, incompatible_opts
('cfg.verbose', 'False'), # init_opts, incompatible_opts
('cfg.passwd_file', ''), # infile_opts - check_infile()
('cfg.quiet', 'False'), # _incompatible_opts
('cfg.verbose', 'False'), # _incompatible_opts
('cfg.passwd_file', ''), # _infile_opts - check_infile()
('cfg.outdir', ''), # check_outdir()
('cfg.cached_balances', 'False'),
('cfg.minconf', '1'),
('cfg.fee_estimate_mode', 'conservative'), # autoset_opts
('cfg.fee_estimate_mode', 'conservative'), # _autoset_opts
)
)

View file

@ -114,7 +114,7 @@ def run_test(network_ids,test_cf_auth=False,daemon_ids=None):
d.remove_datadir()
d.start()
for n,backend in enumerate(cfg.autoset_opts['rpc_backend'].choices):
for n,backend in enumerate(cfg._autoset_opts['rpc_backend'].choices):
test = getattr(init_test,d.proto.coin.lower())
rpc = async_run(test(d.proto,backend,d))
if not n and cfg.verbose: