|
| 1 | +import collections |
| 2 | +import pkgutil |
| 3 | +import importlib |
| 4 | +import os |
| 5 | + |
| 6 | +OPSPlugin = collections.namedtuple( |
| 7 | + "OPSPlugin", ['name', 'location', 'func', 'section', 'plugin_type'] |
| 8 | +) |
| 9 | + |
| 10 | +class CLIPluginLoader(object): |
| 11 | + """Abstract object for CLI plugins |
| 12 | +
|
| 13 | + The overall approach involves 5 steps, each of which can be overridden: |
| 14 | +
|
| 15 | + 1. Find candidate plugins (which must be Python modules) |
| 16 | + 2. Load the namespaces associated into a dict (nsdict) |
| 17 | + 3. Based on those namespaces, validate that the module *is* a plugin |
| 18 | + 4. Get the associated command name |
| 19 | + 5. Return an OPSPlugin object for each plugin |
| 20 | +
|
| 21 | + Details on steps 1, 2, and 4 differ based on whether this is a |
| 22 | + filesystem-based plugin or a namespace-based plugin. |
| 23 | + """ |
| 24 | + def __init__(self, plugin_type, search_path): |
| 25 | + self.plugin_type = plugin_type |
| 26 | + self.search_path = search_path |
| 27 | + |
| 28 | + def _find_candidates(self): |
| 29 | + raise NotImplementedError() |
| 30 | + |
| 31 | + @staticmethod |
| 32 | + def _make_nsdict(candidate): |
| 33 | + raise NotImplementedError() |
| 34 | + |
| 35 | + @staticmethod |
| 36 | + def _validate(nsdict): |
| 37 | + for attr in ['CLI', 'SECTION']: |
| 38 | + if attr not in nsdict: |
| 39 | + return False |
| 40 | + return True |
| 41 | + |
| 42 | + def _get_command_name(self, candidate): |
| 43 | + raise NotImplementedError() |
| 44 | + |
| 45 | + def _find_valid(self): |
| 46 | + candidates = self._find_candidates() |
| 47 | + namespaces = {cand: self._make_nsdict(cand) for cand in candidates} |
| 48 | + valid = {cand: ns for cand, ns in namespaces.items() |
| 49 | + if self._validate(ns)} |
| 50 | + return valid |
| 51 | + |
| 52 | + def __call__(self): |
| 53 | + valid = self._find_valid() |
| 54 | + plugins = [ |
| 55 | + OPSPlugin(name=self._get_command_name(cand), |
| 56 | + location=cand, |
| 57 | + func=ns['CLI'], |
| 58 | + section=ns['SECTION'], |
| 59 | + plugin_type=self.plugin_type) |
| 60 | + for cand, ns in valid.items() |
| 61 | + ] |
| 62 | + return plugins |
| 63 | + |
| 64 | + |
| 65 | +class FilePluginLoader(CLIPluginLoader): |
| 66 | + """File-based plugins (quick and dirty) |
| 67 | +
|
| 68 | + Parameters |
| 69 | + ---------- |
| 70 | + search_path : str |
| 71 | + path to the directory that contains plugins (OS-dependent format) |
| 72 | + """ |
| 73 | + def __init__(self, search_path): |
| 74 | + super().__init__(plugin_type="file", search_path=search_path) |
| 75 | + |
| 76 | + def _find_candidates(self): |
| 77 | + def is_plugin(filename): |
| 78 | + return ( |
| 79 | + filename.endswith(".py") and not filename.startswith("_") |
| 80 | + and not filename.startswith(".") |
| 81 | + ) |
| 82 | + |
| 83 | + if not os.path.exists(os.path.join(self.search_path)): |
| 84 | + return [] |
| 85 | + |
| 86 | + candidates = [os.path.join(self.search_path, f) |
| 87 | + for f in os.listdir(self.search_path) |
| 88 | + if is_plugin(f)] |
| 89 | + return candidates |
| 90 | + |
| 91 | + @staticmethod |
| 92 | + def _make_nsdict(candidate): |
| 93 | + ns = {} |
| 94 | + with open(candidate) as f: |
| 95 | + code = compile(f.read(), candidate, 'exec') |
| 96 | + eval(code, ns, ns) |
| 97 | + return ns |
| 98 | + |
| 99 | + def _get_command_name(self, candidate): |
| 100 | + _, command_name = os.path.split(candidate) |
| 101 | + command_name = command_name[:-3] # get rid of .py |
| 102 | + command_name = command_name.replace('_', '-') # commands use - |
| 103 | + return command_name |
| 104 | + |
| 105 | + |
| 106 | +class NamespacePluginLoader(CLIPluginLoader): |
| 107 | + """Load namespace plugins (plugins for wide distribution) |
| 108 | +
|
| 109 | + Parameters |
| 110 | + ---------- |
| 111 | + search_path : str |
| 112 | + namespace (dot-separated) where plugins can be found |
| 113 | + """ |
| 114 | + def __init__(self, search_path): |
| 115 | + super().__init__(plugin_type="namespace", search_path=search_path) |
| 116 | + |
| 117 | + def _find_candidates(self): |
| 118 | + # based on https://packaging.python.org/guides/creating-and-discovering-plugins/#using-namespace-packages |
| 119 | + def iter_namespace(ns_pkg): |
| 120 | + return pkgutil.iter_modules(ns_pkg.__path__, |
| 121 | + ns_pkg.__name__ + ".") |
| 122 | + |
| 123 | + ns = importlib.import_module(self.search_path) |
| 124 | + candidates = [ |
| 125 | + importlib.import_module(name) |
| 126 | + for _, name, _ in iter_namespace(ns) |
| 127 | + ] |
| 128 | + return candidates |
| 129 | + |
| 130 | + @staticmethod |
| 131 | + def _make_nsdict(candidate): |
| 132 | + return vars(candidate) |
| 133 | + |
| 134 | + def _get_command_name(self, candidate): |
| 135 | + # +1 for the dot |
| 136 | + command_name = candidate.__name__ |
| 137 | + command_name = command_name[len(self.search_path) + 1:] |
| 138 | + command_name = command_name.replace('_', '-') # commands use - |
| 139 | + return command_name |
| 140 | + |
0 commit comments