commit 4e14f0183908587ec8e72692c4a9ac9dac1e04a7
parent 33495ebafcbb9da483574720f00f190969a1953d
Author: gracefu <81774659+gracefuu@users.noreply.github.com>
Date: Fri, 18 Apr 2025 07:37:53 +0800
add small example for compiling c files with motivation for restarting rules
Diffstat:
1 file changed, 33 insertions(+), 1 deletion(-)
diff --git a/examples/examples.py b/examples/examples.py
@@ -1,14 +1,46 @@
import asyncio
+import hashlib
import sys
+from tempfile import TemporaryFile
sys.path += ".."
-from make import hash_cache, rule, detach, Fetch, Task, Build
+from make import hash_cache, rule, detach, Fetch, Task, Build, run_in_executor, shell
# Example rules
# Observe the general pattern that every rule is called to get a task, which can then be fetched.
# res = await fetch(rule(task_args...))
+def hash_file_sync(path: str):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in f:
+ h.update(chunk)
+ return h.digest()
+
+
+@rule
+def hash_file(fetch: Fetch, path: str):
+ return run_in_executor(hash_file_sync, path)
+
+
+@hash_cache
+@rule
+async def c_object(
+ fetch: Fetch, target: str, source: str | None = None, flags: str = ""
+):
+ if source is None:
+ if not target.endswith(".o"):
+ raise RuntimeError("Cannot infer source file")
+ source = target.removesuffix(".o") + ".c"
+ await fetch(hash_file(source))
+ with TemporaryFile() as f:
+ await shell(f"gcc {flags} -MM -MT target {source} -c -o {target} -MF {f.name}")
+ # parse f
+ # new_deps = ("source.h",)
+ # await fetch.restart_if_out_of_date(new_deps)
+
+
@hash_cache
@rule
async def _eg_six(fetch: Fetch):