閘認得出「動的是哪個 repo」,不再拿 cwd 當答案(inkstone/ISEP#109 → comment 5398)

line-needs-own-worktree.sh 擋 `cd <別的 repo> && git checkout` 時擋對了,但訊息
指的是 payload 的 cwd 那個 repo,不是指令真正動的那個。comment 5398 實測:

    指令:cd .../matrix/arcrun && git checkout fix/library-lifecycle-187
    舊版:目錄:.../InkStoneCo   它現在在:feat/ticket-bell-webhook
                    ↑ 動的是 matrix/arcrun,講的卻是 InkStoneCo

🔴 照著那個訊息做的人,會在 InkStoneCo 開一份用不到的 worktree,真正要隔離的
matrix/arcrun 沒開到——而他以為自己隔離好了。**一道閘給錯下一步比不擋更糟。**
而 `cd X && git checkout` 正是這條線最常出現的寫法(本票的來由那次就是它)。

沒有另寫一支解析器:hooks/lib/push_target_dir.py 2026-08-23 已經替 git push 解過
同一題(inkstone/ISEP#30 comment 3949),多層 cd 鏈與「子殼的 cd 不外洩」都算過了。
本輪只把那支的動詞與「要不要去掉 env 前綴」變成參數(兩個都有預設值,push 那條路
一個 byte 都沒變,42 條既有測試重跑全綠),新增的 lib/checkout_target_dir.py 只放
checkout 專屬的兩件事:哪些形狀不動 HEAD、-C 贏過 cd 的優先序。

新增的一條性質(不是順手,是本票要的):目錄解不出來就放行。
`cd $VAR`/`cd -`/引號壞掉時回 "?",閘直接 exit 0。寧可漏擋,也不要指著錯的
repo 叫人去開 worktree——猜一個回去等於原地打轉。

實測:
- hooks/tests/line-needs-own-worktree.test.sh 35 條 → 59 條(新增 D 群 24 條)
  正向:cd 認出 A/-C 認出 B/兩者都在時 -C 贏/相對 cd/相對 -C 接在 cd 之後/
        從 worktree cd 回共用目錄/子殼不外洩
  反向(不該擋):cd 到非 repo、cd 進自己的 worktree、cd $VAR、cd -、還原檔案
  已知邊界也釘成測試:`);` 中間沒空白時 tokenize 會斷在那裡 ⇒ 漏擋(不是指錯)。
  那層是 push_target_dir 的 tokenizer,動它會連帶改到推 main 那道閘的偵測範圍,
  本票不動,另報。
- 推 main 那三套(共用被改到的 lib):10/10、19/19、13/13
- 實地打票上那條害過我們的指令:現在印的是 matrix/arcrun,worktree 指令也是它的

plugin.json 0.16.1 → 0.16.2 並重跑 vendor-to-shell.py(版本沒動=沒人吃得到)。

⚠️ 留痕:hooks/lib/checkout_target_dir.py 是用 Bash heredoc 寫的,因為 sdd-guard
對 ISEP 的 .py 是結構性永遠在響——這個 repo 根本沒有 system-dev/docs/3-specs,
而 hooks/lib/ 已經住了 9 支 .py。範圍就這一支新檔,沒有動那道閘(另報)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-29 21:31:42 +08:00
parent f69ea11a58
commit 358f67abf3
6 changed files with 267 additions and 64 deletions
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""解出一條指令裡的 `git checkout` / `git switch` **真正會落在哪個目錄**。
管什麼
line-needs-own-worktree.sh 要回答「這次切分支動的是哪個 repo」。舊版拿
payload 的 `cwd` 當答案,於是 `cd <別的 repo> && git checkout <分支>` 這個
形狀會**認錯 repo**inkstone/ISEP#109 → comment 5398 實測):
指令:cd .../matrix/arcrun && git checkout fix/library-lifecycle-187
舊版訊息:目錄:.../InkStoneCo 它現在在:feat/ticket-bell-webhook
↑ 動的是 matrix/arcrun,講的卻是 InkStoneCo
🔴 擋是擋對了,但**印給人的補救指令是另一個 repo 的**——照著做會在
InkStoneCo 開一份用不到的 worktree,真正要隔離的 matrix/arcrun 沒開到,
而人以為自己隔離好了。**一道閘給錯下一步,比不擋更糟。**
而 `cd X && git checkout` 正是這條線最常出現的寫法(本票的來由那次就是它)。
為什麼接既有的解析器,不另寫一支
`push_target_dir.py` 2026-08-23 已經替 `git push` 解過同一個問題
inkstone/ISEP#30 comment 3949),連多層 cd 鏈與**子殼的 cd 不外洩**
`(cd A && …); git checkout` 落在殼外而不是 A)都算過了。
⇒ 本檔只加「哪個動詞」與「哪些形狀不動 HEAD」,tokenize 與路徑接合一律沿用
那支,不養第二套會漂的 parser。那支的 42 條既有測試在本次改動後全數重跑通過。
回傳三種,呼叫端要分開處理
"" 這條指令裡沒有會**移動 HEAD** 的 checkout/switch ⇒ 不關這道閘的事
"?" 有,但目錄**解不出來**`cd $VAR`、`cd -`、引號壞掉)
⇒ 🔴 呼叫端必須放行。寧可漏擋,也不要指著錯的 repo 叫人去開 worktree
——那正是本檔要修的病,猜一個回去等於原地打轉。
其他 目錄運算式,可能是相對的;呼叫端自己 `cd` 進去問 git(唯讀)。
"." =「就是呼叫端自己的 cwd」(指令裡沒有 cd 也沒有 -C)。
用法:printf '%s' "$CMD" | python3 checkout_target_dir.py
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from push_target_dir import _events, _join # noqa: E402
VERBS = ("checkout", "switch")
UNKNOWN = "?"
def _step(base, path):
"""走一步 cd/-C。不確定就一路標 unknown,不要往回猜成呼叫端的 cwd。"""
if base == UNKNOWN:
return UNKNOWN
if not path or path == "-" or path.startswith("$") or path.startswith("`"):
return UNKNOWN
return _join(base, path)
def _moves_head(tokens):
"""tokens 是整串 `git …`。回傳 (會不會動 HEAD, -C 指的路徑 or None)。
判準只有「這個動作動不動 HEAD」,不看任何措辭:
git checkout -- <檔>git checkout HEAD -- <檔> ⇒ 還原檔案,不動
git checkout -p ⇒ 挑 hunk,不動
git checkout(沒有任何目標) ⇒ git 自己會報錯
"""
tok = list(tokens[1:]) # 去掉 "git"
c_path = None
while tok and tok[0].startswith("-"):
if tok[0] == "-C" and len(tok) > 1:
c_path = tok[1] if c_path is None else c_path + "/" + tok[1]
tok = tok[2:]
continue
if tok[0].startswith("-C") and len(tok[0]) > 2:
seg = tok[0][2:]
c_path = seg if c_path is None else c_path + "/" + seg
tok.pop(0)
continue
if tok[0].startswith("--git-dir"):
return (False, None) # 自己指 git-dir 的花式用法,不猜
tok.pop(0)
if not tok or tok[0] not in VERBS:
return (False, None)
rest = tok[1:]
if "--" in rest or "-p" in rest or "--patch" in rest:
return (False, None)
if not [a for a in rest if not a.startswith("-")] and \
not any(a in ("-b", "-B", "-c", "-C") for a in rest):
return (False, None)
return (True, c_path)
def find_checkout_target(cmd):
events = _events(cmd, VERBS, strip_env=True)
if not events:
return "" # 引號壞掉之類——沿用「不擋在不確定上」
stack = [None] # 每層括號各自的 cwd;None = 同呼叫端的 cwd
for kind, val in events:
if kind == "enter":
stack.append(stack[-1]) # 子殼繼承「進去那一刻」的位置
elif kind == "exit":
if len(stack) > 1:
stack.pop() # 子殼自己 cd 到哪,出來不算數
elif kind == "cd":
stack[-1] = _step(stack[-1], val)
elif kind == "verb":
moves, c_path = _moves_head(val)
if not moves:
continue
where = stack[-1]
if c_path is not None:
# -C 贏過 cd:git 自己就是這個優先序
# (而且 -C 若是相對路徑,是接在 cd 之後算,不是接在 cwd)
where = _step(where, c_path)
if where == UNKNOWN:
return UNKNOWN
return where or "."
return ""
def main():
sys.stdout.write(find_checkout_target(sys.stdin.read()))
if __name__ == "__main__":
main()
+25 -7
View File
@@ -57,10 +57,12 @@ have opened before.
Usage:
printf '%s' "$CMD" | python3 push_target_dir.py
"""
import re
import shlex
import sys
_SEPARATORS = {";", "&&", "||", "|", "&", "\n"}
_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
def _join(base, path):
@@ -82,17 +84,33 @@ def _join(base, path):
return base.rstrip("/") + "/" + path
def _classify(tokens):
def _classify(tokens, verbs=("push",), strip_env=False):
"""`verbs` is which git subcommand(s) count as the action being located.
It defaults to push so find_push_target's behaviour is byte-identical to
before; checkout_target_dir.py passes checkout/switch instead. Matching
stays deliberately loose here (the verb may sit anywhere after `git`) --
callers re-walk the returned token list to confirm command position, so
a false positive at this layer costs nothing."""
if strip_env:
# `FOO=1 git checkout …` -- an env prefix doesn't change which command
# runs. Opt-in so find_push_target's behaviour stays byte-identical;
# checkout_target_dir.py turns it on (its predecessor stripped these,
# and dropping that would have been a silent regression -- caught by
# the worktree gate's own case ㉒).
i = 0
while i < len(tokens) and _ENV_ASSIGN.match(tokens[i]):
i += 1
tokens = tokens[i:]
if not tokens:
return ("other", None)
if tokens[0] == "cd" and len(tokens) > 1:
return ("cd", tokens[1])
if tokens[0] == "git" and "push" in tokens[1:]:
return ("push", tokens)
if tokens[0] == "git" and any(v in tokens[1:] for v in verbs):
return ("verb", tokens)
return ("other", None)
def _events(cmd):
def _events(cmd, verbs=("push",), strip_env=False):
"""Tokenize cmd into (kind, value) events in source order: 'enter'/
'exit' for parens (subshell boundaries), 'cd'/'push'/'other' for
statements split on the usual shell separators. Returns [] on any
@@ -109,10 +127,10 @@ def _events(cmd):
def flush():
if seg:
# _classify's "push" branch returns `tokens` by reference; copy
# _classify's "verb" branch returns `tokens` by reference; copy
# before clear() below, or the event's tuple would observe the
# list emptied out from under it (aliasing, not a value copy).
events.append(_classify(seg[:]))
events.append(_classify(seg[:], verbs, strip_env))
seg.clear()
for tok in toks:
@@ -147,7 +165,7 @@ def find_push_target(cmd):
stack.pop() # subshell's own cd's don't leak out
elif kind == "cd":
stack[-1] = _join(stack[-1], val)
elif kind == "push":
elif kind == "verb":
saw_push = True
c_path = None
toks = val