-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile.py
201 lines (163 loc) · 4.75 KB
/
compile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Un programma di utility che compila in Cython i moduli richiesti.
python compile.py [COMMAND] [ARGUMENTS]
python compile.py help
python compile.py commands
"""
import os
from pathlib import Path
import sys
from typing import NoReturn
import subprocess
import shutil
CYTHON_VERSION = "3.0.0a10"
def _cython_dep_error() -> NoReturn:
print(f"""\
ERROR: No compatible Cython version found.
Please install this Cython version:
pip install Cython={CYTHON_VERSION}
""", file=sys.stderr)
sys.exit(1)
try:
import cython
from Cython.Build.Cythonize import main as cythonize
except ModuleNotFoundError:
_cython_dep_error()
else:
if cython.__version__ != CYTHON_VERSION:
_cython_dep_error()
SRC = Path(__file__).parent / "src"
TARGETS = [f.stem for f in SRC.glob("*.py")]
PYTHON_FRAMES: bool = True
def list_targets() -> None:
"""Ottieni una lista di tutti i moduli disponibili.
python compile.py list
"""
print("all", *TARGETS, sep=", ")
def build(*targets: str) -> int:
"""Compila con Cython i moduli specificati.
python compile.py build *[TARGETS]
python compile.py build log root stagisti
"""
if "all" in targets:
return build(*TARGETS)
for target in targets:
if target not in TARGETS:
continue
sources = [str(f.resolve()) for f in [SRC / f"{target}.py", SRC / f"{target}.pxd"] if f.exists()]
print(f"--> Building {target} ({', '.join(sources)})")
try:
args = [
"-3i", "--annotate-fullc",
"-j", str(os.cpu_count()),
# "-X", f"linetrace={PYTHON_FRAMES}",
# "-X", f"profile={PYTHON_FRAMES}",
"--lenient",
*sources,
]
print(f"$ cythonize {' '.join(args)}")
cythonize(args)
except SystemExit as e:
return e.code
return 0
def rm(*paths: str | Path):
"""Elimina i file e le cartelle in `paths`."""
for path in paths:
if not isinstance(path, Path):
path = Path(path)
if not path.exists():
continue
print(f"Removing {path.relative_to(SRC.parent)}")
if path.is_dir():
shutil.rmtree(path)
else:
os.unlink(path)
def clean(*targets) -> None:
"""Rimuovi gli elementi creati durante la `build`.
python compile.py clean *[TARGETS]
python compile.py clean root log
python compile.py clean all
python compile.py clean
"""
if not targets or "all" in targets:
rm(
*SRC.glob("*.c"),
*SRC.glob("*.html"),
*SRC.glob("*.so"),
*SRC.glob("*.pyd"),
SRC / "build",
)
return
for target in targets:
rm(
SRC / f"{target}.c",
SRC / f"{target}.html",
*SRC.glob(f"{target}.*.so"),
*SRC.glob(f"build/lib.*/{target}.*.so"),
)
RUN = r"""\
print(f'\n--> Importing $$')
import $$
func = getattr($$, 'main', getattr($$, 'test', None))
print(f'\n--> $$ has been imported from {$$.__file__}')
if func:
print(f'--> Running $$.{func.__name__}()')
func()
"""
def run(*argv: str) -> int:
"""Compila ed esegui il modulo dato con gli argomenti dati.
python compile.py run *[OPZIONI PYTHON] [PROGRAMMA] *[ARGOMENTI/OPZIONI PROGRAMMA]
python compile.py run -O root -vv data.root
"""
args = list(argv)
target = ""
for arg in args:
if not arg.startswith("-"):
target = arg
break
if not target:
raise ValueError("A target must be specified!")
build(target)
os.chdir(SRC)
index = args.index(target)
args[index] = RUN.replace("$$", target)
args.insert(index, "-c")
args.insert(0, sys.executable)
return subprocess.run(args, check=False).returncode
def help(cmd: str | None = None, /) -> None:
"""Get help for a given command.
python compile.py help [COMMAND]
python compile.py help commands
"""
if cmd is None:
print(__doc__)
help("help")
else:
print(COMMANDS.get(cmd, help).__doc__)
def list_commands() -> None:
"""List the available commands.
python compile.py commands
"""
print(*COMMANDS, sep=" ")
COMMANDS = dict(
run=run,
build=build,
clean=clean,
list=list_targets,
help=help,
commands=list_commands,
)
def cli(argv: list[str]) -> int | None:
"""Interfaccia da riga di comando."""
if len(argv) < 1:
return help()
first = argv.pop(0)
if first in COMMANDS:
cmd = COMMANDS[first]
else:
cmd = build
argv = [first] + argv
return cmd(*argv)
if __name__ == "__main__":
sys.exit(cli(sys.argv[1:]) or 0)