-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync
More file actions
executable file
·447 lines (367 loc) · 14.1 KB
/
Copy pathsync
File metadata and controls
executable file
·447 lines (367 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = ["pyyaml"]
# ///
"""Sync skills, agents and commands to local AI tool config directories."""
import filecmp
import os
import shutil
import subprocess
import sys
from pathlib import Path
import yaml
REPO_DIR = Path(__file__).resolve().parent
CONFIG_FILE = REPO_DIR / "sync.yaml"
EXAMPLE_FILE = REPO_DIR / "sync.yaml.example"
# Content types synced. Each is a subdirectory of the same name inside
# every source root (this repo, plus any `sources:` entries in sync.yaml).
CONTENT_TYPES = ("skills", "agents", "commands")
TYPE_LETTER = {"skills": "s", "agents": "a", "commands": "c"}
USAGE = """\
Usage:
./sync # configured full sync (uses sync.yaml targets)
./sync pick --to PATH # interactive multi-select copy into PATH/<type>/
./sync preset NAME --to PATH # copy a named bundle into PATH/<type>/
Flags (any mode):
--dry-run preview only
--force overwrite without prompting
PATH is the base — items land in PATH/skills/<name>, PATH/agents/<name>, etc.
"""
def load_config() -> dict:
if not CONFIG_FILE.exists():
print(f"No sync.yaml found. Copy the example to get started:")
print(f" cp {EXAMPLE_FILE.name} {CONFIG_FILE.name}")
sys.exit(1)
with open(CONFIG_FILE) as f:
return yaml.safe_load(f)
def load_config_optional() -> dict:
"""Like load_config, but an absent sync.yaml just means defaults."""
if not CONFIG_FILE.exists():
return {}
with open(CONFIG_FILE) as f:
return yaml.safe_load(f) or {}
def expand_path(p: str) -> Path:
return Path(os.path.expanduser(p))
def source_roots(config: dict) -> list[Path]:
"""This repo first, then any extra `sources:` roots from sync.yaml."""
roots = [REPO_DIR]
for entry in config.get("sources") or []:
root = expand_path(entry)
if not root.is_dir():
print(f"⚠ source '{entry}' not found — skipping")
continue
roots.append(root)
return roots
def collect_items(config: dict) -> dict[str, dict[str, Path]]:
"""Map content type -> {name: source path} across all source roots.
The first root to provide a name wins (so this repo's own copy beats
an external source's); shadowed duplicates are reported so collisions
stay visible.
"""
items: dict[str, dict[str, Path]] = {ct: {} for ct in CONTENT_TYPES}
for root in source_roots(config):
for content_type in CONTENT_TYPES:
subdir = root / content_type
if not subdir.is_dir():
continue
for item in sorted(subdir.iterdir()):
if item.name.startswith("."):
continue
existing = items[content_type].get(item.name)
if existing is not None:
print(
f"⚠ {content_type}/{item.name}: using {existing}, "
f"ignoring the copy in {root}"
)
continue
items[content_type][item.name] = item
return items
def newest_mtime(path: Path) -> float:
"""Return the newest mtime of a file or any file within a directory."""
if path.is_file():
return path.stat().st_mtime
if path.is_dir():
mtimes = [f.stat().st_mtime for f in path.rglob("*") if f.is_file()]
return max(mtimes) if mtimes else 0
return 0
def show_diff(src: Path, dest: Path) -> None:
"""Show a diff between source and destination."""
try:
result = subprocess.run(
["diff", "-ru", str(src), str(dest)],
capture_output=True,
text=True,
)
print(result.stdout if result.stdout else " (no text differences)")
except FileNotFoundError:
print(" (diff not available)")
def ask_user(prompt: str, src: Path | None = None, dest: Path | None = None) -> bool:
"""Prompt the user. Returns True to overwrite, False to skip. Ctrl-C exits."""
while True:
try:
hint = "[y/N/d]" if src else "[y/N]"
answer = input(f" {prompt} {hint} ").strip().lower()
except (EOFError, KeyboardInterrupt):
print("\nAborted.")
sys.exit(130)
if answer in ("d", "diff") and src and dest:
show_diff(src, dest)
continue
return answer in ("y", "yes")
def ignored_names(config: dict, global_config: dict, content_type: str) -> set[str]:
"""Build the set of ignored names for a content type (global + per-target)."""
global_ignores = global_config.get("ignore", {}).get(content_type, []) or []
target_ignores = config.get("ignore", {}).get(content_type, []) or []
return set(global_ignores) | set(target_ignores)
def _sync_file(src: Path, dest: Path, force: bool = False) -> str:
"""Sync a single file. Returns a status string."""
if dest.exists():
# Identical files need no action; differing files may contain local edits.
if filecmp.cmp(src, dest, shallow=False):
return "unchanged"
if not force:
print(f" ⚠ {dest} differs from source")
if not ask_user("Overwrite with source version?", src, dest):
return "skipped (destination differs)"
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
return "synced"
def sync_item(src: Path, dest: Path, force: bool = False) -> str:
"""Sync a single file or directory. Returns a status string."""
if not src.exists():
return "missing"
if src.is_file():
return _sync_file(src, dest, force)
# For directories, merge by syncing each source file individually
# (preserves any user-added files in the destination)
statuses = []
for src_file in sorted(src.rglob("*")):
if not src_file.is_file():
continue
dest_file = dest / src_file.relative_to(src)
statuses.append(_sync_file(src_file, dest_file, force))
if not statuses:
return "unchanged"
if any("skipped" in s for s in statuses):
if any(s == "synced" for s in statuses):
return "partially synced (some files skipped)"
return "skipped (destination differs)"
if any(s == "synced" for s in statuses):
return "synced"
return "unchanged"
def sync_target(
name: str,
config: dict,
global_config: dict,
items: dict[str, dict[str, Path]],
skipped: list,
force: bool = False,
) -> None:
print(f"\n📁 {name}")
for content_type in CONTENT_TYPES:
dest_base_str = config.get(content_type)
if not dest_base_str:
continue
dest_base = expand_path(dest_base_str)
dest_base.mkdir(parents=True, exist_ok=True)
ignores = ignored_names(config, global_config, content_type)
for item_name, src in sorted(items[content_type].items()):
if item_name in ignores:
print(f" ⊘ {content_type}/{item_name} → ignored")
continue
dest = dest_base / item_name
status = sync_item(src, dest, force=force)
if status == "unchanged":
print(f" → {content_type}/{item_name} unchanged")
continue
icon = "✓" if status == "synced" else "⊘"
print(f" {icon} {content_type}/{item_name} → {status}")
if "skipped" in status:
skipped.append((dest, src))
def apply_picks(
chosen: list[tuple[str, str, Path]],
to: Path,
force: bool,
dry_run: bool = False,
) -> None:
if not chosen:
print("Nothing to copy.")
return
if dry_run:
print(f"\nDry run — would copy {len(chosen)} item(s) to {to}:\n")
for ct, name, _ in chosen:
dest = to / ct / name
exists = "exists" if dest.exists() else "new"
print(f" {ct}/{name} → {dest} ({exists})")
return
print(f"\nCopying {len(chosen)} item(s) to {to}:\n")
skipped: list[tuple[Path, Path]] = []
for ct, name, src in chosen:
dest = to / ct / name
status = sync_item(src, dest, force=force)
icon = "✓" if status == "synced" else ("→" if status == "unchanged" else "⊘")
print(f" {icon} {ct}/{name} → {status}")
if "skipped" in status:
skipped.append((dest, src))
if skipped:
print("\n⚠ Skipped (destination differs from source):")
for dest, src in skipped:
print(f" {dest}")
print(f" ← repo: {src}")
print("\nDone.")
FZF_PREVIEW = (
"if [ -d {2} ]; then "
"cat {2}/SKILL.md 2>/dev/null | head -80; "
"else cat {2} 2>/dev/null | head -80; fi"
)
def picker_mode(
items_map: dict[str, dict[str, Path]], to: Path, force: bool, dry_run: bool
) -> None:
if not shutil.which("fzf"):
print(
"pick mode needs fzf on PATH.\n"
"Install it (https://github.com/junegunn/fzf) "
"or use `./sync preset NAME --to PATH` instead."
)
sys.exit(1)
items = [
(ct, name, src)
for ct in CONTENT_TYPES
for name, src in sorted(items_map[ct].items())
]
if not items:
print("No items found in repo or sources.")
return
items_by_line: dict[str, tuple[str, str, Path]] = {}
fzf_lines: list[str] = []
for ct, name, src in items:
line = f"[{TYPE_LETTER[ct]}] {name}\t{src}"
items_by_line[line] = (ct, name, src)
fzf_lines.append(line)
result = subprocess.run(
[
"fzf",
"--multi",
"--delimiter=\t",
"--with-nth=1",
"--preview", FZF_PREVIEW,
"--preview-window=right:60%:wrap",
"--header=Tab: select Enter: copy Esc: cancel",
"--prompt=skills/agents/commands> ",
],
input="\n".join(fzf_lines),
stdout=subprocess.PIPE,
text=True,
)
if result.returncode == 130 or not result.stdout.strip():
print("Cancelled.")
return
if result.returncode not in (0, 1):
print(f"fzf exited with {result.returncode}")
return
chosen = [items_by_line[line] for line in result.stdout.splitlines() if line in items_by_line]
apply_picks(chosen, to, force, dry_run=dry_run)
def preset_mode(
name: str,
to: Path,
force: bool,
dry_run: bool,
config: dict,
items: dict[str, dict[str, Path]],
) -> None:
presets = config.get("presets") or {}
if name not in presets:
available = ", ".join(sorted(presets)) or "(none defined)"
print(f"Preset '{name}' not found. Available: {available}")
sys.exit(1)
preset = presets[name] or {}
chosen: list[tuple[str, str, Path]] = []
for ct in CONTENT_TYPES:
names = preset.get(ct) or []
for n in names:
# Presets list agents/commands by bare name; the files are .md.
key = n if n in items[ct] else f"{n}.md"
src = items[ct].get(key)
if src is None:
print(
f" ⚠ {ct}/{n} listed in preset '{name}' "
"but not found in repo or sources"
)
continue
chosen.append((ct, key, src))
apply_picks(chosen, to, force, dry_run=dry_run)
def main() -> None:
args = sys.argv[1:]
if "-h" in args or "--help" in args:
print(USAGE)
return
force = "--force" in args
dry_run = "--dry-run" in args
args = [a for a in args if a not in ("--force", "--dry-run")]
to: Path | None = None
if "--to" in args:
i = args.index("--to")
if i + 1 >= len(args):
print("--to requires a path")
sys.exit(1)
to = expand_path(args[i + 1])
args = args[:i] + args[i + 2 :]
if args and args[0] == "pick":
if to is None:
print("Usage: ./sync pick --to PATH")
sys.exit(1)
picker_mode(collect_items(load_config_optional()), to, force, dry_run)
return
if args and args[0] == "preset":
if len(args) < 2 or to is None:
print("Usage: ./sync preset NAME --to PATH")
sys.exit(1)
config = load_config()
preset_mode(args[1], to, force, dry_run, config, collect_items(config))
return
if dry_run:
print("Dry run — showing what would be synced:\n")
config = load_config()
items = collect_items(config)
for name, target in config.get("targets", {}).items():
if not target.get("enabled", False):
continue
print(f"📁 {name}")
for content_type in CONTENT_TYPES:
dest_str = target.get(content_type)
if not dest_str:
continue
ignores = ignored_names(target, config, content_type)
for item_name, src in sorted(items[content_type].items()):
if item_name in ignores:
print(f" {content_type}/{item_name} → ignored")
continue
dest = expand_path(dest_str) / item_name
exists = "exists" if dest.exists() else "new"
print(f" {content_type}/{item_name} → {dest} ({exists})")
return
config = load_config()
items = collect_items(config)
targets = config.get("targets", {})
if not targets:
print("No targets defined in sync.yaml")
sys.exit(1)
enabled = {k: v for k, v in targets.items() if v.get("enabled", False)}
if not enabled:
print("No targets enabled in sync.yaml")
sys.exit(1)
print(f"Syncing to {len(enabled)} target(s)...")
if force:
print("(--force: overwriting without prompts)")
skipped: list[tuple[Path, Path]] = []
for name, target in enabled.items():
sync_target(name, target, config, items, skipped, force=force)
if skipped:
print("\n⚠ Skipped (destination differs from source):")
for dest, src in skipped:
print(f" {dest}")
print(f" ← repo: {src}")
print("\nDone.")
if __name__ == "__main__":
main()