gabriel / muse public
muse.plugin.zsh
281 lines 11.9 KB
4164158d feat(zsh-plugin): revert branch to magenta when clean, yellow when dirty 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 print "[muse:dirty] running: muse status --porcelain in $MUSE_REPO_ROOT" >&2
129 output=$(cd -- "$MUSE_REPO_ROOT" && \
130 timeout -- "${MUSE_DIRTY_TIMEOUT}" muse status --porcelain 2>&1)
131 rc=$?
132 _MUSE_LAST_DIRTY_RC=$rc
133 print "[muse:dirty] rc=$rc output=$(echo $output | head -c 200)" >&2
134 if (( rc == 124 )); then
135 print "[muse:dirty] TIMED OUT — MUSE_DIRTY unchanged ($MUSE_DIRTY)" >&2
136 return
137 fi
138 while IFS= read -r line; do
139 [[ "$line" == "##"* || -z "$line" ]] && continue
140 (( count++ ))
141 done <<< "$output"
142 MUSE_DIRTY=$(( count > 0 ? 1 : 0 ))
143 MUSE_DIRTY_COUNT=$count
144 print "[muse:dirty] MUSE_DIRTY=$MUSE_DIRTY count=$count" >&2
145 }
146
147 # ── §2 Cache management ──────────────────────────────────────────────────────
148
149 # Full refresh: head + domain + dirty. Called on directory change and on load.
150 # One muse subprocess (status --porcelain) runs every time — same model as the
151 # git plugin. The timeout in _muse_check_dirty keeps it bounded.
152 function _muse_refresh() {
153 (( MUSE_DEBUG )) && print "[muse] _muse_refresh start $(date +%T.%3N)" >&2
154 if ! _muse_find_root; then
155 MUSE_DOMAIN="midi"; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
156 (( MUSE_DEBUG )) && print "[muse] _muse_find_root: no repo" >&2
157 return 1
158 fi
159 (( MUSE_DEBUG )) && print "[muse] root=$MUSE_REPO_ROOT" >&2
160 _muse_parse_head
161 (( MUSE_DEBUG )) && print "[muse] head done branch=$MUSE_BRANCH $(date +%T.%3N)" >&2
162 _muse_parse_domain
163 (( MUSE_DEBUG )) && print "[muse] domain done domain=$MUSE_DOMAIN $(date +%T.%3N)" >&2
164 _muse_check_dirty
165 (( MUSE_DEBUG )) && print "[muse] dirty done dirty=$MUSE_DIRTY rc=$_MUSE_LAST_DIRTY_RC $(date +%T.%3N)" >&2
166 }
167
168 # Post-command refresh: same as _muse_refresh but resets the command flag.
169 function _muse_refresh_full() {
170 (( MUSE_DEBUG )) && print "[muse] _muse_refresh_full (cmd_ran=$_MUSE_CMD_RAN)" >&2
171 _muse_refresh || return
172 _MUSE_CMD_RAN=0
173 }
174
175 # ── §3 ZSH hooks ─────────────────────────────────────────────────────────────
176
177 # On directory change: refresh head and domain; clear dirty (stale after cd).
178 # Pre-clear MUSE_REPO_ROOT so any silent failure in _muse_refresh leaves the
179 # prompt blank rather than showing stale data from the previous directory.
180 function _muse_hook_chpwd() {
181 MUSE_REPO_ROOT=""; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
182 _muse_refresh
183 }
184 chpwd_functions+=(_muse_hook_chpwd)
185
186 # Before a command: flag when the user runs muse so we refresh after.
187 function _muse_hook_preexec() {
188 [[ "${${(z)1}[1]}" == "muse" ]] && _MUSE_CMD_RAN=1
189 }
190 preexec_functions+=(_muse_hook_preexec)
191
192 # Before the prompt: full refresh only when a muse command just ran.
193 function _muse_hook_precmd() {
194 print "[muse:precmd] _MUSE_CMD_RAN=$_MUSE_CMD_RAN" >&2
195 (( _MUSE_CMD_RAN )) && _muse_refresh_full
196 }
197 precmd_functions+=(_muse_hook_precmd)
198
199 # ── §4 Prompt ────────────────────────────────────────────────────────────────
200
201 # Primary prompt segment. Example usage in ~/.zshrc:
202 # PROMPT='%~ $(muse_prompt_info) %# '
203 # Emits nothing when not inside a muse repo.
204 #
205 # Clean: muse:(code:main) — domain:branch in magenta
206 # Dirty: muse:(code:main) — domain:branch in yellow
207 #
208 # The color of the domain:branch text is the only dirty signal — no extra
209 # symbol. Yellow means "uncommitted changes exist"; magenta means clean.
210 function muse_prompt_info() {
211 [[ -z "$MUSE_REPO_ROOT" ]] && return
212
213 local _dbg_color; (( MUSE_DIRTY )) && _dbg_color=YELLOW || _dbg_color=MAGENTA
214 print "[muse:prompt] MUSE_DIRTY=$MUSE_DIRTY → color=$_dbg_color" >&2
215
216 # Escape % so ZSH does not treat branch-name content as prompt directives.
217 local branch="${MUSE_BRANCH//\%/%%}"
218 local domain="${MUSE_DOMAIN//\%/%%}"
219
220 # Branch: magenta when clean, yellow when dirty. Domain is always magenta.
221 local branch_color="%F{magenta}"
222 (( MUSE_DIRTY )) && branch_color="%F{yellow}"
223
224 # Format: %F{cyan}muse:(%F{magenta}<domain>:%F{yellow|magenta}<branch>%F{cyan})%f
225 if [[ "$MUSE_PROMPT_ICONS" == "1" ]]; then
226 local icon="${MUSE_DOMAIN_ICONS[$MUSE_DOMAIN]:-${MUSE_DOMAIN_ICONS[_default]}}"
227 echo -n "%F{cyan}${icon} muse:(%F{magenta}${domain}:${branch_color}${branch}%F{cyan})%f"
228 else
229 echo -n "%F{cyan}muse:(%F{magenta}${domain}:${branch_color}${branch}%F{cyan})%f"
230 fi
231 }
232
233 # ── §5 Debug ─────────────────────────────────────────────────────────────────
234
235 # Print current plugin state. Run when the prompt looks wrong.
236 # muse_debug
237 function muse_debug() {
238 print "MUSE_REPO_ROOT = ${MUSE_REPO_ROOT:-(not set)}"
239 print "MUSE_BRANCH = ${MUSE_BRANCH:-(not set)}"
240 print "MUSE_DOMAIN = ${MUSE_DOMAIN:-(not set)}"
241 print "MUSE_DIRTY = $MUSE_DIRTY (count: $MUSE_DIRTY_COUNT)"
242 print "MUSE_DIRTY_TIMEOUT = ${MUSE_DIRTY_TIMEOUT}s"
243 print "_MUSE_LAST_DIRTY_RC = $_MUSE_LAST_DIRTY_RC (124 = timed out)"
244 print "_MUSE_CMD_RAN = $_MUSE_CMD_RAN"
245 print "PWD = $PWD"
246 if [[ -n "$MUSE_REPO_ROOT" ]]; then
247 print "repo.json = $MUSE_REPO_ROOT/.muse/repo.json"
248 print "HEAD = $(< "$MUSE_REPO_ROOT/.muse/HEAD" 2>/dev/null || print '(missing)')"
249 print "--- muse status --porcelain (live, timed) ---"
250 time (cd -- "$MUSE_REPO_ROOT" && muse status --porcelain 2>&1)
251 print "--------------------------------------------"
252 fi
253 }
254
255 # ── §6 Aliases ───────────────────────────────────────────────────────────────
256 alias mst='muse status'
257 alias msts='muse status --short'
258 alias mcm='muse commit -m'
259 alias mco='muse checkout'
260 alias mlg='muse log'
261 alias mlgo='muse log --oneline'
262 alias mlgg='muse log --graph'
263 alias mdf='muse diff'
264 alias mdfst='muse diff --stat'
265 alias mbr='muse branch'
266 alias mtg='muse tag'
267 alias mfh='muse fetch'
268 alias mpull='muse pull'
269 alias mpush='muse push'
270 alias mrm='muse remote'
271
272 # ── §7 Completion ────────────────────────────────────────────────────────────
273 if [[ -f "${0:A:h}/_muse" ]]; then
274 fpath=("${0:A:h}" $fpath)
275 autoload -Uz compinit
276 compdef _muse muse 2>/dev/null
277 fi
278
279 # ── §8 Init ──────────────────────────────────────────────────────────────────
280 # Warm head + domain on load so the first prompt is not blank.
281 _muse_refresh 2>/dev/null