Changelog: All nRF52 images build on a pinned platform (nordicnrf52 10.12.0, as the masts and the bench) and exact library versions from platformio.lock, so a build no longer depends on the day it ran Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
253 lines
8.8 KiB
Python
253 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
|
# SPDX-License-Identifier: MIT
|
|
"""Library lock file for PlatformIO, which has none (platformio.lock).
|
|
|
|
Upstream's lib_deps are ranges (`^2.1.3`) and every library pulls in its own
|
|
dependencies, so a build takes whatever is newest that day: the same commit
|
|
built twice can differ. platformio.lock records, per env, the exact version of
|
|
every library in .pio/libdeps/<env> (direct and transitive). The platform and
|
|
the toolchain are pinned in platformio.ini itself.
|
|
|
|
pio_lock.py install -e ENV [-e ENV ...]
|
|
install the locked registry versions into .pio/libdeps/<env> (no
|
|
dependencies, nothing saved to platformio.ini). Run it before `pio
|
|
run`: PlatformIO keeps an installed library that satisfies lib_deps.
|
|
git and file libraries are pinned in platformio.ini and only checked.
|
|
pio_lock.py check -e ENV [-e ENV ...]
|
|
exit 1 when .pio/libdeps/<env> is not exactly the lock: a library
|
|
missing, extra, or of another version (run it after the build).
|
|
pio_lock.py freeze -e ENV [-e ENV ...]
|
|
write what .pio/libdeps/<env> holds into the lock (replaces those
|
|
envs' sections). After `pio pkg install -e ENV` in a clean libdeps
|
|
dir this locks today's resolution.
|
|
pio_lock.py envs
|
|
the envs the lock has a section for, one per line.
|
|
pio_lock.py moved [--base REV]
|
|
what changed against the lock in git REV (default HEAD), one
|
|
`name old -> new` line per registry library (any env).
|
|
|
|
Lock format: `[env]` sections; one library per line, `owner/name@version`
|
|
from the registry, `<remote>#<commit>` of a git library, or a file: URI.
|
|
--lock FILE (default: platformio.lock next to platformio.ini);
|
|
PLATFORMIO_LIBDEPS_DIR is honoured as by PlatformIO.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
REPO = Path(__file__).resolve().parent.parent
|
|
HEADER = """\
|
|
; Library lock for PlatformIO (tools/pio_lock.py; PlatformIO has no lockfile).
|
|
; Per env, every library in .pio/libdeps/<env>, transitive ones included:
|
|
; `owner/name@version` from the registry, `<remote>#<commit>` of a git library
|
|
; (pinned in platformio.ini, only checked here) or a file: URI.
|
|
; CI installs these before building and fails when a build resolved anything
|
|
; else. Renovate bumps the registry lines; tools/pio_lock.py freeze rewrites
|
|
; an env from what it resolved.
|
|
"""
|
|
|
|
|
|
def libdeps_dir() -> Path:
|
|
d = os.environ.get("PLATFORMIO_LIBDEPS_DIR")
|
|
return Path(d) if d else REPO / ".pio" / "libdeps"
|
|
|
|
|
|
def read_lock(path: Path) -> dict[str, list[str]]:
|
|
envs: dict[str, list[str]] = {}
|
|
cur: list[str] | None = None
|
|
if not path.exists():
|
|
return envs
|
|
for raw in path.read_text().splitlines():
|
|
line = raw.strip()
|
|
if not line or line.startswith((";", "#")):
|
|
continue
|
|
if line.startswith("[") and line.endswith("]"):
|
|
cur = envs.setdefault(line[1:-1], [])
|
|
elif cur is None:
|
|
raise SystemExit(f"{path}: library line before any [env]: {line}")
|
|
else:
|
|
cur.append(line)
|
|
return envs
|
|
|
|
|
|
def write_lock(path: Path, envs: dict[str, list[str]]) -> None:
|
|
out = [HEADER]
|
|
for env in sorted(envs):
|
|
out.append(f"[{env}]")
|
|
out.extend(sorted(envs[env], key=str.lower))
|
|
out.append("")
|
|
path.write_text("\n".join(out))
|
|
|
|
|
|
def git_uri(lib: Path) -> str:
|
|
"""`<remote>#<commit>` of a library PlatformIO cloned (it leaves no .piopm)."""
|
|
|
|
def git(*args: str) -> str:
|
|
return subprocess.run(
|
|
["git", "-C", str(lib), *args], check=True, capture_output=True, text=True
|
|
).stdout.strip()
|
|
|
|
return f"{git('remote', 'get-url', 'origin')}#{git('rev-parse', 'HEAD')}"
|
|
|
|
|
|
def installed(env: str) -> list[str]:
|
|
"""Lock lines for what .pio/libdeps/<env> holds."""
|
|
d = libdeps_dir() / env
|
|
if not d.is_dir():
|
|
raise SystemExit(
|
|
f"{d}: no such libdeps dir (run `pio pkg install -e {env}` first)"
|
|
)
|
|
lines = []
|
|
for lib in sorted(p for p in d.iterdir() if p.is_dir()):
|
|
pm = lib / ".piopm"
|
|
if not pm.exists():
|
|
if (lib / ".git").exists():
|
|
lines.append(git_uri(lib))
|
|
continue
|
|
raise SystemExit(f"{lib}: neither .piopm nor .git")
|
|
meta = json.loads(pm.read_text())
|
|
if meta.get("type") != "library":
|
|
continue
|
|
spec = meta.get("spec") or {}
|
|
if spec.get("uri"):
|
|
lines.append(spec["uri"])
|
|
elif spec.get("owner"):
|
|
lines.append(f"{spec['owner']}/{spec['name']}@{meta['version']}")
|
|
else:
|
|
raise SystemExit(f"{pm}: neither a registry owner nor a URI")
|
|
return lines
|
|
|
|
|
|
def pio() -> str:
|
|
exe = shutil.which("pio") or str(Path.home() / ".platformio/penv/bin/pio")
|
|
if not Path(exe).exists():
|
|
raise SystemExit("pio not found (PATH, ~/.platformio/penv/bin)")
|
|
return exe
|
|
|
|
|
|
def cmd_install(lock: dict[str, list[str]], envs: list[str]) -> int:
|
|
for env in envs:
|
|
if env not in lock:
|
|
print(f"{env}: not in the lock", file=sys.stderr)
|
|
return 1
|
|
# URI libraries (git, file) are pinned in platformio.ini itself and
|
|
# come from there; the lock only checks them
|
|
reg = [line for line in lock[env] if "://" not in line]
|
|
args = [
|
|
pio(),
|
|
"pkg",
|
|
"install",
|
|
"-d",
|
|
str(REPO),
|
|
"-e",
|
|
env,
|
|
"--no-save",
|
|
"--skip-dependencies",
|
|
"-s",
|
|
]
|
|
for line in reg:
|
|
args += ["-l", line]
|
|
print(f"{env}: installing {len(reg)} locked libraries", flush=True)
|
|
subprocess.run(args, check=True)
|
|
return 0
|
|
|
|
|
|
def cmd_check(lock: dict[str, list[str]], envs: list[str]) -> int:
|
|
bad = 0
|
|
for env in envs:
|
|
want, have = set(lock.get(env, [])), set(installed(env))
|
|
if env not in lock:
|
|
print(f"{env}: not in the lock", file=sys.stderr)
|
|
bad = 1
|
|
continue
|
|
if want == have:
|
|
print(f"{env}: {len(have)} libraries as locked")
|
|
continue
|
|
bad = 1
|
|
for line in sorted(want - have):
|
|
print(f"{env}: locked but not installed: {line}", file=sys.stderr)
|
|
for line in sorted(have - want):
|
|
print(f"{env}: installed but not locked: {line}", file=sys.stderr)
|
|
if bad:
|
|
print(
|
|
"fix: tools/pio_lock.py freeze -e <env> after a clean `pio pkg install -e <env>`",
|
|
file=sys.stderr,
|
|
)
|
|
return bad
|
|
|
|
|
|
def moved(base: dict[str, list[str]], lock: dict[str, list[str]]) -> list[str]:
|
|
def versions(envs: dict[str, list[str]]) -> dict[str, set[str]]:
|
|
out: dict[str, set[str]] = {}
|
|
for lines in envs.values():
|
|
for line in lines:
|
|
if "://" not in line:
|
|
name, _, ver = line.rpartition("@")
|
|
out.setdefault(name, set()).add(ver)
|
|
return out
|
|
|
|
old, new = versions(base), versions(lock)
|
|
res = []
|
|
for name in sorted(set(old) | set(new), key=str.lower):
|
|
o, n = sorted(old.get(name, set())), sorted(new.get(name, set()))
|
|
if o != n:
|
|
res.append(
|
|
f"{name.split('/', 1)[-1]} {', '.join(o) or '-'} -> {', '.join(n) or '-'}"
|
|
)
|
|
return res
|
|
|
|
|
|
def main() -> None:
|
|
ap = argparse.ArgumentParser(
|
|
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
|
)
|
|
ap.add_argument("command", choices=["install", "check", "freeze", "envs", "moved"])
|
|
ap.add_argument(
|
|
"-e", "--env", action="append", default=[], help="PlatformIO env (repeat)"
|
|
)
|
|
ap.add_argument("--lock", type=Path, default=REPO / "platformio.lock")
|
|
ap.add_argument(
|
|
"--base", default="HEAD", help="moved: git revision to compare with"
|
|
)
|
|
a = ap.parse_args()
|
|
lock = read_lock(a.lock)
|
|
if a.command == "envs":
|
|
print("\n".join(sorted(lock)))
|
|
return
|
|
if a.command == "moved":
|
|
rel = a.lock.resolve().relative_to(REPO)
|
|
old = subprocess.run(
|
|
["git", "-C", str(REPO), "show", f"{a.base}:{rel}"],
|
|
capture_output=True,
|
|
text=True,
|
|
check=False,
|
|
).stdout
|
|
tmp = Path(os.environ.get("TMPDIR", "/tmp")) / f"pio-lock-base-{os.getpid()}"
|
|
tmp.write_text(old)
|
|
try:
|
|
print("\n".join(moved(read_lock(tmp), lock)))
|
|
finally:
|
|
tmp.unlink()
|
|
return
|
|
if not a.env:
|
|
ap.error("at least one -e ENV")
|
|
if a.command == "install":
|
|
sys.exit(cmd_install(lock, a.env))
|
|
if a.command == "check":
|
|
sys.exit(cmd_check(lock, a.env))
|
|
for env in a.env:
|
|
lock[env] = installed(env)
|
|
print(f"{env}: {len(lock[env])} libraries locked")
|
|
write_lock(a.lock, lock)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|