Skip to content

Commit

Permalink
cli: auto-load all subcommand libraries
Browse files Browse the repository at this point in the history
Prior to this change, every time we added a new sub-command, we had to
list the sub-command twice in main.py.

Use pkgutil.iter_modules and importlib.import_module to import all the
sub-command modules dynamically. This reduces the copy-and-paste
boilerplate and makes it easier to scale this tool to more sub-commands.
  • Loading branch information
ktdreyer committed Mar 6, 2020
1 parent 5cf0c1d commit 72dcb56
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions errata_tool/cli/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import argparse
import errata_tool.cli.advisory
import errata_tool.cli.build
import errata_tool.cli.product
import errata_tool.cli.release
import os
import pkgutil
from importlib import import_module


def import_commands():
modules = []
directory = os.path.dirname(__file__)
for (_, name, _) in pkgutil.iter_modules([directory]):
if name == 'main':
continue
imported_module = import_module('errata_tool.cli.' + name)
modules.append(imported_module)
return modules


def main():
Expand All @@ -17,10 +27,9 @@ def main():
subparsers.required = True

# add arguments for each subcommand:
errata_tool.cli.advisory.add_parser(subparsers)
errata_tool.cli.build.add_parser(subparsers)
errata_tool.cli.product.add_parser(subparsers)
errata_tool.cli.release.add_parser(subparsers)
commands = import_commands()
for command in commands:
command.add_parser(subparsers)

args = parser.parse_args()

Expand Down

0 comments on commit 72dcb56

Please sign in to comment.