gabriel / muse public
muse.plugin.zsh
249 lines 9.9 KB
5e504f28 fix(omzsh-plugin): require repo.json for repo detection, pre-clear stat… Gabriel Cardona <gabriel@tellurstori.com> 3d ago
1 # muse.plugin.zsh — Oh My ZSH plugin for Muse version control
2 # ==============================================================================
3 # Minimal, secure shell integration. Shows domain + branch in your prompt.
4 # Nothing else runs automatically; everything else is a muse command away.
5 #
6 # Setup (after running tools/install-omzsh-plugin.sh):
7 # Add $(muse_prompt_info) to your PROMPT in ~/.zshrc, e.g.:
8 # PROMPT='%~ $(muse_prompt_info) %# '
9 #
10 # Configuration (set in ~/.zshrc BEFORE plugins=(… muse …)):
11 # MUSE_PROMPT_ICONS=1 Use emoji icons; set 0 for plain ASCII (default 1)
12 # MUSE_DIRTY_TIMEOUT=1 Seconds before dirty-check gives up (default 1)
13 #
14 # Security notes:
15 # - No eval of any data read from disk or env.
16 # - Branch names are regex-validated and %-escaped before prompt display.
17 # - Domain name is validated as alphanumeric before use.
18 # - All repo paths passed to subprocesses via env vars (not -c strings).
19 # - Dirty check runs only after a muse command, never on every keystroke.
20 # - Zero subprocesses on prompt render; one python3 on directory change.
21 # ==============================================================================
22
23 autoload -Uz is-at-least
24 if ! is-at-least 5.0; then
25 print "[muse] ZSH 5.0+ required. Plugin not loaded." >&2
26 return 1
27 fi
28
29 # ── Configuration ─────────────────────────────────────────────────────────────
30 : ${MUSE_PROMPT_ICONS:=0}
31 : ${MUSE_DIRTY_TIMEOUT:=1}
32
33 # Domain icon map. Override individual elements in ~/.zshrc before plugins=().
34 typeset -gA MUSE_DOMAIN_ICONS
35 MUSE_DOMAIN_ICONS=(
36 midi "♪"
37 code "⌥"
38 bitcoin "₿"
39 scaffold "⬡"
40 _default "◈"
41 )
42
43 # ── Internal state ────────────────────────────────────────────────────────────
44 typeset -g MUSE_REPO_ROOT="" # absolute path to repo root, or ""
45 typeset -g MUSE_DOMAIN="midi" # active domain plugin name
46 typeset -g MUSE_BRANCH="" # branch name, 8-char SHA, or "?"
47 typeset -gi MUSE_DIRTY=0 # 1 when working tree has uncommitted changes
48 typeset -gi MUSE_DIRTY_COUNT=0 # number of changed paths
49 typeset -gi _MUSE_CMD_RAN=0 # 1 after any muse command runs
50
51 # ── §1 Core detection (zero subprocesses) ───────────────────────────────────
52
53 # Walk up from $PWD to find a valid Muse repo root. Sets MUSE_REPO_ROOT.
54 # A valid repo requires .muse/repo.json — a bare .muse/ directory is not
55 # enough. This prevents false positives from stray or partial .muse/ dirs
56 # (e.g. a forgotten muse init in a parent directory).
57 function _muse_find_root() {
58 local dir="$PWD"
59 while [[ "$dir" != "/" ]]; do
60 if [[ -f "$dir/.muse/repo.json" ]]; then
61 MUSE_REPO_ROOT="$dir"
62 return 0
63 fi
64 dir="${dir:h}"
65 done
66 MUSE_REPO_ROOT=""
67 return 1
68 }
69
70 # Read branch from .muse/HEAD without forking. Validates before storing.
71 # Branch names are restricted to [a-zA-Z0-9/_.-] to prevent prompt injection.
72 #
73 # Muse HEAD format (canonical, written by muse/core/store.py):
74 # ref: refs/heads/<branch> — on a branch (symbolic ref)
75 # commit: <sha256> — detached HEAD (direct commit reference)
76 function _muse_parse_head() {
77 local head_file="$MUSE_REPO_ROOT/.muse/HEAD"
78 if [[ ! -f "$head_file" ]]; then
79 MUSE_BRANCH=""; return 1
80 fi
81 local raw
82 raw=$(<"$head_file")
83 if [[ "$raw" == "ref: refs/heads/"* ]]; then
84 local branch="${raw#ref: refs/heads/}"
85 # Reject anything that could inject prompt escapes or path components.
86 if [[ "$branch" =~ '^[[:alnum:]/_.-]+$' ]]; then
87 MUSE_BRANCH="$branch"
88 else
89 MUSE_BRANCH="?"
90 fi
91 elif [[ "$raw" == "commit: "* ]]; then
92 local sha="${raw#commit: }"
93 MUSE_BRANCH="${sha:0:8}" # detached HEAD — show short SHA
94 else
95 MUSE_BRANCH="?"
96 fi
97 }
98
99 # Read domain from .muse/repo.json. One python3 call; path via env var only.
100 function _muse_parse_domain() {
101 local repo_json="$MUSE_REPO_ROOT/.muse/repo.json"
102 if [[ ! -f "$repo_json" ]]; then
103 MUSE_DOMAIN="midi"; return
104 fi
105 MUSE_DOMAIN=$(MUSE_REPO_JSON="$repo_json" python3 <<'PYEOF' 2>/dev/null
106 import json, os
107 try:
108 d = json.load(open(os.environ['MUSE_REPO_JSON']))
109 v = str(d.get('domain', 'midi'))
110 # Accept only safe domain names: alphanumeric plus hyphens/underscores,
111 # max 32 chars. Anything else falls back to 'midi'.
112 safe = v.replace('-', '').replace('_', '')
113 print(v if (safe.isalnum() and 1 <= len(v) <= 32) else 'midi')
114 except Exception:
115 print('midi')
116 PYEOF
117 )
118 : ${MUSE_DOMAIN:=midi}
119 }
120
121 # Check dirty state. Runs with timeout; only called after a muse command.
122 function _muse_check_dirty() {
123 local output rc count=0
124 output=$(cd -- "$MUSE_REPO_ROOT" && \
125 timeout -- "${MUSE_DIRTY_TIMEOUT}" muse status --porcelain 2>/dev/null)
126 rc=$?
127 if (( rc == 124 )); then
128 # Timeout — leave previous dirty state in place rather than lying.
129 return
130 fi
131 while IFS= read -r line; do
132 [[ "$line" == "##"* || -z "$line" ]] && continue
133 (( count++ ))
134 done <<< "$output"
135 MUSE_DIRTY=$(( count > 0 ? 1 : 0 ))
136 MUSE_DIRTY_COUNT=$count
137 }
138
139 # ── §2 Cache management ──────────────────────────────────────────────────────
140
141 # Lightweight refresh: head + domain only. Called on directory change.
142 function _muse_refresh() {
143 if ! _muse_find_root; then
144 MUSE_DOMAIN="midi"; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
145 return 1
146 fi
147 _muse_parse_head
148 _muse_parse_domain
149 }
150
151 # Full refresh: head + domain + dirty. Called after a muse command.
152 function _muse_refresh_full() {
153 _muse_refresh || return
154 _muse_check_dirty
155 _MUSE_CMD_RAN=0
156 }
157
158 # ── §3 ZSH hooks ─────────────────────────────────────────────────────────────
159
160 # On directory change: refresh head and domain; clear dirty (stale after cd).
161 # Pre-clear MUSE_REPO_ROOT so any silent failure in _muse_refresh leaves the
162 # prompt blank rather than showing stale data from the previous directory.
163 function _muse_hook_chpwd() {
164 MUSE_REPO_ROOT=""; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
165 _muse_refresh 2>/dev/null
166 }
167 chpwd_functions+=(_muse_hook_chpwd)
168
169 # Before a command: flag when the user runs muse so we refresh after.
170 function _muse_hook_preexec() {
171 [[ "${${(z)1}[1]}" == "muse" ]] && _MUSE_CMD_RAN=1
172 }
173 preexec_functions+=(_muse_hook_preexec)
174
175 # Before the prompt: full refresh only when a muse command just ran.
176 function _muse_hook_precmd() {
177 (( _MUSE_CMD_RAN )) && _muse_refresh_full 2>/dev/null
178 }
179 precmd_functions+=(_muse_hook_precmd)
180
181 # ── §4 Prompt ────────────────────────────────────────────────────────────────
182
183 # Primary prompt segment. Example usage in ~/.zshrc:
184 # PROMPT='%~ $(muse_prompt_info) %# '
185 # Emits nothing when not inside a muse repo.
186 function muse_prompt_info() {
187 [[ -z "$MUSE_REPO_ROOT" ]] && return
188
189 # Escape % so ZSH does not treat branch-name content as prompt directives.
190 local branch="${MUSE_BRANCH//\%/%%}"
191 local domain="${MUSE_DOMAIN//\%/%%}"
192
193 local dirty=""
194 (( MUSE_DIRTY )) && dirty=" %F{red}✗ ${MUSE_DIRTY_COUNT}%f"
195
196 # Format: muse:(domain:branch) — mirrors git:(branch) but adds the domain.
197 # Set MUSE_PROMPT_ICONS=1 in ~/.zshrc to prepend a domain icon.
198 if [[ "$MUSE_PROMPT_ICONS" == "1" ]]; then
199 local icon="${MUSE_DOMAIN_ICONS[$MUSE_DOMAIN]:-${MUSE_DOMAIN_ICONS[_default]}}"
200 echo -n "%F{cyan}${icon} muse:(%F{magenta}${domain}:${branch}%F{cyan})%f${dirty}"
201 else
202 echo -n "%F{cyan}muse:(%F{magenta}${domain}:${branch}%F{cyan})%f${dirty}"
203 fi
204 }
205
206 # ── §5 Debug ─────────────────────────────────────────────────────────────────
207
208 # Print current plugin state. Run when the prompt looks wrong.
209 # muse_debug
210 function muse_debug() {
211 print "MUSE_REPO_ROOT = ${MUSE_REPO_ROOT:-(not set)}"
212 print "MUSE_BRANCH = ${MUSE_BRANCH:-(not set)}"
213 print "MUSE_DOMAIN = ${MUSE_DOMAIN:-(not set)}"
214 print "MUSE_DIRTY = $MUSE_DIRTY (count: $MUSE_DIRTY_COUNT)"
215 print "_MUSE_CMD_RAN = $_MUSE_CMD_RAN"
216 print "PWD = $PWD"
217 if [[ -n "$MUSE_REPO_ROOT" ]]; then
218 print "repo.json = $MUSE_REPO_ROOT/.muse/repo.json"
219 print "HEAD = $(< "$MUSE_REPO_ROOT/.muse/HEAD" 2>/dev/null || print '(missing)')"
220 fi
221 }
222
223 # ── §6 Aliases ───────────────────────────────────────────────────────────────
224 alias mst='muse status'
225 alias msts='muse status --short'
226 alias mcm='muse commit -m'
227 alias mco='muse checkout'
228 alias mlg='muse log'
229 alias mlgo='muse log --oneline'
230 alias mlgg='muse log --graph'
231 alias mdf='muse diff'
232 alias mdfst='muse diff --stat'
233 alias mbr='muse branch'
234 alias mtg='muse tag'
235 alias mfh='muse fetch'
236 alias mpull='muse pull'
237 alias mpush='muse push'
238 alias mrm='muse remote'
239
240 # ── §7 Completion ────────────────────────────────────────────────────────────
241 if [[ -f "${0:A:h}/_muse" ]]; then
242 fpath=("${0:A:h}" $fpath)
243 autoload -Uz compinit
244 compdef _muse muse 2>/dev/null
245 fi
246
247 # ── §8 Init ──────────────────────────────────────────────────────────────────
248 # Warm head + domain on load so the first prompt is not blank.
249 _muse_refresh 2>/dev/null