gabriel / muse public
muse.plugin.zsh
258 lines 10.4 KB
72738443 fix(zsh-plugin): run dirty check on cd and shell load, not only 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:=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 # Full refresh: head + domain + dirty. Called on directory change and on load.
142 # One muse subprocess (status --porcelain) runs every time — same model as the
143 # git plugin. The timeout in _muse_check_dirty keeps it bounded.
144 function _muse_refresh() {
145 if ! _muse_find_root; then
146 MUSE_DOMAIN="midi"; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
147 return 1
148 fi
149 _muse_parse_head
150 _muse_parse_domain
151 _muse_check_dirty
152 }
153
154 # Post-command refresh: same as _muse_refresh but resets the command flag.
155 function _muse_refresh_full() {
156 _muse_refresh || return
157 _MUSE_CMD_RAN=0
158 }
159
160 # ── §3 ZSH hooks ─────────────────────────────────────────────────────────────
161
162 # On directory change: refresh head and domain; clear dirty (stale after cd).
163 # Pre-clear MUSE_REPO_ROOT so any silent failure in _muse_refresh leaves the
164 # prompt blank rather than showing stale data from the previous directory.
165 function _muse_hook_chpwd() {
166 MUSE_REPO_ROOT=""; MUSE_BRANCH=""; MUSE_DIRTY=0; MUSE_DIRTY_COUNT=0
167 _muse_refresh 2>/dev/null
168 }
169 chpwd_functions+=(_muse_hook_chpwd)
170
171 # Before a command: flag when the user runs muse so we refresh after.
172 function _muse_hook_preexec() {
173 [[ "${${(z)1}[1]}" == "muse" ]] && _MUSE_CMD_RAN=1
174 }
175 preexec_functions+=(_muse_hook_preexec)
176
177 # Before the prompt: full refresh only when a muse command just ran.
178 function _muse_hook_precmd() {
179 (( _MUSE_CMD_RAN )) && _muse_refresh_full 2>/dev/null
180 }
181 precmd_functions+=(_muse_hook_precmd)
182
183 # ── §4 Prompt ────────────────────────────────────────────────────────────────
184
185 # Primary prompt segment. Example usage in ~/.zshrc:
186 # PROMPT='%~ $(muse_prompt_info) %# '
187 # Emits nothing when not inside a muse repo.
188 #
189 # Clean: muse:(code:main) — domain:branch in magenta
190 # Dirty: muse:(code:main) — domain:branch in yellow
191 #
192 # The color of the domain:branch text is the only dirty signal — no extra
193 # symbol. Yellow means "uncommitted changes exist"; magenta means clean.
194 function muse_prompt_info() {
195 [[ -z "$MUSE_REPO_ROOT" ]] && return
196
197 # Escape % so ZSH does not treat branch-name content as prompt directives.
198 local branch="${MUSE_BRANCH//\%/%%}"
199 local domain="${MUSE_DOMAIN//\%/%%}"
200
201 # Yellow interior when dirty; magenta when clean.
202 local inner_color="%F{magenta}"
203 (( MUSE_DIRTY )) && inner_color="%F{yellow}"
204
205 # Format: muse:(domain:branch) — mirrors git:(branch) but adds the domain.
206 # Set MUSE_PROMPT_ICONS=1 in ~/.zshrc to prepend a domain icon.
207 if [[ "$MUSE_PROMPT_ICONS" == "1" ]]; then
208 local icon="${MUSE_DOMAIN_ICONS[$MUSE_DOMAIN]:-${MUSE_DOMAIN_ICONS[_default]}}"
209 echo -n "%F{cyan}${icon} muse:(${inner_color}${domain}:${branch}%F{cyan})%f"
210 else
211 echo -n "%F{cyan}muse:(${inner_color}${domain}:${branch}%F{cyan})%f"
212 fi
213 }
214
215 # ── §5 Debug ─────────────────────────────────────────────────────────────────
216
217 # Print current plugin state. Run when the prompt looks wrong.
218 # muse_debug
219 function muse_debug() {
220 print "MUSE_REPO_ROOT = ${MUSE_REPO_ROOT:-(not set)}"
221 print "MUSE_BRANCH = ${MUSE_BRANCH:-(not set)}"
222 print "MUSE_DOMAIN = ${MUSE_DOMAIN:-(not set)}"
223 print "MUSE_DIRTY = $MUSE_DIRTY (count: $MUSE_DIRTY_COUNT)"
224 print "_MUSE_CMD_RAN = $_MUSE_CMD_RAN"
225 print "PWD = $PWD"
226 if [[ -n "$MUSE_REPO_ROOT" ]]; then
227 print "repo.json = $MUSE_REPO_ROOT/.muse/repo.json"
228 print "HEAD = $(< "$MUSE_REPO_ROOT/.muse/HEAD" 2>/dev/null || print '(missing)')"
229 fi
230 }
231
232 # ── §6 Aliases ───────────────────────────────────────────────────────────────
233 alias mst='muse status'
234 alias msts='muse status --short'
235 alias mcm='muse commit -m'
236 alias mco='muse checkout'
237 alias mlg='muse log'
238 alias mlgo='muse log --oneline'
239 alias mlgg='muse log --graph'
240 alias mdf='muse diff'
241 alias mdfst='muse diff --stat'
242 alias mbr='muse branch'
243 alias mtg='muse tag'
244 alias mfh='muse fetch'
245 alias mpull='muse pull'
246 alias mpush='muse push'
247 alias mrm='muse remote'
248
249 # ── §7 Completion ────────────────────────────────────────────────────────────
250 if [[ -f "${0:A:h}/_muse" ]]; then
251 fpath=("${0:A:h}" $fpath)
252 autoload -Uz compinit
253 compdef _muse muse 2>/dev/null
254 fi
255
256 # ── §8 Init ──────────────────────────────────────────────────────────────────
257 # Warm head + domain on load so the first prompt is not blank.
258 _muse_refresh 2>/dev/null