#!/usr/bin/env python3 """Record expected state for Debian Compose services; never operates Docker.""" import argparse import fcntl import json import os from pathlib import Path import re import tempfile def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--file", type=Path, required=True) parser.add_argument("action", choices=("stopped", "running", "clear", "list")) parser.add_argument("services", nargs="*") args = parser.parse_args() if (args.action == "list") != (not args.services): parser.error("list takes no services; other actions require project/service names") if any(not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*/[a-zA-Z0-9][a-zA-Z0-9_.-]*", name) for name in args.services): parser.error("services must be exact project/service names") args.file.parent.mkdir(mode=0o700, parents=True, exist_ok=True) with (args.file.parent / (args.file.name + ".lock")).open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX) data = json.loads(args.file.read_text()) if args.file.exists() else {"version": 1, "services": {}} if data.get("version") != 1 or not isinstance(data.get("services"), dict): raise ValueError("invalid Compose intent record") if args.action == "list": print(json.dumps(data, indent=2, sort_keys=True)) return for name in args.services: if args.action == "clear": data["services"].pop(name, None) else: data["services"][name] = args.action fd, temporary = tempfile.mkstemp(prefix=".compose-intent-", dir=args.file.parent) try: with os.fdopen(fd, "w") as stream: json.dump(data, stream, indent=2, sort_keys=True) stream.write("\n") os.replace(temporary, args.file) finally: if os.path.exists(temporary): os.unlink(temporary) print("Recorded expected state only; no containers were started or stopped.") if __name__ == "__main__": try: main() except (OSError, ValueError, AttributeError) as exc: raise SystemExit(f"Compose intent: {exc}")