Repository navigation
Expand file tree
/
Copy pathgit_symlinks.py
More file actions
594 lines (517 loc) · 22.2 KB
/
Copy pathgit_symlinks.py
File metadata and controls
594 lines (517 loc) · 22.2 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
#!/usr/bin/env python3
"""
================================================================
Tool: git-symlinks
Coded by: Claude Opus 4.7
Copyright: 2026 Trenton Tompkins
Email: TrentTompkins@gmail.com
Web: trentontompkins.com · tristate.digital
GitHub: github.com/tibberous/git-symlinks
Phone: (724) 431-5207
================================================================
What it does
------------
Makes git follow symbolic links — opt-in, with a consent UX shown before any
commit or checkout. Survives every git release because it talks to git only
through frozen, documented APIs (`git hash-object`, `git update-index`, and
the `post-checkout` hook). Cross-platform: Linux, macOS, Windows.
How it works
------------
Two pieces. No `.gitattributes` filter — the filter approach can't handle
directory symlinks because the OS rejects `open()` on a directory before the
filter ever runs. Instead:
1. `git symlinks add <path>` — detects symlinks at the user-facing CLI,
prompts for consent, snapshots the target
(raw bytes for files, tar.gz for dirs),
stages the snapshot as a marker file blob
via git plumbing (hash-object +
update-index --cacheinfo). The user's
working-tree symlink stays untouched.
2. `post-checkout` hook — on checkout, marker files arrive at the
symlink's path. The hook walks the worktree
for markers and for each: if the original
target resolves on this machine, recreates
the symlink; else extracts the content
(tar.gz to a dir, raw bytes to a file).
CLI usage
---------
git symlinks init # one-time per repo
git symlinks add path/to/link # like `git add`, with consent UX
git symlinks refresh # re-snapshot all tracked symlinks
git symlinks status # list tracked markers + state
git symlinks uninstall # remove the hook
git symlinks --usage # worked examples
git symlinks --help # argparse help
Notes
-----
- `git symlinks add` does NOT replace the working-tree symlink with a marker.
It stages the marker via git's plumbing so the index has the marker but the
user's local symlink keeps working.
- On clone / checkout the marker arrives as a regular file. The post-checkout
hook rebuilds the symlink (or extracts content if the target is missing).
- Per-repo state lives in `.git/info/git-symlinks/config.json` — not shared
via clone, plain JSON, inspectable + revocable.
"""
from __future__ import annotations
import argparse
import datetime
import hashlib
import io
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tarfile
import tempfile
from typing import Optional
# Windows: force UTF-8 on stdout/stderr so the box-drawing chars in the
# consent prompt don't trip cp1252. Idempotent + harmless on POSIX.
try:
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
MARKER_PREFIX = b"__GIT_SYMLINKS__\n"
MARKER_END = b"--END-HEADER--\n"
CONFIG_DIR = "info/git-symlinks" # under .git/
USAGE_TEXT = """\
git-symlinks — make git follow symbolic links, opt-in, future-proof
QUICK EXAMPLES
One-time setup in a repo git symlinks init
Stage a symlink (with prompt) git symlinks add hooks
Re-snapshot after target edit git symlinks refresh
See what's tracked git symlinks status
Tear down git symlinks uninstall
INTERNAL (called by git's post-checkout hook)
git symlinks post-checkout — rebuild symlinks from markers after checkout
HOW DATA FLOWS
add → snapshot target → marker blob staged via git plumbing
(working-tree symlink untouched)
commit → marker tracked as plain file content
checkout → marker arrives at symlink path → post-checkout hook fires:
if target resolves → rm marker, recreate symlink
else → extract content (untar dir, write file)
WHERE STATE LIVES
.git/info/git-symlinks/config.json per-repo consent settings
.git/hooks/post-checkout dispatches to `git symlinks post-checkout`
"""
# ── git plumbing helpers ────────────────────────────────────────────────
def _run(cmd: list[str], **kw) -> subprocess.CompletedProcess:
return subprocess.run(cmd, capture_output=True, **kw)
def repo_root() -> pathlib.Path:
p = _run(["git", "rev-parse", "--show-toplevel"], text=True)
if p.returncode != 0:
sys.exit("ERR: not inside a git repo (or `git` not on PATH)")
return pathlib.Path(p.stdout.strip())
def git_dir() -> pathlib.Path:
p = _run(["git", "rev-parse", "--git-dir"], text=True)
if p.returncode != 0:
sys.exit("ERR: not inside a git repo")
out = pathlib.Path(p.stdout.strip())
if not out.is_absolute():
out = (pathlib.Path.cwd() / out).resolve()
return out
def config_path() -> pathlib.Path:
return git_dir() / CONFIG_DIR
def load_config() -> dict:
p = config_path() / "config.json"
if p.exists():
return json.loads(p.read_text(encoding="utf-8"))
return {"version": 1, "always_continue": False, "approved_links": []}
def save_config(cfg: dict) -> None:
p = config_path() / "config.json"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
def hash_object_stdin(blob: bytes) -> str:
"""Write a blob to git's object DB; return its SHA."""
p = subprocess.run(
["git", "hash-object", "-w", "--stdin"],
input=blob, capture_output=True,
)
if p.returncode != 0:
raise RuntimeError(f"git hash-object failed: {p.stderr.decode(errors='replace')}")
return p.stdout.decode().strip()
def update_index_add(path_rel: str, sha: str) -> None:
"""Stage `path_rel` as mode 100644 with the given blob SHA."""
p = subprocess.run(
["git", "update-index", "--add", "--cacheinfo",
f"100644,{sha},{path_rel}"],
capture_output=True,
)
if p.returncode != 0:
raise RuntimeError(f"git update-index failed: {p.stderr.decode(errors='replace')}")
# ── symlink + target helpers ────────────────────────────────────────────
def target_of(link: pathlib.Path) -> pathlib.Path:
return pathlib.Path(os.readlink(str(link)))
def absolute_target(link: pathlib.Path) -> pathlib.Path:
t = target_of(link)
if t.is_absolute():
return t
return (link.parent / t).resolve()
def count_target(target: pathlib.Path) -> tuple[int, int]:
if target.is_file():
try: return 1, target.stat().st_size
except OSError: return 0, 0
if not target.is_dir():
return 0, 0
n_files, n_bytes = 0, 0
for p in target.rglob("*"):
if p.is_file():
try:
n_files += 1
n_bytes += p.stat().st_size
except OSError:
pass
return n_files, n_bytes
# ── marker format ───────────────────────────────────────────────────────
def build_marker(link: pathlib.Path) -> bytes:
"""Build a marker blob for the given symlink. Snapshots target content."""
target_raw = os.readlink(str(link))
target_abs = absolute_target(link)
kind = "dir" if target_abs.is_dir() else ("file" if target_abs.is_file() else "missing")
if kind == "dir":
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tf:
tf.add(str(target_abs), arcname=".")
body = buf.getvalue()
elif kind == "file":
body = target_abs.read_bytes()
else:
body = b""
sha = hashlib.sha256(body).hexdigest()
header = (
MARKER_PREFIX
+ f"target={target_raw}\n".encode("utf-8")
+ f"target_resolved={target_abs}\n".encode("utf-8")
+ f"kind={kind}\n".encode("ascii")
+ f"sha256={sha}\n".encode("ascii")
+ f"size={len(body)}\n".encode("ascii")
+ f"created={datetime.datetime.now().isoformat()}\n".encode("ascii")
+ MARKER_END
)
return header + body
def parse_marker(blob: bytes) -> Optional[dict]:
if not blob.startswith(MARKER_PREFIX):
return None
end = blob.find(MARKER_END)
if end == -1:
return None
header = blob[len(MARKER_PREFIX):end].decode("utf-8", "replace")
body = blob[end + len(MARKER_END):]
meta = {"body": body}
for line in header.splitlines():
if "=" in line:
k, v = line.split("=", 1)
meta[k.strip()] = v.strip()
return meta
# ── consent UX ──────────────────────────────────────────────────────────
def prompt_warning(links: list[tuple[pathlib.Path, pathlib.Path, int, int]]) -> str:
"""Return one of: 'gitignore', 'once', 'always'."""
W = 71
bar = "─" * W
print(f"┌{bar}┐")
print(f"│ {'WARNING: this repo is about to follow the following symbolic links:':<{W-1}}│")
print(f"│ {'':<{W-1}}│")
for link, target, n_files, n_bytes in links:
size_kb = max(n_bytes // 1024, 1) if n_bytes else 0
unit = "KB" if n_bytes >= 1024 else "bytes"
line = f" {link.name} → {target} ({n_files} files, {size_kb if n_bytes>=1024 else n_bytes} {unit})"
print(f"│ {line:<{W-1}}│")
print(f"│ {'':<{W-1}}│")
print(f"│ {'All files under those targets will be included in commits made':<{W-1}}│")
print(f"│ {'from this repo. Proceed?':<{W-1}}│")
print(f"│ {'':<{W-1}}│")
print(f"│ {' [1] add the link path to .gitignore':<{W-1}}│")
print(f"│ {' [2] continue once (approve only the link(s) shown above)':<{W-1}}│")
print(f"│ {' [3] continue always (do not ask again on this repo)':<{W-1}}│")
print(f"└{bar}┘")
while True:
try:
choice = input("Choice [1/2/3]: ").strip()
except (EOFError, KeyboardInterrupt):
print(); return "gitignore"
if choice == "1": return "gitignore"
if choice == "2": return "once"
if choice == "3":
print()
print(" Setting [3] means a future commit could add a NEW symlink")
print(" pointing at ~/.ssh, /etc/passwd, or any path on this machine,")
print(" and it will be followed silently with no prompt.")
confirm = input(" Are you sure? [y/N]: ").strip().lower()
if confirm == "y":
return "always"
print("Please enter 1, 2, or 3.")
# ── subcommands ─────────────────────────────────────────────────────────
def cmd_init(args) -> int:
root = repo_root()
cfgd = config_path()
cfgd.mkdir(parents=True, exist_ok=True)
save_config(load_config())
hook_path = git_dir() / "hooks" / "post-checkout"
hook_body = (
"#!/bin/sh\n"
"# Installed by git-symlinks. Rebuilds symlinks from marker files.\n"
'exec git symlinks post-checkout "$@"\n'
)
if hook_path.exists():
existing = hook_path.read_text(errors="replace")
if "git symlinks post-checkout" not in existing:
hook_path.write_text(existing.rstrip() + "\n\n" + hook_body)
print(f" appended dispatch to existing {hook_path}")
else:
print(f" hook already wired at {hook_path}")
else:
hook_path.parent.mkdir(parents=True, exist_ok=True)
hook_path.write_text(hook_body)
try: hook_path.chmod(0o755)
except Exception: pass
print(f" wrote {hook_path}")
print(f"\ngit-symlinks initialized in {root}")
print(f" config: {cfgd}")
print(f" post-checkout hook installed")
print(f"\nNext: `git symlinks add <path>` to stage a symbolic link.")
return 0
def cmd_add(args) -> int:
root = repo_root()
cfg = load_config()
# Use absolute(), not resolve() — resolve follows symlinks, which would
# turn `hooks` into its target before we can detect it as a symlink.
paths = [pathlib.Path(p).absolute() for p in args.paths]
symlinks = [p for p in paths if p.is_symlink()]
plain = [p for p in paths if not p.is_symlink()]
if symlinks:
approved = set(cfg.get("approved_links", []))
always = bool(cfg.get("always_continue", False))
novel = [p for p in symlinks if str(p) not in approved]
if novel and not always:
info = []
for link in novel:
tgt = absolute_target(link)
n_f, n_b = count_target(tgt)
info.append((link, tgt, n_f, n_b))
choice = prompt_warning(info)
if choice == "gitignore":
gi = root / ".gitignore"
with gi.open("a", encoding="utf-8") as f:
for link in novel:
try: rel = link.relative_to(root)
except ValueError: rel = link
f.write(f"{rel}\n")
print(f" added {rel} to .gitignore")
return 0
if choice == "always":
cfg["always_continue"] = True
cfg.setdefault("approved_links", [])
cfg["approved_links"].extend(str(p) for p in novel)
save_config(cfg)
for link in symlinks:
try: rel = link.relative_to(root)
except ValueError:
print(f" SKIP {link}: outside repo root", file=sys.stderr)
continue
blob = build_marker(link)
sha = hash_object_stdin(blob)
update_index_add(str(rel).replace("\\", "/"), sha)
size_label = f"{len(blob)//1024} KB" if len(blob) >= 1024 else f"{len(blob)} bytes"
print(f" staged {rel} (marker {sha[:10]}, {size_label})")
if plain:
rel = []
for p in plain:
try: rel.append(str(p.relative_to(root)))
except ValueError: rel.append(str(p))
subprocess.run(["git", "add", *rel], check=False)
return 0
def cmd_refresh(args) -> int:
"""Re-snapshot every tracked marker. Use after editing a target."""
root = repo_root()
p = _run(["git", "ls-files"], text=True, cwd=str(root))
refreshed = 0
for path_rel in p.stdout.splitlines():
full = root / path_rel
try:
blob = subprocess.run(
["git", "show", f":{path_rel}"],
capture_output=True, cwd=str(root),
).stdout
except Exception:
continue
meta = parse_marker(blob)
if not meta:
continue
target_raw = meta.get("target", "")
if full.is_symlink():
link_for_build = full
else:
tgt_path = pathlib.Path(target_raw)
if not tgt_path.is_absolute():
tgt_path = (full.parent / tgt_path).resolve()
if not tgt_path.exists():
print(f" SKIP {path_rel}: target {tgt_path} not present")
continue
with tempfile.TemporaryDirectory() as td:
tmplink = pathlib.Path(td) / "x"
try:
os.symlink(str(tgt_path), str(tmplink),
target_is_directory=tgt_path.is_dir())
except OSError as e:
print(f" SKIP {path_rel}: temp symlink failed ({e})")
continue
link_for_build = tmplink
fresh = build_marker(link_for_build)
sha = hash_object_stdin(fresh)
update_index_add(path_rel, sha)
refreshed += 1
continue
fresh = build_marker(link_for_build)
sha = hash_object_stdin(fresh)
update_index_add(path_rel, sha)
refreshed += 1
print(f"refreshed {refreshed} marker(s)")
return 0
def cmd_post_checkout(args) -> int:
root = repo_root()
fixed_links = 0
materialized_files = 0
materialized_dirs = 0
p = _run(["git", "ls-files"], text=True, cwd=str(root))
candidates = [root / line for line in p.stdout.splitlines()]
for path in candidates:
if not path.exists() or path.is_symlink():
continue
try:
head = path.read_bytes()[:len(MARKER_PREFIX)]
except (OSError, PermissionError):
continue
if head != MARKER_PREFIX:
continue
try:
blob = path.read_bytes()
except OSError:
continue
meta = parse_marker(blob)
if not meta:
continue
target_raw = meta.get("target", "")
kind = meta.get("kind", "file")
if not target_raw:
continue
target = pathlib.Path(target_raw)
if not target.is_absolute():
target_abs = (path.parent / target).resolve()
else:
target_abs = target
if target_abs.exists():
try:
path.unlink()
os.symlink(str(target), str(path),
target_is_directory=(kind == "dir"))
fixed_links += 1
continue
except OSError as e:
print(f" could not symlink {path} -> {target} ({e}); using content")
try:
if kind == "dir":
path.unlink()
path.mkdir(exist_ok=True)
buf = io.BytesIO(meta["body"])
with tarfile.open(fileobj=buf, mode="r:gz") as tf:
try:
tf.extractall(str(path), filter="data")
except TypeError:
# Python <3.12 has no filter kw — fall back.
tf.extractall(str(path))
materialized_dirs += 1
elif kind == "file":
path.write_bytes(meta["body"])
materialized_files += 1
except Exception as e:
print(f" ERR materializing {path}: {e}")
if fixed_links or materialized_files or materialized_dirs:
print(f"git-symlinks: rebuilt {fixed_links} symlink(s), "
f"extracted {materialized_dirs} dir(s), "
f"wrote {materialized_files} file(s)")
return 0
def cmd_status(args) -> int:
root = repo_root()
p = _run(["git", "ls-files"], text=True, cwd=str(root))
rows = []
for path_rel in p.stdout.splitlines():
full = root / path_rel
if not full.exists():
continue
if full.is_symlink():
tgt = absolute_target(full)
rows.append((path_rel, "symlink", str(tgt),
"ok" if tgt.exists() else "broken-target"))
continue
try:
head = full.read_bytes()[:len(MARKER_PREFIX)]
except OSError:
continue
if head != MARKER_PREFIX:
continue
blob = full.read_bytes()
meta = parse_marker(blob)
if not meta:
continue
target_raw = meta.get("target", "")
target_abs = pathlib.Path(target_raw)
if not target_abs.is_absolute():
target_abs = (full.parent / target_abs).resolve()
state = "marker-here-target-ok" if target_abs.exists() else "marker-here-target-missing"
rows.append((path_rel, meta.get("kind", "?"), str(target_abs), state))
if not rows:
print("no tracked symlinks or markers in this repo")
return 0
print(f"{'path':<40} {'kind':<8} {'target':<48} state")
print("-" * 116)
for path_rel, kind, tgt, state in rows:
print(f"{path_rel:<40} {kind:<8} {tgt[:48]:<48} {state}")
return 0
def cmd_uninstall(args) -> int:
hook = git_dir() / "hooks" / "post-checkout"
if hook.exists():
body = hook.read_text(errors="replace")
body = "\n".join(l for l in body.splitlines()
if "git symlinks post-checkout" not in l)
if body.strip() in ("", "#!/bin/sh"):
hook.unlink()
print(f" removed {hook}")
else:
hook.write_text(body)
print(f" stripped dispatch from {hook}")
print("git-symlinks uninstalled.")
print("Markers stay in the index; symlinks stay in the worktree.")
return 0
# ── main ────────────────────────────────────────────────────────────────
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
if any(a in ("--usage", "-?", "/?") for a in argv):
print(USAGE_TEXT); return 0
ap = argparse.ArgumentParser(
prog="git-symlinks",
description="Make git follow symbolic links — opt-in, future-proof.",
epilog="Run `--usage` for worked examples.",
)
sub = ap.add_subparsers(dest="action", required=True)
sub.add_parser("init", help="Install post-checkout hook in current repo")
a = sub.add_parser("add", help="Stage path(s); warns on symlinks")
a.add_argument("paths", nargs="+")
sub.add_parser("refresh", help="Re-snapshot every tracked marker")
sub.add_parser("status", help="List tracked symlinks + markers + state")
sub.add_parser("uninstall", help="Remove the post-checkout hook")
sub.add_parser("post-checkout", help="[internal] post-checkout hook")
args = ap.parse_args(argv)
dispatch = {
"init": cmd_init,
"add": cmd_add,
"refresh": cmd_refresh,
"status": cmd_status,
"uninstall": cmd_uninstall,
"post-checkout": cmd_post_checkout,
}
return dispatch[args.action](args)
if __name__ == "__main__":
raise SystemExit(main())