|
| 1 | +import ast |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +from PyInstaller.utils.hooks import collect_data_files |
| 5 | + |
| 6 | +from collagraph.cgx.cgx import CGXParser, get_script_ast |
| 7 | + |
| 8 | + |
| 9 | +def hook(hook_api): |
| 10 | + collagraph_uses = hook_api.analysis.graph.get_code_using("collagraph") |
| 11 | + |
| 12 | + hidden_imports = set() |
| 13 | + datas = [] |
| 14 | + for package, code in collagraph_uses.items(): |
| 15 | + filename = Path(code.co_filename) |
| 16 | + hidden_imports |= collect_hidden_imports(filename.parent) |
| 17 | + datas += collect_data_files(package, includes=["**/*.cgx"]) |
| 18 | + |
| 19 | + hook_api.add_imports(*hidden_imports) |
| 20 | + hook_api.add_datas(datas) |
| 21 | + |
| 22 | + |
| 23 | +def collect_hidden_imports(folder): |
| 24 | + folder = Path(folder) |
| 25 | + |
| 26 | + hidden_imports = set() |
| 27 | + for path in folder.glob("**/*.cgx"): |
| 28 | + template = path.read_text() |
| 29 | + # Parse the file component into a tree of Node instances |
| 30 | + parser = CGXParser() |
| 31 | + parser.feed(template) |
| 32 | + |
| 33 | + # Get the AST from the script tag |
| 34 | + script_tree = get_script_ast(parser, path) |
| 35 | + |
| 36 | + # Find a list of imported names (or aliases, if any) |
| 37 | + # Those names don't have to be wrapped by `_lookup` |
| 38 | + imported_names = ImportsCollector() |
| 39 | + imported_names.visit(script_tree) |
| 40 | + |
| 41 | + hidden_imports |= imported_names.names |
| 42 | + |
| 43 | + return hidden_imports |
| 44 | + |
| 45 | + |
| 46 | +class ImportsCollector(ast.NodeVisitor): |
| 47 | + def __init__(self): |
| 48 | + self.names = set() |
| 49 | + |
| 50 | + def visit_ImportFrom(self, node): |
| 51 | + for alias in node.names: |
| 52 | + self.names.add(".".join([node.module, alias.name])) |
| 53 | + self.names.add(node.module) |
| 54 | + |
| 55 | + def visit_Import(self, node): |
| 56 | + for alias in node.names: |
| 57 | + self.names.add(alias.name) |
0 commit comments