"""Test worktree creation, shared refs, detached reviews, and ordinary removal."""
from hashlib import sha256
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
def main():
codex = shutil.which("codex.exe") or shutil.which("codex")
git = shutil.which("git")
if not codex or not git:
raise SystemExit("Install Codex CLI and Git and add both to PATH.")
observations = []
with TemporaryDirectory(prefix="mbsky-worktree-lifecycle-") as temporary:
root = Path(temporary).resolve()
repo = root / "repo"
repo.mkdir()
topic = root / "topic"
review = root / "review"
conflict = root / "duplicate"
env = {k:v for k,v in os.environ.items() if not k.startswith(("GIT_", "CODEX_"))}
env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, CODEX_HOME=str(root/"diagnostic-profile"))
def run(cwd, *args, binary=git, check=True):
result = subprocess.run([binary,*args], cwd=cwd, env=env, capture_output=True,
encoding="utf8", check=check, timeout=15)
return result if not check else result.stdout.strip()
def verify(name, inputs, operation, expected, actual):
assert expected == actual, (name, expected, actual)
observations.append(dict(name="worktrees_"+name,input=inputs,operation=operation,
expected=expected,actual=actual))
def listed():
return run(repo,"worktree","list","--porcelain").count("worktree ")
run(repo,"init","--quiet","--initial-branch=main","--template=")
run(repo,"config","core.autocrlf","false")
run(repo,"config","commit.gpgsign","false")
(repo/"notes.txt").write_bytes(b"catalog=ready\n")
run(repo,"add","notes.txt")
run(repo,"-c","user.name=Tutorial Lab","-c","user.email=fixture@example.invalid","commit","--quiet","-m","Baseline")
verify("initial","fresh repository","Observe the initial worktree listing",1,listed())
run(repo,"worktree","add","--quiet","-b","topic/catalog",str(topic),"main")
run(repo,"worktree","add","--quiet","--detach",str(review),"main")
verify("add",["topic/catalog","detached main"],"Observe listing after adding two fixtures",3,listed())
verify("detached","main base commit","Compare HEADs and check detached branch name",
[True,""],[run(review,"rev-parse","HEAD")==run(repo,"rev-parse","HEAD"),run(review,"branch","--show-current")])
occupied = run(repo,"worktree","add",str(conflict),"topic/catalog",check=False)
verify("occupied","topic/catalog","Attempt a second checkout of an occupied branch",
[True,False],[occupied.returncode != 0,conflict.exists()])
(topic/"notes.txt").write_bytes(b"catalog=draft\n")
run(topic,"add","notes.txt")
verify("index","notes.txt staged only in topic","Read each index and file contents",
[["","notes.txt",""],["catalog=ready","catalog=draft","catalog=ready"]],
[[run(path,"diff","--cached","--name-only") for path in (repo,topic,review)],
[(path/"notes.txt").read_text().strip() for path in (repo,topic,review)]])
refusal = run(repo,"worktree","remove",str(topic),check=False)
verify("dirty_remove","staged change","Attempt ordinary removal from the owning repository",
[True,True],[refusal.returncode != 0,topic.exists()])
run(topic,"-c","user.name=Tutorial Lab","-c","user.email=fixture@example.invalid","commit","--quiet","-m","Update catalog")
for target in (review,topic):
assert target.parent.resolve() == root
run(repo,"worktree","remove",str(target))
verify("cleanup","saved branch and clean worktrees","Remove the two fixtures, then read the branch ref",
[1,"catalog=draft"],[listed(),run(repo,"show","topic/catalog:notes.txt")])
print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":run(repo,"--version",binary=codex),
"git":run(repo,"--version")},codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(),cases=observations)))
if __name__ == "__main__":
main()
本例需在 Windows、Python 3.12.14、git version 2.54.0.windows.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、git version 2.54.0.windows.1。
入口文件:projects/codex-worktree_lifecycle/worktree_lifecycle_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
worktree_lifecycle_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、git version 2.54.0.windows.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a127.zip