Last active
January 23, 2019 00:53
-
-
Save ibejohn818/2828ed0736fbb94b12ece06d752d6f08 to your computer and use it in GitHub Desktop.
quick way to load all stack weights
This file contains hidden or 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
| import sys | |
| import os | |
| import inspect | |
| import re | |
| import importlib | |
| from functools import cmp_to_key | |
| import pkgutil | |
| from nimbi.aws import CloudFormationStack | |
| import nimbi | |
| from pprint import pprint | |
| def list_modules(package_path): | |
| """Get list of modules from path | |
| """ | |
| mods = [] | |
| package_name = package_path.replace("/", ".") | |
| for py in os.listdir(package_path): | |
| if re.match('.*\.py$', py): | |
| mod_name = os.path.splitext(py)[0] | |
| mod_separator = "." | |
| if mod_name == '__init__': | |
| mod_name = '' | |
| mod_separator = '' | |
| mods.append("{}{}{}".format(package_name, mod_separator, mod_name)) | |
| return mods | |
| def get_classes(module): | |
| """ | |
| """ | |
| c = [] | |
| mod = importlib.import_module(module) | |
| for k, v in inspect.getmembers(mod, inspect.isclass): | |
| c.append(v) | |
| return mod, c | |
| def load_all_classes(package_path): | |
| """Get all classes from path. | |
| Returns list with classes and | |
| module link. | |
| [{ | |
| 'module': <python module>, | |
| 'classes': [<python class]> | |
| }] | |
| """ | |
| mods = list_modules(package_path) | |
| classes = [] | |
| for m in mods: | |
| mod, c = get_classes(m) | |
| d = { | |
| 'module': mod, | |
| 'classes': c} | |
| classes.append(d) | |
| return classes | |
| def load_all_stacks(package_path): | |
| classes = load_all_classes(package_path) | |
| stacks = [] | |
| for mods in classes: | |
| for cl in mods['classes']: | |
| if cl.__base__ == nimbi.aws.CloudFormationStack: | |
| stacks.append(cl) | |
| return stacks | |
| def sorter(a, b): | |
| if a['weight'] > b['weight']: | |
| return 0 | |
| else: | |
| return -1 | |
| if __name__ == '__main__': | |
| stacks = load_all_stacks('nimbi/aws') | |
| res = [] | |
| for s in stacks: | |
| if s.__name__ in ('CFTemplateStack', 'LegacyCFStack'): | |
| continue | |
| spec = inspect.getfullargspec(s) | |
| args = spec.args | |
| args.pop() | |
| try: | |
| inst = s(*args) | |
| res.append({'name':type(inst).__name__, 'weight': int(inst.weight)}) | |
| except Exception as e: | |
| print(str(e)) | |
| print("COULD NOT LOAD", s.__name__) | |
| print("ARG SPEC: ", spec) | |
| res = sorted(res, key=cmp_to_key(sorter)) | |
| pprint(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment