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 bootstrap module's initialize wrapper.
48 [--module_do_the_thing MODULE_DO_THE_THING]
52 Args related to module doing the thing.
54 --module_do_the_thing MODULE_DO_THE_THING
55 Should the module do the thing?
58 A program that does the thing
61 Should we really do the thing?
63 Arguments themselves should be accessed via
64 config.config['arg_name']. e.g.
66 if not config.config['dry_run']:
76 from typing import Any, Dict, List, Optional
78 # This module is commonly used by others in here and should avoid
79 # taking any unnecessary dependencies back on them.
81 # Defer logging messages until later when logging has been initialized.
82 SAVED_MESSAGES: List[str] = []
84 # Make a copy of the original program arguments.
85 PROGRAM_NAME: str = os.path.basename(sys.argv[0])
86 ORIG_ARGV: List[str] = sys.argv.copy()
89 class OptionalRawFormatter(argparse.HelpFormatter):
90 """This formatter has the same bahavior as the normal argparse text
91 formatter except when the help text of an argument begins with
92 "RAW|". In that case, the line breaks are preserved and the text
97 def _split_lines(self, text, width):
98 if text.startswith('RAW|'):
99 return text[4:].splitlines()
100 return argparse.HelpFormatter._split_lines(self, text, width)
103 # A global parser that we will collect arguments into.
104 ARGS = argparse.ArgumentParser(
106 formatter_class=OptionalRawFormatter,
107 fromfile_prefix_chars="@",
108 epilog=f'{PROGRAM_NAME} uses config.py ({__file__}) for global, cross-module configuration setup and parsing.',
111 # Keep track of if we've been called and prevent being called more
113 CONFIG_PARSE_CALLED = False
116 # A global configuration dictionary that will contain parsed arguments.
117 # It is also this variable that modules use to access parsed arguments.
118 # This is the data that is most interesting to our callers; it will hold
119 # the configuration result.
120 config: Dict[str, Any] = {}
122 # It would be really nice if this shit worked from interactive python
125 def add_commandline_args(title: str, description: str = ""):
126 """Create a new context for arguments and return a handle."""
127 return ARGS.add_argument_group(title, description)
130 group = add_commandline_args(
131 f'Global Config ({__file__})',
132 'Args that control the global config itself; how meta!',
138 help='Config file (populated via --config_savefile) from which to read args in lieu or in addition to commandline.',
144 help='Display the global configuration (possibly derived from multiple sources) on STDERR at program startup.',
151 help='Populate config file compatible with --config_loadfile to save global config for later use.',
154 '--config_rejects_unrecognized_arguments',
158 'If present, config will raise an exception if it doesn\'t recognize an argument. The '
159 + 'default behavior is to ignore this so as to allow interoperability with programs that '
160 + 'want to use their own argparse calls to parse their own, separate commandline args.'
165 def overwrite_argparse_epilog(msg: str) -> None:
169 def is_flag_already_in_argv(var: str):
170 """Is a particular flag passed on the commandline?"""
177 def reorder_arg_action_groups_before_help(entry_module: Optional[str]):
178 reordered_action_groups = []
179 for grp in ARGS._action_groups:
180 if entry_module is not None and entry_module in grp.title: # type: ignore
181 reordered_action_groups.append(grp)
182 elif PROGRAM_NAME in group.title: # type: ignore
183 reordered_action_groups.append(grp)
185 reordered_action_groups.insert(0, grp)
186 return reordered_action_groups
189 def augment_sys_argv_from_environment_variables():
190 usage_message = ARGS.format_usage()
193 for x in usage_message.split():
207 # Environment vars the same as flag names without
208 # the initial -'s and in UPPERCASE.
209 env = var.strip('-').upper()
210 if env in os.environ:
211 if not is_flag_already_in_argv(var):
212 value = os.environ[env]
213 SAVED_MESSAGES.append(f'Initialized from environment: {var} = {value}')
214 from string_utils import to_bool
216 if len(chunks) == 1 and to_bool(value):
218 elif len(chunks) > 1:
220 sys.argv.append(value)
225 def augment_sys_argv_from_loadfile():
227 saw_other_args = False
228 grab_next_arg = False
229 for arg in sys.argv[1:]:
230 if 'config_loadfile' in arg:
231 pieces = arg.split('=')
239 saw_other_args = True
241 if loadfile is not None:
242 if not os.path.exists(loadfile):
244 f'ERROR: --config_loadfile argument must be a file, {loadfile} not found.'
247 msg = f'Augmenting commandline arguments with those from {loadfile}.'
249 msg = f'Reading commandline arguments from {loadfile}.'
250 print(msg, file=sys.stderr)
251 SAVED_MESSAGES.append(msg)
253 with open(loadfile, 'r') as rf:
254 newargs = rf.readlines()
255 newargs = [arg.strip('\n') for arg in newargs if 'config_savefile' not in arg]
259 def parse(entry_module: Optional[str]) -> Dict[str, Any]:
260 """Main program should call this early in main(). Note that the
261 bootstrap.initialize wrapper takes care of this automatically.
264 global CONFIG_PARSE_CALLED
265 if CONFIG_PARSE_CALLED:
268 # If we're about to do the usage message dump, put the main
269 # module's argument group last in the list (if possible) so that
270 # when the user passes -h or --help, it will be visible on the
271 # screen w/o scrolling.
273 if arg in ('--help', '-h'):
274 if entry_module is not None:
275 entry_module = os.path.basename(entry_module)
276 ARGS._action_groups = reorder_arg_action_groups_before_help(entry_module)
278 # Examine the environment for variables that match known flags.
279 # For a flag called --example_flag the corresponding environment
280 # variable would be called EXAMPLE_FLAG. If found, hackily add
281 # these into sys.argv to be parsed.
282 augment_sys_argv_from_environment_variables()
284 # Look for loadfile and read/parse it if present. This also
285 # works by jamming these values onto sys.argv.
286 augment_sys_argv_from_loadfile()
288 # Parse (possibly augmented, possibly completely overwritten)
289 # commandline args with argparse normally and populate config.
290 known, unknown = ARGS.parse_known_args()
291 config.update(vars(known))
293 # Reconstruct the argv with unrecognized flags for the benefit of
294 # future argument parsers. For example, unittest_main in python
295 # has some of its own flags. If we didn't recognize it, maybe
298 if config['config_rejects_unrecognized_arguments']:
300 f'Encountered unrecognized config argument(s) {unknown} with --config_rejects_unrecognized_arguments enabled; halting.'
302 SAVED_MESSAGES.append(f'Config encountered unrecognized commandline arguments: {unknown}')
303 sys.argv = sys.argv[:1] + unknown
305 # Check for savefile and populate it if requested.
306 savefile = config['config_savefile']
307 if savefile and len(savefile) > 0:
308 with open(savefile, 'w') as wf:
309 wf.write("\n".join(ORIG_ARGV[1:]))
311 # Also dump the config on stderr if requested.
312 if config['config_dump']:
315 CONFIG_PARSE_CALLED = True
319 def has_been_parsed() -> bool:
320 """Has the global config been parsed yet?"""
321 return CONFIG_PARSE_CALLED
325 """Print the current config to stdout."""
326 print("Global Configuration:", file=sys.stderr)
327 pprint.pprint(config, stream=sys.stderr)
332 """Log messages saved earlier now that logging has been initialized."""
333 logger = logging.getLogger(__name__)
334 logger.debug('Original commandline was: %s', ORIG_ARGV)
335 for _ in SAVED_MESSAGES: