SPB Git

Repository Public

sp_install.py 13.6 KB 344 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project          : SP Boucher Development Standard8# File             : tools/sp_install.py9# Module           : Installer10# Repository       : https://git.spboucher.ai/sp-development-standard11# Project Website  : https://git.spboucher.ai/sp-development-standard12# Created          : 2026-12-0213# Last Modified    : 2026-12-0214#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: contact@spboucher.ai23# Development      : dev@spboucher.ai24# Support          : support@spboucher.ai25# Security/Admin   : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License          : None specified (no license file in this repository)34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142"""Installer of the SP Boucher development standard into a Claude Code user directory (default ~/.claude).4344  sp_install.py install   [--claude-dir DIR] [--no-path]45  sp_install.py uninstall [--claude-dir DIR]46  sp_install.py restore   [--claude-dir DIR] [--from TIMESTAMP]     (CLAUDE.md and settings.json from a backup)47  sp_install.py status    [--claude-dir DIR]4849Idempotent, non-interactive, Python 3.8+. Existing instructions, hooks, skills and permissions are preserved:50only the marked CLAUDE.md block and the hook entries pointing into <claude-dir>/hooks/sp-* are managed."""51import datetime52import json53import os54import shutil55import sys5657KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))58PAYLOAD = os.path.join(KIT, "payload")59START, END = "<!-- sp-development-standard:start -->", "<!-- sp-development-standard:end -->"60HOOKS = [("SessionStart", None, "hooks/sp-git-governance/session-start", 20, "SP standard: loading development policy"),61         ("PreToolUse", "Bash", "hooks/sp-security/pre-tool-use", 60, "SP standard: git safety and secret scan"),62         ("PostToolUse", "Write|Edit|MultiEdit|NotebookEdit", "hooks/sp-source-header/post-tool-use", 30, "SP standard: source header"),63         ("SubagentStop", None, "hooks/sp-git-governance/subagent-stop", 45, None),64         ("Stop", None, "hooks/sp-git-governance/stop", 60, "SP standard: completion check")]65BINS = ("sp-header", "sp-git", "sp-security-scan", "sp-dev-doctor")666768def log(msg):69    print("  " + msg)707172def read(p, default=""):73    try:74        with open(p, encoding="utf-8") as f:75            return f.read()76    except OSError:77        return default787980def write(p, text):81    os.makedirs(os.path.dirname(p), exist_ok=True)82    tmp = p + ".sp-tmp"83    with open(tmp, "w", encoding="utf-8") as f:84        f.write(text)85    if os.path.exists(p):86        shutil.copymode(p, tmp)87    os.replace(tmp, p)888990def backup(cd):91    stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")92    dest = os.path.join(cd, "backups", "sp-development-standard", stamp)93    n = 194    while os.path.exists(dest):                                  # two operations within the same second95        n += 196        dest = os.path.join(cd, "backups", "sp-development-standard", "%s-%d" % (stamp, n))97    os.makedirs(dest)98    saved = []99    for name in ("CLAUDE.md", "settings.json"):100        src = os.path.join(cd, name)101        if os.path.isfile(src):102            shutil.copy2(src, os.path.join(dest, name))103            saved.append(name)104    for sub in ("bin", "hooks", "standards", "skills"):105        src = os.path.join(cd, sub)106        if not os.path.isdir(src):107            continue108        for n in sorted(os.listdir(src)):109            if n.startswith("sp-") or sub == "standards":110                s = os.path.join(src, n)111                d = os.path.join(dest, sub, n)112                os.makedirs(os.path.dirname(d), exist_ok=True)113                if os.path.isdir(s):114                    shutil.copytree(s, d, symlinks=True, ignore=shutil.ignore_patterns("__pycache__"))115                else:116                    shutil.copy2(s, d)117                saved.append("%s/%s" % (sub, n))118    log("backup: %s (%s)" % (dest, ", ".join(saved) or "nothing to save: clean environment"))119    return dest120121122def copy_tree(src, dst, manifest, cd, keep=()):123    for base, dirs, files in os.walk(src):124        dirs[:] = [d for d in dirs if d != "__pycache__"]125        rel = os.path.relpath(base, src)126        for f in files:127            if f.endswith((".pyc", ".DS_Store")):128                continue129            s = os.path.join(base, f)130            d = os.path.normpath(os.path.join(dst, rel, f))131            if any(os.path.relpath(d, cd).startswith(k) for k in keep):132                continue133            os.makedirs(os.path.dirname(d), exist_ok=True)134            shutil.copy2(s, d)135            manifest.append(os.path.relpath(d, cd))136137138def claude_md(cd, remove=False):139    p = os.path.join(cd, "CLAUDE.md")140    text = read(p)141    block = read(os.path.join(PAYLOAD, "CLAUDE-block.md")).strip() + "\n"142    if START in text and END in text:143        a, b = text.index(START), text.index(END) + len(END)144        new = text[:a] + ("" if remove else block.rstrip("\n")) + text[b:]145        if remove:146            new = new.rstrip("\n") + "\n" if new.strip() else ""147    elif remove:148        return False149    else:150        new = (text.rstrip("\n") + "\n\n" if text.strip() else "") + block151    if new != text:152        write(p, new)153        return True154    return False155156157def settings(cd, remove=False):158    p = os.path.join(cd, "settings.json")159    raw = read(p)160    if raw.strip():161        try:162            data = json.loads(raw)163        except ValueError as e:164            raise SystemExit("settings.json is not valid JSON (%s): left untouched, installation aborted" % e)165    else:166        data = {}167    hooks = data.setdefault("hooks", {})168    marker = os.path.join(cd, "hooks", "sp-")169    for event in list(hooks.keys()):170        groups = []171        for g in hooks[event]:172            hs = [h for h in g.get("hooks", []) if marker not in (h.get("command") or "")]173            if hs:174                g = dict(g)175                g["hooks"] = hs176                groups.append(g)177        if groups:178            hooks[event] = groups179        else:180            del hooks[event]181    if not remove:182        for event, matcher, rel, timeout, status in HOOKS:183            h = {"type": "command", "command": '"%s"' % os.path.join(cd, rel), "timeout": timeout}184            if status:185                h["statusMessage"] = status186            g = {"hooks": [h]}187            if matcher:188                g = {"matcher": matcher, "hooks": [h]}189            hooks.setdefault(event, []).append(g)190    if not hooks:191        del data["hooks"]192    new = json.dumps(data, indent=2, ensure_ascii=False) + "\n"193    if new != raw:194        write(p, new)195        return True196    return False197198199def path_links(cd, remove=False):200    dirs = [os.path.expanduser("~/.local/bin")]201    for d in ("/opt/homebrew/bin", "/usr/local/bin"):202        if os.path.isdir(d) and os.access(d, os.W_OK):203            dirs.append(d)204            break205    done = []206    for d in dirs:207        try:208            os.makedirs(d, exist_ok=True)209        except OSError:210            continue211        for b in BINS:212            link, target = os.path.join(d, b), os.path.join(cd, "bin", b)213            if os.path.islink(link) and os.readlink(link) == target:214                if remove:215                    os.remove(link)216                continue217            if remove or os.path.lexists(link):218                continue                                         # never overwrite a foreign file of the same name219            try:220                os.symlink(target, link)221                done.append(link)222            except OSError:223                pass224    return dirs, done225226227def install(cd, no_path):228    if not os.path.isdir(PAYLOAD):229        raise SystemExit("payload/ not found next to the installer")230    os.makedirs(cd, exist_ok=True)231    version = read(os.path.join(KIT, "VERSION")).strip()232    print("SP Boucher development standard %s → %s" % (version, cd))233    settings_probe = read(os.path.join(cd, "settings.json"))234    if settings_probe.strip():235        try:236            json.loads(settings_probe)237        except ValueError as e:238            raise SystemExit("settings.json is not valid JSON (%s): nothing was changed" % e)239    bdir = backup(cd)240    old = []241    try:242        old = json.loads(read(os.path.join(cd, "standards", "manifest.json"), "{}")).get("files", [])243    except ValueError:244        pass245    manifest = []246    for sub in ("bin", "hooks", "skills"):247        copy_tree(os.path.join(PAYLOAD, sub), os.path.join(cd, sub), manifest, cd)248    copy_tree(os.path.join(PAYLOAD, "standards"), os.path.join(cd, "standards"), manifest, cd, keep=("standards/local",))249    copy_tree(os.path.join(KIT, "tests"), os.path.join(cd, "tests", "sp-development-standard"), manifest, cd)250    for rel in manifest:251        if rel.startswith(("bin/", "hooks/")):252            os.chmod(os.path.join(cd, rel), 0o755)253    for rel in old:                                              # files of a previous version that no longer exist254        if rel not in manifest and os.path.isfile(os.path.join(cd, rel)):255            os.remove(os.path.join(cd, rel))256    shutil.copy2(os.path.join(KIT, "VERSION"), os.path.join(cd, "standards", "VERSION"))257    write(os.path.join(cd, "standards", "manifest.json"), json.dumps(258        {"version": version, "installed": datetime.datetime.now().isoformat(timespec="seconds"), "backup": bdir,259         "kit": KIT, "files": sorted(set(manifest + ["standards/VERSION"]))}, indent=2) + "\n")260    log("files installed: %d (bin, hooks, skills, standards, tests)" % len(manifest))261    log("CLAUDE.md permanent directive: %s" % ("written" if claude_md(cd) else "already up to date"))262    log("settings.json hooks: %s" % ("registered" if settings(cd) else "already registered"))263    if not no_path:264        dirs, done = path_links(cd)265        log("PATH links in %s: %s" % (", ".join(dirs), "%d created" % len(done) if done else "already present"))266    print("Installed. Verify with: %s/bin/sp-dev-doctor" % cd)267268269def uninstall(cd):270    print("Removing the SP Boucher development standard from %s" % cd)271    backup(cd)272    try:273        files = json.loads(read(os.path.join(cd, "standards", "manifest.json"), "{}")).get("files", [])274    except ValueError:275        files = []276    path_links(cd, remove=True)277    n = 0278    for rel in files + ["standards/manifest.json"]:279        p = os.path.join(cd, rel)280        if os.path.isfile(p):281            os.remove(p)282            n += 1283    for sub in ("bin", "hooks", "skills", "standards", "tests"):284        top = os.path.join(cd, sub)285        for base, dirs, fs in os.walk(top, topdown=False):286            for d in dirs:287                full = os.path.join(base, d)288                if d == "__pycache__":289                    shutil.rmtree(full, ignore_errors=True)290                elif not os.listdir(full) and (d.startswith("sp-") or "sp-" in base or sub == "standards" or "spstd" in full):291                    os.rmdir(full)292        if os.path.isdir(top) and not os.listdir(top):293            os.rmdir(top)294    log("files removed: %d" % n)295    log("CLAUDE.md directive: %s" % ("removed" if claude_md(cd, remove=True) else "absent"))296    log("settings.json hooks: %s" % ("removed" if settings(cd, remove=True) else "absent"))297    print("Uninstalled. Backups are kept in %s/backups/sp-development-standard/." % cd)298299300def restore(cd, stamp):301    base = os.path.join(cd, "backups", "sp-development-standard")302    stamps = sorted(os.listdir(base)) if os.path.isdir(base) else []303    if not stamps:304        raise SystemExit("no backup found in %s" % base)305    stamp = stamp or stamps[0]306    src = os.path.join(base, stamp)307    if not os.path.isdir(src):308        raise SystemExit("no such backup: %s (available: %s)" % (stamp, ", ".join(stamps)))309    backup(cd)310    for name in ("CLAUDE.md", "settings.json"):311        if os.path.isfile(os.path.join(src, name)):312            shutil.copy2(os.path.join(src, name), os.path.join(cd, name))313            log("restored %s from %s" % (name, stamp))314    print("Restored. The tools remain installed; run uninstall to remove them, or install to re-register.")315316317def status(cd):318    m = read(os.path.join(cd, "standards", "manifest.json"))319    print(m.strip() and "installed: " + json.loads(m)["version"] or "not installed")320    base = os.path.join(cd, "backups", "sp-development-standard")321    print("backups: %s" % (", ".join(sorted(os.listdir(base))) if os.path.isdir(base) else "none"))322323324def main():325    args = sys.argv[1:]326    cmd = args[0] if args else "install"327    cd = os.path.expanduser("~/.claude")328    if "--claude-dir" in args:329        cd = os.path.abspath(args[args.index("--claude-dir") + 1])330    if cmd == "install":331        install(cd, "--no-path" in args)332    elif cmd == "uninstall":333        uninstall(cd)334    elif cmd == "restore":335        restore(cd, args[args.index("--from") + 1] if "--from" in args else None)336    elif cmd == "status":337        status(cd)338    else:339        raise SystemExit(__doc__)340341342if __name__ == "__main__":343    main()344
Files main
Menu

Theme