3 """Global configuration driven by commandline arguments, environment variables
4 and saved configuration files. This works across several modules.
12 parser = config.add_commandline_args(
14 "Args related to module doing the thing.",
17 "--module_do_the_thing",
20 help="Should the module do the thing?"
28 parser = config.add_commandline_args(
30 "A program that does the thing.",
36 help="Should we really do the thing?"
38 config.parse() # Very important, this must be invoked!
40 If you set this up and remember to invoke config.parse(), all commandline
41 arguments will play nicely together. This is done automatically for you
42 if you're using the bootstrap module's initialize wrapper.
46 [--module_do_the_thing MODULE_DO_THE_THING]
50 Args related to module doing the thing.
52 --module_do_the_thing MODULE_DO_THE_THING
53 Should the module do the thing?
56 A program that does the thing
59 Should we really do the thing?
61 Arguments themselves should be accessed via
62 config.config['arg_name']. e.g.
64 if not config.config['dry_run']:
74 from typing import Any, Dict, List, Optional
76 # This module is commonly used by others in here and should avoid
77 # taking any unnecessary dependencies back on them.
79 # Defer logging messages until later when logging has been initialized.
80 saved_messages: List[str] = []
82 # Make a copy of the original program arguments.
83 program_name: str = os.path.basename(sys.argv[0])
84 original_argv: List[str] = [arg for arg in sys.argv]
87 class OptionalRawFormatter(argparse.HelpFormatter):
88 """This formatter has the same bahavior as the normal argparse text
89 formatter except when the help text of an argument begins with
90 "RAW|". In that case, the line breaks are preserved and the text
95 def _split_lines(self, text, width):
96 if text.startswith('RAW|'):
97 return text[4:].splitlines()
98 return argparse.HelpFormatter._split_lines(self, text, width)
101 # A global parser that we will collect arguments into.
102 args = argparse.ArgumentParser(
104 formatter_class=OptionalRawFormatter,
105 fromfile_prefix_chars="@",
106 epilog=f'{program_name} uses config.py ({__file__}) for global, cross-module configuration setup and parsing.',
109 # Keep track of if we've been called and prevent being called more
111 config_parse_called = False
114 # A global configuration dictionary that will contain parsed arguments.
115 # It is also this variable that modules use to access parsed arguments.
116 # This is the data that is most interesting to our callers; it will hold
117 # the configuration result.
118 config: Dict[str, Any] = {}
119 # It would be really nice if this shit worked from interactive python
122 def add_commandline_args(title: str, description: str = ""):
123 """Create a new context for arguments and return a handle."""
124 return args.add_argument_group(title, description)
127 group = add_commandline_args(
128 f'Global Config ({__file__})',
129 'Args that control the global config itself; how meta!',
135 help='Config file (populated via --config_savefile) from which to read args in lieu or in addition to commandline.',
141 help='Display the global configuration (possibly derived from multiple sources) on STDERR at program startup.',
148 help='Populate config file compatible with --config_loadfile to save global config for later use.',
151 '--config_rejects_unrecognized_arguments',
155 'If present, config will raise an exception if it doesn\'t recognize an argument. The '
156 + 'default behavior is to ignore this so as to allow interoperability with programs that '
157 + 'want to use their own argparse calls to parse their own, separate commandline args.'
162 def is_flag_already_in_argv(var: str):
163 """Is a particular flag passed on the commandline?"""
170 def reorder_arg_action_groups(entry_module: Optional[str]):
171 global program_name, args
172 reordered_action_groups = []
173 for group in args._action_groups:
174 if entry_module is not None and entry_module in group.title: # type: ignore
175 reordered_action_groups.append(group)
176 elif program_name in group.title: # type: ignore
177 reordered_action_groups.append(group)
179 reordered_action_groups.insert(0, group)
180 return reordered_action_groups
183 def augment_sys_argv_from_environment_variables():
184 global saved_messages
185 usage_message = args.format_usage()
188 for x in usage_message.split():
202 # Environment vars the same as flag names without
203 # the initial -'s and in UPPERCASE.
204 env = var.strip('-').upper()
205 if env in os.environ:
206 if not is_flag_already_in_argv(var):
207 value = os.environ[env]
208 saved_messages.append(f'Initialized from environment: {var} = {value}')
209 from string_utils import to_bool
211 if len(chunks) == 1 and to_bool(value):
213 elif len(chunks) > 1:
215 sys.argv.append(value)
220 def augment_sys_argv_from_loadfile():
221 global saved_messages
223 saw_other_args = False
224 grab_next_arg = False
225 for arg in sys.argv[1:]:
226 if 'config_loadfile' in arg:
227 pieces = arg.split('=')
235 saw_other_args = True
237 if loadfile is not None:
238 if not os.path.exists(loadfile):
240 f'ERROR: --config_loadfile argument must be a file, {loadfile} not found.'
243 msg = f'Augmenting commandline arguments with those from {loadfile}.'
245 msg = f'Reading commandline arguments from {loadfile}.'
246 print(msg, file=sys.stderr)
247 saved_messages.append(msg)
249 with open(loadfile, 'r') as rf:
250 newargs = rf.readlines()
251 newargs = [arg.strip('\n') for arg in newargs if 'config_savefile' not in arg]
255 def parse(entry_module: Optional[str]) -> Dict[str, Any]:
256 """Main program should call this early in main(). Note that the
257 bootstrap.initialize wrapper takes care of this automatically.
260 global config_parse_called
261 if config_parse_called:
263 global saved_messages
265 # If we're about to do the usage message dump, put the main
266 # module's argument group last in the list (if possible) so that
267 # when the user passes -h or --help, it will be visible on the
268 # screen w/o scrolling.
270 if arg == '--help' or arg == '-h':
271 args._action_groups = reorder_arg_action_groups(entry_module)
273 # Examine the environment for variables that match known flags.
274 # For a flag called --example_flag the corresponding environment
275 # variable would be called EXAMPLE_FLAG. If found, hackily add
276 # these into sys.argv to be parsed.
277 augment_sys_argv_from_environment_variables()
279 # Look for loadfile and read/parse it if present. This also
280 # works by jamming these values onto sys.argv.
281 augment_sys_argv_from_loadfile()
283 # Parse (possibly augmented, possibly completely overwritten)
284 # commandline args with argparse normally and populate config.
285 known, unknown = args.parse_known_args()
286 config.update(vars(known))
288 # Reconstruct the argv with unrecognized flags for the benefit of
289 # future argument parsers. For example, unittest_main in python
290 # has some of its own flags. If we didn't recognize it, maybe
293 if config['config_rejects_unrecognized_arguments']:
295 f'Encountered unrecognized config argument(s) {unknown} with --config_rejects_unrecognized_arguments enabled; halting.'
297 saved_messages.append(f'Config encountered unrecognized commandline arguments: {unknown}')
298 sys.argv = sys.argv[:1] + unknown
300 # Check for savefile and populate it if requested.
301 savefile = config['config_savefile']
302 if savefile and len(savefile) > 0:
303 with open(savefile, 'w') as wf:
304 wf.write("\n".join(original_argv[1:]))
306 # Also dump the config on stderr if requested.
307 if config['config_dump']:
310 config_parse_called = True
314 def has_been_parsed() -> bool:
315 """Has the global config been parsed yet?"""
316 global config_parse_called
317 return config_parse_called
321 """Print the current config to stdout."""
322 print("Global Configuration:", file=sys.stderr)
323 pprint.pprint(config, stream=sys.stderr)
328 """Log messages saved earlier now that logging has been initialized."""
329 logger = logging.getLogger(__name__)
330 global saved_messages
331 for _ in saved_messages: