Last active
July 29, 2021 03:18
-
-
Save mikepietruszka/c91596f3dfddf54acc285356561761ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import importlib | |
import importlib.util | |
import sys | |
from pathlib import Path | |
# Get our command | |
command = sys.argv[1] | |
# Define some lists | |
plugins = [] | |
all_methods = [] | |
callable_methods = {} | |
found_plugins_obj = [] | |
# Get the path with the plugins (this gets us a generator so we should deposit | |
# its elements in a list) | |
pathlist = Path('plugins/').glob('**/[!_]*.py') | |
plugin_paths = [] | |
# This for loop iterates over every plugin found in plugins/ | |
for path in pathlist: | |
plugin_paths.append(path) | |
path_split = str(path).split('/') | |
plugin_name = path_split[1] | |
spec = importlib.util.spec_from_file_location(plugin_name, path) | |
foo = importlib.util.module_from_spec(spec) | |
spec.loader.exec_module(foo) | |
# Get available method names in all of our plugins | |
found_methods = {foo.Plugin.__module__:[m for m in dir(foo.Plugin) if not m.startswith('__')]} | |
# Append found_methods to callable_methods dictionary | |
callable_methods = {**callable_methods, **found_methods} | |
# Store our plugin object in a list so we can use them later | |
found_plugins_obj.append(foo) | |
print(f"INFO: Found plugins in these paths: {plugin_paths}") | |
print(f"INFO: Printing callable methods: {callable_methods}") | |
# List plugins and their methods separately so we can search them | |
plugins = list(callable_methods.keys()) | |
all_methods = list(callable_methods.values()) | |
# Turn all methods lists into a flat list; essentially: | |
# [['a', 'b', 'c']] -> ['a', 'b', 'c'] | |
all_methods = [item for sublist in all_methods for item in sublist] | |
print(f"INFO: Printing all methods: {all_methods}") | |
# Print our callable methods | |
print(f"Command: {command}") | |
plugin = None | |
for plugin in callable_methods.keys(): | |
if command in callable_methods[plugin]: | |
print(plugin) | |
# How do we make below call parameterized? | |
# below function call works | |
# module = importlib.import_module("plugins.plugin_name.plugin", ".") | |
# Let's iterate over our list of plugin objects | |
for module in found_plugins_obj: | |
if module.Plugin.__module__ == plugin: | |
# Instantiate the module | |
m = module.Plugin() | |
# Print all available methods (while skipping __ methods) | |
methods = [m for m in dir(m) if not m.startswith('__')] | |
print(methods) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment