all repos — dot @ ed21d1270007a8f9cbaa2ca7da0fee1eefeb405f

Shell, editor and terminal configuration, and the tools that go with them

link/pi-models.py (view raw)

 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
"""Generate ~/.pi/agent/models.json from the repo and its fragments.

Run by link/pi.sh. It lives in a file rather than a heredoc inside $( ):
macOS ships bash 3.2, which does not skip heredoc content when it scans
for the end of a command substitution, so an odd number of apostrophes in
here would stop the whole script parsing -- which it did, on 2026-09-25.
"""

import glob, json, os, sys

base_path, frag_dir, target = sys.argv[1:4]


def load(path):
    with open(path) as f:
        return json.load(f)


# The repo's providers, then each fragment's. A fragment may add a provider or
# replace one of the same name; any other top-level key takes the last file's
# value. Which provider came from where is reported: a fragment quietly
# shadowing a provider the repo ships would otherwise be invisible.
desired = {}
notes = []
for path in [base_path] + sorted(glob.glob(os.path.join(frag_dir, "*.json"))):
    try:
        layer = load(path)
    except (OSError, ValueError) as e:
        print("error:cannot read %s: %s" % (path, e))
        sys.exit(0)
    for key, value in layer.items():
        if key == "providers":
            providers = desired.setdefault("providers", {})
            if path != base_path:
                for name in value:
                    notes.append("%s %s by %s" % (
                        name,
                        "replaced" if name in providers else "added",
                        os.path.basename(path),
                    ))
            providers.update(value)
        else:
            desired[key] = value

# A symlink is the pre-generation state: replace it, even with no fragments, so
# the live file is never the tracked one.
was_link = os.path.islink(target)
try:
    current = None if was_link else load(target)
except (OSError, ValueError):
    current = None

for note in notes:
    print("note:" + note)

if current == desired:
    print("unchanged:")
elif os.environ.get("DRY_RUN"):
    print("would-write:" + ("replacing the link" if was_link else "merged changes"))
else:
    tmp = target + ".dotfiles-tmp"
    with open(tmp, "w") as f:
        json.dump(desired, f, indent=2)
        f.write("\n")
    os.replace(tmp, target)
    print("wrote:" + ("replaced the link" if was_link else "merged changes"))