Skip to content

Commit c23e173

Browse files
Find cgx files and imports from cgx files from project that includes collagraph (#96)
1 parent 0dbf413 commit c23e173

3 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from os.path import dirname
2+
3+
4+
HERE = dirname(__file__)
5+
6+
7+
def get_hook_dirs():
8+
return [HERE]
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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)

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ optional = true
3939
pytest-qt = "*"
4040
pytest-xvfb = "*"
4141

42+
[tool.poetry.plugins.pyinstaller40]
43+
hook-dirs = "collagraph.__pyinstaller:get_hook_dirs"
44+
4245
[build-system]
4346
requires = ["poetry>=1.0.0"]
4447
build-backend = "poetry.masonry.api"

0 commit comments

Comments
 (0)