opts.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. opts.py: MMGen-specific options processing after generic processing by share.Opts
  20. """
  21. import sys,os,stat
  22. class opt_cls(object):
  23. pass
  24. opt = opt_cls()
  25. from .exception import UserOptError
  26. from .globalvars import g
  27. import mmgen.share.Opts
  28. from .util import *
  29. def usage():
  30. Die(1,'USAGE: {} {}'.format(g.prog_name,usage_txt))
  31. def version():
  32. Die(0,fmt("""
  33. {pn} version {g.version}
  34. Part of the {g.proj_name} suite, an online/offline cryptocurrency wallet for the
  35. command line. Copyright (C){g.Cdates} {g.author} {g.email}
  36. """.format(g=g,pn=g.prog_name.upper()),indent=' ').rstrip())
  37. def print_help(po,opts_data,opt_filter):
  38. if not 'code' in opts_data:
  39. opts_data['code'] = {}
  40. if getattr(opt,'longhelp',None):
  41. opts_data['code']['long_options'] = common_opts_data['code']
  42. def remove_unneeded_long_opts():
  43. d = opts_data['text']['long_options']
  44. if g.prog_name != 'mmgen-tool':
  45. d = '\n'.join(''+i for i in d.split('\n') if not '--monero-wallet' in i)
  46. if g.proto.base_proto != 'Ethereum':
  47. d = '\n'.join(''+i for i in d.split('\n') if not '--token' in i)
  48. opts_data['text']['long_options'] = d
  49. remove_unneeded_long_opts()
  50. mmgen.share.Opts.print_help( # exits
  51. po,
  52. opts_data,
  53. opt_filter )
  54. def fmt_opt(o):
  55. return '--' + o.replace('_','-')
  56. def die_on_incompatible_opts(incompat_list):
  57. for group in incompat_list:
  58. bad = [k for k in opt.__dict__ if k in group and getattr(opt,k) != None]
  59. if len(bad) > 1:
  60. die(1,'Conflicting options: {}'.format(', '.join(map(fmt_opt,bad))))
  61. def _show_hash_presets():
  62. fs = ' {:<7} {:<6} {:<3} {}'
  63. msg('Available parameters for scrypt.hash():')
  64. msg(fs.format('Preset','N','r','p'))
  65. for i in sorted(g.hash_presets.keys()):
  66. msg(fs.format(i,*g.hash_presets[i]))
  67. msg('N = memory usage (power of two), p = iterations (rounds)')
  68. def opt_preproc_debug(po):
  69. d = (
  70. ('Cmdline', ' '.join(sys.argv)),
  71. ('Opts', po.opts),
  72. ('Skipped opts', po.skipped_opts),
  73. ('User-selected opts', po.user_opts),
  74. ('Cmd args', po.cmd_args),
  75. )
  76. Msg('\n=== opts.py debug ===')
  77. for e in d:
  78. Msg(' {:<20}: {}'.format(*e))
  79. def opt_postproc_debug():
  80. a = [k for k in dir(opt) if k[:2] != '__' and getattr(opt,k) != None]
  81. b = [k for k in dir(opt) if k[:2] != '__' and getattr(opt,k) == None]
  82. Msg(' Opts after processing:')
  83. for k in a:
  84. v = getattr(opt,k)
  85. Msg(' {:18}: {!r:<6} [{}]'.format(k,v,type(v).__name__))
  86. Msg(" Opts set to 'None':")
  87. Msg(' {}\n'.format('\n '.join(b)))
  88. Msg(' Global vars:')
  89. for e in [d for d in dir(g) if d[:2] != '__']:
  90. Msg(' {:<20}: {}'.format(e, getattr(g,e)))
  91. Msg('\n=== end opts.py debug ===\n')
  92. def init_term_and_color():
  93. from .term import init_term
  94. init_term()
  95. if g.color: # MMGEN_DISABLE_COLOR sets this to False
  96. from .color import start_mscolor,init_color
  97. if g.platform == 'win':
  98. start_mscolor()
  99. init_color(num_colors=('auto',256)[bool(g.force_256_color)])
  100. def override_globals_from_cfg_file(ucfg):
  101. from .protocol import CoinProtocol,init_proto
  102. for d in ucfg.parse():
  103. val = d.value
  104. if d.name in g.cfg_file_opts:
  105. ns = d.name.split('_')
  106. if ns[0] in CoinProtocol.coins:
  107. nse,tn = (ns[2:],True) if len(ns) > 2 and ns[1] == 'testnet' else (ns[1:],False)
  108. cls = init_proto(ns[0],tn)
  109. attr = '_'.join(nse)
  110. else:
  111. cls = g
  112. attr = d.name
  113. refval = getattr(cls,attr)
  114. if type(refval) is dict and type(val) is str: # hack - catch single colon-separated value
  115. try:
  116. val = dict([val.split(':')])
  117. except:
  118. raise CfgFileParseError(f'Parse error in file {ucfg.fn!r}, line {d.lineno}')
  119. val_conv = set_for_type(val,refval,attr,src=ucfg.fn)
  120. setattr(cls,attr,val_conv)
  121. else:
  122. raise CfgFileParseError(f'{d.name!r}: unrecognized option in {ucfg.fn!r}, line {d.lineno}')
  123. def override_globals_and_set_opts_from_env(opt):
  124. for name in g.env_opts:
  125. if name == 'MMGEN_DEBUG_ALL':
  126. continue
  127. disable = name[:14] == 'MMGEN_DISABLE_'
  128. val = os.getenv(name) # os.getenv() returns None if env var is unset
  129. if val: # exclude empty string values; string value of '0' or 'false' sets variable to False
  130. gname = name[(6,14)[disable]:].lower()
  131. if hasattr(g,gname):
  132. setattr(g,gname,set_for_type(val,getattr(g,gname),name,disable))
  133. elif hasattr(opt,gname):
  134. if getattr(opt,gname) is None: # env must not override cmdline!
  135. setattr(opt,gname,val)
  136. else:
  137. raise ValueError(f'Name {gname} not present in globals or opts')
  138. def show_common_opts_diff():
  139. def common_opts_data_to_list():
  140. for l in common_opts_data['text'].splitlines():
  141. if l.startswith('--,'):
  142. yield l.split()[1].split('=')[0][2:].replace('-','_')
  143. def do_fmt(set_data):
  144. return fmt_list(['--'+s.replace('_','-') for s in set_data],fmt='col',indent=' ')
  145. a = set(g.common_opts)
  146. b = set(common_opts_data_to_list())
  147. m1 = 'g.common_opts - common_opts_data:\n {}\n'
  148. msg(m1.format(do_fmt(a-b) if a-b else 'None'))
  149. m2 = 'common_opts_data - g.common_opts (these do not set global var):\n{}\n'
  150. msg(m2.format(do_fmt(b-a)))
  151. m3 = 'common_opts_data ^ g.common_opts (these set global var):\n{}\n'
  152. msg(m3.format(do_fmt(b.intersection(a))))
  153. sys.exit(0)
  154. common_opts_data = {
  155. # Most but not all of these set the corresponding global var
  156. # View differences with show_common_opts_diff()
  157. 'text': """
  158. --, --accept-defaults Accept defaults at all prompts
  159. --, --coin=c Choose coin unit. Default: BTC. Current choice: {cu_dfl}
  160. --, --token=t Specify an ERC20 token by address or symbol
  161. --, --color=0|1 Disable or enable color output
  162. --, --force-256-color Force 256-color output when color is enabled
  163. --, --data-dir=path Specify {pnm} data directory location
  164. --, --daemon-data-dir=path Specify {dn} data directory location
  165. --, --no-license Suppress the GPL license prompt
  166. --, --rpc-host=host Communicate with {dn} running on host 'host'
  167. --, --rpc-port=port Communicate with {dn} listening on port 'port'
  168. --, --rpc-user=user Authenticate to {dn} using username 'user'
  169. --, --rpc-password=pass Authenticate to {dn} using password 'pass'
  170. --, --rpc-backend=backend Use backend 'backend' for JSON-RPC communications
  171. --, --aiohttp-rpc-queue-len=N Use 'N' simultaneous RPC connections with aiohttp
  172. --, --monero-wallet-rpc-host=host Specify Monero wallet daemon host
  173. --, --monero-wallet-rpc-user=user Specify Monero wallet daemon username
  174. --, --monero-wallet-rpc-password=pass Specify Monero wallet daemon password
  175. --, --regtest=0|1 Disable or enable regtest mode
  176. --, --testnet=0|1 Disable or enable testnet
  177. --, --skip-cfg-file Skip reading the configuration file
  178. --, --version Print version information and exit
  179. --, --bob Switch to user "Bob" in MMGen regtest setup
  180. --, --alice Switch to user "Alice" in MMGen regtest setup
  181. """,
  182. 'code': lambda s: s.format(
  183. pnm = g.proj_name,
  184. dn = g.proto.daemon_name,
  185. cu_dfl = g.coin,
  186. )
  187. }
  188. opts_data_dfl = {
  189. 'text': {
  190. 'desc': '',
  191. 'usage':'',
  192. 'options': """
  193. -h, --help Print this help message
  194. --, --longhelp Print help message for long (common) options
  195. """
  196. }
  197. }
  198. def init(opts_data=None,add_opts=[],opt_filter=None,parse_only=False):
  199. if opts_data is None:
  200. opts_data = opts_data_dfl
  201. opts_data['text']['long_options'] = common_opts_data['text']
  202. # po: (user_opts,cmd_args,opts,skipped_opts)
  203. po = mmgen.share.Opts.parse_opts(opts_data,opt_filter=opt_filter,parse_only=parse_only)
  204. if parse_only:
  205. return po
  206. if g.debug_opts:
  207. opt_preproc_debug(po)
  208. # Copy parsed opts to opt, setting values to None if not set by user
  209. for o in set(
  210. po.opts
  211. + po.skipped_opts
  212. + tuple(add_opts)
  213. + g.required_opts
  214. + g.common_opts ):
  215. setattr(opt,o,po.user_opts[o] if o in po.user_opts else None)
  216. # Make this available to usage()
  217. global usage_txt
  218. usage_txt = opts_data['text']['usage']
  219. if opt.version:
  220. version() # exits
  221. # === begin global var initialization === #
  222. # NB: user opt --data-dir is actually g.data_dir_root
  223. # cfg file is in g.data_dir_root, wallet and other data are in g.data_dir
  224. # We must set g.data_dir_root from --data-dir before processing cfg file
  225. g.data_dir_root = (
  226. os.path.normpath(os.path.expanduser(opt.data_dir))
  227. if opt.data_dir else
  228. os.path.join(g.home_dir,'.'+g.proj_name.lower()) )
  229. check_or_create_dir(g.data_dir_root)
  230. init_term_and_color()
  231. if not opt.skip_cfg_file:
  232. from .cfg import cfg_file
  233. cfg_file('sample') # check for changes in system template file
  234. override_globals_from_cfg_file(cfg_file('usr'))
  235. override_globals_and_set_opts_from_env(opt)
  236. # Set globals from opts, setting type from original global value
  237. # Do here, before opts are set from globals below
  238. # g.coin is finalized here
  239. for k in (g.common_opts + g.opt_sets_global):
  240. if hasattr(opt,k):
  241. val = getattr(opt,k)
  242. if val != None and hasattr(g,k):
  243. setattr(g,k,set_for_type(val,getattr(g,k),'--'+k))
  244. from .protocol import init_genonly_altcoins,init_proto
  245. altcoin_trust_level = init_genonly_altcoins(
  246. opt.coin or 'btc',
  247. testnet = g.testnet or g.regtest )
  248. g.proto = init_proto(
  249. opt.coin or 'btc',
  250. testnet = g.testnet,
  251. regtest = g.regtest )
  252. # this could have been set from long opts
  253. if g.daemon_data_dir:
  254. g.proto.daemon_data_dir = g.daemon_data_dir
  255. # g.proto is set, so we can set g.data_dir
  256. g.data_dir = os.path.normpath(os.path.join(g.data_dir_root,g.proto.data_subdir))
  257. # Set user opts from globals:
  258. # - if opt is unset, set it to global value
  259. # - if opt is set, convert its type to that of global value
  260. opt.set_by_user = []
  261. for k in g.global_sets_opt:
  262. if hasattr(opt,k) and getattr(opt,k) != None:
  263. setattr(opt,k,set_for_type(getattr(opt,k),getattr(g,k),'--'+k))
  264. opt.set_by_user.append(k)
  265. else:
  266. setattr(opt,k,getattr(g,k))
  267. if opt.show_hash_presets:
  268. _show_hash_presets()
  269. sys.exit(0)
  270. if opt.verbose:
  271. opt.quiet = None
  272. if g.bob or g.alice:
  273. g.proto = init_proto(g.coin,regtest=True)
  274. g.rpc_host = 'localhost'
  275. g.data_dir = os.path.join(g.data_dir_root,'regtest',g.coin.lower(),('alice','bob')[g.bob])
  276. from .regtest import MMGenRegtest
  277. g.rpc_user = MMGenRegtest.rpc_user
  278. g.rpc_password = MMGenRegtest.rpc_password
  279. g.rpc_port = MMGenRegtest(g.coin).d.rpc_port
  280. # === end global var initialization === #
  281. die_on_incompatible_opts(g.incompatible_opts)
  282. # print help screen only after global vars are initialized:
  283. if getattr(opt,'help',None) or getattr(opt,'longhelp',None):
  284. print_help(po,opts_data,opt_filter) # exits
  285. check_or_create_dir(g.data_dir) # g.data_dir is finalized, so we can create it
  286. # Check user-set opts without modifying them
  287. check_usr_opts(po.user_opts)
  288. # Check all opts against g.autoset_opts, setting if unset
  289. check_and_set_autoset_opts()
  290. if g.debug and g.prog_name != 'test.py':
  291. opt.verbose,opt.quiet = (True,None)
  292. if g.debug_opts:
  293. opt_postproc_debug()
  294. warn_altcoins(g.coin,altcoin_trust_level)
  295. # We don't need this data anymore
  296. del mmgen.share.Opts
  297. for k in ('text','notes','code'):
  298. if k in opts_data:
  299. del opts_data[k]
  300. return po.cmd_args
  301. def opt_is_tx_fee(key,val,desc): # 'key' must remain a placeholder
  302. # contract data or non-standard startgas: disable fee checking
  303. if hasattr(opt,'contract_data') and opt.contract_data:
  304. return
  305. if hasattr(opt,'tx_gas') and opt.tx_gas:
  306. return
  307. from .tx import MMGenTX
  308. tx = MMGenTX()
  309. # Size of 224 is just a ball-park figure to eliminate the most extreme cases at startup
  310. # This check will be performed again once we know the true size
  311. ret = tx.process_fee_spec(val,224)
  312. if ret == False:
  313. raise UserOptError('{!r}: invalid {}\n(not a {} amount or {} specification)'.format(
  314. val,desc,g.coin.upper(),tx.rel_fee_desc))
  315. if ret > g.proto.max_tx_fee:
  316. raise UserOptError('{!r}: invalid {}\n({} > max_tx_fee ({} {}))'.format(
  317. val,desc,ret.fmt(fs='1.1'),g.proto.max_tx_fee,g.coin.upper()))
  318. def check_usr_opts(usr_opts): # Raises an exception if any check fails
  319. def opt_splits(val,sep,n,desc):
  320. sepword = 'comma' if sep == ',' else 'colon' if sep == ':' else repr(sep)
  321. try:
  322. l = val.split(sep)
  323. except:
  324. raise UserOptError('{!r}: invalid {} (not {}-separated list)'.format(val,desc,sepword))
  325. if len(l) != n:
  326. raise UserOptError('{!r}: invalid {} ({} {}-separated items required)'.format(val,desc,n,sepword))
  327. def opt_compares(val,op_str,target,desc,desc2=''):
  328. import operator as o
  329. op_f = { '<':o.lt, '<=':o.le, '>':o.gt, '>=':o.ge, '=':o.eq }[op_str]
  330. if not op_f(val,target):
  331. d2 = desc2 + ' ' if desc2 else ''
  332. raise UserOptError('{}: invalid {} ({}not {} {})'.format(val,desc,d2,op_str,target))
  333. def opt_is_int(val,desc):
  334. if not is_int(val):
  335. raise UserOptError('{!r}: invalid {} (not an integer)'.format(val,desc))
  336. def opt_is_float(val,desc):
  337. try:
  338. float(val)
  339. except:
  340. raise UserOptError('{!r}: invalid {} (not a floating-point number)'.format(val,desc))
  341. def opt_is_in_list(val,tlist,desc):
  342. if val not in tlist:
  343. q,sep = (('',','),("'","','"))[type(tlist[0]) == str]
  344. fs = '{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}'
  345. raise UserOptError(fs.format(v=val,w=desc,q=q,o=sep.join(map(str,sorted(tlist)))))
  346. def opt_unrecognized(key,val,desc='value'):
  347. raise UserOptError('{!r}: unrecognized {} for option {!r}'.format(val,desc,fmt_opt(key)))
  348. def opt_display(key,val='',beg='For selected',end=':\n'):
  349. s = '{}={}'.format(fmt_opt(key),val) if val else fmt_opt(key)
  350. msg_r('{} option {!r}{}'.format(beg,s,end))
  351. def chk_in_fmt(key,val,desc):
  352. from .wallet import Wallet,IncogWallet,Brainwallet,IncogWalletHidden
  353. sstype = Wallet.fmt_code_to_type(val)
  354. if not sstype:
  355. opt_unrecognized(key,val)
  356. if key == 'out_fmt':
  357. p = 'hidden_incog_output_params'
  358. if sstype == IncogWalletHidden and not getattr(opt,p):
  359. m1 = 'Hidden incog format output requested. '
  360. m2 = 'You must supply a file and offset with the {!r} option'
  361. raise UserOptError(m1+m2.format(fmt_opt(p)))
  362. if issubclass(sstype,IncogWallet) and opt.old_incog_fmt:
  363. opt_display(key,val,beg='Selected',end=' ')
  364. opt_display('old_incog_fmt',beg='conflicts with',end=':\n')
  365. raise UserOptError('Export to old incog wallet format unsupported')
  366. elif issubclass(sstype,Brainwallet):
  367. raise UserOptError('Output to brainwallet format unsupported')
  368. chk_out_fmt = chk_in_fmt
  369. def chk_hidden_incog_input_params(key,val,desc):
  370. a = val.rsplit(',',1) # permit comma in filename
  371. if len(a) != 2:
  372. opt_display(key,val)
  373. raise UserOptError('Option requires two comma-separated arguments')
  374. fn,offset = a
  375. opt_is_int(offset,desc)
  376. if key == 'hidden_incog_input_params':
  377. check_infile(fn,blkdev_ok=True)
  378. key2 = 'in_fmt'
  379. else:
  380. try: os.stat(fn)
  381. except:
  382. b = os.path.dirname(fn)
  383. if b: check_outdir(b)
  384. else:
  385. check_outfile(fn,blkdev_ok=True)
  386. key2 = 'out_fmt'
  387. if hasattr(opt,key2):
  388. val2 = getattr(opt,key2)
  389. from .wallet import IncogWalletHidden
  390. if val2 and val2 not in IncogWalletHidden.fmt_codes:
  391. fs = 'Option conflict:\n {}, with\n {}={}'
  392. raise UserOptError(fs.format(fmt_opt(key),fmt_opt(key2),val2))
  393. chk_hidden_incog_output_params = chk_hidden_incog_input_params
  394. def chk_seed_len(key,val,desc):
  395. opt_is_int(val,desc)
  396. opt_is_in_list(int(val),g.seed_lens,desc)
  397. def chk_hash_preset(key,val,desc):
  398. opt_is_in_list(val,list(g.hash_presets.keys()),desc)
  399. def chk_brain_params(key,val,desc):
  400. a = val.split(',')
  401. if len(a) != 2:
  402. opt_display(key,val)
  403. raise UserOptError('Option requires two comma-separated arguments')
  404. opt_is_int(a[0],'seed length '+desc)
  405. opt_is_in_list(int(a[0]),g.seed_lens,'seed length '+desc)
  406. opt_is_in_list(a[1],list(g.hash_presets.keys()),'hash preset '+desc)
  407. def chk_usr_randchars(key,val,desc):
  408. if val == 0:
  409. return
  410. opt_is_int(val,desc)
  411. opt_compares(val,'>=',g.min_urandchars,desc)
  412. opt_compares(val,'<=',g.max_urandchars,desc)
  413. def chk_tx_fee(key,val,desc):
  414. pass
  415. # opt_is_tx_fee(key,val,desc) # TODO: move this check elsewhere
  416. def chk_tx_confs(key,val,desc):
  417. opt_is_int(val,desc)
  418. opt_compares(val,'>=',1,desc)
  419. def chk_vsize_adj(key,val,desc):
  420. opt_is_float(val,desc)
  421. ymsg('Adjusting transaction vsize by a factor of {:1.2f}'.format(float(val)))
  422. def chk_key_generator(key,val,desc):
  423. opt_compares(val,'<=',len(g.key_generators),desc)
  424. opt_compares(val,'>',0,desc)
  425. def chk_coin(key,val,desc):
  426. from .protocol import CoinProtocol
  427. opt_is_in_list(val.lower(),CoinProtocol.coins,'coin')
  428. def chk_rbf(key,val,desc):
  429. if not g.proto.cap('rbf'):
  430. m = '--rbf requested, but {} does not support replace-by-fee transactions'
  431. raise UserOptError(m.format(g.coin))
  432. def chk_bob(key,val,desc):
  433. m = "Regtest (Bob and Alice) mode not set up yet. Run '{}-regtest setup' to initialize."
  434. from .regtest import MMGenRegtest
  435. try:
  436. os.stat(os.path.join(MMGenRegtest(g.coin).d.datadir,'regtest','debug.log'))
  437. except:
  438. raise UserOptError(m.format(g.proj_name.lower()))
  439. chk_alice = chk_bob
  440. def chk_locktime(key,val,desc):
  441. opt_is_int(val,desc)
  442. opt_compares(int(val),'>',0,desc)
  443. def chk_token(key,val,desc):
  444. if not 'token' in g.proto.caps:
  445. raise UserOptError('Coin {!r} does not support the --token option'.format(g.coin))
  446. if len(val) == 40 and is_hex_str(val):
  447. return
  448. if len(val) > 20 or not all(s.isalnum() for s in val):
  449. raise UserOptError('{!r}: invalid parameter for --token option'.format(val))
  450. cfuncs = { k:v for k,v in locals().items() if k.startswith('chk_') }
  451. for key in usr_opts:
  452. val = getattr(opt,key)
  453. desc = 'parameter for {!r} option'.format(fmt_opt(key))
  454. if key in g.infile_opts:
  455. check_infile(val) # file exists and is readable - dies on error
  456. elif key == 'outdir':
  457. check_outdir(val) # dies on error
  458. elif 'chk_'+key in cfuncs:
  459. cfuncs['chk_'+key](key,val,desc)
  460. elif g.debug:
  461. Msg('check_usr_opts(): No test for opt {!r}'.format(key))
  462. def check_and_set_autoset_opts(): # Raises exception if any check fails
  463. def nocase_str(key,val,asd):
  464. try:
  465. return asd.choices.index(val)
  466. except:
  467. return 'one of'
  468. def nocase_pfx(key,val,asd):
  469. cs = [s.startswith(val.lower()) for s in asd.choices]
  470. if cs.count(True) == 1:
  471. return cs.index(True)
  472. else:
  473. return 'unique substring of'
  474. for key,asd in g.autoset_opts.items():
  475. if hasattr(opt,key):
  476. val = getattr(opt,key)
  477. if val is None:
  478. setattr(opt,key,asd.choices[0])
  479. else:
  480. ret = locals()[asd.type](key,val,asd)
  481. if type(ret) is str:
  482. m = '{!r}: invalid parameter for option --{} (not {}: {})'
  483. raise UserOptError(m.format(val,key.replace('_','-'),ret,fmt_list(asd.choices)))
  484. elif ret is True:
  485. setattr(opt,key,val)
  486. else:
  487. setattr(opt,key,asd.choices[ret])