Adds a __repr__ to graph.
[pyutils.git] / src / pyutils / config.py
index 64eb2025d7db8b8b2cddff3ff56dcb90c9e2b70e..a1aa5f97d89d9e3ebebe044436271dafef1a37a8 100644 (file)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python3
 
-# © Copyright 2021-2022, Scott Gasch
+# © Copyright 2021-2023, Scott Gasch
 
 """Global program configuration driven by commandline arguments and,
 optionally, from saved (local or Zookeeper) configuration files... with
@@ -341,18 +341,31 @@ class Config:
         return False
 
     @staticmethod
-    def print_usage() -> None:
-        """Prints the normal help usage message out."""
-        ARGS.print_help()
+    def usage() -> str:
+        """
+        Returns:
+            full program usage help text as a string.
+        """
+        return ARGS.format_help()
 
     @staticmethod
-    def usage() -> str:
+    def short_usage() -> str:
         """
         Returns:
-            program usage help text as a string.
+            program short usage text as a string.
         """
         return ARGS.format_usage()
 
+    @staticmethod
+    def print_usage() -> None:
+        """Prints the full help usage message out."""
+        print(config.usage())
+
+    @staticmethod
+    def print_short_usage() -> None:
+        """Prints a short usage/help message."""
+        print(config.short_usage())
+
     @staticmethod
     def _reorder_arg_action_groups_before_help(entry_module: Optional[str]):
         """Internal.  Used to reorder the arguments before dumping out a
@@ -390,6 +403,9 @@ class Config:
 
             Otherwise False is returned.
 
+        Raises:
+            Exception: On error reading from zookeeper
+
         >>> to_bool('True')
         True
 
@@ -408,9 +424,9 @@ class Config:
         >>> to_bool('on')
         True
         """
-        return in_str.lower() in ("true", "1", "yes", "y", "t", "on")
+        return in_str.lower() in {"true", "1", "yes", "y", "t", "on"}
 
-    def _process_dynamic_args(self, event):
+    def _process_dynamic_args(self, event) -> None:
         """Invoked as a callback when a zk-based config changed."""
 
         if not self.zk:
@@ -442,7 +458,7 @@ class Config:
                     temp_argv.append(arg)
                     logger.info("Updating %s from zookeeper async config change.", arg)
 
-            if len(temp_argv) > 0:
+            if temp_argv:
                 old_argv = sys.argv
                 sys.argv = temp_argv
                 known, _ = ARGS.parse_known_args()
@@ -506,7 +522,7 @@ class Config:
             else:
                 saw_other_args = True
 
-        if not loadfile or len(loadfile) == 0:
+        if not loadfile:
             return
 
         # Get contents from wherever.
@@ -591,6 +607,10 @@ class Config:
             A dict containing the parsed program configuration.  Note that this can
                 be safely ignored since it is also saved in `config.config` and may
                 be used directly using that identifier.
+
+        Raises:
+            Exception: if unrecognized config argument(s) are detected and the
+                --config_rejects_unrecognized_arguments argument is enabled.
         """
         if self.config_parse_called:
             return self.config
@@ -600,7 +620,7 @@ class Config:
         # when the user passes -h or --help, it will be visible on the
         # screen w/o scrolling.  This just makes for a nicer --help screen.
         for arg in sys.argv:
-            if arg in ("--help", "-h"):
+            if arg in {"--help", "-h"}:
                 if entry_module is not None:
                     entry_module = os.path.basename(entry_module)
                 ARGS._action_groups = Config._reorder_arg_action_groups_before_help(
@@ -622,7 +642,7 @@ class Config:
         # didn't recognize it, maybe someone else will.  Or, if
         # --config_rejects_unrecognized_arguments was passed, die
         # if we have unknown arguments.
-        if len(unknown) > 0:
+        if unknown:
             if config["config_rejects_unrecognized_arguments"]:
                 raise Exception(
                     f"Encountered unrecognized config argument(s) {unknown} with --config_rejects_unrecognized_arguments enabled; halting."
@@ -635,7 +655,7 @@ class Config:
 
         # Check for savefile and populate it if requested.
         savefile = config["config_savefile"]
-        if savefile and len(savefile) > 0:
+        if savefile:
             data = "\n".join(ORIG_ARGV[1:])
             if savefile[:3] == "zk:":
                 self._write_config_to_zookeeper(savefile[3:], data)
@@ -664,7 +684,7 @@ class Config:
     def late_logging(self):
         """Log messages saved earlier now that logging has been initialized."""
         logger = logging.getLogger(__name__)
-        logger.debug("Original commandline was: %s", ORIG_ARGV)
+        logger.debug("Invocation commandline: %s", ORIG_ARGV)
         for _ in self.saved_messages:
             logger.debug(_)
 
@@ -733,7 +753,7 @@ def dump_config() -> None:
 
 def argv_after_parse() -> Optional[List[str]]:
     """Return the argv with all known arguments removed."""
-    if CONFIG.has_been_parsed:
+    if CONFIG.has_been_parsed():
         return CONFIG.parsed_argv
     return None
 
@@ -763,9 +783,21 @@ def print_usage() -> None:
     Config.print_usage()
 
 
+def print_short_usage() -> None:
+    Config.print_short_usage()
+
+
 def usage() -> str:
     """
     Returns:
         program usage help text as a string.
     """
     return Config.usage()
+
+
+def short_usage() -> str:
+    """
+    Returns:
+        program short usage help text as a string.
+    """
+    return Config.short_usage()