返回 CodeWhale
sync-marketplace.py
根目录 / scripts / sync-marketplace.py
1 #!/usr/bin/env python3
2 """Generate the built-in catalog from the first-party marketplace checkout.
3
4 No install, trust, enablement, network fetch, or plugin execution occurs here.
5 Run with --check in CI; without it, review the generated snapshot diff.
6 """
7 import argparse
8 import json
9 import re
10 from pathlib import Path
11 import subprocess
12 from urllib.parse import urlsplit
13
14 ROOT = Path(__file__).resolve().parents[1]
15 REPOSITORY = "https://github.com/codewhale-hq/codewhale-plugin-marketplace"
16 HOSTS = {"darwin": "macos", "linux": "linux", "win32": "windows"}
17
18
19 def admitted_dsh_archives():
20 pins_path = ROOT / "crates/engine/tests/fixtures/dsh-plugin-acceptance/pins.json"
21 pins = json.loads(pins_path.read_text())
22 if pins["schema"] != "codewhale.dsh-acceptance-pins/1":
23 raise SystemExit("unrecognized DSH acceptance pin schema")
24 archives = {}
25 for pin in pins["rows"]:
26 if pin["admission"] != "admit" or "manifest_os" not in pin:
27 continue
28 package, version = pin["package"], pin["version"]
29 stem = package.rsplit("/", 1)[-1]
30 url = f"https://registry.npmjs.org/{package}/-/{stem}-{version}.tgz"
31 archives[url, version, pin["tarball_sha256"]] = pin["manifest_os"]
32 return archives
33
34
35 def check_remote(candidate, archives):
36 name, url = candidate["name"], candidate["source"]
37 version, digest = candidate.get("version"), candidate.get("sha256")
38 if "/latest/" in url or not isinstance(version, str) or not version.strip():
39 raise SystemExit(f"{name}: remote source requires a pinned version")
40 if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
41 raise SystemExit(f"{name}: remote source requires a SHA-256 digest")
42 if "platforms" in candidate:
43 platforms = candidate["platforms"]
44 if (not isinstance(platforms, list) or not platforms
45 or any(platform not in HOSTS.values() for platform in platforms)
46 or len(set(platforms)) != len(platforms)):
47 raise SystemExit(f"{name}: invalid remote platforms")
48 return
49 declared = archives.get((url, version, digest))
50 if declared == {}:
51 return
52 if (isinstance(declared, dict) and set(declared) == {"os"}
53 and isinstance(declared["os"], list) and sorted(declared["os"]) == sorted(HOSTS)):
54 candidate["platforms"] = [HOSTS[os] for os in declared["os"]]
55 return
56 raise SystemExit(f"{name}: remote source requires platforms or an exact DSH pin with reviewed OS declarations")
57
58
59 def main():
60 parser = argparse.ArgumentParser(description=__doc__)
61 parser.add_argument("--marketplace", type=Path, default=ROOT.parent / "codewhale-plugin-marketplace")
62 parser.add_argument("--check", action="store_true")
63 args = parser.parse_args()
64 source = args.marketplace.resolve()
65 raw = subprocess.check_output(["git", "show", "HEAD:marketplace.json"], cwd=source)
66 revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=source, text=True).strip()
67 catalog = json.loads(raw)
68 archives = admitted_dsh_archives()
69 for candidate in catalog["plugins"]:
70 spec = candidate["source"]
71 if not spec.startswith("path:"):
72 if re.fullmatch(r"github:[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", spec):
73 continue
74 parsed = urlsplit(spec)
75 if (parsed.scheme == "https" and parsed.hostname and not parsed.username
76 and not parsed.password and not any(c.isspace() or ord(c) < 32 for c in spec)):
77 check_remote(candidate, archives)
78 continue
79 raise SystemExit(f"unexpected first-party source: {spec}")
80 relative = spec[5:]
81 if any(part in ("", ".", "..") or not all(c.isascii() and (c.isalnum() or c in "-_.") for c in part) for part in relative.split("/")):
82 raise SystemExit(f"unsafe bundle path: {relative}")
83 # Pin local bundles to the reviewed marketplace revision so the
84 # bytes a user installs are the bytes this snapshot describes. Freshness
85 # comes from bumping the pin (the marketplace-sync workflow reports drift
86 # against `main` weekly); `/plugin update` re-downloads the same archive
87 # and reports no change until the pin moves.
88 candidate["source"] = f"https://codeload.github.com/codewhale-hq/codewhale-plugin-marketplace/tar.gz/{revision}#path={relative}"
89 snapshot = {"repository": REPOSITORY, "revision": revision, "catalog": catalog}
90 rendered = json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n"
91 output = ROOT / "crates/plugins/assets/first-party-marketplace.json"
92 if args.check:
93 if not output.exists() or output.read_text() != rendered:
94 raise SystemExit("First-party catalog drift: run python3 scripts/sync-marketplace.py, review, and rebuild.")
95 print(f"First-party catalog matches marketplace {revision}")
96 else:
97 output.write_text(rendered)
98 print(f"Updated {output} from marketplace {revision}")
99
100
101 if __name__ == "__main__":
102 main()
103
103 lines PYTHON