|
|
@@ -0,0 +1,392 @@
|
|
|
+#!/usr/bin/env python3
|
|
|
+"""Five commands: list, sync, status, snapshot, restore. No Git rewrite."""
|
|
|
+
|
|
|
+from __future__ import annotations
|
|
|
+
|
|
|
+import argparse
|
|
|
+import os
|
|
|
+import re
|
|
|
+import shutil
|
|
|
+import subprocess
|
|
|
+import sys
|
|
|
+from datetime import datetime, timezone
|
|
|
+from pathlib import Path
|
|
|
+
|
|
|
+try:
|
|
|
+ import yaml
|
|
|
+except ImportError: # pragma: no cover
|
|
|
+ sys.stderr.write("需要 PyYAML:pip install -r requirements.txt\n")
|
|
|
+ raise SystemExit(2)
|
|
|
+
|
|
|
+ROOT = Path(__file__).resolve().parents[1]
|
|
|
+SHA_RE = re.compile(r"^[0-9a-f]{40}$")
|
|
|
+BAD_PATH = re.compile(r"[\s\u4e00-\u9fff]|/\.\.(/|$)|^\.\.")
|
|
|
+FORBIDDEN_GIT = {"clean", "reset", "rebase", "filter-repo", "filter-branch"}
|
|
|
+
|
|
|
+
|
|
|
+def die(msg: str, code: int = 2) -> None:
|
|
|
+ print(msg, file=sys.stderr)
|
|
|
+ raise SystemExit(code)
|
|
|
+
|
|
|
+
|
|
|
+def git_bin() -> str:
|
|
|
+ env = os.environ.get("GIT_BIN", "").strip()
|
|
|
+ if env:
|
|
|
+ return env
|
|
|
+ found = shutil.which("git")
|
|
|
+ return found or "git"
|
|
|
+
|
|
|
+
|
|
|
+def git(args: list[str], cwd: Path | None = None, check: bool = True) -> subprocess.CompletedProcess[str]:
|
|
|
+ if any(tok in FORBIDDEN_GIT for tok in args):
|
|
|
+ die(f"拒绝执行危险 Git 参数: {args}")
|
|
|
+ cmd = [git_bin()]
|
|
|
+ if os.name == "nt":
|
|
|
+ cmd.extend(["-c", "core.longpaths=true"])
|
|
|
+ cmd.extend(args)
|
|
|
+ result = subprocess.run(
|
|
|
+ cmd,
|
|
|
+ cwd=str(cwd) if cwd else None,
|
|
|
+ capture_output=True,
|
|
|
+ text=True,
|
|
|
+ encoding="utf-8",
|
|
|
+ errors="replace",
|
|
|
+ )
|
|
|
+ if check and result.returncode != 0:
|
|
|
+ detail = (result.stderr or result.stdout or "").strip()
|
|
|
+ die(detail or f"git {' '.join(args)} 失败")
|
|
|
+ return result
|
|
|
+
|
|
|
+
|
|
|
+def git_out(args: list[str], cwd: Path | None = None) -> str:
|
|
|
+ return (git(args, cwd=cwd, check=False).stdout or "").strip()
|
|
|
+
|
|
|
+
|
|
|
+def load_yaml(path: Path) -> dict:
|
|
|
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
|
+ if not isinstance(data, dict):
|
|
|
+ die(f"不是映射: {path}")
|
|
|
+ return data
|
|
|
+
|
|
|
+
|
|
|
+def load_workspace(root: Path | None = None) -> dict:
|
|
|
+ root = root or ROOT
|
|
|
+ ws = load_yaml(root / "workspace.yaml")
|
|
|
+ repos = ws.get("repositories") or {}
|
|
|
+ if not repos:
|
|
|
+ die("workspace.yaml 缺少 repositories")
|
|
|
+ paths: set[str] = set()
|
|
|
+ for rid, spec in repos.items():
|
|
|
+ if not isinstance(spec, dict) or not spec.get("repo") or not spec.get("path"):
|
|
|
+ die(f"仓库 {rid} 需要 repo 和 path")
|
|
|
+ path = spec["path"]
|
|
|
+ if BAD_PATH.search(path):
|
|
|
+ die(f"非法路径 {path}")
|
|
|
+ if path in paths:
|
|
|
+ die(f"重复工作区路径 {path}")
|
|
|
+ paths.add(path)
|
|
|
+ return ws
|
|
|
+
|
|
|
+
|
|
|
+def load_projects(root: Path | None = None) -> dict[str, dict]:
|
|
|
+ root = root or ROOT
|
|
|
+ projects: dict[str, dict] = {}
|
|
|
+ folder = root / "projects"
|
|
|
+ if not folder.exists():
|
|
|
+ return projects
|
|
|
+ known = set((load_workspace(root).get("repositories") or {}).keys())
|
|
|
+ for path in sorted(folder.glob("*.yaml")):
|
|
|
+ data = load_yaml(path)
|
|
|
+ name = data.get("project") or path.stem
|
|
|
+ branches = data.get("branches") or {}
|
|
|
+ if not isinstance(branches, dict):
|
|
|
+ die(f"{path}: branches 必须是映射")
|
|
|
+ unknown = set(branches) - known
|
|
|
+ if unknown:
|
|
|
+ die(f"{path}: 未知仓库 ID {', '.join(sorted(unknown))}")
|
|
|
+ projects[name] = data
|
|
|
+ return projects
|
|
|
+
|
|
|
+
|
|
|
+def load_snapshots(root: Path | None = None) -> dict[str, dict]:
|
|
|
+ root = root or ROOT
|
|
|
+ snaps: dict[str, dict] = {}
|
|
|
+ folder = root / "snapshots"
|
|
|
+ if not folder.exists():
|
|
|
+ return snaps
|
|
|
+ for path in sorted(folder.glob("*.yaml")):
|
|
|
+ data = load_yaml(path)
|
|
|
+ sid = data.get("snapshot_id") or path.stem
|
|
|
+ snaps[sid] = data
|
|
|
+ return snaps
|
|
|
+
|
|
|
+
|
|
|
+def repo_url(ws: dict, spec: dict) -> str:
|
|
|
+ base = str(ws.get("git_base") or "").rstrip("/\\")
|
|
|
+ repo = spec["repo"]
|
|
|
+ if repo.startswith("http") or repo.startswith("ssh://") or repo.startswith("git@"):
|
|
|
+ return repo
|
|
|
+ if Path(base).exists() or (ROOT / base).exists():
|
|
|
+ base_path = Path(base)
|
|
|
+ if not base_path.is_absolute():
|
|
|
+ base_path = (ROOT / base).resolve()
|
|
|
+ return str(base_path / repo)
|
|
|
+ return f"{base}/{repo}"
|
|
|
+
|
|
|
+
|
|
|
+def default_branch_for(ws: dict, spec: dict) -> str:
|
|
|
+ return str(spec.get("track") or ws.get("default_branch") or "dev")
|
|
|
+
|
|
|
+
|
|
|
+def resolve_branches(ws: dict, projects: dict[str, dict], target: str) -> tuple[str, dict[str, str]]:
|
|
|
+ repos = ws["repositories"]
|
|
|
+ if target == "dev":
|
|
|
+ return "dev", {rid: default_branch_for(ws, spec) for rid, spec in repos.items()}
|
|
|
+ if target == "stable":
|
|
|
+ stable = str(ws.get("stable_branch") or "master")
|
|
|
+ return "stable", {rid: stable for rid in repos}
|
|
|
+ if target in projects:
|
|
|
+ mapping = {rid: default_branch_for(ws, spec) for rid, spec in repos.items()}
|
|
|
+ mapping.update(projects[target].get("branches") or {})
|
|
|
+ return target, mapping
|
|
|
+ die(f"未知目标 {target}。可用: dev, stable, {', '.join(sorted(projects))}")
|
|
|
+
|
|
|
+
|
|
|
+def workspace_dir(ws: dict, explicit: str | None) -> Path:
|
|
|
+ if explicit:
|
|
|
+ return Path(explicit).expanduser().resolve()
|
|
|
+ return (ROOT / str(ws.get("workspace_root") or "workspace")).resolve()
|
|
|
+
|
|
|
+
|
|
|
+def is_dirty(path: Path) -> bool:
|
|
|
+ if not (path / ".git").exists():
|
|
|
+ return False
|
|
|
+ return bool(git_out(["status", "--porcelain=v1"], cwd=path))
|
|
|
+
|
|
|
+
|
|
|
+def ahead_behind(path: Path) -> str:
|
|
|
+ result = git(["rev-list", "--left-right", "--count", "@{upstream}...HEAD"], cwd=path, check=False)
|
|
|
+ if result.returncode != 0:
|
|
|
+ return "-"
|
|
|
+ parts = (result.stdout or "0\t0").strip().split()
|
|
|
+ if len(parts) != 2:
|
|
|
+ return "-"
|
|
|
+ return f"{parts[1]}/{parts[0]}"
|
|
|
+
|
|
|
+
|
|
|
+def cmd_list(args: argparse.Namespace) -> int:
|
|
|
+ ws = load_workspace()
|
|
|
+ projects = load_projects()
|
|
|
+ snaps = load_snapshots()
|
|
|
+ print("dev")
|
|
|
+ print("stable")
|
|
|
+ for name, data in projects.items():
|
|
|
+ status = data.get("status") or "unknown"
|
|
|
+ print(f"{name} [{status}]")
|
|
|
+ if snaps:
|
|
|
+ print("snapshots:")
|
|
|
+ for sid in snaps:
|
|
|
+ print(f" {sid}")
|
|
|
+ else:
|
|
|
+ print("snapshots: (无)")
|
|
|
+ print(f"仓库数: {len(ws['repositories'])}")
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+def ensure_clone(ws: dict, rid: str, spec: dict, dest: Path) -> None:
|
|
|
+ dest.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ if (dest / ".git").exists():
|
|
|
+ git(["fetch", "--tags", "origin"], cwd=dest, check=False)
|
|
|
+ return
|
|
|
+ url = repo_url(ws, spec)
|
|
|
+ print(f"clone {rid} <- {url}")
|
|
|
+ git(["clone", url, str(dest)])
|
|
|
+
|
|
|
+
|
|
|
+def checkout_branch(dest: Path, branch: str) -> None:
|
|
|
+ checked = git(["checkout", branch], cwd=dest, check=False)
|
|
|
+ if checked.returncode != 0:
|
|
|
+ checked = git(["checkout", f"origin/{branch}"], cwd=dest, check=False)
|
|
|
+ if checked.returncode != 0:
|
|
|
+ die(f"{dest}: 无法检出 {branch}\n{(checked.stderr or '').strip()}")
|
|
|
+ git(["checkout", "-B", branch], cwd=dest, check=False)
|
|
|
+
|
|
|
+
|
|
|
+def cmd_sync(args: argparse.Namespace) -> int:
|
|
|
+ ws = load_workspace()
|
|
|
+ projects = load_projects()
|
|
|
+ label, mapping = resolve_branches(ws, projects, args.target)
|
|
|
+ dest_root = workspace_dir(ws, args.directory)
|
|
|
+ dest_root.mkdir(parents=True, exist_ok=True)
|
|
|
+ if label == "stable":
|
|
|
+ print("提示: stable 只是各仓当前 master 组合,不是已验收发布。精确历史请 ws restore。")
|
|
|
+ print(f"同步目标 {label} -> {dest_root}")
|
|
|
+ for rid, spec in ws["repositories"].items():
|
|
|
+ dest = dest_root / spec["path"]
|
|
|
+ want = mapping[rid]
|
|
|
+ if (dest / ".git").exists() and is_dirty(dest):
|
|
|
+ head = git_out(["rev-parse", "--abbrev-ref", "HEAD"], cwd=dest)
|
|
|
+ die(f"{rid} 工作区有未提交修改,拒绝切换(当前 {head},目标 {want})")
|
|
|
+ ensure_clone(ws, rid, spec, dest)
|
|
|
+ checkout_branch(dest, want)
|
|
|
+ commit = git_out(["rev-parse", "HEAD"], cwd=dest)
|
|
|
+ print(f"ok {rid:16} {want:28} {commit[:12]}")
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+def cmd_status(args: argparse.Namespace) -> int:
|
|
|
+ ws = load_workspace()
|
|
|
+ projects = load_projects()
|
|
|
+ target = args.target or "dev"
|
|
|
+ _, mapping = resolve_branches(ws, projects, target)
|
|
|
+ dest_root = workspace_dir(ws, args.directory)
|
|
|
+ print(f"{'ID':16} {'路径':28} {'当前':24} {'目标':24} {'commit':12} {'dirty':5} ahead/behind")
|
|
|
+ for rid, spec in ws["repositories"].items():
|
|
|
+ dest = dest_root / spec["path"]
|
|
|
+ want = mapping[rid]
|
|
|
+ if not (dest / ".git").exists():
|
|
|
+ print(f"{rid:16} {spec['path']:28} {'-':24} {want:24} {'-':12} miss -")
|
|
|
+ continue
|
|
|
+ branch = git_out(["rev-parse", "--abbrev-ref", "HEAD"], cwd=dest)
|
|
|
+ commit = git_out(["rev-parse", "HEAD"], cwd=dest)
|
|
|
+ dirty = "yes" if is_dirty(dest) else "no"
|
|
|
+ print(
|
|
|
+ f"{rid:16} {spec['path']:28} {branch:24} {want:24} {commit[:12]:12} {dirty:5} {ahead_behind(dest)}"
|
|
|
+ )
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+def cmd_snapshot(args: argparse.Namespace) -> int:
|
|
|
+ ws = load_workspace()
|
|
|
+ projects = load_projects()
|
|
|
+ label, mapping = resolve_branches(ws, projects, args.target)
|
|
|
+ dest_root = workspace_dir(ws, args.directory)
|
|
|
+ snap_id = f"{args.target}-{args.name}"
|
|
|
+ out = ROOT / "snapshots" / f"{snap_id}.yaml"
|
|
|
+ if out.exists():
|
|
|
+ die(f"Snapshot 已存在,拒绝覆盖: {out.name}")
|
|
|
+ rows: dict[str, dict] = {}
|
|
|
+ for rid, spec in ws["repositories"].items():
|
|
|
+ dest = dest_root / spec["path"]
|
|
|
+ if not (dest / ".git").exists():
|
|
|
+ die(f"{rid} 不存在,先 ws sync {args.target}")
|
|
|
+ if is_dirty(dest):
|
|
|
+ die(f"{rid} 有未提交修改,拒绝生成 Snapshot")
|
|
|
+ commit = git_out(["rev-parse", "HEAD"], cwd=dest)
|
|
|
+ if not SHA_RE.match(commit):
|
|
|
+ die(f"{rid} HEAD 不是完整 SHA: {commit}")
|
|
|
+ branch = git_out(["rev-parse", "--abbrev-ref", "HEAD"], cwd=dest)
|
|
|
+ rows[rid] = {"branch": mapping[rid], "commit": commit, "head_name": branch}
|
|
|
+ created = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
+ payload = {
|
|
|
+ "snapshot_id": snap_id,
|
|
|
+ "project": args.target,
|
|
|
+ "created_at_utc": created,
|
|
|
+ "status": "unvalidated",
|
|
|
+ "repositories": {rid: {"branch": row["branch"], "commit": row["commit"]} for rid, row in rows.items()},
|
|
|
+ "validation": {
|
|
|
+ "build": "not-run",
|
|
|
+ "simulation": "not-run",
|
|
|
+ "software_test": "not-run",
|
|
|
+ "hardware_test": "not-run",
|
|
|
+ },
|
|
|
+ "artifacts": [],
|
|
|
+ "external_components": {
|
|
|
+ "algorithm": {
|
|
|
+ "source_access": "private",
|
|
|
+ "owner": "algorithm-owner",
|
|
|
+ "artifact_version": "pending",
|
|
|
+ "artifact_sha256": "pending",
|
|
|
+ }
|
|
|
+ },
|
|
|
+ "notes": [
|
|
|
+ "由 ws snapshot 自动生成,不代表正式验收。",
|
|
|
+ "请补全 validation 与 artifacts 后再考虑 dev→master。",
|
|
|
+ ],
|
|
|
+ }
|
|
|
+ out.parent.mkdir(parents=True, exist_ok=True)
|
|
|
+ out.write_text(yaml.safe_dump(payload, allow_unicode=True, sort_keys=False), encoding="utf-8")
|
|
|
+ print(f"已写入 {out.relative_to(ROOT)}")
|
|
|
+ print("status: unvalidated")
|
|
|
+ print("待填写: validation.build / software_test / hardware_test / artifacts[].sha256")
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+def cmd_restore(args: argparse.Namespace) -> int:
|
|
|
+ ws = load_workspace()
|
|
|
+ snaps = load_snapshots()
|
|
|
+ data = snaps.get(args.snapshot_id)
|
|
|
+ if not data:
|
|
|
+ die(f"找不到 Snapshot {args.snapshot_id}")
|
|
|
+ dest_root = Path(args.directory).expanduser().resolve() if args.directory else (ROOT / "workspace-restore" / args.snapshot_id)
|
|
|
+ dest_root.mkdir(parents=True, exist_ok=True)
|
|
|
+ print(f"恢复 {args.snapshot_id} -> {dest_root}")
|
|
|
+ print("检出为 detached HEAD,不要在此目录当开发分支使用。")
|
|
|
+ ok = True
|
|
|
+ for rid, spec in ws["repositories"].items():
|
|
|
+ rec = (data.get("repositories") or {}).get(rid)
|
|
|
+ if not rec:
|
|
|
+ die(f"Snapshot 缺少仓库 {rid}")
|
|
|
+ commit = rec.get("commit") or ""
|
|
|
+ if not SHA_RE.match(commit):
|
|
|
+ die(f"{rid} 的 commit 不是完整 SHA")
|
|
|
+ dest = dest_root / spec["path"]
|
|
|
+ if dest.exists() and is_dirty(dest):
|
|
|
+ die(f"{rid} 恢复目录 dirty,拒绝覆盖")
|
|
|
+ ensure_clone(ws, rid, spec, dest)
|
|
|
+ checked = git(["checkout", "--detach", commit], cwd=dest, check=False)
|
|
|
+ if checked.returncode != 0:
|
|
|
+ die(f"{rid} 无法检出 {commit}\n{(checked.stderr or '').strip()}")
|
|
|
+ head = git_out(["rev-parse", "HEAD"], cwd=dest)
|
|
|
+ branch = git_out(["rev-parse", "--abbrev-ref", "HEAD"], cwd=dest)
|
|
|
+ dirty = is_dirty(dest)
|
|
|
+ match = head == commit and branch == "HEAD" and not dirty
|
|
|
+ print(f"{'ok' if match else 'FAIL'} {rid:16} {head} dirty={dirty} {branch}")
|
|
|
+ ok = ok and match
|
|
|
+ if not ok:
|
|
|
+ die("恢复校验失败", 1)
|
|
|
+ print("恢复完成,HEAD 与 Snapshot 一致且 clean。")
|
|
|
+ return 0
|
|
|
+
|
|
|
+
|
|
|
+def build_parser() -> argparse.ArgumentParser:
|
|
|
+ parser = argparse.ArgumentParser(prog="ws", description="四人团队多仓库同步与 Snapshot")
|
|
|
+ sub = parser.add_subparsers(dest="cmd", required=True)
|
|
|
+ sub.add_parser("list", help="列出 dev / stable / 项目 / Snapshot")
|
|
|
+ p_sync = sub.add_parser("sync", help="同步工作区")
|
|
|
+ p_sync.add_argument("target", help="dev | stable | 项目名")
|
|
|
+ p_sync.add_argument("-C", "--directory", default="")
|
|
|
+ p_st = sub.add_parser("status", help="查看状态表")
|
|
|
+ p_st.add_argument("target", nargs="?", default="dev")
|
|
|
+ p_st.add_argument("-C", "--directory", default="")
|
|
|
+ p_sn = sub.add_parser("snapshot", help="从干净工作区生成 Snapshot")
|
|
|
+ p_sn.add_argument("target")
|
|
|
+ p_sn.add_argument("name")
|
|
|
+ p_sn.add_argument("-C", "--directory", default="")
|
|
|
+ p_rs = sub.add_parser("restore", help="按 Snapshot 恢复到 detached HEAD")
|
|
|
+ p_rs.add_argument("snapshot_id")
|
|
|
+ p_rs.add_argument("-C", "--directory", default="")
|
|
|
+ return parser
|
|
|
+
|
|
|
+
|
|
|
+def main(argv: list[str] | None = None) -> int:
|
|
|
+ if hasattr(sys.stdout, "reconfigure"):
|
|
|
+ try:
|
|
|
+ sys.stdout.reconfigure(encoding="utf-8")
|
|
|
+ sys.stderr.reconfigure(encoding="utf-8")
|
|
|
+ except Exception:
|
|
|
+ pass
|
|
|
+ args = build_parser().parse_args(argv)
|
|
|
+ if args.cmd == "list":
|
|
|
+ return cmd_list(args)
|
|
|
+ if args.cmd == "sync":
|
|
|
+ return cmd_sync(args)
|
|
|
+ if args.cmd == "status":
|
|
|
+ return cmd_status(args)
|
|
|
+ if args.cmd == "snapshot":
|
|
|
+ return cmd_snapshot(args)
|
|
|
+ return cmd_restore(args)
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ raise SystemExit(main())
|