|
1 | 1 | #!/usr/bin/python |
2 | 2 | import os |
3 | 3 | import sys |
4 | | -import inspect |
5 | | -import importlib |
| 4 | +import ast |
| 5 | + |
| 6 | + |
| 7 | +VALID_NODE_TYPE = ['BaseNode', 'AutoNode'] |
| 8 | + |
| 9 | + |
| 10 | +def detectNodesFromText(filepath): |
| 11 | + """returns Node names from a python script""" |
| 12 | + froms = [] |
| 13 | + |
| 14 | + with open(filepath, "r") as source: |
| 15 | + tree = ast.parse(source.read()) |
| 16 | + |
| 17 | + for node in tree.body: |
| 18 | + if isinstance(node, ast.ClassDef): |
| 19 | + for base in node.bases: |
| 20 | + if base.id in VALID_NODE_TYPE: |
| 21 | + for indef in node.body: |
| 22 | + if isinstance(indef, ast.Assign): |
| 23 | + for target in indef.targets: |
| 24 | + if target.id == '__identifier__': |
| 25 | + froms.append(node.name) |
| 26 | + return froms |
6 | 27 |
|
7 | 28 |
|
8 | 29 | def getNodesRecursively(path=__file__): |
| 30 | + """ Returns imported nodes. """ |
9 | 31 | Nodes = [] |
10 | 32 | basedir, filename = os.path.split(path) |
| 33 | + rootModule = os.path.basename(basedir) |
| 34 | + |
11 | 35 | for root, dirs, files in os.walk(basedir, topdown=False): |
12 | 36 | if root not in sys.path: |
13 | 37 | sys.path.append(root) |
14 | 38 |
|
15 | 39 | for name in files: |
16 | 40 | if name.endswith('.py') and not name.startswith('_'): |
17 | | - module_name = name[:-3] |
18 | | - module = importlib.import_module(module_name) |
19 | | - for name, obj in inspect.getmembers(module): |
20 | | - if inspect.isclass(obj) and not obj.__name__ == 'BaseNode': |
21 | | - for clsObj in inspect.getmro(obj): |
22 | | - if clsObj.__name__ == 'BaseNode': |
23 | | - Nodes.append(obj) |
24 | | - break |
| 41 | + module_name = root.split(rootModule)[1].replace('\\', '.') + name[:-3] |
| 42 | + modulePath = os.path.join(root, name) |
| 43 | + froms = detectNodesFromText(modulePath) |
| 44 | + if not froms: |
| 45 | + continue |
| 46 | + |
| 47 | + try: |
| 48 | + mod = __import__(module_name, globals(), locals(), froms, 0) |
| 49 | + for node in froms: |
| 50 | + Nodes.append(getattr(mod, node)) |
| 51 | + |
| 52 | + except ImportError as e: |
| 53 | + print ('Error in importing class: %s' % (e)) |
| 54 | + continue |
| 55 | + |
25 | 56 | return Nodes |
26 | 57 |
|
27 | 58 |
|
|
0 commit comments