Skip to content

Commit

Permalink
Update tools.py
Browse files Browse the repository at this point in the history
Here’s an updated version of your tools.py script with improved readability, better error handling, and code optimizations
  • Loading branch information
yuvashrikarunakaran authored Jan 9, 2025
1 parent 41b61f9 commit 456b5ee
Showing 1 changed file with 32 additions and 16 deletions.
48 changes: 32 additions & 16 deletions tools.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
#!/usr/bin/env python3
""" The master tools.py script """
"""The master tools.py script."""
import gettext
import os
import sys

from importlib import import_module

# Importing the various tools
# Importing the argument parser for CLI
from lib.cli.args import FullHelpArgumentParser

# LOCALES
Expand All @@ -15,34 +14,51 @@

# Python version check
if sys.version_info < (3, 10):
raise ValueError("This program requires at least python 3.10")

raise ValueError("This program requires at least Python 3.10")

def bad_args(*args): # pylint:disable=unused-argument
""" Print help on bad arguments """
"""Print help when invalid arguments are provided."""
PARSER.print_help()
sys.exit(0)

sys.exit(1) # Exit with a non-zero status to indicate an error

def _get_cli_opts():
""" Optain the subparsers and cli options for available tools """
"""Obtain the subparsers and CLI options for available tools."""
base_path = os.path.realpath(os.path.dirname(sys.argv[0]))
tools_dir = os.path.join(base_path, "tools")

# Loop through each tool in the tools directory
for tool_name in sorted(os.listdir(tools_dir)):
cli_file = os.path.join(tools_dir, tool_name, "cli.py")
tool_path = os.path.join(tools_dir, tool_name)
cli_file = os.path.join(tool_path, "cli.py")

if os.path.exists(cli_file):
mod = ".".join(("tools", tool_name, "cli"))
module = import_module(mod)
cliarg_class = getattr(module, f"{tool_name.title()}Args")
help_text = getattr(module, "_HELPTEXT")
yield tool_name, help_text, cliarg_class

try:
# Dynamically import the CLI module for the tool
mod = f"tools.{tool_name}.cli"
module = import_module(mod)

# Retrieve the necessary class and help text
cliarg_class = getattr(module, f"{tool_name.title()}Args")
help_text = getattr(module, "_HELPTEXT")
yield tool_name, help_text, cliarg_class
except ImportError as e:
print(f"Error importing module {mod}: {e}")
continue
except AttributeError as e:
print(f"Error retrieving arguments for {tool_name}: {e}")
continue

if __name__ == "__main__":
PARSER = FullHelpArgumentParser()
SUBPARSER = PARSER.add_subparsers()

# Add arguments for each tool dynamically
for tool, helptext, cli_args in _get_cli_opts():
cli_args(SUBPARSER, tool, helptext)

# Set the default function for invalid arguments
PARSER.set_defaults(func=bad_args)

# Parse the arguments and execute the corresponding function
ARGUMENTS = PARSER.parse_args()
ARGUMENTS.func(ARGUMENTS)

0 comments on commit 456b5ee

Please sign in to comment.