gabriel / muse public
muse.plugin.zsh
275 lines 11.6 KB
2bf18039 fix(zsh-plugin): remove no-commit guard that kept branch purple after m… 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:=5}
32 : ${MUSE_DEBUG:=0} # set to 1 to print timestamped trace to stderr
33
34 # Domain icon map. Override individual elements in ~/.zshrc before plugins=().
35 typeset -gA MUSE_DOMAIN_ICONS
36 MUSE_DOMAIN_ICONS=(
37 midi "♪"
38 code "⌥"
39 bitcoin "₿"
40 scaffold "⬡"
41 _default "◈"
42 )
43
44 # ── Internal state ────────────────────────────────────────────────────────────
45 typeset -g MUSE_REPO_ROOT="" # absolute path to repo root, or ""
46 typeset -g MUSE_DOMAIN="midi" # active domain plugin name
47 typeset -g MUSE_BRANCH="" # branch name, 8-char SHA, or "?"
48 typeset -gi MUSE_DIRTY=0 # 1 when working tree has uncommitted changes
49 typeset -gi MUSE_DIRTY_COUNT=0 # number of changed paths
50 typeset -gi _MUSE_CMD_RAN=0 # 1 after any muse command runs
51
52 # ── §1 Core detection (zero subprocesses) ───────────────────────────────────
53
54 # Walk up from $PWD to find a valid Muse repo root. Sets MUSE_REPO_ROOT.
55 # A valid repo requires .muse/repo.json — a bare .muse/ directory is not
56 # enough. This prevents false positives from stray or partial .muse/ dirs
57 # (e.g. a forgotten muse init in a parent directory).
58 function _muse_find_root() {
59 local dir="$PWD"
60 while [[ "$dir" != "/" ]]; do
61 if [[ -f "$dir/.muse/repo.json" ]]; then
62 MUSE_REPO_ROOT="$dir"
63 return 0
64 fi
65 dir="${dir:h}"
66 done
67 MUSE_REPO_ROOT=""
68 return 1
69 }
70
71 # Read branch from .muse/HEAD without forking. Validates before storing.
72 # Branch names are restricted to [a-zA-Z0-9/_.-] to prevent prompt injection.
73 #
74 # Muse HEAD format (canonical, written by muse/core/store.py):
75 # ref: refs/heads/<branch> — on a branch (symbolic ref)
76 # commit: <sha256> — detached HEAD (direct commit reference)
77 function _muse_parse_head() {
78 local head_file="$MUSE_REPO_ROOT/.muse/HEAD"
79 if [[ ! -f "$head_file" ]]; then
80 MUSE_BRANCH=""; return 1
81 fi
82 local raw
83 raw=$(<"$head_file")
84 if [[ "$raw" == "ref: refs/heads/"* ]]; then
85 local branch="${raw#ref: refs/heads/}"
86 # Reject anything that could inject prompt escapes or path components.
87 if [[ "$branch" =~ '^[[:alnum:]/_.-]+$' ]]; then
88 MUSE_BRANCH="$branch"
89 else
90 MUSE_BRANCH="?"
91 fi
92 elif [[ "$raw" == "commit: "* ]]; then
93 local sha="${raw#commit: }"
94 MUSE_BRANCH="${sha:0:8}" # detached HEAD — show short SHA
95 else
96 MUSE_BRANCH="?"
97 fi
98 }
99
100 # Read domain from .muse/repo.json. One python3 call; path via env var only.
101 function _muse_parse_domain() {
102 local repo_json="$MUSE_REPO_ROOT/.muse/repo.json"
103 if [[ ! -f "$repo_json" ]]; then
104 MUSE_DOMAIN="midi"; return
105 fi
106 MUSE_DOMAIN=$(MUSE_REPO_JSON="$repo_json" python3 <<'PYEOF' 2>/dev/null
107 import json, os
108 try:
109 d = json.load(open(os.environ['MUSE_REPO_JSON']))
110 v = str(d.get('domain', 'midi'))
111 # Accept only safe domain names: alphanumeric plus hyphens/underscores,
112 # max 32 chars. Anything else falls back to 'midi'.
113 safe = v.replace('-', '').replace('_', '')
114 print(v if (safe.isalnum() and 1 <= len(v) <= 32) else 'midi')
115 except Exception:
116 print('midi')
117 PYEOF
118 )
119 : ${MUSE_DOMAIN:=midi}
120 }
121
122 # Check dirty state. Runs with timeout; called on cd, shell load, and after
123 # any muse command. MUSE_DIRTY_TIMEOUT (default 5s) caps the wait.
124 typeset -gi _MUSE_LAST_DIRTY_RC=0 # last exit code from the dirty check subprocess
125
126 function _muse_check_dirty() {
127 local output rc count=0
128 output=$(cd -- "$MUSE_REPO_ROOT" && \
129 timeout -- "${MUSE_DIRTY_TIMEOUT}" muse status --porcelain 2>/dev/null)
130 rc=$?
131 _MUSE_LAST_DIRTY_RC=$rc
132 if (( rc == 124 )); then
133 # Timeout — leave previous dirty state in place rather than lying.
134 return
135 fi
136 while IFS= read -r line; do
137 [[ "$line" == "##"* || -z "$line" ]] && continue
138 (( count++ ))
139 done <<< "$output"
140 MUSE_DIRTY=$(( count > 0 ? 1 : 0 ))
141 MUSE_DIRTY_COUNT=$count
142 }
143
144 # ── §2 Cache management ──────────────────────────────────────────────────────
145
146 # Full refresh: head + domain + dirty. Called on directory change and on load.
147 # One muse subprocess (status --porcelain) runs every time — same model as the
148 # git plugin. The timeout in _muse_check_dirty keeps it bounded.
149 function _muse_refresh() {
150 (( MUSE_DEBUG )) && print "[muse] _muse_refresh start $(date +%T.%3N)" >&2
151 if ! _muse_find_root; then
152 MUSE_DOMAIN="midi"; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
153 (( MUSE_DEBUG )) && print "[muse] _muse_find_root: no repo" >&2
154 return 1
155 fi
156 (( MUSE_DEBUG )) && print "[muse] root=$MUSE_REPO_ROOT" >&2
157 _muse_parse_head
158 (( MUSE_DEBUG )) && print "[muse] head done branch=$MUSE_BRANCH $(date +%T.%3N)" >&2
159 _muse_parse_domain
160 (( MUSE_DEBUG )) && print "[muse] domain done domain=$MUSE_DOMAIN $(date +%T.%3N)" >&2
161 _muse_check_dirty
162 (( MUSE_DEBUG )) && print "[muse] dirty done dirty=$MUSE_DIRTY rc=$_MUSE_LAST_DIRTY_RC $(date +%T.%3N)" >&2
163 }
164
165 # Post-command refresh: same as _muse_refresh but resets the command flag.
166 function _muse_refresh_full() {
167 (( MUSE_DEBUG )) && print "[muse] _muse_refresh_full (cmd_ran=$_MUSE_CMD_RAN)" >&2
168 _muse_refresh || return
169 _MUSE_CMD_RAN=0
170 }
171
172 # ── §3 ZSH hooks ─────────────────────────────────────────────────────────────
173
174 # On directory change: refresh head and domain; clear dirty (stale after cd).
175 # Pre-clear MUSE_REPO_ROOT so any silent failure in _muse_refresh leaves the
176 # prompt blank rather than showing stale data from the previous directory.
177 function _muse_hook_chpwd() {
178 MUSE_REPO_ROOT=""; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
179 _muse_refresh 2>/dev/null
180 }
181 chpwd_functions+=(_muse_hook_chpwd)
182
183 # Before a command: flag when the user runs muse so we refresh after.
184 function _muse_hook_preexec() {
185 [[ "${${(z)1}[1]}" == "muse" ]] && _MUSE_CMD_RAN=1
186 }
187 preexec_functions+=(_muse_hook_preexec)
188
189 # Before the prompt: full refresh only when a muse command just ran.
190 function _muse_hook_precmd() {
191 (( _MUSE_CMD_RAN )) && _muse_refresh_full 2>/dev/null
192 }
193 precmd_functions+=(_muse_hook_precmd)
194
195 # ── §4 Prompt ────────────────────────────────────────────────────────────────
196
197 # Primary prompt segment. Example usage in ~/.zshrc:
198 # PROMPT='%~ $(muse_prompt_info) %# '
199 # Emits nothing when not inside a muse repo.
200 #
201 # Clean: muse:(code:main) — domain:branch in magenta
202 # Dirty: muse:(code:main) — domain:branch in yellow
203 #
204 # The color of the domain:branch text is the only dirty signal — no extra
205 # symbol. Yellow means "uncommitted changes exist"; magenta means clean.
206 function muse_prompt_info() {
207 [[ -z "$MUSE_REPO_ROOT" ]] && return
208
209 # Escape % so ZSH does not treat branch-name content as prompt directives.
210 local branch="${MUSE_BRANCH//\%/%%}"
211 local domain="${MUSE_DOMAIN//\%/%%}"
212
213 # Yellow interior when dirty; magenta when clean.
214 local inner_color="%F{magenta}"
215 (( MUSE_DIRTY )) && inner_color="%F{yellow}"
216
217 # Format: muse:(domain:branch) — mirrors git:(branch) but adds the domain.
218 # Set MUSE_PROMPT_ICONS=1 in ~/.zshrc to prepend a domain icon.
219 if [[ "$MUSE_PROMPT_ICONS" == "1" ]]; then
220 local icon="${MUSE_DOMAIN_ICONS[$MUSE_DOMAIN]:-${MUSE_DOMAIN_ICONS[_default]}}"
221 echo -n "%F{cyan}${icon} muse:(${inner_color}${domain}:${branch}%F{cyan})%f"
222 else
223 echo -n "%F{cyan}muse:(${inner_color}${domain}:${branch}%F{cyan})%f"
224 fi
225 }
226
227 # ── §5 Debug ─────────────────────────────────────────────────────────────────
228
229 # Print current plugin state. Run when the prompt looks wrong.
230 # muse_debug
231 function muse_debug() {
232 print "MUSE_REPO_ROOT = ${MUSE_REPO_ROOT:-(not set)}"
233 print "MUSE_BRANCH = ${MUSE_BRANCH:-(not set)}"
234 print "MUSE_DOMAIN = ${MUSE_DOMAIN:-(not set)}"
235 print "MUSE_DIRTY = $MUSE_DIRTY (count: $MUSE_DIRTY_COUNT)"
236 print "MUSE_DIRTY_TIMEOUT = ${MUSE_DIRTY_TIMEOUT}s"
237 print "_MUSE_LAST_DIRTY_RC = $_MUSE_LAST_DIRTY_RC (124 = timed out)"
238 print "_MUSE_CMD_RAN = $_MUSE_CMD_RAN"
239 print "PWD = $PWD"
240 if [[ -n "$MUSE_REPO_ROOT" ]]; then
241 print "repo.json = $MUSE_REPO_ROOT/.muse/repo.json"
242 print "HEAD = $(< "$MUSE_REPO_ROOT/.muse/HEAD" 2>/dev/null || print '(missing)')"
243 print "--- muse status --porcelain (live, timed) ---"
244 time (cd -- "$MUSE_REPO_ROOT" && muse status --porcelain 2>&1)
245 print "--------------------------------------------"
246 fi
247 }
248
249 # ── §6 Aliases ───────────────────────────────────────────────────────────────
250 alias mst='muse status'
251 alias msts='muse status --short'
252 alias mcm='muse commit -m'
253 alias mco='muse checkout'
254 alias mlg='muse log'
255 alias mlgo='muse log --oneline'
256 alias mlgg='muse log --graph'
257 alias mdf='muse diff'
258 alias mdfst='muse diff --stat'
259 alias mbr='muse branch'
260 alias mtg='muse tag'
261 alias mfh='muse fetch'
262 alias mpull='muse pull'
263 alias mpush='muse push'
264 alias mrm='muse remote'
265
266 # ── §7 Completion ────────────────────────────────────────────────────────────
267 if [[ -f "${0:A:h}/_muse" ]]; then
268 fpath=("${0:A:h}" $fpath)
269 autoload -Uz compinit
270 compdef _muse muse 2>/dev/null
271 fi
272
273 # ── §8 Init ──────────────────────────────────────────────────────────────────
274 # Warm head + domain on load so the first prompt is not blank.
275 _muse_refresh 2>/dev/null