73 lines
3.0 KiB
Python
73 lines
3.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate committed Go from the server's Ziran sources, or verify it."""
|
|
|
|
import argparse
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
|
|
|
|
def project_flags(repo):
|
|
if (repo / "ziran.local.toml").is_file():
|
|
return ["--project"]
|
|
return ["--project", "--locked"]
|
|
|
|
|
|
def generate_go(ziran, repo, sources, output, env, source_root=None):
|
|
"""Keep the public library surface and obtain the native entry from zi2go."""
|
|
arguments = [ziran, "build", *project_flags(repo), "--target=go", "--pkg", "main"]
|
|
if source_root is not None:
|
|
arguments.extend(["--root", str(source_root)])
|
|
subprocess.run([*arguments, "--no-main", "-o", str(output), *sources],
|
|
cwd=repo, env=env, check=True)
|
|
with tempfile.TemporaryDirectory(prefix="entry-go-", dir=repo / "build") as entry:
|
|
subprocess.run([*arguments, "--exe", "--entry", "main:Main", "-o", entry, *sources],
|
|
cwd=repo, env=env, check=True)
|
|
shutil.copyfile(Path(entry) / "ziran_entry.go", Path(output) / "ziran_entry.go")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--check", action="store_true")
|
|
parser.add_argument("--ziran", default=os.environ.get("ZIRAN", "ziran"))
|
|
args = parser.parse_args()
|
|
repo = Path(__file__).resolve().parent.parent
|
|
sources = sorted(path.name for path in repo.glob("*.zi"))
|
|
if not sources:
|
|
parser.error("no Ziran server sources found")
|
|
env = os.environ.copy()
|
|
env.pop("DISPLAY", None)
|
|
env.pop("WAYLAND_DISPLAY", None)
|
|
env["LDLIBS"] = "-loqs"
|
|
build = repo / "build"
|
|
build.mkdir(exist_ok=True)
|
|
env.setdefault("XDG_CACHE_HOME", str(build / "package-cache"))
|
|
with tempfile.TemporaryDirectory(prefix="zi-go-", dir=build) as output:
|
|
generate_go(args.ziran, repo, sources, output, env)
|
|
generated = sorted(Path(output).glob("*.go"))
|
|
subprocess.run(["gofmt", "-w", *(str(path) for path in generated)],
|
|
cwd=repo, env=env, check=True)
|
|
expected = {path.name for path in generated}
|
|
stale = [path for path in repo.glob("*.go")
|
|
if path.read_bytes().startswith(b"// Code generated by zi2go from ")
|
|
and path.name not in expected]
|
|
if stale:
|
|
parser.error("obsolete generated files: " + ", ".join(path.name for path in stale))
|
|
different = []
|
|
for path in generated:
|
|
target = repo / path.name
|
|
if target.exists() and target.read_bytes() == path.read_bytes():
|
|
continue
|
|
different.append(path.name)
|
|
if not args.check:
|
|
shutil.copyfile(path, target)
|
|
if args.check and different:
|
|
parser.error("generated Go differs; run make generate: " + ", ".join(different))
|
|
print(f"Ziran Go {'checked' if args.check else 'generated'}: {len(generated)} files")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|