cs-plugin 0.1.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cs_plugin/__init__.py +3 -0
- cs_plugin/claude.py +32 -0
- cs_plugin/cli.py +233 -0
- cs_plugin/project.py +329 -0
- cs_plugin/releases.py +91 -0
- cs_plugin/remote.py +95 -0
- cs_plugin/sources.py +82 -0
- cs_plugin-0.1.5.dist-info/METADATA +147 -0
- cs_plugin-0.1.5.dist-info/RECORD +12 -0
- cs_plugin-0.1.5.dist-info/WHEEL +5 -0
- cs_plugin-0.1.5.dist-info/entry_points.txt +2 -0
- cs_plugin-0.1.5.dist-info/top_level.txt +1 -0
cs_plugin/__init__.py
ADDED
cs_plugin/claude.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Running Claude Code's own `claude plugin` commands: the only code that does."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import project
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def available() -> bool:
|
|
14
|
+
return shutil.which("claude") is not None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run(*args: str) -> subprocess.CompletedProcess:
|
|
18
|
+
out = subprocess.run(["claude", *args], capture_output=True, text=True)
|
|
19
|
+
if out.returncode != 0:
|
|
20
|
+
raise project.ProjectError(f"claude {' '.join(args)} failed:\n{out.stdout}{out.stderr}")
|
|
21
|
+
return out
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def installed(cfg: project.Config, root: Path) -> dict[str, str]:
|
|
25
|
+
"""Plugin -> version, for this project's plugins installed in this project."""
|
|
26
|
+
rows = json.loads(run("plugin", "list", "--json").stdout or "[]")
|
|
27
|
+
here = str(root.resolve())
|
|
28
|
+
suffix = f"@{cfg.marketplace}"
|
|
29
|
+
return {r["id"][: -len(suffix)]: r.get("version", "")
|
|
30
|
+
for r in rows
|
|
31
|
+
if r.get("id", "").endswith(suffix) and r.get("scope") == "project"
|
|
32
|
+
and str(Path(r.get("projectPath", "")).resolve()) == here}
|
cs_plugin/cli.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""cs-plugin: pin a project's Claude Code plugins in plugins.toml, install exactly that.
|
|
2
|
+
|
|
3
|
+
cs-plugin list every plugin in the sources, with releases
|
|
4
|
+
cs-plugin versions NAME every release of one plugin
|
|
5
|
+
cs-plugin add NAME[@VERSION]... pin plugins (newest release by default)
|
|
6
|
+
cs-plugin remove NAME... drop plugins
|
|
7
|
+
cs-plugin upgrade [NAME...] move pins to the newest release
|
|
8
|
+
cs-plugin outdated pins with a newer release
|
|
9
|
+
cs-plugin generate rewrite the generated files from plugins.toml
|
|
10
|
+
cs-plugin sync install exactly what plugins.toml pins
|
|
11
|
+
cs-plugin sources the repos plugins are read from
|
|
12
|
+
|
|
13
|
+
Run from the project's root. Which plugins exist is read live from the source
|
|
14
|
+
repos' own marketplaces: plugins.toml [sources], or the defaults. add, remove
|
|
15
|
+
and upgrade regenerate the files Claude Code reads; sync is what a teammate runs
|
|
16
|
+
after cloning, and after every pull that changes plugins.toml.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import sys
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from . import __version__, claude, project, releases, remote, sources
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _index(cfg: project.Config) -> dict[str, dict]:
|
|
29
|
+
return sources.index(cfg.repos, remote.read_json)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def cmd_list(args: argparse.Namespace) -> int:
|
|
33
|
+
cfg = project.load(Path.cwd())
|
|
34
|
+
cat = _index(cfg)
|
|
35
|
+
found = releases.newest_first(list(cat.values()))
|
|
36
|
+
width = max(map(len, cat), default=0)
|
|
37
|
+
for name in sorted(cat):
|
|
38
|
+
rel = found[name]
|
|
39
|
+
newest = rel[0] if rel else ("no releases" if rel is not None else "not git")
|
|
40
|
+
mark = "*" if name in cfg.plugins else " "
|
|
41
|
+
clash = f" (also in {', '.join(cat[name]['also_in'])})" if cat[name].get("also_in") else ""
|
|
42
|
+
print(f"{mark} {name:<{width}} {newest:<12} {cat[name]['repo']}{clash}")
|
|
43
|
+
if args.long and cat[name].get("description"):
|
|
44
|
+
print(f" {'':<{width}} {cat[name]['description']}")
|
|
45
|
+
if cfg.plugins:
|
|
46
|
+
print(f"\n* pinned in {project.CONFIG}")
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cmd_versions(args: argparse.Namespace) -> int:
|
|
51
|
+
cfg = project.load(Path.cwd())
|
|
52
|
+
cat = _index(cfg)
|
|
53
|
+
name = args.plugin
|
|
54
|
+
spec = cfg.plugins.get(name, {})
|
|
55
|
+
source, repo = releases.source_of(name, spec, cat)
|
|
56
|
+
found = releases.released(name, source)
|
|
57
|
+
pinned = spec.get("version")
|
|
58
|
+
rows = []
|
|
59
|
+
for v in found:
|
|
60
|
+
notes = ["newest"] if v == found[0] else []
|
|
61
|
+
if v == pinned:
|
|
62
|
+
notes.append(f"pinned in {project.CONFIG}")
|
|
63
|
+
link = (remote.release_url(source, name, v) or "") if args.long else ""
|
|
64
|
+
rows.append((v, ", ".join(notes), link))
|
|
65
|
+
vw = max(len(v) for v, _, _ in rows)
|
|
66
|
+
nw = max(len(n) for _, n, _ in rows)
|
|
67
|
+
print(f"{name} ({repo})")
|
|
68
|
+
for v, notes, link in rows:
|
|
69
|
+
print(f" {v:<{vw}} {notes:<{nw}} {link}".rstrip())
|
|
70
|
+
if pinned and pinned not in found:
|
|
71
|
+
print(f"\npinned in {project.CONFIG} to {pinned}, which is not a release")
|
|
72
|
+
for k in ("ref", "sha"):
|
|
73
|
+
if k in spec:
|
|
74
|
+
print(f"\npinned in {project.CONFIG} to {k} {spec[k]}, not a release")
|
|
75
|
+
return 0
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _write(cfg: project.Config, cat: dict[str, dict]) -> None:
|
|
79
|
+
root = Path.cwd()
|
|
80
|
+
project.save(root, cfg)
|
|
81
|
+
for path in project.generate(root, cfg, cat):
|
|
82
|
+
print(f"wrote {path.relative_to(root)}")
|
|
83
|
+
print(f"Next: `cs-plugin sync` to install, then commit {project.CONFIG} and .claude/.")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def cmd_add(args: argparse.Namespace) -> int:
|
|
87
|
+
cfg = project.load(Path.cwd())
|
|
88
|
+
cat = _index(cfg)
|
|
89
|
+
for item in args.plugins:
|
|
90
|
+
name, _, version = item.partition("@")
|
|
91
|
+
spec = cfg.plugins.get(name, {})
|
|
92
|
+
version = releases.resolve(name, version or None, cat, spec)
|
|
93
|
+
old = spec.get("version")
|
|
94
|
+
cfg.plugins[name] = project.repinned(spec, version)
|
|
95
|
+
print(f"{name} {old + ' -> ' if old and old != version else ''}{version}")
|
|
96
|
+
_write(cfg, cat)
|
|
97
|
+
return 0
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def cmd_remove(args: argparse.Namespace) -> int:
|
|
101
|
+
cfg = project.load(Path.cwd())
|
|
102
|
+
missing = [n for n in args.plugins if n not in cfg.plugins]
|
|
103
|
+
if missing:
|
|
104
|
+
raise project.ProjectError(f"not in {project.CONFIG}: {', '.join(missing)}")
|
|
105
|
+
for name in args.plugins:
|
|
106
|
+
del cfg.plugins[name]
|
|
107
|
+
print(f"removed {name}")
|
|
108
|
+
_write(cfg, _index(cfg))
|
|
109
|
+
print("`cs-plugin sync` also uninstalls them from this project.")
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def cmd_outdated(args: argparse.Namespace) -> int:
|
|
114
|
+
cfg = project.load(Path.cwd())
|
|
115
|
+
behind = releases.behind(cfg, _index(cfg), None)
|
|
116
|
+
for name, have, newest in behind:
|
|
117
|
+
print(f"{name} {have} -> {newest}")
|
|
118
|
+
unversioned = [n for n, s in cfg.plugins.items() if "version" not in s]
|
|
119
|
+
if unversioned:
|
|
120
|
+
print(f"pinned to a ref or commit, not checked: {', '.join(sorted(unversioned))}")
|
|
121
|
+
if not behind:
|
|
122
|
+
print("every versioned pin is the newest release")
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def cmd_upgrade(args: argparse.Namespace) -> int:
|
|
127
|
+
cfg = project.load(Path.cwd())
|
|
128
|
+
unknown = [n for n in args.plugins if n not in cfg.plugins]
|
|
129
|
+
if unknown:
|
|
130
|
+
raise project.ProjectError(f"not in {project.CONFIG}: {', '.join(unknown)}")
|
|
131
|
+
cat = _index(cfg)
|
|
132
|
+
behind = releases.behind(cfg, cat, args.plugins or None)
|
|
133
|
+
for name, have, newest in behind:
|
|
134
|
+
cfg.plugins[name] = project.repinned(cfg.plugins[name], newest)
|
|
135
|
+
print(f"{name} {have} -> {newest}")
|
|
136
|
+
if not behind:
|
|
137
|
+
print("already at the newest releases")
|
|
138
|
+
return 0
|
|
139
|
+
_write(cfg, cat)
|
|
140
|
+
return 0
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def cmd_generate(args: argparse.Namespace) -> int:
|
|
144
|
+
root = Path.cwd()
|
|
145
|
+
cfg = project.load(root)
|
|
146
|
+
changed = project.generate(root, cfg, _index(cfg))
|
|
147
|
+
for path in changed:
|
|
148
|
+
print(f"wrote {path.relative_to(root)}")
|
|
149
|
+
if not changed:
|
|
150
|
+
print("generated files are current")
|
|
151
|
+
return 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def cmd_sync(args: argparse.Namespace) -> int:
|
|
155
|
+
root = Path.cwd()
|
|
156
|
+
if not claude.available():
|
|
157
|
+
raise project.ProjectError("`claude` is not on PATH; install Claude Code first")
|
|
158
|
+
cfg = project.load(root)
|
|
159
|
+
problems = project.stale(root, cfg)
|
|
160
|
+
if problems:
|
|
161
|
+
raise project.ProjectError("the generated files do not match plugins.toml:\n "
|
|
162
|
+
+ "\n ".join(problems) + "\nRun `cs-plugin generate`.")
|
|
163
|
+
settings = root / project.SETTINGS
|
|
164
|
+
committed = settings.read_text() if settings.exists() else None
|
|
165
|
+
try:
|
|
166
|
+
# Local scope: registering writes the marketplace's absolute path, which
|
|
167
|
+
# belongs in the uncommitted settings file, not the shared one.
|
|
168
|
+
claude.run("plugin", "marketplace", "add", str((root / project.GEN_DIR).resolve()),
|
|
169
|
+
"--scope", "local")
|
|
170
|
+
claude.run("plugin", "marketplace", "update", cfg.marketplace)
|
|
171
|
+
for cmd in project.sync_plan(cfg, claude.installed(cfg, root)):
|
|
172
|
+
print("claude " + " ".join(cmd))
|
|
173
|
+
print(" " + (claude.run(*cmd).stdout.strip().splitlines() or [""])[-1])
|
|
174
|
+
finally:
|
|
175
|
+
project.restore_layout(settings, committed)
|
|
176
|
+
after = claude.installed(cfg, root)
|
|
177
|
+
print()
|
|
178
|
+
status = 0
|
|
179
|
+
for name in sorted(cfg.plugins):
|
|
180
|
+
want = cfg.plugins[name].get("version")
|
|
181
|
+
have = after.get(name)
|
|
182
|
+
ok = have is not None and (want is None or have == want)
|
|
183
|
+
status |= not ok
|
|
184
|
+
print(f"{'ok ' if ok else 'BAD'} {name} {have or 'not installed'}"
|
|
185
|
+
+ (f" (pinned {want})" if want and have != want else ""))
|
|
186
|
+
print("\nRestart Claude Code in this project to load the changes.")
|
|
187
|
+
return status
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def cmd_sources(args: argparse.Namespace) -> int:
|
|
191
|
+
cfg = project.load(Path.cwd())
|
|
192
|
+
where = f"[sources] in {project.CONFIG}" if cfg.sources is not None else "the defaults"
|
|
193
|
+
print(f"Plugins are read from these repos' marketplaces ({where}):")
|
|
194
|
+
for repo in cfg.repos:
|
|
195
|
+
print(f" {repo}")
|
|
196
|
+
return 0
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def main(argv: list[str] | None = None) -> int:
|
|
200
|
+
ap = argparse.ArgumentParser(prog="cs-plugin", description=__doc__,
|
|
201
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
202
|
+
ap.add_argument("--version", action="version", version=f"cs-plugin {__version__}")
|
|
203
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
204
|
+
p = sub.add_parser("list", help="every plugin in the sources, with releases")
|
|
205
|
+
p.add_argument("-l", "--long", action="store_true", help="also show descriptions")
|
|
206
|
+
p.set_defaults(fn=cmd_list)
|
|
207
|
+
p = sub.add_parser("versions", help="every release of one plugin, newest first")
|
|
208
|
+
p.add_argument("plugin", metavar="NAME")
|
|
209
|
+
p.add_argument("-l", "--long", action="store_true", help="also link each release")
|
|
210
|
+
p.set_defaults(fn=cmd_versions)
|
|
211
|
+
p = sub.add_parser("add", help="pin plugins, newest release unless NAME@VERSION")
|
|
212
|
+
p.add_argument("plugins", nargs="+", metavar="NAME[@VERSION]")
|
|
213
|
+
p.set_defaults(fn=cmd_add)
|
|
214
|
+
p = sub.add_parser("remove", help="drop plugins from plugins.toml")
|
|
215
|
+
p.add_argument("plugins", nargs="+", metavar="NAME")
|
|
216
|
+
p.set_defaults(fn=cmd_remove)
|
|
217
|
+
p = sub.add_parser("upgrade", help="move pins to the newest release")
|
|
218
|
+
p.add_argument("plugins", nargs="*", metavar="NAME")
|
|
219
|
+
p.set_defaults(fn=cmd_upgrade)
|
|
220
|
+
sub.add_parser("outdated", help="pins with a newer release").set_defaults(fn=cmd_outdated)
|
|
221
|
+
sub.add_parser("generate", help="rewrite the generated files").set_defaults(fn=cmd_generate)
|
|
222
|
+
sub.add_parser("sync", help="install exactly what plugins.toml pins").set_defaults(fn=cmd_sync)
|
|
223
|
+
sub.add_parser("sources", help="the repos plugins are read from").set_defaults(fn=cmd_sources)
|
|
224
|
+
args = ap.parse_args(argv)
|
|
225
|
+
try:
|
|
226
|
+
return args.fn(args)
|
|
227
|
+
except (project.ProjectError, sources.SourceError, remote.RemoteError) as e:
|
|
228
|
+
print(f"cs-plugin: {e}", file=sys.stderr)
|
|
229
|
+
return 1
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
if __name__ == "__main__":
|
|
233
|
+
sys.exit(main())
|
cs_plugin/project.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""A project's plugins.toml, and the files Claude Code reads that are made from it.
|
|
2
|
+
|
|
3
|
+
plugins.toml what you edit
|
|
4
|
+
.claude/cs-plugin/.claude-plugin/marketplace.json
|
|
5
|
+
the project's own marketplace:
|
|
6
|
+
one entry per plugin, pinned
|
|
7
|
+
to its release tag
|
|
8
|
+
.claude/cs-plugin/<project>-set/ a bundle plugin depending on
|
|
9
|
+
every pinned plugin, so one
|
|
10
|
+
install brings in all of them
|
|
11
|
+
.claude/settings.json declares the marketplace and
|
|
12
|
+
enables its plugins
|
|
13
|
+
.gitignore gains .claude/settings.local.json,
|
|
14
|
+
where sync writes this machine's
|
|
15
|
+
path
|
|
16
|
+
|
|
17
|
+
The marketplace is named after the project because Claude Code keeps one
|
|
18
|
+
registration per marketplace name per machine: a name shared by two projects
|
|
19
|
+
would give both whichever pins registered last. With one name per project,
|
|
20
|
+
two projects on one machine can hold different releases of the same plugin.
|
|
21
|
+
|
|
22
|
+
Pins live on the entries, as git refs, not as version ranges on the bundle's
|
|
23
|
+
dependencies: a marketplace is cloned without its tags, so a range has nothing
|
|
24
|
+
to resolve against and silently installs the newest release instead.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import re
|
|
31
|
+
import subprocess
|
|
32
|
+
import tomllib
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
from .remote import tag_for
|
|
37
|
+
from .sources import DEFAULT_SOURCES, ambiguity
|
|
38
|
+
|
|
39
|
+
CONFIG = "plugins.toml"
|
|
40
|
+
GEN_DIR = Path(".claude/cs-plugin")
|
|
41
|
+
SETTINGS = Path(".claude/settings.json")
|
|
42
|
+
LOCAL_SETTINGS = Path(".claude/settings.local.json")
|
|
43
|
+
PIN_KEYS = ("version", "ref", "sha")
|
|
44
|
+
SOURCE_KEYS = ("repo", "url", "path")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ProjectError(Exception):
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def slug(text: str) -> str:
|
|
52
|
+
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
|
53
|
+
if not s:
|
|
54
|
+
raise ProjectError(f"cannot make a project name from {text!r}; set [project] name")
|
|
55
|
+
return s
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class Config:
|
|
60
|
+
name: str
|
|
61
|
+
plugins: dict[str, dict] # name -> {"version": ...} | {"ref"|"sha": ..., source keys}
|
|
62
|
+
# The repos whose marketplaces say which plugins exist; None for the defaults.
|
|
63
|
+
sources: list[str] | None = None
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def repos(self) -> list[str]:
|
|
67
|
+
return list(DEFAULT_SOURCES) if self.sources is None else self.sources
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def marketplace(self) -> str:
|
|
71
|
+
return f"{self.name}-plugins"
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def bundle(self) -> str:
|
|
75
|
+
return f"{self.name}-set"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def load(root: Path) -> Config:
|
|
79
|
+
path = root / CONFIG
|
|
80
|
+
if not path.exists():
|
|
81
|
+
return Config(slug(root.resolve().name), {})
|
|
82
|
+
data = tomllib.loads(path.read_text())
|
|
83
|
+
name = slug(data.get("project", {}).get("name") or root.resolve().name)
|
|
84
|
+
sources = data.get("sources", {}).get("repos")
|
|
85
|
+
if sources is not None and not (isinstance(sources, list)
|
|
86
|
+
and all(isinstance(r, str) for r in sources)):
|
|
87
|
+
raise ProjectError(f'{CONFIG}: [sources] repos must be a list of "owner/name"')
|
|
88
|
+
plugins = {}
|
|
89
|
+
for plugin, spec in data.get("plugins", {}).items():
|
|
90
|
+
spec = {"version": spec} if isinstance(spec, str) else dict(spec)
|
|
91
|
+
pins = [k for k in PIN_KEYS if k in spec]
|
|
92
|
+
if len(pins) != 1:
|
|
93
|
+
raise ProjectError(f"{CONFIG}: {plugin} needs exactly one of "
|
|
94
|
+
f"version, ref or sha; found {pins or 'none'}")
|
|
95
|
+
plugins[plugin] = spec
|
|
96
|
+
return Config(name, plugins, sources)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _toml_value(v: str) -> str:
|
|
100
|
+
return json.dumps(v) # a JSON string is a valid TOML basic string
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def save(root: Path, cfg: Config) -> None:
|
|
104
|
+
lines = [
|
|
105
|
+
"# The Claude Code plugins this project uses, each pinned to a release.",
|
|
106
|
+
"# Managed with cs-plugin (add, remove, upgrade); after editing by hand, run",
|
|
107
|
+
"# `cs-plugin generate`. Teammates run `cs-plugin sync` after cloning.",
|
|
108
|
+
"",
|
|
109
|
+
"[project]",
|
|
110
|
+
f"name = {_toml_value(cfg.name)}",
|
|
111
|
+
"",
|
|
112
|
+
]
|
|
113
|
+
if cfg.sources is not None:
|
|
114
|
+
repos = ", ".join(_toml_value(r) for r in cfg.sources)
|
|
115
|
+
lines += ["[sources]", f"repos = [{repos}]", ""]
|
|
116
|
+
lines.append("[plugins]")
|
|
117
|
+
for plugin in sorted(cfg.plugins):
|
|
118
|
+
spec = cfg.plugins[plugin]
|
|
119
|
+
if set(spec) == {"version"}:
|
|
120
|
+
lines.append(f"{plugin} = {_toml_value(spec['version'])}")
|
|
121
|
+
else:
|
|
122
|
+
inner = ", ".join(f"{k} = {_toml_value(spec[k])}" for k in sorted(spec))
|
|
123
|
+
lines.append(f"{plugin} = {{ {inner} }}")
|
|
124
|
+
(root / CONFIG).write_text("\n".join(lines) + "\n")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def repinned(spec: dict, version: str) -> dict:
|
|
128
|
+
"""`spec` pinned to release `version`, keeping any repo, url or path it names."""
|
|
129
|
+
return {**{k: spec[k] for k in SOURCE_KEYS if k in spec}, "version": version}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def pinned_source(plugin: str, spec: dict, index: dict[str, dict]) -> dict:
|
|
133
|
+
"""The marketplace `source` for one pinned plugin."""
|
|
134
|
+
if any(k in spec for k in SOURCE_KEYS):
|
|
135
|
+
if "repo" in spec:
|
|
136
|
+
source = {"source": "github", "repo": spec["repo"]}
|
|
137
|
+
if "path" in spec:
|
|
138
|
+
source = {"source": "git-subdir", "url": f"https://github.com/{spec['repo']}.git",
|
|
139
|
+
"path": spec["path"]}
|
|
140
|
+
elif "path" in spec:
|
|
141
|
+
source = {"source": "git-subdir", "url": spec["url"], "path": spec["path"]}
|
|
142
|
+
else:
|
|
143
|
+
source = {"source": "url", "url": spec["url"]}
|
|
144
|
+
elif plugin in index:
|
|
145
|
+
why = ambiguity(index[plugin])
|
|
146
|
+
if why:
|
|
147
|
+
raise ProjectError(why)
|
|
148
|
+
source = dict(index[plugin]["source"])
|
|
149
|
+
else:
|
|
150
|
+
raise ProjectError(f"{plugin} is not in any source; give its repo or url in "
|
|
151
|
+
f"{CONFIG}, or check the name with `cs-plugin list`")
|
|
152
|
+
if source.get("source") not in ("github", "url", "git-subdir"):
|
|
153
|
+
raise ProjectError(f"{plugin}: a {source.get('source')!r} source cannot be pinned "
|
|
154
|
+
f"to a git ref")
|
|
155
|
+
for k in ("ref", "sha"):
|
|
156
|
+
source.pop(k, None)
|
|
157
|
+
if "version" in spec:
|
|
158
|
+
source["ref"] = tag_for(plugin, spec["version"])
|
|
159
|
+
elif "ref" in spec:
|
|
160
|
+
source["ref"] = spec["ref"]
|
|
161
|
+
else:
|
|
162
|
+
source["sha"] = spec["sha"]
|
|
163
|
+
return source
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _read(path: Path) -> dict | None:
|
|
167
|
+
return json.loads(path.read_text()) if path.exists() else None
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def bundle_version(previous: dict | None, deps: list[str]) -> str:
|
|
171
|
+
"""The bundle's version: bumped whenever its dependency list changes.
|
|
172
|
+
|
|
173
|
+
Claude Code refreshes an installed plugin only when its version string
|
|
174
|
+
changes, so an unbumped bundle would never pick up an added plugin.
|
|
175
|
+
"""
|
|
176
|
+
if previous is None:
|
|
177
|
+
return "1.0.0"
|
|
178
|
+
if previous.get("dependencies") == deps:
|
|
179
|
+
return previous["version"]
|
|
180
|
+
major, minor, patch = (int(p) for p in previous["version"].split("."))
|
|
181
|
+
return f"{major}.{minor}.{patch + 1}"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def generate(root: Path, cfg: Config, index: dict[str, dict]) -> list[Path]:
|
|
185
|
+
"""Write the marketplace, the bundle and the settings. Returns what changed."""
|
|
186
|
+
hub = root / GEN_DIR
|
|
187
|
+
bundle_manifest = hub / cfg.bundle / ".claude-plugin" / "plugin.json"
|
|
188
|
+
deps = sorted(cfg.plugins)
|
|
189
|
+
# A plugin pinned earlier keeps the source it was pinned from, even after
|
|
190
|
+
# its repo leaves [sources]: the generated marketplace already records it.
|
|
191
|
+
previous = _read(hub / ".claude-plugin" / "marketplace.json") or {}
|
|
192
|
+
index = {**{p["name"]: p for p in previous.get("plugins", []) if p["name"] != cfg.bundle},
|
|
193
|
+
**index}
|
|
194
|
+
entries = []
|
|
195
|
+
for plugin in deps:
|
|
196
|
+
entry = {"name": plugin, "source": pinned_source(plugin, cfg.plugins[plugin], index)}
|
|
197
|
+
if plugin in index and "description" in index[plugin]:
|
|
198
|
+
entry["description"] = index[plugin]["description"]
|
|
199
|
+
entries.append(entry)
|
|
200
|
+
entries.append({
|
|
201
|
+
"name": cfg.bundle, "source": f"./{cfg.bundle}",
|
|
202
|
+
"description": f"Installs every plugin {cfg.name} uses, at the release pinned in "
|
|
203
|
+
f"{CONFIG}. Carries nothing of its own.",
|
|
204
|
+
})
|
|
205
|
+
marketplace = {
|
|
206
|
+
"name": cfg.marketplace,
|
|
207
|
+
"owner": {"name": "cs-plugin"},
|
|
208
|
+
"metadata": {"description": f"The plugins {cfg.name} uses, each pinned to a release. "
|
|
209
|
+
f"Generated from {CONFIG} by cs-plugin; do not edit."},
|
|
210
|
+
"plugins": entries,
|
|
211
|
+
}
|
|
212
|
+
bundle = {
|
|
213
|
+
"name": cfg.bundle,
|
|
214
|
+
"version": bundle_version(_read(bundle_manifest), deps),
|
|
215
|
+
"description": f"Every plugin {cfg.name} uses, as pinned in {CONFIG}.",
|
|
216
|
+
"dependencies": deps,
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
settings_path = root / SETTINGS
|
|
220
|
+
settings = _read(settings_path) or {}
|
|
221
|
+
known = settings.setdefault("extraKnownMarketplaces", {})
|
|
222
|
+
# Relative, so the committed file works in every clone. `claude plugin
|
|
223
|
+
# marketplace add` would write an absolute path here; sync registers the
|
|
224
|
+
# marketplace at local scope instead, which leaves this entry alone.
|
|
225
|
+
known[cfg.marketplace] = {"source": {"source": "directory", "path": f"./{GEN_DIR.as_posix()}"}}
|
|
226
|
+
enabled = settings.setdefault("enabledPlugins", {})
|
|
227
|
+
for key in [k for k in enabled if k.endswith(f"@{cfg.marketplace}")]:
|
|
228
|
+
del enabled[key]
|
|
229
|
+
for plugin in [*deps, cfg.bundle]:
|
|
230
|
+
enabled[f"{plugin}@{cfg.marketplace}"] = True
|
|
231
|
+
|
|
232
|
+
changed = [p for p in [ignore_local_settings(root)] if p]
|
|
233
|
+
for path, doc in ((hub / ".claude-plugin" / "marketplace.json", marketplace),
|
|
234
|
+
(bundle_manifest, bundle), (settings_path, settings)):
|
|
235
|
+
text = json.dumps(doc, indent=2) + "\n"
|
|
236
|
+
if not path.exists() or path.read_text() != text:
|
|
237
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
238
|
+
path.write_text(text)
|
|
239
|
+
changed.append(path)
|
|
240
|
+
return changed
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def restore_layout(path: Path, before: str | None) -> bool:
|
|
244
|
+
"""Put back `before` when the file now holds the same settings, reordered.
|
|
245
|
+
|
|
246
|
+
Installing a plugin makes Claude Code rewrite .claude/settings.json with its
|
|
247
|
+
known keys in its own order, so a sync that changed nothing would still show
|
|
248
|
+
the committed file as modified. A real change to the content is left alone.
|
|
249
|
+
"""
|
|
250
|
+
if before is None or not path.exists():
|
|
251
|
+
return False
|
|
252
|
+
now = path.read_text()
|
|
253
|
+
if now == before:
|
|
254
|
+
return False
|
|
255
|
+
try:
|
|
256
|
+
same = json.loads(now) == json.loads(before)
|
|
257
|
+
except json.JSONDecodeError:
|
|
258
|
+
return False
|
|
259
|
+
if same:
|
|
260
|
+
path.write_text(before)
|
|
261
|
+
return same
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def ignore_local_settings(root: Path) -> Path | None:
|
|
265
|
+
"""Make the project's own .gitignore cover .claude/settings.local.json.
|
|
266
|
+
|
|
267
|
+
sync registers the marketplace at local scope, which writes this machine's
|
|
268
|
+
absolute path into that file. Only the repo's rules count: a rule in one
|
|
269
|
+
person's global excludes file does not stop a teammate committing it.
|
|
270
|
+
"""
|
|
271
|
+
if not (root / ".git").exists():
|
|
272
|
+
return None
|
|
273
|
+
out = subprocess.run(["git", "-c", "core.excludesFile=/dev/null", "check-ignore", "-q",
|
|
274
|
+
LOCAL_SETTINGS.as_posix()], cwd=root, capture_output=True)
|
|
275
|
+
if out.returncode == 0:
|
|
276
|
+
return None
|
|
277
|
+
gitignore = root / ".gitignore"
|
|
278
|
+
text = gitignore.read_text() if gitignore.exists() else ""
|
|
279
|
+
gitignore.write_text(text + ("" if not text or text.endswith("\n") else "\n")
|
|
280
|
+
+ f"{LOCAL_SETTINGS.as_posix()}\n")
|
|
281
|
+
return gitignore
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def stale(root: Path, cfg: Config) -> list[str]:
|
|
285
|
+
"""How the generated marketplace disagrees with plugins.toml, offline."""
|
|
286
|
+
market = _read(root / GEN_DIR / ".claude-plugin" / "marketplace.json")
|
|
287
|
+
if market is None:
|
|
288
|
+
return [f"{GEN_DIR}/.claude-plugin/marketplace.json does not exist"]
|
|
289
|
+
problems = []
|
|
290
|
+
if market.get("name") != cfg.marketplace:
|
|
291
|
+
problems.append(f"marketplace is named {market.get('name')!r}, expected {cfg.marketplace!r}")
|
|
292
|
+
listed = {p["name"]: p["source"] for p in market.get("plugins", []) if p["name"] != cfg.bundle}
|
|
293
|
+
for plugin, spec in cfg.plugins.items():
|
|
294
|
+
source = listed.get(plugin)
|
|
295
|
+
if source is None:
|
|
296
|
+
problems.append(f"{plugin} is in {CONFIG} but not in the marketplace")
|
|
297
|
+
continue
|
|
298
|
+
want = (("ref", tag_for(plugin, spec["version"])) if "version" in spec
|
|
299
|
+
else ("ref", spec["ref"]) if "ref" in spec else ("sha", spec["sha"]))
|
|
300
|
+
if source.get(want[0]) != want[1]:
|
|
301
|
+
problems.append(f"{plugin}: marketplace pins {source.get('ref') or source.get('sha')}, "
|
|
302
|
+
f"{CONFIG} pins {want[1]}")
|
|
303
|
+
for plugin in listed.keys() - cfg.plugins.keys():
|
|
304
|
+
problems.append(f"{plugin} is in the marketplace but not in {CONFIG}")
|
|
305
|
+
return problems
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def sync_plan(cfg: Config, installed: dict[str, str]) -> list[list[str]]:
|
|
309
|
+
"""`claude plugin` commands that make this project's installs match the pins.
|
|
310
|
+
|
|
311
|
+
`installed` maps plugin name to version, for this project's installs from its
|
|
312
|
+
own marketplace. Updating the bundle does not move its dependencies, so each
|
|
313
|
+
pinned plugin already installed is updated on its own; an update to the
|
|
314
|
+
version already installed is a no-op.
|
|
315
|
+
"""
|
|
316
|
+
m, scope = cfg.marketplace, ["--scope", "project"]
|
|
317
|
+
plan = []
|
|
318
|
+
verb = "update" if cfg.bundle in installed else "install"
|
|
319
|
+
plan.append(["plugin", verb, f"{cfg.bundle}@{m}", *scope])
|
|
320
|
+
for plugin in sorted(cfg.plugins):
|
|
321
|
+
if plugin in installed:
|
|
322
|
+
plan.append(["plugin", "update", f"{plugin}@{m}", *scope])
|
|
323
|
+
elif verb == "update":
|
|
324
|
+
# Added since the bundle was installed: the bundle update does not
|
|
325
|
+
# install new dependencies either.
|
|
326
|
+
plan.append(["plugin", "install", f"{plugin}@{m}", *scope])
|
|
327
|
+
for plugin in sorted(installed.keys() - cfg.plugins.keys() - {cfg.bundle}):
|
|
328
|
+
plan.append(["plugin", "uninstall", f"{plugin}@{m}", *scope])
|
|
329
|
+
return plan
|
cs_plugin/releases.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Which release of a plugin to use: read from its repo's tags, checked before pinning.
|
|
2
|
+
|
|
3
|
+
The commands that choose a release -- add, versions, outdated, upgrade -- all
|
|
4
|
+
decide here, so they agree on where a plugin lives and what counts as released.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
10
|
+
|
|
11
|
+
from . import project, remote, sources
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def newest_first(entries: list[dict]) -> dict[str, list[str] | None]:
|
|
15
|
+
"""Released versions per plugin, None where the source has no git tags."""
|
|
16
|
+
def one(entry: dict) -> tuple[str, list[str] | None]:
|
|
17
|
+
url = remote.git_url(entry["source"])
|
|
18
|
+
return entry["name"], (remote.versions(url, entry["name"]) if url else None)
|
|
19
|
+
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
20
|
+
return dict(pool.map(one, entries))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def entry(name: str, cat: dict[str, dict]) -> dict:
|
|
24
|
+
"""A plugin's index entry, when its name alone says where it is."""
|
|
25
|
+
found = cat.get(name)
|
|
26
|
+
if found is None:
|
|
27
|
+
raise project.ProjectError(f"{name} is not in any source; see `cs-plugin list`")
|
|
28
|
+
why = sources.ambiguity(found)
|
|
29
|
+
if why:
|
|
30
|
+
raise project.ProjectError(why)
|
|
31
|
+
return found
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def source_of(name: str, spec: dict, cat: dict[str, dict]) -> tuple[dict, str]:
|
|
35
|
+
"""Where a plugin's releases are read from, and the repo to name for it.
|
|
36
|
+
|
|
37
|
+
A plugin pinned by its repo or url is read from there, as sync would.
|
|
38
|
+
"""
|
|
39
|
+
if any(k in spec for k in project.SOURCE_KEYS):
|
|
40
|
+
return project.pinned_source(name, spec, cat), spec.get("repo") or spec["url"]
|
|
41
|
+
found = entry(name, cat)
|
|
42
|
+
return found["source"], found["repo"]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def released(name: str, source: dict) -> list[str]:
|
|
46
|
+
"""A plugin's released versions, newest first; an error if there are none."""
|
|
47
|
+
url = remote.git_url(source)
|
|
48
|
+
found = remote.versions(url, name) if url else []
|
|
49
|
+
if not found:
|
|
50
|
+
raise project.ProjectError(
|
|
51
|
+
f"{name} has no releases (no {name}--v* tags in its repo). Pin it to a commit "
|
|
52
|
+
f"in {project.CONFIG} instead: {name} = {{ sha = \"<40-char commit>\" }}")
|
|
53
|
+
return found
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def resolve(name: str, version: str | None, cat: dict[str, dict],
|
|
57
|
+
spec: dict | None = None) -> str:
|
|
58
|
+
"""The release `add` pins: `version`, or the newest, checked to exist.
|
|
59
|
+
|
|
60
|
+
`spec` is the plugin's current pin, if any: one naming a repo or url is
|
|
61
|
+
resolved against that, not the sources.
|
|
62
|
+
"""
|
|
63
|
+
source, _ = source_of(name, spec or {}, cat)
|
|
64
|
+
found = released(name, source)
|
|
65
|
+
version = version or found[0]
|
|
66
|
+
if version not in found:
|
|
67
|
+
more = f"; all of them: `cs-plugin versions {name}`" if len(found) > 10 else ""
|
|
68
|
+
raise project.ProjectError(f"{name} {version} is not released; releases: "
|
|
69
|
+
+ ", ".join(found[:10]) + more)
|
|
70
|
+
deps = (remote.manifest(source, remote.tag_for(name, version)) or {}).get("dependencies")
|
|
71
|
+
if deps:
|
|
72
|
+
# Its dependencies name another marketplace, which Claude Code would
|
|
73
|
+
# install from at whatever that marketplace holds -- unpinned, and shared
|
|
74
|
+
# with every other project on the machine.
|
|
75
|
+
names = [d if isinstance(d, str) else d["name"] for d in deps]
|
|
76
|
+
names = [n.split("@", 1)[0] for n in names]
|
|
77
|
+
raise project.ProjectError(
|
|
78
|
+
f"{name} {version} is a bundle of {', '.join(names)}; its dependencies "
|
|
79
|
+
f"would install outside this project's pins. Add those instead:\n"
|
|
80
|
+
f" cs-plugin add {' '.join(names)}")
|
|
81
|
+
return version
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def behind(cfg: project.Config, cat: dict[str, dict],
|
|
85
|
+
names: list[str] | None) -> list[tuple[str, str, str]]:
|
|
86
|
+
"""(name, pinned, newest) for each version pin with a newer release."""
|
|
87
|
+
pinned = {n: s for n, s in cfg.plugins.items() if "version" in s and (not names or n in names)}
|
|
88
|
+
entries = [{"name": n, "source": project.pinned_source(n, s, cat)} for n, s in pinned.items()]
|
|
89
|
+
found = newest_first(entries)
|
|
90
|
+
return [(n, pinned[n]["version"], found[n][0]) for n in sorted(pinned)
|
|
91
|
+
if found[n] and remote.semver(found[n][0]) > remote.semver(pinned[n]["version"])]
|
cs_plugin/remote.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Reading other repos: their marketplace.json, and their plugin release tags.
|
|
2
|
+
|
|
3
|
+
Releases are read from tags, never from a stored list, so a release in any
|
|
4
|
+
source repo is visible the moment its tag is pushed. Tags are listed with
|
|
5
|
+
`git ls-remote`, which needs no API token and has no rate limit for public repos.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
import subprocess
|
|
13
|
+
import urllib.request
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
VERSION = re.compile(r"^\d+(\.\d+)*$")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RemoteError(Exception):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def read_json(location: str) -> dict:
|
|
24
|
+
"""A JSON document from an https URL or a local path."""
|
|
25
|
+
if location.startswith(("https://", "http://")):
|
|
26
|
+
try:
|
|
27
|
+
with urllib.request.urlopen(location, timeout=30) as r:
|
|
28
|
+
return json.load(r)
|
|
29
|
+
except OSError as e:
|
|
30
|
+
raise RemoteError(f"cannot fetch {location}: {e}") from e
|
|
31
|
+
try:
|
|
32
|
+
return json.loads(Path(location).read_text())
|
|
33
|
+
except OSError as e:
|
|
34
|
+
raise RemoteError(f"cannot read {location}: {e}") from e
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def semver(v: str) -> tuple[int, ...]:
|
|
38
|
+
return tuple(int(p) for p in v.split("."))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def tag_for(plugin: str, version: str) -> str:
|
|
42
|
+
"""The tag `claude plugin tag` writes for a plugin release."""
|
|
43
|
+
return f"{plugin}--v{version}"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def git_url(source: dict) -> str | None:
|
|
47
|
+
"""The git URL a index source fetches from, or None for a non-git source."""
|
|
48
|
+
if source.get("source") == "github":
|
|
49
|
+
return f"https://github.com/{source['repo']}.git"
|
|
50
|
+
if source.get("source") in ("url", "git-subdir"):
|
|
51
|
+
return source["url"]
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def release_url(source: dict, plugin: str, version: str) -> str | None:
|
|
56
|
+
"""The GitHub page of a plugin release, or None for a repo not on GitHub.
|
|
57
|
+
|
|
58
|
+
GitHub serves this page for a bare tag too, so it exists even where no
|
|
59
|
+
GitHub Release was cut for the tag.
|
|
60
|
+
"""
|
|
61
|
+
url = git_url(source) or ""
|
|
62
|
+
if not url.startswith("https://github.com/"):
|
|
63
|
+
return None
|
|
64
|
+
return f"{url.removesuffix('.git')}/releases/tag/{tag_for(plugin, version)}"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def manifest(source: dict, ref: str) -> dict | None:
|
|
68
|
+
"""A plugin's plugin.json at `ref`, or None where it cannot be read cheaply.
|
|
69
|
+
|
|
70
|
+
Only GitHub-hosted sources are read, through raw.githubusercontent.com: the
|
|
71
|
+
one host that serves a single file at a ref without a clone.
|
|
72
|
+
"""
|
|
73
|
+
url = git_url(source) or ""
|
|
74
|
+
if not url.startswith("https://github.com/"):
|
|
75
|
+
return None
|
|
76
|
+
repo = url.removeprefix("https://github.com/").removesuffix(".git")
|
|
77
|
+
path = source.get("path", ".").strip("/")
|
|
78
|
+
try:
|
|
79
|
+
return read_json(f"https://raw.githubusercontent.com/{repo}/{ref}/{path}/"
|
|
80
|
+
".claude-plugin/plugin.json")
|
|
81
|
+
except RemoteError:
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def versions(url: str, plugin: str) -> list[str]:
|
|
86
|
+
"""Released versions of `plugin` in the repo at `url`, newest first."""
|
|
87
|
+
out = subprocess.run(
|
|
88
|
+
["git", "ls-remote", "--tags", "--refs", url, f"refs/tags/{plugin}--v*"],
|
|
89
|
+
capture_output=True, text=True)
|
|
90
|
+
if out.returncode != 0:
|
|
91
|
+
raise RemoteError(f"cannot list tags of {url}: {out.stderr.strip()}")
|
|
92
|
+
prefix = f"refs/tags/{plugin}--v"
|
|
93
|
+
found = [line.split("\t", 1)[1][len(prefix):] for line in out.stdout.splitlines()]
|
|
94
|
+
# A pre-release or a malformed tag is not offered; pin it by `ref` if wanted.
|
|
95
|
+
return sorted((v for v in found if VERSION.match(v)), key=semver, reverse=True)
|
cs_plugin/sources.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Which plugins exist: read live from the plugin repos' own marketplaces.
|
|
2
|
+
|
|
3
|
+
Each source repo keeps a .claude-plugin/marketplace.json at its root, and that
|
|
4
|
+
file is the only list of its plugins -- nothing is copied anywhere. A plugin a
|
|
5
|
+
source lists by relative path is seen from outside as a `git-subdir` entry
|
|
6
|
+
pointing back into its repo. Versions are not read here: releases come from
|
|
7
|
+
each repo's `<plugin>--v<version>` tags, when they are needed.
|
|
8
|
+
|
|
9
|
+
A project names its sources in plugins.toml; without that, DEFAULT_SOURCES.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import posixpath
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
17
|
+
|
|
18
|
+
from .remote import RemoteError
|
|
19
|
+
|
|
20
|
+
DEFAULT_SOURCES = (
|
|
21
|
+
"Cellular-Semantics/cap_skills",
|
|
22
|
+
"Cellular-Semantics/atlas-skills",
|
|
23
|
+
)
|
|
24
|
+
# Plugin manifest fields worth showing in `list`; the rest stay in the source.
|
|
25
|
+
CARRIED = ("description", "homepage", "category")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SourceError(Exception):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def marketplace_url(repo: str) -> str:
|
|
33
|
+
ref = "HEAD"
|
|
34
|
+
if "@" in repo:
|
|
35
|
+
repo, ref = repo.split("@", 1)
|
|
36
|
+
return (f"https://raw.githubusercontent.com/{repo}/{ref}/"
|
|
37
|
+
".claude-plugin/marketplace.json")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def entry_source(repo: str, marketplace: dict, source: str | dict) -> dict:
|
|
41
|
+
"""A plugin's source as seen from outside its repo."""
|
|
42
|
+
if isinstance(source, dict):
|
|
43
|
+
return dict(source)
|
|
44
|
+
root = marketplace.get("metadata", {}).get("pluginRoot", "")
|
|
45
|
+
rel = source if source.startswith("./") else posixpath.join(root or ".", source)
|
|
46
|
+
return {"source": "git-subdir", "url": f"https://github.com/{repo.split('@')[0]}.git",
|
|
47
|
+
"path": posixpath.normpath(rel)}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def index(repos: list[str], fetch: Callable[[str], dict]) -> dict[str, dict]:
|
|
51
|
+
"""Every plugin in every source, by name: {name, source, repo, description...}."""
|
|
52
|
+
def one(repo: str) -> tuple[str, dict]:
|
|
53
|
+
try:
|
|
54
|
+
return repo, fetch(marketplace_url(repo))
|
|
55
|
+
except RemoteError as e:
|
|
56
|
+
raise SourceError(f"source {repo}: {e}") from e
|
|
57
|
+
|
|
58
|
+
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
59
|
+
markets = list(pool.map(one, repos))
|
|
60
|
+
plugins: dict[str, dict] = {}
|
|
61
|
+
for repo, market in markets:
|
|
62
|
+
for p in market.get("plugins", []):
|
|
63
|
+
name = p["name"]
|
|
64
|
+
if name in plugins:
|
|
65
|
+
# Not fatal for the other plugins: only using this name is.
|
|
66
|
+
plugins[name].setdefault("also_in", []).append(repo)
|
|
67
|
+
continue
|
|
68
|
+
entry = {"name": name, "repo": repo,
|
|
69
|
+
"source": entry_source(repo, market, p["source"])}
|
|
70
|
+
entry.update({k: p[k] for k in CARRIED if k in p})
|
|
71
|
+
plugins[name] = entry
|
|
72
|
+
return plugins
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def ambiguity(entry: dict) -> str | None:
|
|
76
|
+
"""Why a plugin name cannot be pinned by name alone, or None."""
|
|
77
|
+
if not entry.get("also_in"):
|
|
78
|
+
return None
|
|
79
|
+
repos = " and ".join([entry["repo"], *entry["also_in"]])
|
|
80
|
+
return (f"{entry['name']} is in both {repos}; pin it with an explicit repo in "
|
|
81
|
+
f"plugins.toml, e.g. {entry['name']} = {{ repo = \"{entry['repo']}\", "
|
|
82
|
+
f"path = \"{entry['source'].get('path', '.')}\", version = \"...\" }}")
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cs-plugin
|
|
3
|
+
Version: 0.1.5
|
|
4
|
+
Summary: Pin a project's Claude Code plugins, from any number of plugin repos, in one plugins.toml; generate the project's own marketplace from it, and install exactly that.
|
|
5
|
+
Author: Cellular Semantics
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ubyndr/cs-plugin
|
|
8
|
+
Project-URL: Repository, https://github.com/ubyndr/cs-plugin
|
|
9
|
+
Project-URL: Issues, https://github.com/ubyndr/cs-plugin/issues
|
|
10
|
+
Keywords: claude-code,claude,plugins,marketplace,version-pinning
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Software Development
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest>=8.0; extra == "test"
|
|
25
|
+
|
|
26
|
+
# cs-plugin
|
|
27
|
+
|
|
28
|
+
Pin a project's Claude Code plugins in one `plugins.toml`, like `pyproject.toml`,
|
|
29
|
+
from any number of plugin repos, and install exactly that.
|
|
30
|
+
|
|
31
|
+
Two projects on one machine can use different releases of the same plugin, and a
|
|
32
|
+
teammate's whole setup after cloning is one command.
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
uvx cs-plugin list # what is available
|
|
36
|
+
uvx cs-plugin add cap-tools remote-h5ad-obs # pin the newest releases
|
|
37
|
+
uvx cs-plugin sync # install them in this project
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Needs [uv](https://docs.astral.sh/uv/) (or `pipx run cs-plugin`), `git`, and
|
|
41
|
+
Claude Code for `sync`. `uv tool install cs-plugin` puts `cs-plugin` on your PATH
|
|
42
|
+
so you can drop the `uvx`.
|
|
43
|
+
|
|
44
|
+
## See what is available
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
cs-plugin list # every plugin in the source repos, and its newest release
|
|
48
|
+
cs-plugin list -l # with descriptions
|
|
49
|
+
cs-plugin versions cap-tools # every release of one plugin, newest first
|
|
50
|
+
cs-plugin versions -l cap-tools # with a link to each release
|
|
51
|
+
cs-plugin sources # which repos those are
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Plugins are read live from each source repo's own
|
|
55
|
+
`.claude-plugin/marketplace.json`, and releases from its `<plugin>--v<version>`
|
|
56
|
+
tags (what `claude plugin tag` writes). A release anywhere shows up at once.
|
|
57
|
+
`versions` marks the release this project pins, and works before you `add`,
|
|
58
|
+
so you can pick an older release to pin with `cs-plugin add NAME@VERSION`.
|
|
59
|
+
|
|
60
|
+
## Set up a project
|
|
61
|
+
|
|
62
|
+
From the project's root:
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
cs-plugin add cap-tools remote-h5ad-obs # newest releases
|
|
66
|
+
cs-plugin add onto-mapping@0.5.0 # or a specific one
|
|
67
|
+
cs-plugin sync # install them
|
|
68
|
+
git add plugins.toml .claude .gitignore && git commit -m "Pin Claude Code plugins"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`plugins.toml` is the file you read and edit:
|
|
72
|
+
|
|
73
|
+
```toml
|
|
74
|
+
[project]
|
|
75
|
+
name = "cap-report-hacking"
|
|
76
|
+
|
|
77
|
+
[plugins]
|
|
78
|
+
cap-tools = "0.4.1"
|
|
79
|
+
remote-h5ad-obs = "0.3.0"
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
A plugin with no release tags can be pinned to a commit instead, and a plugin
|
|
83
|
+
in no source repo by its repo:
|
|
84
|
+
|
|
85
|
+
```toml
|
|
86
|
+
some-plugin = { sha = "22a10275db2768304021549cd8300bc05a704b42" }
|
|
87
|
+
other = { repo = "someone/their-plugins", path = "plugins/other", version = "1.2.0" }
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
To read plugins from other repos than the defaults, list them all (this replaces
|
|
91
|
+
the defaults; `owner/name@ref` reads a branch or tag instead of the default
|
|
92
|
+
branch):
|
|
93
|
+
|
|
94
|
+
```toml
|
|
95
|
+
[sources]
|
|
96
|
+
repos = ["Cellular-Semantics/cap_skills", "your-org/your-plugins"]
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
After editing `plugins.toml` by hand, run `cs-plugin generate`.
|
|
100
|
+
|
|
101
|
+
## After cloning, or pulling a change to plugins.toml
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
cs-plugin sync
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Then restart Claude Code in the project. `sync` reads no source repo: everything
|
|
108
|
+
it installs is already written in the committed files.
|
|
109
|
+
|
|
110
|
+
## Keep up to date
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
cs-plugin outdated # pins with a newer release
|
|
114
|
+
cs-plugin upgrade # move every pin to the newest release
|
|
115
|
+
cs-plugin upgrade cap-tools # or just one
|
|
116
|
+
cs-plugin remove cap-tools # sync then uninstalls it here
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Each of these rewrites the generated files; run `sync`, then commit.
|
|
120
|
+
|
|
121
|
+
## What it writes, and why
|
|
122
|
+
|
|
123
|
+
| File | What it is |
|
|
124
|
+
|---|---|
|
|
125
|
+
| `plugins.toml` | what you edit |
|
|
126
|
+
| `.claude/cs-plugin/.claude-plugin/marketplace.json` | the project's own marketplace, `<project>-plugins`: one entry per plugin, its `source` pinned to the release tag |
|
|
127
|
+
| `.claude/cs-plugin/<project>-set/` | a bundle plugin that depends on every pinned plugin, so one install brings in all of them |
|
|
128
|
+
| `.claude/settings.json` | declares the marketplace and enables its plugins; other settings are left alone |
|
|
129
|
+
| `.gitignore` | gains `.claude/settings.local.json`, where `sync` records this machine's path |
|
|
130
|
+
|
|
131
|
+
**A marketplace per project.** Claude Code keeps one registration per
|
|
132
|
+
marketplace name per machine. Pinning by putting a `ref` on a shared marketplace
|
|
133
|
+
means every project on the machine gets whichever pin registered last. A
|
|
134
|
+
marketplace named after the project is that project's alone.
|
|
135
|
+
|
|
136
|
+
**Pins on the entries, not version ranges.** Claude Code clones a marketplace
|
|
137
|
+
without its tags, so a dependency range like `~0.4.0` has nothing to resolve
|
|
138
|
+
against and silently installs the newest release (Claude Code 2.1.305).
|
|
139
|
+
|
|
140
|
+
**Bundles are refused.** A plugin such as `atlas-tools` that only depends on
|
|
141
|
+
others names their marketplace, so they would install from it unpinned and
|
|
142
|
+
shared. `add` refuses it and names the plugins to add instead.
|
|
143
|
+
|
|
144
|
+
**Browsing inside Claude Code.** Each source repo is itself a marketplace:
|
|
145
|
+
`claude plugin marketplace add Cellular-Semantics/cap_skills` lets `/plugin`
|
|
146
|
+
show its plugins. Browse there, but install with `cs-plugin`; installing from
|
|
147
|
+
the shared marketplace gives an unpinned plugin, shared by every project.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
cs_plugin/__init__.py,sha256=K5r8yyWM0gDCrhBLZMjQMoH-7eErjhF124yhfXWP0dM,108
|
|
2
|
+
cs_plugin/claude.py,sha256=gdO8sZm2LMXs4wtbWxMNFemNw1eGK8OTPjEPgndJ2WM,1077
|
|
3
|
+
cs_plugin/cli.py,sha256=K4giALP6CG743uyC5Uvsk4bOVWTbQVvsrXjzbqrCQ2Y,9849
|
|
4
|
+
cs_plugin/project.py,sha256=trUmlHsLavT1m9FKbyM4T7ILD26Qfv6DcG8KzsA6hH8,14243
|
|
5
|
+
cs_plugin/releases.py,sha256=PfHEuN_giu5-4aqzr2ZRX-VHCr5PC_N73DJ4vyvwDWQ,4119
|
|
6
|
+
cs_plugin/remote.py,sha256=Z4biPWOXx_fNpByeqkWIygB_48DupyDYWg8pUM_lXBQ,3437
|
|
7
|
+
cs_plugin/sources.py,sha256=vtRpTgcSAhMDCNyE_NQ91_deq15ZugM9BHQmKJZceoQ,3210
|
|
8
|
+
cs_plugin-0.1.5.dist-info/METADATA,sha256=D-oiMStRDqZsV-2Q_giPn5ZLcUk5K1mI7JcjMJVY7zI,5785
|
|
9
|
+
cs_plugin-0.1.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
cs_plugin-0.1.5.dist-info/entry_points.txt,sha256=DogW3jmvONL7btFuI7WOBLPAbUwIbWBlKUtqgYq9_fQ,49
|
|
11
|
+
cs_plugin-0.1.5.dist-info/top_level.txt,sha256=VwHvKiP3XUJxIeDir82j1SHJWk_XiptSISqYk3LYs7w,10
|
|
12
|
+
cs_plugin-0.1.5.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cs_plugin
|