3 # © Copyright 2021-2022, Scott Gasch
5 """Global configuration driven by commandline arguments, environment variables
6 and saved configuration files. This works across several modules.
14 parser = config.add_commandline_args(
16 "Args related to module doing the thing.",
19 "--module_do_the_thing",
22 help="Should the module do the thing?"
30 parser = config.add_commandline_args(
32 "A program that does the thing.",
38 help="Should we really do the thing?"
40 config.parse() # Very important, this must be invoked!
42 If you set this up and remember to invoke config.parse(), all commandline
43 arguments will play nicely together. This is done automatically for you
44 if you're using the :meth:`bootstrap.initialize` decorator on
45 your program's entry point. See :meth:`python_modules.bootstrap.initialize`
54 if __name__ == '__main__':
57 Either way, you'll get this behavior from the commandline::
61 [--module_do_the_thing MODULE_DO_THE_THING]
65 Args related to module doing the thing.
67 --module_do_the_thing MODULE_DO_THE_THING
68 Should the module do the thing?
71 A program that does the thing
74 Should we really do the thing?
76 Arguments themselves should be accessed via
77 :code:`config.config['arg_name']`. e.g.::
79 if not config.config['dry_run']:
89 from typing import Any, Dict, List, Optional
91 # This module is commonly used by others in here and should avoid
92 # taking any unnecessary dependencies back on them.
94 # Defer logging messages until later when logging has been initialized.
95 SAVED_MESSAGES: List[str] = []
97 # Make a copy of the original program arguments.
98 PROGRAM_NAME: str = os.path.basename(sys.argv[0])
99 ORIG_ARGV: List[str] = sys.argv.copy()
102 class OptionalRawFormatter(argparse.HelpFormatter):
103 """This formatter has the same bahavior as the normal argparse text
104 formatter except when the help text of an argument begins with
105 "RAW|". In that case, the line breaks are preserved and the text
108 Use this, for example, when you need the helptext of an argument
109 to have its spacing preserved exactly, e.g.::
115 choices=['CHEAT', 'AUTOPLAY', 'SELFTEST', 'PRECOMPUTE', 'PLAY'],
117 help='''RAW|Our mode of operation. One of:
119 PLAY = play wordle with me! Pick a random solution or
120 specify a solution with --template.
122 CHEAT = given a --template and, optionally, --letters_in_word
123 and/or --letters_to_avoid, return the best guess word;
125 AUTOPLAY = given a complete word in --template, guess it step
126 by step showing work;
128 SELFTEST = autoplay every possible solution keeping track of
129 wins/losses and average number of guesses;
131 PRECOMPUTE = populate hash table with optimal guesses.
137 def _split_lines(self, text, width):
138 if text.startswith('RAW|'):
139 return text[4:].splitlines()
140 return argparse.HelpFormatter._split_lines(self, text, width)
143 # A global parser that we will collect arguments into.
144 ARGS = argparse.ArgumentParser(
146 formatter_class=OptionalRawFormatter,
147 fromfile_prefix_chars="@",
148 epilog=f'{PROGRAM_NAME} uses config.py ({__file__}) for global, cross-module configuration setup and parsing.',
149 # I don't fully understand why but when loaded by sphinx sometimes
150 # the same module is loaded many times causing any arguments it
151 # registers via module-level code to be redefined. Work around
152 # this iff the program is 'sphinx-build'
153 conflict_handler='resolve' if PROGRAM_NAME == 'sphinx-build' else 'error',
156 # Keep track of if we've been called and prevent being called more
158 CONFIG_PARSE_CALLED = False
161 # A global configuration dictionary that will contain parsed arguments.
162 # It is also this variable that modules use to access parsed arguments.
163 # This is the data that is most interesting to our callers; it will hold
164 # the configuration result.
165 config: Dict[str, Any] = {}
167 # It would be really nice if this shit worked from interactive python
170 def add_commandline_args(title: str, description: str = "") -> argparse._ArgumentGroup:
171 """Create a new context for arguments and return a handle.
174 title: A title for your module's commandline arguments group.
175 description: A helpful description of your module.
178 An argparse._ArgumentGroup to be populated by the caller.
180 return ARGS.add_argument_group(title, description)
183 group = add_commandline_args(
184 f'Global Config ({__file__})',
185 'Args that control the global config itself; how meta!',
191 help='Config file (populated via --config_savefile) from which to read args in lieu or in addition to commandline.',
197 help='Display the global configuration (possibly derived from multiple sources) on STDERR at program startup.',
204 help='Populate config file compatible with --config_loadfile to save global config for later use.',
207 '--config_rejects_unrecognized_arguments',
211 'If present, config will raise an exception if it doesn\'t recognize an argument. The '
212 + 'default behavior is to ignore this so as to allow interoperability with programs that '
213 + 'want to use their own argparse calls to parse their own, separate commandline args.'
218 def overwrite_argparse_epilog(msg: str) -> None:
219 """Allows your code to override the default epilog created by
223 msg: The epilog message to substitute for the default.
228 def is_flag_already_in_argv(var: str) -> bool:
229 """Returns true if a particular flag is passed on the commandline?
232 var: The flag to search for.
240 def _reorder_arg_action_groups_before_help(entry_module: Optional[str]):
241 """Internal. Used to reorder the arguments before dumping out a
242 generated help string such that the main program's arguments come
246 reordered_action_groups = []
247 for grp in ARGS._action_groups:
248 if entry_module is not None and entry_module in grp.title: # type: ignore
249 reordered_action_groups.append(grp)
250 elif PROGRAM_NAME in group.title: # type: ignore
251 reordered_action_groups.append(grp)
253 reordered_action_groups.insert(0, grp)
254 return reordered_action_groups
257 def _augment_sys_argv_from_environment_variables():
258 """Internal. Look at the system environment for variables that match
259 arg names. This is done via some munging such that:
261 :code:`--argument_to_match`
265 :code:`ARGUMENT_TO_MATCH`
267 This allows programmers to set args via shell environment variables
268 in lieu of passing them on the cmdline.
272 usage_message = ARGS.format_usage()
275 for x in usage_message.split():
289 # Environment vars the same as flag names without
290 # the initial -'s and in UPPERCASE.
291 env = var.strip('-').upper()
292 if env in os.environ:
293 if not is_flag_already_in_argv(var):
294 value = os.environ[env]
295 SAVED_MESSAGES.append(f'Initialized from environment: {var} = {value}')
296 from string_utils import to_bool
298 if len(chunks) == 1 and to_bool(value):
300 elif len(chunks) > 1:
302 sys.argv.append(value)
307 def _augment_sys_argv_from_loadfile():
308 """Internal. Augment with arguments persisted in a saved file."""
311 saw_other_args = False
312 grab_next_arg = False
313 for arg in sys.argv[1:]:
314 if 'config_loadfile' in arg:
315 pieces = arg.split('=')
323 saw_other_args = True
325 if loadfile is not None:
326 if not os.path.exists(loadfile):
328 f'ERROR: --config_loadfile argument must be a file, {loadfile} not found.'
331 msg = f'Augmenting commandline arguments with those from {loadfile}.'
333 msg = f'Reading commandline arguments from {loadfile}.'
334 print(msg, file=sys.stderr)
335 SAVED_MESSAGES.append(msg)
337 with open(loadfile, 'r') as rf:
338 newargs = rf.readlines()
339 newargs = [arg.strip('\n') for arg in newargs if 'config_savefile' not in arg]
343 def parse(entry_module: Optional[str]) -> Dict[str, Any]:
344 """Main program should call this early in main(). Note that the
345 :code:`bootstrap.initialize` wrapper takes care of this automatically.
346 This should only be called once per program invocation.
349 global CONFIG_PARSE_CALLED
350 if CONFIG_PARSE_CALLED:
353 # If we're about to do the usage message dump, put the main
354 # module's argument group last in the list (if possible) so that
355 # when the user passes -h or --help, it will be visible on the
356 # screen w/o scrolling.
358 if arg in ('--help', '-h'):
359 if entry_module is not None:
360 entry_module = os.path.basename(entry_module)
361 ARGS._action_groups = _reorder_arg_action_groups_before_help(entry_module)
363 # Examine the environment for variables that match known flags.
364 # For a flag called --example_flag the corresponding environment
365 # variable would be called EXAMPLE_FLAG. If found, hackily add
366 # these into sys.argv to be parsed.
367 _augment_sys_argv_from_environment_variables()
369 # Look for loadfile and read/parse it if present. This also
370 # works by jamming these values onto sys.argv.
371 _augment_sys_argv_from_loadfile()
373 # Parse (possibly augmented, possibly completely overwritten)
374 # commandline args with argparse normally and populate config.
375 known, unknown = ARGS.parse_known_args()
376 config.update(vars(known))
378 # Reconstruct the argv with unrecognized flags for the benefit of
379 # future argument parsers. For example, unittest_main in python
380 # has some of its own flags. If we didn't recognize it, maybe
383 if config['config_rejects_unrecognized_arguments']:
385 f'Encountered unrecognized config argument(s) {unknown} with --config_rejects_unrecognized_arguments enabled; halting.'
387 SAVED_MESSAGES.append(f'Config encountered unrecognized commandline arguments: {unknown}')
388 sys.argv = sys.argv[:1] + unknown
390 # Check for savefile and populate it if requested.
391 savefile = config['config_savefile']
392 if savefile and len(savefile) > 0:
393 with open(savefile, 'w') as wf:
394 wf.write("\n".join(ORIG_ARGV[1:]))
396 # Also dump the config on stderr if requested.
397 if config['config_dump']:
400 CONFIG_PARSE_CALLED = True
404 def has_been_parsed() -> bool:
405 """Returns True iff the global config has already been parsed"""
406 return CONFIG_PARSE_CALLED
410 """Print the current config to stdout."""
411 print("Global Configuration:", file=sys.stderr)
412 pprint.pprint(config, stream=sys.stderr)
417 """Log messages saved earlier now that logging has been initialized."""
418 logger = logging.getLogger(__name__)
419 logger.debug('Original commandline was: %s', ORIG_ARGV)
420 for _ in SAVED_MESSAGES: