Adds unittest.
[python_utils.git] / config.py
index f543b0aab2ed1c2a72760b934c813426426df3a8..1ac5cff30add3fcbd0eb0a03d7361f06515cbbfe 100644 (file)
--- a/config.py
+++ b/config.py
@@ -80,14 +80,28 @@ from typing import Any, Dict, List, Optional
 saved_messages: List[str] = []
 
 # Make a copy of the original program arguments.
-program_name = os.path.basename(sys.argv[0])
-original_argv = [arg for arg in sys.argv]
+program_name: str = os.path.basename(sys.argv[0])
+original_argv: List[str] = [arg for arg in sys.argv]
+
+
+class OptionalRawFormatter(argparse.HelpFormatter):
+    """This formatter has the same bahavior as the normal argparse text
+    formatter except when the help text of an argument begins with
+    "RAW|".  In that case, the line breaks are preserved and the text
+    is not wrapped.
+
+    """
+
+    def _split_lines(self, text, width):
+        if text.startswith('RAW|'):
+            return text[4:].splitlines()
+        return argparse.HelpFormatter._split_lines(self, text, width)
 
 
 # A global parser that we will collect arguments into.
 args = argparse.ArgumentParser(
     description=None,
-    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+    formatter_class=OptionalRawFormatter,
     fromfile_prefix_chars="@",
     epilog=f'{program_name} uses config.py ({__file__}) for global, cross-module configuration setup and parsing.',
 )
@@ -101,7 +115,7 @@ config_parse_called = False
 # It is also this variable that modules use to access parsed arguments.
 # This is the data that is most interesting to our callers; it will hold
 # the configuration result.
-config = {}
+config: Dict[str, Any] = {}
 # It would be really nice if this shit worked from interactive python
 
 
@@ -145,6 +159,10 @@ group.add_argument(
 )
 
 
+def overwrite_argparse_epilog(msg: str) -> None:
+    args.epilog = msg
+
+
 def is_flag_already_in_argv(var: str):
     """Is a particular flag passed on the commandline?"""
     for _ in sys.argv:
@@ -154,11 +172,12 @@ def is_flag_already_in_argv(var: str):
 
 
 def reorder_arg_action_groups(entry_module: Optional[str]):
+    global program_name, args
     reordered_action_groups = []
     for group in args._action_groups:
-        if entry_module is not None and entry_module in group.title:
+        if entry_module is not None and entry_module in group.title:  # type: ignore
             reordered_action_groups.append(group)
-        elif program_name in group.title:
+        elif program_name in group.title:  # type: ignore
             reordered_action_groups.append(group)
         else:
             reordered_action_groups.insert(0, group)
@@ -190,9 +209,7 @@ def augment_sys_argv_from_environment_variables():
                 if env in os.environ:
                     if not is_flag_already_in_argv(var):
                         value = os.environ[env]
-                        saved_messages.append(
-                            f'Initialized from environment: {var} = {value}'
-                        )
+                        saved_messages.append(f'Initialized from environment: {var} = {value}')
                         from string_utils import to_bool
 
                         if len(chunks) == 1 and to_bool(value):
@@ -281,9 +298,7 @@ def parse(entry_module: Optional[str]) -> Dict[str, Any]:
             raise Exception(
                 f'Encountered unrecognized config argument(s) {unknown} with --config_rejects_unrecognized_arguments enabled; halting.'
             )
-        saved_messages.append(
-            f'Config encountered unrecognized commandline arguments: {unknown}'
-        )
+        saved_messages.append(f'Config encountered unrecognized commandline arguments: {unknown}')
     sys.argv = sys.argv[:1] + unknown
 
     # Check for savefile and populate it if requested.