#!/usr/bin/env python3 """Check, test, or re-lock the workspace packages under packages/ and extensions/. See robot-docs/workspace-packages.md#checks. Each package builds on its own manifest in its own build/ directory, as its Nix derivation does. check the static checks below, a format check, and a build of each package that fails on any warning (test/quick.sh) test each package's own tests, for packages that have a test/ directory (test.sh) sync re-lock packages whose manifests the checks refuse, with the root manifest as the starting lock, through `gleam deps download` Static checks, run before any build: - A package's manifest locks what its gleam.toml asks for, and every Hex package the package or its path dependencies constrain satisfies each constraint. The closure of a path dependency comes from its gleam.toml: Gleam does not rewrite a path dependency's `requirements` in a manifest when that dependency's gleam.toml changes, so those lists can be stale (the root manifest's are) and are never read. - Every Hex package in a package's production closure is locked by the root manifest at the same version and checksum, so a package is checked against exactly what albedo ships. A dev-only one must match the root's when the root locks it. A path dependency the root also locks resolves to the same place. - Dependency direction: a package never depends on albedo, nor on an extension package (`albedo_ext_*`), and a path dependency is a workspace package or a patched copy under vendor/. Each extension package is a path dependency of albedo and imported by the extension registry. Builds run in dependency order, several at once. A dependency's compiled artefacts are reused from a cache under build/package-artefacts/ only under a key over its source checksum, the keys of its own dependency closure, the toolchain (store paths and versions of gleam, erl, rebar3 and cc), the build mode, and the platform. The package under check is never seeded: its own artefacts come from its own build directory, and are deleted whenever any dependency it compiled against changed. A workspace package's cached artefact is compiled from its src/ alone with `gleam compile-package --no-dev`, so no dependency's tests are ever copied. Others (Hex, vendor/) are exported from the first build that compiled them as dependencies. """ from __future__ import annotations import argparse from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait from dataclasses import dataclass, field import fcntl import hashlib import json import os from pathlib import Path import platform import re import shutil import subprocess import sys import tempfile import time import tomllib ROOT = Path(__file__).resolve().parents[1] WORKSPACES = (ROOT / "packages", ROOT / "extensions") APP = ROOT / "apps" / "albedo" VENDOR = ROOT / "vendor" CACHE = ROOT / "build" / "package-artefacts" REGISTRY = APP / "src" / "albedo" / "composition" / "extensions.gleam" EXTENSION_PREFIX = "albedo_ext_" # Dependency artefacts are only ever reused by `gleam build` and `gleam test`, # which compile dependencies for the dev mode of the Erlang target. MODE = "erlang-dev" SEEDS = ".albedo-seeds.json" STALE_AFTER_SECONDS = 14 * 24 * 3600 class CheckFailed(Exception): pass # --- Hex version requirements ------------------------------------------------ # (major, minor, patch, 1 for a release or 0 for a pre-release, identifiers). # A release sorts after its pre-releases, numeric identifiers before others. Version = tuple[int, int, int, int, tuple[tuple[int, int, str], ...]] VERSION = re.compile(r"^(\d+)\.(\d+)(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$") def parse_version(text: str) -> tuple[Version, bool]: """Parses `1.2.3-rc.1`; the flag tells whether the patch was written.""" match = VERSION.match(text.strip()) if not match: raise ValueError(f"not a version: {text!r}") major, minor, patch, pre = match.groups() identifiers = tuple( (0, int(p), "") if p.isdigit() else (1, 0, p) for p in (pre or "").split(".") ) version: Version = ( int(major), int(minor), int(patch or 0), 0 if pre else 1, identifiers if pre else (), ) return version, patch is not None def satisfies(version: str, requirement: str) -> bool: """Whether a version meets a Hex requirement such as `>= 1.0.0 and < 2.0.0`.""" have, _ = parse_version(version) for alternative in re.split(r"\s+(?:or|\|\|)\s+", requirement.strip()): if all( _meets(have, clause) for clause in re.split(r"\s+and\s+", alternative.strip()) ): return True return False def _meets(have: Version, clause: str) -> bool: match = re.match(r"^(==|!=|>=|<=|~>|>|<)?\s*(\S+)$", clause.strip()) if not match: raise ValueError(f"not a requirement: {clause!r}") operator, text = match.groups() want, has_patch = parse_version(text) if operator in (None, "=="): return have == want if operator == "!=": return have != want if operator == ">=": return have >= want if operator == ">": return have > want if operator == "<=": return have <= want if operator == "<": return have < want # ~> 1.2 means >= 1.2.0 and < 2.0.0; ~> 1.2.3 means >= 1.2.3 and < 1.3.0. # The lowest version there is below the next minor or major release. upper: Version = ( (want[0], want[1] + 1, 0, 0, ()) if has_patch else (want[0] + 1, 0, 0, 0, ()) ) return want <= have < upper # --- The workspace ----------------------------------------------------------- @dataclass(frozen=True) class Requirement: """One entry of a gleam.toml dependency table, resolved.""" name: str version: str | None = None path: Path | None = None @dataclass class Project: """A gleam.toml and, when it has one, its manifest.""" dir: Path config: dict manifest: dict | None @property def name(self) -> str: return self.config["name"] def requirements(self, table: str) -> list[Requirement]: found = [] for name, spec in self.config.get(table, {}).items(): if isinstance(spec, str): found.append(Requirement(name, version=spec)) elif "path" in spec: found.append( Requirement(name, path=(self.dir / spec["path"]).resolve()) ) elif "version" in spec: found.append(Requirement(name, version=spec["version"])) else: raise CheckFailed( f"{rel(self.dir)}/gleam.toml: {name} is neither a Hex nor a path dependency" ) return found def locked(self) -> dict[str, dict]: assert self.manifest is not None return {entry["name"]: entry for entry in self.manifest.get("packages", [])} def rel(path: Path) -> str: try: return str(path.relative_to(ROOT)) except ValueError: return str(path) def load_project(directory: Path) -> Project: config = tomllib.loads((directory / "gleam.toml").read_text()) manifest_file = directory / "manifest.toml" manifest = ( tomllib.loads(manifest_file.read_text()) if manifest_file.exists() else None ) return Project(directory.resolve(), config, manifest) @dataclass class Workspace: root: Project packages: dict[str, Project] path_projects: dict[Path, Project] = field(default_factory=dict) @classmethod def load(cls) -> Workspace: packages = {} for config in sorted( config for directory in WORKSPACES for config in directory.glob("*/gleam.toml") ): project = load_project(config.parent) packages[project.name] = project return cls(load_project(APP), packages) def project_at(self, directory: Path) -> Project: if directory not in self.path_projects: self.path_projects[directory] = load_project(directory) return self.path_projects[directory] # --- Static checks ----------------------------------------------------------- @dataclass class Closure: """What one package's manifest must lock, read from the sources of truth.""" production: set[str] = field(default_factory=set) everything: set[str] = field(default_factory=set) # Hex requirements by package, with the gleam.toml that declares each. constraints: dict[str, list[tuple[str, str]]] = field(default_factory=dict) # The directory each path dependency resolves to. paths: dict[str, Path] = field(default_factory=dict) # Each locked package's own requirements: a path dependency's from its # gleam.toml, a Hex package's from the manifest. edges: dict[str, list[str]] = field(default_factory=dict) def closure_of(workspace: Workspace, package: Project, errors: list[str]) -> Closure: locked = package.locked() closure = Closure() where = f"{rel(package.dir)}/manifest.toml" def visit(requirement: Requirement, declarer: str, production: bool) -> None: name = requirement.name if requirement.path is not None: known = closure.paths.setdefault(name, requirement.path) if known != requirement.path: errors.append( f"{where}: {name} is a path dependency at both {rel(known)} and {rel(requirement.path)}" ) return elif requirement.version is not None: closure.constraints.setdefault(name, []).append( (declarer, requirement.version) ) seen = name in (closure.production if production else closure.everything) closure.everything.add(name) if production: closure.production.add(name) if seen: return entry = locked.get(name) if entry is None: errors.append(f"{where}: does not lock {name}, which {declarer} needs") return if requirement.path is not None: if entry.get("source") != "local": errors.append( f"{where}: locks {name} from {entry.get('source')}, but it is a path dependency" ) return locked_path = entry.get("path") if ( locked_path is None or (package.dir / locked_path).resolve() != requirement.path ): # Gleam builds from the locked path, and keys and the # closure follow the declared one, so they must agree. errors.append( f"{where}: locks {name} at {locked_path}, but {declarer} declares {rel(requirement.path)}" ) return dependency = workspace.project_at(requirement.path) children = dependency.requirements("dependencies") closure.edges[name] = [child.name for child in children] for child in children: visit(child, f"{rel(dependency.dir)}/gleam.toml", production) else: if entry.get("source") != "hex": errors.append( f"{where}: locks {name} from {entry.get('source')}, but it is a Hex dependency" ) return closure.edges[name] = list(entry.get("requirements", [])) for child in entry.get("requirements", []): visit(Requirement(child), f"{name} {entry['version']}", production) declarer = f"{rel(package.dir)}/gleam.toml" for requirement in package.requirements("dependencies"): visit(requirement, declarer, True) for requirement in package.requirements("dev-dependencies") + package.requirements( "dev_dependencies" ): visit(requirement, declarer, False) return closure def normalized_requirements(project: Project, table: dict) -> dict[str, tuple]: found = {} for name, spec in table.items(): if isinstance(spec, str): spec = {"version": spec} if "path" in spec: found[name] = ("path", (project.dir / spec["path"]).resolve()) else: found[name] = tuple( sorted((k, " ".join(str(v).split())) for k, v in spec.items()) ) return found def check_package( workspace: Workspace, package: Project, errors: list[str] ) -> Closure | None: where = rel(package.dir) hint = f"run `test/packages.sh sync {package.name}`" before = len(errors) if package.dir.name != package.name and not ( package.dir.parent == ROOT / "extensions" and package.name == EXTENSION_PREFIX + package.dir.name ): errors.append(f"{where}/gleam.toml: names the package {package.name}") if package.manifest is None: errors.append(f"{where}: has no manifest.toml; {hint}") return None declared = { **package.config.get("dependencies", {}), **package.config.get("dev-dependencies", {}), **package.config.get("dev_dependencies", {}), } if normalized_requirements(package, declared) != normalized_requirements( package, package.manifest.get("requirements", {}) ): errors.append( f"{where}/manifest.toml: its requirements differ from gleam.toml; {hint}" ) closure = closure_of(workspace, package, errors) locked = package.locked() root = workspace.root.locked() for name in sorted(set(locked) - closure.everything): errors.append( f"{where}/manifest.toml: locks {name}, which nothing requires; {hint}" ) for name, constraints in sorted(closure.constraints.items()): entry = locked.get(name) if entry is None or entry.get("source") != "hex": continue for declarer, requirement in constraints: if not satisfies(entry["version"], requirement): errors.append( f"{where}/manifest.toml: locks {name} {entry['version']}, but {declarer} requires {requirement}; {hint}" ) for name in sorted(closure.everything): entry = locked.get(name) if entry is None: continue theirs = root.get(name) if entry.get("source") == "local": if theirs is not None and theirs.get("source") == "local": if (workspace.root.dir / theirs["path"]).resolve() != closure.paths.get( name ): errors.append( f"{where}: takes {name} from {rel(closure.paths[name])}, albedo from {theirs['path']}" ) continue if theirs is None: if name in closure.production: errors.append( f"{where}/manifest.toml: locks {name} {entry['version']}, which albedo does not ship; {hint}" ) continue if (theirs["version"], theirs.get("outer_checksum")) != ( entry["version"], entry.get("outer_checksum"), ): errors.append( f"{where}/manifest.toml: locks {name} {entry['version']}, albedo locks {theirs['version']}; {hint}" ) return closure if len(errors) == before else None def check_direction(workspace: Workspace, errors: list[str]) -> None: workspace_dirs = {p.dir: p for p in workspace.packages.values()} for package in workspace.packages.values(): where = f"{rel(package.dir)}/gleam.toml" for table in ("dependencies", "dev-dependencies", "dev_dependencies"): for requirement in package.requirements(table): name = requirement.name if ( name == workspace.root.name or requirement.path == workspace.root.dir ): errors.append(f"{where}: depends on albedo, which no package may") continue if name.startswith(EXTENSION_PREFIX): errors.append( f"{where}: depends on the extension package {name}; only albedo may" ) continue if requirement.path is None: continue if ( requirement.path not in workspace_dirs and not requirement.path.is_relative_to(VENDOR) ): errors.append( f"{where}: {name} is a path dependency outside packages/, extensions/, and vendor/" ) root_paths = {r.name: r.path for r in workspace.root.requirements("dependencies")} registry = REGISTRY.read_text() if REGISTRY.exists() else "" for name, package in workspace.packages.items(): if not name.startswith(EXTENSION_PREFIX): continue if root_paths.get(name) != package.dir: errors.append( f"gleam.toml: albedo does not depend on the extension package {name} by path" ) if not re.search(rf"^import {re.escape(name)}(\s|$)", registry, re.MULTILINE): errors.append( f"{rel(REGISTRY)}: does not import the extension package {name}" ) def dependency_order(workspace: Workspace, errors: list[str]) -> list[str]: edges = { name: sorted( r.name for table in ("dependencies", "dev-dependencies", "dev_dependencies") for r in package.requirements(table) if r.name in workspace.packages ) for name, package in workspace.packages.items() } order: list[str] = [] state: dict[str, str] = {} def visit(name: str, trail: list[str]) -> None: if state.get(name) == "done": return if state.get(name) == "open": errors.append( "workspace packages depend on each other in a cycle: " + " -> ".join(trail[trail.index(name) :] + [name]) ) return state[name] = "open" for dependency in edges[name]: visit(dependency, trail + [name]) state[name] = "done" order.append(name) for name in sorted(edges): visit(name, []) return order # --- Artefact keys ----------------------------------------------------------- # Variables that change what the Erlang compiler, rebar3 or a NIF's C # build produce, so an artefact built under one value is not reused under # another. COMPILE_PREFIXES = ("ERL_", "REBAR_", "NIX_CFLAGS", "NIX_LDFLAGS") COMPILE_VARIABLES = {"CC", "CXX", "CFLAGS", "CXXFLAGS", "CPPFLAGS", "LDFLAGS"} def compile_environment() -> list[str]: return [ name for name in os.environ if name in COMPILE_VARIABLES or name.startswith(COMPILE_PREFIXES) ] def toolchain_key() -> str: def tool(name: str) -> str: found = shutil.which(name) return os.path.realpath(found) if found else "none" otp = subprocess.run( [ "erl", "-noshell", "-eval", 'io:format("~s ~s", [erlang:system_info(otp_release), erlang:system_info(version)]), halt().', ], capture_output=True, text=True, check=True, ).stdout gleam = subprocess.run( ["gleam", "--version"], capture_output=True, text=True, check=True ).stdout parts = [ MODE, platform.system(), platform.machine(), otp, gleam.strip(), *(f"{name}={tool(name)}" for name in ("gleam", "erl", "rebar3", "cc")), *(f"{name}={os.environ[name]}" for name in sorted(compile_environment())), ] return hashlib.sha256("\n".join(parts).encode()).hexdigest() def source_checksum(directory: Path) -> str: """Hashes what a dependent compiles: gleam.toml, src/ and priv/.""" digest = hashlib.sha256() files = [directory / "gleam.toml"] for sub in ("src", "priv"): files += sorted(p for p in (directory / sub).rglob("*") if p.is_file()) for path in files: digest.update(str(path.relative_to(directory)).encode() + b"\0") digest.update(hashlib.sha256(path.read_bytes()).digest()) return digest.hexdigest() def digest(parts: list[str]) -> str: return hashlib.sha256("\n".join(parts).encode()).hexdigest() def local_key( toolchain: str, name: str, directory: Path, children: dict[str, str] ) -> str: """The key of a path dependency: its sources and its closure's keys.""" return digest( [toolchain, "local", name, rel(directory), source_checksum(directory)] + sorted(f"{child}={key}" for child, key in children.items()) ) class Keys: """The artefact key of each package one manifest locks.""" def __init__(self, toolchain: str, package: Project, closure: Closure): self.toolchain = toolchain self.package = package self.locked = package.locked() self.closure = closure self.memo: dict[str, str] = {} def __call__(self, name: str) -> str: if name not in self.memo: entry = self.locked[name] children = {c: self(c) for c in self.closure.edges.get(name, [])} if entry["source"] == "hex": self.memo[name] = digest( [ self.toolchain, "hex", name, entry["version"], entry.get("outer_checksum", ""), ] + sorted(f"{child}={key}" for child, key in children.items()) ) else: self.memo[name] = local_key( self.toolchain, name, self.closure.paths[name], children ) return self.memo[name] def still(self, name: str, key: str) -> bool: """Whether a path dependency's sources still give the key, after a build.""" if self.locked[name]["source"] != "local": return True children = {c: self(c) for c in self.closure.edges.get(name, [])} return ( local_key(self.toolchain, name, self.closure.paths[name], children) == key ) def own(self) -> str: """The key a dependent computes for this package.""" children = { r.name: self(r.name) for r in self.package.requirements("dependencies") } return local_key(self.toolchain, self.package.name, self.package.dir, children) # --- Builds ------------------------------------------------------------------ @dataclass class Plan: name: str project: Project closure: Closure keys: Keys workspace_deps: set[str] def app_dir(entry: dict) -> str: """The directory under build/dev/erlang a locked package compiles into.""" return entry.get("otp_app") or entry["name"] class Builder: def __init__(self, mode: str, toolchain: str): self.mode = mode self.toolchain = toolchain self.cache = CACHE / toolchain[:16] self.cache.mkdir(parents=True, exist_ok=True) def entry(self, name: str, key: str) -> Path: return self.cache / f"{name}-{key[:32]}" def publish(self, source: Path, destination: Path) -> None: """Copies a directory into the cache, atomically.""" if destination.exists(): return staging = Path(tempfile.mkdtemp(prefix=".publish-", dir=self.cache)) try: copy_tree(source, staging / "tree") os.rename(staging / "tree", destination) except OSError: if not destination.exists(): raise finally: shutil.rmtree(staging, ignore_errors=True) def run(self, plan: Plan) -> tuple[bool, str]: try: return self.attempt(plan) except Exception as error: # reported as this package's failure return False, f"{type(error).__name__}: {error}\n" def attempt(self, plan: Plan) -> tuple[bool, str]: log: list[str] = [] env = { **os.environ, # A git dependency fetch must not walk up into the checkout's # shared .git (see nix/devShells.nix). "GIT_CEILING_DIRECTORIES": str(plan.project.dir / "build") + ( ":" + os.environ["GIT_CEILING_DIRECTORIES"] if os.environ.get("GIT_CEILING_DIRECTORIES") else "" ), } wanted = {name: plan.keys(name) for name in plan.project.locked()} # Another run may share this package's build/: staging, building, # recording and exporting all read or replace it, so one run at a # time owns it from staging until its tests finish. (plan.project.dir / "build").mkdir(exist_ok=True) with open(plan.project.dir / "build" / ".packages.lock", "w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) return self.locked_attempt(plan, wanted, env, log) def locked_attempt( self, plan: Plan, wanted: dict[str, str], env: dict[str, str], log: list[str], ) -> tuple[bool, str]: self.stage(plan, wanted) def gleam(*args: str) -> bool: result = subprocess.run( ["gleam", *args], cwd=plan.project.dir, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) log.append(f"$ gleam {' '.join(args)}\n{result.stdout}") return result.returncode == 0 # Every build unpacks its Hex dependencies from gleam's shared tarball # cache and downloads any that are missing. Two builds fetching the # same tarball at once let one read it half written ("Unable to # locate Hex package contents.tar.gz"), as on a runner whose cache # starts empty, so downloads take turns; compiling stays parallel. (ROOT / "build").mkdir(exist_ok=True) with open(ROOT / "build" / ".hex-download.lock", "w") as downloads: fcntl.flock(downloads, fcntl.LOCK_EX) if not gleam("deps", "download"): return False, "".join(log) build = ["build", "--warnings-as-errors"] if self.mode == "check" else ["build"] if not gleam(*build): return False, "".join(log) self.record(plan, wanted) self.export(plan, wanted, gleam) if self.mode == "test" and not gleam("test"): return False, "".join(log) return True, "".join(log) def stage(self, plan: Plan, wanted: dict[str, str]) -> None: """Seeds dependency artefacts whose keys match; never the package itself.""" build = plan.project.dir / "build" erlang = build / "dev" / "erlang" seeds_file = erlang / SEEDS try: seeds = json.loads(seeds_file.read_text()) except (OSError, ValueError): seeds = {} if seeds.get("toolchain") != self.toolchain: shutil.rmtree(build / "dev", ignore_errors=True) seeds = {} installed: dict[str, str] = seeds.get("deps", {}) erlang.mkdir(parents=True, exist_ok=True) compiler = self.cache / "fingerprint" if not (erlang / "fingerprint").exists() and compiler.exists(): shutil.copy2(compiler, erlang / "fingerprint") changed = seeds.get("self") is None current: dict[str, str] = {} for name, key in wanted.items(): destination = erlang / app_dir(plan.keys.locked[name]) if installed.get(name) == key and destination.exists(): current[name] = key continue changed = True shutil.rmtree(destination, ignore_errors=True) cached = self.entry(name, key) if cached.exists() and (erlang / "fingerprint").exists(): copy_tree(cached, destination) os.utime(cached) current[name] = key apps = {app_dir(plan.keys.locked[name]) for name in wanted} | {plan.name} for stale in erlang.iterdir(): if stale.is_dir() and stale.name not in apps: changed = True shutil.rmtree(stale) if changed: shutil.rmtree(erlang / plan.name, ignore_errors=True) # Only what is known to match is recorded before the build; whatever # it compiles is recorded once it succeeds. seeds_file.write_text( json.dumps({"toolchain": self.toolchain, "deps": current}) ) # Gleam resolves versions again, over the Hex API, for a path # dependency whose gleam.toml is newer than this file. The static # checks have already compared the manifest with every gleam.toml. packages = build / "packages" packages.mkdir(parents=True, exist_ok=True) for name, directory in plan.closure.paths.items(): fingerprint = packages / f"{name}.config_fingerprint" config = directory / "gleam.toml" if ( not fingerprint.exists() or fingerprint.stat().st_mtime < config.stat().st_mtime ): fingerprint.write_text("") def record(self, plan: Plan, wanted: dict[str, str]) -> None: erlang = plan.project.dir / "build" / "dev" / "erlang" (erlang / SEEDS).write_text( json.dumps({"toolchain": self.toolchain, "deps": wanted, "self": True}) ) compiler = self.cache / "fingerprint" if not compiler.exists(): shutil.copy2(erlang / "fingerprint", compiler) def export(self, plan: Plan, wanted: dict[str, str], gleam) -> None: """Caches the dependencies this build compiled, then this package as one.""" erlang = plan.project.dir / "build" / "dev" / "erlang" for name, key in wanted.items(): # A source that changed during the build is not exported. if not self.entry(name, key).exists() and plan.keys.still(name, key): self.publish( erlang / app_dir(plan.keys.locked[name]), self.entry(name, key) ) destination = self.entry(plan.name, plan.keys.own()) if destination.exists(): return apps = ",".join( f"{e['name']}={e['otp_app']}" for e in plan.keys.locked.values() if e.get("otp_app") and e["otp_app"] != e["name"] ) staging = Path(tempfile.mkdtemp(prefix=".compile-", dir=self.cache)) try: tree = staging / "tree" args = [ "compile-package", "--target", "erlang", "--no-dev", "--package", str(plan.project.dir), "--out", str(tree), "--lib", str(erlang), ] if apps: args += ["--otp-app-names", apps] if not gleam(*args): return if (plan.project.dir / "priv").is_dir(): copy_tree(plan.project.dir / "priv", tree / "priv") try: os.rename(tree, destination) except OSError: if not destination.exists(): raise finally: shutil.rmtree(staging, ignore_errors=True) def collect(self) -> None: for toolchain in CACHE.iterdir(): if toolchain != self.cache: shutil.rmtree(toolchain, ignore_errors=True) cutoff = time.time() - STALE_AFTER_SECONDS for entry in self.cache.iterdir(): if entry.is_dir() and entry.stat().st_mtime < cutoff: shutil.rmtree(entry, ignore_errors=True) def copy_tree(source: Path, destination: Path) -> None: """A copy that shares extents where the filesystem can; never a hard link, since gleam rewrites the files it compiles in place.""" subprocess.run( [ "cp", "-R", "--preserve=mode,timestamps", "--reflink=auto", str(source), str(destination), ], check=True, ) def build_all( mode: str, workspace: Workspace, order: list[str], closures: dict[str, Closure], selected: set[str], ) -> bool: builder = Builder(mode, toolchain_key()) plans: dict[str, Plan] = {} for name in order: project = workspace.packages[name] closure = closures[name] plans[name] = Plan( name, project, closure, Keys(builder.toolchain, project, closure), {d for d in closure.paths if d in workspace.packages}, ) todo = [ name for name in order if name in selected and (mode == "check" or (plans[name].project.dir / "test").is_dir()) ] for name in order: if name in selected and name not in todo: print(f"skip {name} (no test/)") jobs = int(os.environ.get("ALBEDO_TEST_BUILD_JOBS") or min(8, os.cpu_count() or 1)) finished: dict[str, bool] = {} running: dict[Future, tuple[str, float]] = {} ok = True with ThreadPoolExecutor(max_workers=jobs) as pool: while todo or running: for name in list(todo): # A dependency still in this run builds first, so its artefact # is cached for this one. waiting = [ d for d in plans[name].workspace_deps if d in todo or d in {n for n, _ in running.values()} ] failed = [ d for d in plans[name].workspace_deps if finished.get(d) is False ] if failed: todo.remove(name) finished[name] = False ok = False print( f"FAILED {name}: not built, since {', '.join(sorted(failed))} failed" ) elif not waiting and len(running) < jobs: todo.remove(name) running[pool.submit(builder.run, plans[name])] = ( name, time.monotonic(), ) if not running: continue done, _ = wait(running, return_when=FIRST_COMPLETED) for future in done: name, started = running.pop(future) success, log = future.result() finished[name] = success seconds = time.monotonic() - started if success: print(f"ok {name} ({seconds:.1f}s)") else: ok = False print(f"FAILED {name} ({seconds:.1f}s)\n{log}") builder.collect() return ok def sync(workspace: Workspace, names: list[str]) -> None: """Re-locks each package through gleam, starting from albedo's lock. The starting manifest holds the root's packages, and the root's requirements together with the package's own. Gleam keeps a locked version for every requirement the package shares with that starting point, and resolves the rest, so a package that newly requires something albedo already locks, as albedo_sqlite does esqlite, keeps albedo's version. """ text = (workspace.root.dir / "manifest.toml").read_text() packages, _, _ = text.partition("[requirements]") for name in names: package = workspace.packages[name] print(f"re-locking {name} from the root manifest") assert workspace.root.manifest is not None requirements = { dependency: ( { **spec, "path": os.path.relpath( workspace.root.dir / spec["path"], package.dir ), } if "path" in spec else spec ) for dependency, spec in workspace.root.manifest["requirements"].items() } for table in ("dependencies", "dev-dependencies", "dev_dependencies"): for dependency, spec in package.config.get(table, {}).items(): requirements[dependency] = ( {"version": spec} if isinstance(spec, str) else spec ) lines = [ f"{dependency} = {{ " + ", ".join(f"{k} = {json.dumps(v)}" for k, v in spec.items()) + " }" for dependency, spec in sorted(requirements.items()) ] (package.dir / "manifest.toml").write_text( re.sub( r'path = "([^"]+)"', lambda match: ( 'path = "' + os.path.relpath(workspace.root.dir / match[1], package.dir) + '"' ), packages, ) + "[requirements]\n" + "\n".join(lines) + "\n" ) for fingerprint in (package.dir / "build" / "packages").glob( "*.config_fingerprint" ): fingerprint.unlink() subprocess.run(["gleam", "deps", "download"], cwd=package.dir, check=True) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("mode", choices=["check", "test", "sync"]) parser.add_argument("packages", nargs="*", help="only these packages") args = parser.parse_args() started = time.monotonic() workspace = Workspace.load() unknown = set(args.packages) - set(workspace.packages) if unknown: print( f"no such workspace package: {', '.join(sorted(unknown))}", file=sys.stderr ) return 2 selected = set(args.packages or workspace.packages) errors: list[str] = [] closures: dict[str, Closure] = {} refused: list[str] = [] for name, package in workspace.packages.items(): before = len(errors) closure = check_package(workspace, package, errors) if closure is not None: closures[name] = closure if len(errors) > before: refused.append(name) if args.mode == "sync": sync(workspace, [n for n in (args.packages or refused)]) return 0 check_direction(workspace, errors) order = dependency_order(workspace, errors) if errors: print("\n".join(errors), file=sys.stderr) return 1 if args.mode == "check": dirs = [ str(p.dir / sub) for n, p in workspace.packages.items() if n in selected for sub in ("src", "test") if (p.dir / sub).is_dir() ] if subprocess.run(["gleam", "format", "--check", *dirs]).returncode != 0: return 1 ok = build_all(args.mode, workspace, order, closures, selected) print( f"workspace packages: {args.mode} {'passed' if ok else 'FAILED'} in {time.monotonic() - started:.1f}s" ) return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())