cbuild.py 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cbuild/__init__.py ADDED
@@ -0,0 +1,397 @@
1
+ from typing import Callable
2
+ from pathlib import Path
3
+ from packaging.specifiers import SpecifierSet
4
+ from functools import wraps
5
+ from typing import Any
6
+ import asyncio
7
+ from collections.abc import Coroutine, Awaitable
8
+ import copy
9
+ from wcmatch import glob
10
+ from . import av_compilers
11
+ from rich.console import Console
12
+ from rich.progress import Progress
13
+ import argparse
14
+ import hashlib
15
+ import json
16
+ import base64
17
+ import os
18
+
19
+ repos = set()
20
+ global_cons: Console
21
+
22
+ _data_dir: Path = Path.cwd() / ".cbuild"
23
+
24
+ def cli_main() -> None:
25
+ parser = argparse.ArgumentParser("CBuild")
26
+ parser.add_argument("-B", dest="build_dir", default=str(Path.cwd().absolute()), required=False)
27
+ parser.add_argument("-T", "--target", dest="target", default=None, required=False)
28
+ args = parser.parse_args()
29
+
30
+ import importlib.util
31
+
32
+ build_dir = Path(args.build_dir)
33
+ recipe_dir = build_dir / "cbuild_blueprint.py"
34
+
35
+ global _data_dir
36
+ _data_dir = build_dir / ".cbuild"
37
+
38
+ spec = importlib.util.spec_from_file_location(recipe_dir.stem, recipe_dir)
39
+ if spec and spec.loader:
40
+ module = importlib.util.module_from_spec(spec)
41
+ else:
42
+ raise RuntimeError("Failed to load recipe file.")
43
+ spec.loader.exec_module(module)
44
+
45
+ for name, value in vars(module).items():
46
+ if isinstance(value, BuildTarget):
47
+ if args.target and value.name == args.target:
48
+ asyncio.run(value.build())
49
+ break
50
+ elif args.target is None:
51
+ asyncio.run(value.build())
52
+ break
53
+
54
+ def set_repositories(*_repos: str):
55
+ global repos
56
+ repos = set()
57
+ for repo in _repos:
58
+ repos.add(repo)
59
+
60
+ class _BuildStep:
61
+ def __init__(self, name: str, fileTargets: list[str], buildDependencies: list[str], fn: Callable[..., Coroutine]):
62
+ self.name = name
63
+ self.ft = fileTargets
64
+ self.bd = buildDependencies
65
+ self.fn = fn
66
+ self.stepsDone = 0
67
+
68
+ def __call__(self, *args: Any, **kwds: Any) -> Coroutine:
69
+ return self.fn(*args, **kwds)
70
+
71
+ def steps(self) -> int:
72
+ return sum(
73
+ map(
74
+ lambda x: len(glob.glob(
75
+ x,
76
+ flags=glob.GLOBSTAR | glob.BRACE
77
+ )),
78
+ self.ft
79
+ )
80
+ )
81
+
82
+ class BuildTarget:
83
+ def __init__(self, name: str):
84
+ self.name = name
85
+ self.requirements = []
86
+ self.build_steps: dict[str, _BuildStep] = {}
87
+ self.build_progress: dict[_BuildStep, list[asyncio.Task]]
88
+
89
+ def dependency(self, *packages: tuple[str, SpecifierSet | None] | str):
90
+ self.requirements.extend(packages)
91
+
92
+ def _auto_cache(self, bs: _BuildStep) -> _BuildStep:
93
+ @wraps(bs.fn)
94
+ async def new_fn(*args, **kwargs):
95
+ (_data_dir / ".file-dependency-caches").mkdir(parents=True, exist_ok=True)
96
+ if not (_data_dir / ".file-dependency-caches" / (bs.name + ".json")).exists():
97
+ with open(_data_dir / ".file-dependency-caches" / (bs.name + ".json"), "w") as f:
98
+ json.dump({}, f)
99
+
100
+ cache_file = open(_data_dir / ".file-dependency-caches" / (bs.name + ".json"))
101
+ if cache_file.read().strip():
102
+ cache_file.seek(0)
103
+ cache: dict = json.loads(cache_file.read())
104
+ else:
105
+ cache: dict = {}
106
+ cache_file.close()
107
+
108
+ file_paths: list[Path] = []
109
+ for arg in args:
110
+ if isinstance(arg, Path):
111
+ file_paths.append(arg)
112
+ elif isinstance(arg, list):
113
+ for item in arg:
114
+ if isinstance(item, Path):
115
+ file_paths.append(item)
116
+ for arg in kwargs.values():
117
+ if isinstance(arg, Path):
118
+ file_paths.append(arg)
119
+ elif isinstance(arg, list):
120
+ for item in arg:
121
+ if isinstance(item, Path):
122
+ file_paths.append(item)
123
+ file_hashes = {}
124
+ for file_path in file_paths:
125
+ with open(file_path, 'rb') as f:
126
+ data = f.read()
127
+ h = hashlib.sha3_512(data, usedforsecurity=True)
128
+ file_hashes[base64.urlsafe_b64encode(hashlib.sha1(str(file_path.resolve().relative_to(_data_dir.parent)).encode('utf8')).digest()).decode('ascii')] = base64.urlsafe_b64encode(h.digest()).decode('ascii')
129
+ cached_hashes = cache.get("file_hashes", {})
130
+ if file_hashes and all(
131
+ cached_hashes.get(key) == value
132
+ for key, value in file_hashes.items()
133
+ ):
134
+ return
135
+ else:
136
+ r = await bs.fn(*args, **kwargs)
137
+ with open(_data_dir / ".file-dependency-caches" / (bs.name + ".json"), "r") as f:
138
+ current_cache = json.load(f)
139
+ with open(_data_dir / ".file-dependency-caches" / (bs.name + ".json"), "w") as f:
140
+ json.dump({
141
+ "file_hashes": current_cache.get("file_hashes", {}) | file_hashes
142
+ }, f, indent=4)
143
+ return r
144
+
145
+ bs2 = copy.deepcopy(bs)
146
+ bs2.fn = new_fn
147
+ self.build_steps[bs2.name] = bs2
148
+ return bs2
149
+
150
+ def step(self, fn: Callable) -> _BuildStep:
151
+ b = _BuildStep(fn.__qualname__, [], [], fn)
152
+ @wraps(fn)
153
+ def _fn(*args, **kwargs):
154
+ a = fn(*args, **kwargs)
155
+ b.stepsDone += 1
156
+ return a
157
+
158
+ b.fn = _fn
159
+ b = self._auto_cache(b)
160
+ self.build_steps[b.name] = b
161
+ return b
162
+
163
+ def configured_step(self, autoCache: bool = True) -> Callable[[Callable], _BuildStep]:
164
+ def decorator(fn: Callable) -> _BuildStep:
165
+ b = _BuildStep(fn.__qualname__, [], [], fn)
166
+ @wraps(fn)
167
+ def _fn(*args, **kwargs):
168
+ a = fn(*args, **kwargs)
169
+ b.stepsDone += 1
170
+ return a
171
+
172
+ b.fn = _fn
173
+ if autoCache:
174
+ b = self._auto_cache(b)
175
+ self.build_steps[b.name] = b
176
+ return b
177
+ return decorator
178
+
179
+ def require(self, *steps: _BuildStep) -> Callable[[_BuildStep], _BuildStep]:
180
+ def decorator(fn: _BuildStep):
181
+ @wraps(fn.fn)
182
+ async def __inner2(*args, **kwargs):
183
+ for step in steps:
184
+ for substep in self.build_progress[step]:
185
+ await substep
186
+ await fn.fn(*args, **kwargs)
187
+ fn2 = copy.deepcopy(fn)
188
+ fn2.bd.extend(map(lambda x: x.name, steps))
189
+ fn2.fn = __inner2
190
+ self.build_steps[fn2.name] = fn2
191
+ return fn2
192
+ return decorator
193
+
194
+ def forEach(self, *globs: str) -> Callable[[_BuildStep], _BuildStep]:
195
+ def decorator(fn: _BuildStep):
196
+ nb = copy.deepcopy(fn)
197
+ @wraps(fn.fn)
198
+ async def fn2(*args, **kwargs):
199
+ for globPattern in globs:
200
+ files = glob.glob(
201
+ globPattern,
202
+ flags=glob.GLOBSTAR | glob.BRACE
203
+ )
204
+ for file in files:
205
+ path = Path(file)
206
+ async def __inner(path: Path, *args, **kwargs):
207
+ await fn(path, *args, **kwargs)
208
+ nb.stepsDone += 1
209
+
210
+ promise: asyncio.Task = asyncio.create_task(__inner(path, *args, **kwargs))
211
+ progress = (self.build_progress.get(nb) or [])
212
+ progress.append(promise)
213
+ self.build_progress[nb] = progress
214
+
215
+ nb.fn = fn2
216
+ nb.ft.extend(globs)
217
+ self.build_steps[nb.name] = nb
218
+ return nb
219
+
220
+ return decorator
221
+
222
+ def forAll(self, *globs: str) -> Callable[[_BuildStep], _BuildStep]:
223
+ def decorator(fn: _BuildStep):
224
+ nb = copy.deepcopy(fn)
225
+ @wraps(fn.fn)
226
+ async def fn2(*args, **kwargs):
227
+ all_files = []
228
+ for globPattern in globs:
229
+ files = glob.glob(
230
+ globPattern,
231
+ flags=glob.GLOBSTAR | glob.BRACE
232
+ )
233
+ all_files.extend(map(lambda x: Path(x), files))
234
+
235
+ return await fn(all_files, *args, **kwargs)
236
+
237
+ nb.fn = fn2
238
+ self.build_steps[nb.name] = nb
239
+ return nb
240
+
241
+ return decorator
242
+
243
+ async def build(self):
244
+ global global_cons
245
+ cons = Console()
246
+ import builtins
247
+ _original_print = builtins.print
248
+ builtins.print = cons.print
249
+ global_cons = cons
250
+
251
+ progress = Progress(console = cons)
252
+ progress.start()
253
+ task0 = progress.add_task(f"Building {self.name}", total = sum(map(lambda x: x.steps(), self.build_steps.values())) + len(self.build_steps))
254
+
255
+ self.build_progress = {}
256
+
257
+ for name, step in self.build_steps.items():
258
+ await step()
259
+ progress.advance(task0)
260
+
261
+ tasks = {}
262
+
263
+ for bs, steps in self.build_progress.items():
264
+ task = progress.add_task(bs.name, total = len(steps))
265
+ tasks[bs] = task
266
+
267
+ await_all = []
268
+ for bs, steps in self.build_progress.items():
269
+ for coroutine in steps:
270
+ async def __inner(bs):
271
+ await coroutine
272
+ progress.advance(tasks[bs])
273
+ progress.advance(task0)
274
+ await_all.append(__inner(bs))
275
+
276
+ results = await asyncio.gather(*await_all)
277
+ builtins.print = _original_print
278
+ progress.stop()
279
+
280
+ async def compile_c(file: Path, static: bool = False, shared_library: bool = False, position_independent: bool = True):
281
+ global global_cons
282
+ (Path.cwd() / "build").mkdir(0o755, True, True)
283
+
284
+ gnuflags = (
285
+ ["-fPIC"] if shared_library else
286
+ ["-fPIE"] if position_independent else
287
+ ["-fno-pie", "-fno-pic"]
288
+ )
289
+
290
+ if av_compilers.has_clang():
291
+ p = await asyncio.create_subprocess_exec(
292
+ "clang", "-c", file.absolute(), *gnuflags, "-o", Path.cwd() / "build" / (file.name.removesuffix(".c") + ".o")
293
+ )
294
+ elif av_compilers.has_gcc():
295
+ p = await asyncio.create_subprocess_exec(
296
+ "gcc", "-c", file.absolute(), *gnuflags, "-o", Path.cwd() / "build" / (file.name.removesuffix(".c") + ".o")
297
+ )
298
+ elif av_compilers.has_msvc():
299
+ p = await asyncio.create_subprocess_exec(
300
+ "cl", "/c", "/TC", "/MT" if static else "/MD", file.absolute(), "/Fo" + str((Path.cwd() / "build" / (file.name.removesuffix(".c") + ".o")).relative_to(Path.cwd()))
301
+ )
302
+ else:
303
+ raise RuntimeError()
304
+
305
+ if await p.wait() != 0:
306
+ raise RuntimeError(f"Compilation failed: {file}")
307
+ global_cons.print(f"CC\t{file.absolute().relative_to(Path.cwd()).name}")
308
+
309
+ async def compile_cpp(file: Path, static: bool = False, shared_library: bool = False, position_independent: bool = True):
310
+ global global_cons
311
+ (Path.cwd() / "build").mkdir(0o755, True, True)
312
+
313
+ gnuflags = (
314
+ ["-fPIC"] if shared_library else
315
+ ["-fPIE"] if position_independent else
316
+ ["-fno-pie", "-fno-pic"]
317
+ )
318
+
319
+ if av_compilers.has_clang():
320
+ p = await asyncio.create_subprocess_exec(
321
+ "clang++", "-c", file.absolute(), *gnuflags, "-o", Path.cwd() / "build" / (file.name.removesuffix(".cpp").removesuffix(".cxx") + ".o")
322
+ )
323
+ elif av_compilers.has_gcc():
324
+ p = await asyncio.create_subprocess_exec(
325
+ "g++", "-c", file.absolute(), *gnuflags, "-o", Path.cwd() / "build" / (file.name.removesuffix(".cpp").removesuffix(".cxx") + ".o")
326
+ )
327
+ elif av_compilers.has_msvc():
328
+ p = await asyncio.create_subprocess_exec(
329
+ "cl", "/c", "/TP", "/MT" if static else "/MD", file.absolute(), "/Fo" + str((Path.cwd() / "build" / (file.name.removesuffix(".cpp").removesuffix(".cxx") + ".o")).relative_to(Path.cwd()))
330
+ )
331
+ else:
332
+ raise RuntimeError()
333
+
334
+ if await p.wait() != 0:
335
+ raise RuntimeError(f"Compilation failed: {file}")
336
+ global_cons.print(f"CXX\t{file.absolute().relative_to(Path.cwd()).name}")
337
+
338
+ async def compile_auto(file: Path, static: bool = False, shared_library: bool = False, position_independent: bool = True):
339
+ name = file.name.lower()
340
+ if name.endswith(".cpp") or name.endswith("cxx"):
341
+ await compile_cpp(file, static, shared_library, position_independent)
342
+ elif name.endswith(".c"):
343
+ await compile_c(file, static, shared_library, position_independent)
344
+ else:
345
+ raise RuntimeError()
346
+
347
+ async def link(files: list[Path], output: Path, *_, static: bool = False, shared_library: bool = False, position_independent: bool = True):
348
+ objects = [str((Path.cwd() / file).absolute()) for file in files]
349
+ destination = Path.cwd() / "build" / output
350
+
351
+ destination.parent.mkdir(0o755, parents=True, exist_ok=True)
352
+
353
+ if not objects:
354
+ raise ValueError("No object files provided")
355
+
356
+ if shared_library and static:
357
+ raise RuntimeError("Tried to build static shared library.")
358
+
359
+ if shared_library and not position_independent:
360
+ raise RuntimeError("Tried to build non-PIC shared library.")
361
+
362
+ if av_compilers.has_clang_cpp():
363
+ process = await asyncio.create_subprocess_exec(
364
+ "clang++",
365
+ *objects,
366
+ *(['-fpic', '-shared'] if shared_library else ['-static-pie'] if static and position_independent else ['-pie'] if position_independent else ['-no-pie', '-static'] if static else ['-no-pie', ]),
367
+ "-o",
368
+ str(destination)
369
+ )
370
+
371
+ elif av_compilers.has_gpp():
372
+ process = await asyncio.create_subprocess_exec(
373
+ "g++",
374
+ *objects,
375
+ *(['-fpic', '-shared'] if shared_library else ['-static-pie'] if static and position_independent else ['-pie'] if position_independent else ['-no-pie', '-static'] if static else ['-no-pie', ]),
376
+ "-o",
377
+ str(destination)
378
+ )
379
+
380
+ elif av_compilers.has_msvc():
381
+ process = await asyncio.create_subprocess_exec(
382
+ "cl.exe",
383
+ "/nologo",
384
+ *objects,
385
+ *(["/LD"] if shared_library else []),
386
+ f"/Fe{destination}",
387
+ "/link",
388
+ "/DYNAMICBASE" if position_independent else "/DYNAMICBASE:NO"
389
+ )
390
+
391
+ else:
392
+ raise RuntimeError("No compatible compiler found")
393
+
394
+ if await process.wait() != 0:
395
+ raise RuntimeError(f"Linking failed: {destination}")
396
+
397
+ global_cons.print(f"LD\t{destination.absolute().relative_to(Path.cwd()).name}")
cbuild/av_compilers.py ADDED
@@ -0,0 +1,30 @@
1
+ import subprocess
2
+
3
+ def check_compiler(*args: str) -> bool:
4
+ try:
5
+ subprocess.run(
6
+ args,
7
+ stdout=subprocess.DEVNULL,
8
+ stderr=subprocess.DEVNULL,
9
+ timeout=5,
10
+ check=False
11
+ )
12
+ return True
13
+ except (OSError, subprocess.TimeoutExpired):
14
+ return False
15
+
16
+
17
+ def has_clang() -> bool:
18
+ return check_compiler("clang", "--version")
19
+
20
+ def has_clang_cpp() -> bool:
21
+ return check_compiler("clang++", "--version")
22
+
23
+ def has_gcc() -> bool:
24
+ return check_compiler("gcc", "--version")
25
+
26
+ def has_gpp() -> bool:
27
+ return check_compiler("g++", "--version")
28
+
29
+ def has_msvc() -> bool:
30
+ return check_compiler("cl.exe", "/?")
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.3
2
+ Name: cbuild.py
3
+ Version: 0.1.0
4
+ Summary: CBuild - a Python-based C/C++ build system
5
+ Author: Bogdan
6
+ Author-email: Bogdan <github.34373732@gmail.com>
7
+ Requires-Dist: packaging>=26.4
8
+ Requires-Dist: resolvelib>=1.2.1
9
+ Requires-Dist: rich>=15.0.0
10
+ Requires-Dist: wcmatch>=13.0
11
+ Requires-Python: >=3.12
12
+ Description-Content-Type: text/markdown
13
+
@@ -0,0 +1,6 @@
1
+ cbuild/__init__.py,sha256=9qunVrJue6om45blW_5v7Kh9NO2UwSyeEYOODFljkV0,14840
2
+ cbuild/av_compilers.py,sha256=GVSOU-RbKu2UDq1xrD6KaWavhveqjnHvBBqsLf4QVCs,697
3
+ cbuild_py-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
4
+ cbuild_py-0.1.0.dist-info/entry_points.txt,sha256=6IOZ1fQPSZKPJ8IaT3ObLvB7jCcN8NKs_cwdQVqDKJM,44
5
+ cbuild_py-0.1.0.dist-info/METADATA,sha256=ePAJYUGX0wfbMsenUz9JKk5C3Oq41sOkYFSJDwIhkiw,355
6
+ cbuild_py-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ cbuild = cbuild:cli_main
3
+