From 720be1959e02579bc127457bd726d51c18f38b83 Mon Sep 17 00:00:00 2001 From: DandreYang <13072547+Dandre126@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:23:45 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E7=BA=BF):=20=E6=96=B0=E5=A2=9E=20line=20?= =?UTF-8?q?add-repo=20=E5=B9=B6=E4=BF=AE=E5=A4=8D=E5=BB=BA=E7=BA=BF?= =?UTF-8?q?=E5=9B=9E=E6=BB=9A=E9=81=97=E7=95=99=E5=88=86=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 dyro line add-repo:把一个已登记仓库加入现有开发线;子线保持不变,子线只能加入父线已有的仓库,基线与存储方式从父线派生。 - 锁顺序与 line retire 相同(身份锁、线合并锁、仓库锁),清单在合并锁内重读。 - 失败时只删除新建的目标及其变空的父目录。 - create、spawn、add-repo 回滚时删除本次用 -b 新建的分支,已有分支保持不动;路径清理失败时仍尝试删除并一并报告。 --- CHANGELOG.md | 3 + src/dyro/cli.py | 37 ++++ src/dyro/workspace.py | 259 ++++++++++++++++++----- tests/test_line_add_repo.py | 402 ++++++++++++++++++++++++++++++++++++ 4 files changed, 646 insertions(+), 55 deletions(-) create mode 100644 tests/test_line_add_repo.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dd0d5d..6a495c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- 新增 `dyro line add-repo`:把一个已经登记的仓库加入现有开发线。已有子线保持不变;子线只能加入父线里已经有的仓库。 +- 修复 `dyro line create` / `dyro line spawn` 中途失败回滚时留下本次新建分支的问题:之前用另一个基线重试会静默复用旧分支;现在回滚会删除本次新建的分支,原本就有的分支保持不动。 + ## 0.7.18 - 2026-11-14 对使用者的影响:修复 0.7.17 中 `dyro line merge --into --push` 不写远端锚点、推送前就报完成的问题;macOS 上工作区或主目录位于 `/var`、`/tmp` 下时不再误报不安全文件或清单过期。 diff --git a/src/dyro/cli.py b/src/dyro/cli.py index ff86989..3185a20 100644 --- a/src/dyro/cli.py +++ b/src/dyro/cli.py @@ -250,6 +250,7 @@ ) from .workspace import ( OBSERVATION_DEADLINE_FINDING, + add_line_repository, blocking_line_doctor_failures, create_line, doctor, @@ -3124,6 +3125,23 @@ def cmd_line_spawn(args: argparse.Namespace) -> None: ) +def cmd_line_add_repo(args: argparse.Namespace) -> None: + config = _config(args) + _require_yes(args, "向开发线加入仓库") + line = add_line_repository( + config, + args.line, + args.repo, + base=args.base, + storage=args.storage, + dry_run=args.dry_run, + ) + print( + f"{'DRY RUN: ' if args.dry_run else ''}已为 {line.kind} {line.id} 加入仓库 {args.repo}," + f"分支 {line.branch},基线 {line.base_for(args.repo)},存储 {line.storage_for(args.repo)}" + ) + + def cmd_line_merge(args: argparse.Namespace) -> None: config = _config(args) if getattr(args, "recover", None) is not None: @@ -5401,6 +5419,25 @@ def build_parser() -> argparse.ArgumentParser: ) line_spawn.add_argument("--yes", action="store_true") line_spawn.set_defaults(func=cmd_line_spawn) + line_add_repo = line_sub.add_parser( + "add-repo", help="把一个已登记仓库加入现有开发线(不改子线)" + ) + line_add_repo.add_argument("line", help="开发线 ID") + line_add_repo.add_argument("repo", help="已登记的仓库 ID") + line_add_repo.add_argument("--base", help="该仓库的基线;顶层线默认用线的 base") + line_add_repo.add_argument( + "--storage", + help="存储方式:linked-worktree 或 anchor-reference;默认 linked-worktree", + ) + line_add_repo.add_argument( + "--dry-run", + dest="dry_run", + action="store_true", + default=argparse.SUPPRESS, + help="只打印计划,不创建工作树或改清单(兼容全局 --dry-run)", + ) + line_add_repo.add_argument("--yes", action="store_true") + line_add_repo.set_defaults(func=cmd_line_add_repo) line_merge = line_sub.add_parser( "merge", help="子线合入父线(--into)、跨线合入(--from)或 --recover 对账", diff --git a/src/dyro/workspace.py b/src/dyro/workspace.py index 1cb2145..cadac72 100644 --- a/src/dyro/workspace.py +++ b/src/dyro/workspace.py @@ -434,8 +434,17 @@ def _linked_worktree_command( ) -def _remove_line_worktree(config: Config, line: Line, repo_id: str, destination: Path) -> str | None: - """Best-effort cleanup for one worktree or anchor-reference created during line setup.""" +def _remove_line_worktree( + config: Config, line: Line, repo_id: str, destination: Path, *, new_branch: bool = False +) -> str | None: + """Best-effort cleanup for one worktree or anchor-reference created during line setup. + + ``new_branch`` means this setup created ``line.branch`` with ``-b``; delete it too, + otherwise a retry with another base would silently reuse the leftover branch. + The delete is attempted even after a path-cleanup failure; Git refuses it while + the branch is still checked out, and both failures are reported. + """ + failure: str | None = None try: if line.storage_for(repo_id) == "anchor-reference" or destination.is_symlink(): if destination.is_symlink() or destination.exists(): @@ -452,18 +461,29 @@ def _remove_line_worktree(config: Config, line: Line, repo_id: str, destination: shutil.rmtree(destination) prune = git(anchor, "worktree", "prune", timeout=60) if prune.code != 0: - return f"{repo_id}: worktree remove failed: {result.stdout.strip() or 'unknown error'}" - return None + failure = f"{repo_id}: worktree remove failed: {result.stdout.strip() or 'unknown error'}" except OSError as exc: - return f"{repo_id}: {exc}" - return None + failure = f"{repo_id}: {exc}" + if new_branch: + deleted = git(repository_path(config, repo_id), "branch", "-D", line.branch, timeout=60) + if deleted.code != 0: + note = ( + f"{repo_id}: 删除本次新建分支 {line.branch} 失败:" + f"{deleted.stdout.strip() or 'unknown error'}" + ) + failure = f"{failure}; {note}" if failure else note + return failure -def _rollback_line_creations(config: Config, line: Line, created: list[str]) -> list[str]: +def _rollback_line_creations( + config: Config, line: Line, created: list[tuple[str, bool]] +) -> list[str]: failures: list[str] = [] - for repo_id in reversed(created): + for repo_id, new_branch in reversed(created): destination = line_repository_path(config, line, repo_id) - failure = _remove_line_worktree(config, line, repo_id, destination) + failure = _remove_line_worktree( + config, line, repo_id, destination, new_branch=new_branch + ) if failure: failures.append(failure) target_root = line_root(config, line) @@ -480,6 +500,20 @@ def _rollback_line_creations(config: Config, line: Line, created: list[str]) -> return failures +def _remove_empty_parents(destination: Path, stop: Path) -> str | None: + """Remove empty ancestors of destination, stopping before stop itself.""" + current = destination.parent + try: + while current != stop and stop in current.parents: + if not current.is_dir() or any(current.iterdir()): + return None + current.rmdir() + current = current.parent + except OSError as exc: + return str(exc) + return None + + def _build_line( config: Config, *, @@ -527,6 +561,37 @@ def _build_line( ) +def _plan_repository_creation( + config: Config, line: Line, repo_id: str +) -> tuple[str, Path, tuple[str, ...]]: + """Validate one repository and return its worktree destination and Git command.""" + anchor = repository_path(config, repo_id) + destination = line_repository_path(config, line, repo_id) + if not _is_git_repo(anchor): + raise DyroError(f"仓库 anchor 不存在或不是 Git 仓库:{anchor}") + _ensure_clean(anchor) + repo_base = line.base_for(repo_id) + require_ok( + git_read(anchor, "rev-parse", "--verify", f"{repo_base}^{{commit}}"), + f"校验 {repo_id} 基线 {repo_base}", + ) + if destination.exists() or destination.is_symlink(): + raise DyroError(f"worktree 目标已存在:{destination}") + if line.storage_for(repo_id) == "anchor-reference": + anchor_branch = require_ok( + git_read(anchor, "branch", "--show-current"), + f"读取 {repo_id} anchor 分支", + ).stdout.strip() + if anchor_branch != line.branch: + raise DyroError( + f"{repo_id} 的 anchor-reference 要求 anchor 正位于 {line.branch}," + f"当前为 {anchor_branch or 'DETACHED'}" + ) + return (repo_id, destination, ()) + command = _linked_worktree_command(anchor, repo_id, line, repo_base, destination) + return (repo_id, destination, command) + + def _plan_line_creation( config: Config, line: Line ) -> list[tuple[str, Path, tuple[str, ...]]]: @@ -536,37 +601,9 @@ def _plan_line_creation( raise DyroError(f"目标工作区已存在且非空:{target_root}") # Validate every repository before mutating any worktree so partial creates are rare. - planned: list[tuple[str, Path, tuple[str, ...]]] = [] - for repo_id in line.repositories: - anchor = repository_path(config, repo_id) - destination = line_repository_path(config, line, repo_id) - if not _is_git_repo(anchor): - raise DyroError(f"仓库 anchor 不存在或不是 Git 仓库:{anchor}") - _ensure_clean(anchor) - repo_base = line.base_for(repo_id) - require_ok( - git_read(anchor, "rev-parse", "--verify", f"{repo_base}^{{commit}}"), - f"校验 {repo_id} 基线 {repo_base}", - ) - if destination.exists() or destination.is_symlink(): - raise DyroError(f"worktree 目标已存在:{destination}") - if line.storage_for(repo_id) == "anchor-reference": - anchor_branch = require_ok( - git_read(anchor, "branch", "--show-current"), - f"读取 {repo_id} anchor 分支", - ).stdout.strip() - if anchor_branch != line.branch: - raise DyroError( - f"{repo_id} 的 anchor-reference 要求 anchor 正位于 {line.branch}," - f"当前为 {anchor_branch or 'DETACHED'}" - ) - planned.append((repo_id, destination, ())) - continue - command = _linked_worktree_command( - anchor, repo_id, line, repo_base, destination - ) - planned.append((repo_id, destination, command)) - return planned + return [ + _plan_repository_creation(config, line, repo_id) for repo_id in line.repositories + ] def preflight_line( @@ -632,27 +669,42 @@ def create_line( return _create_line_worktrees(config, line, dry_run=dry_run) +def _create_repository_worktree( + config: Config, + line: Line, + repo_id: str, + destination: Path, + command: tuple[str, ...], + *, + dry_run: bool, +) -> bool: + """Create one worktree. Return whether a path was actually created.""" + if line.storage_for(repo_id) == "anchor-reference": + if dry_run: + return False + destination.parent.mkdir(parents=True, exist_ok=True) + destination.symlink_to(repository_path(config, repo_id), target_is_directory=True) + return True + if not dry_run: + destination.parent.mkdir(parents=True, exist_ok=True) + require_ok( + git(repository_path(config, repo_id), *command, dry_run=dry_run, timeout=300), + f"创建 {repo_id} worktree", + ) + return not dry_run + + def _create_line_worktrees(config: Config, line: Line, *, dry_run: bool) -> Line: """Create and roll back only while the caller holds L0 and every L2.""" planned = _plan_line_creation(config, line) - created: list[str] = [] + created: list[tuple[str, bool]] = [] try: for repo_id, destination, command in planned: - if line.storage_for(repo_id) == "anchor-reference": - if not dry_run: - destination.parent.mkdir(parents=True, exist_ok=True) - destination.symlink_to(repository_path(config, repo_id), target_is_directory=True) - created.append(repo_id) - continue - if not dry_run: - destination.parent.mkdir(parents=True, exist_ok=True) - require_ok( - git(repository_path(config, repo_id), *command, dry_run=dry_run, timeout=300), - f"创建 {repo_id} worktree", - ) - if not dry_run: - created.append(repo_id) + if _create_repository_worktree( + config, line, repo_id, destination, command, dry_run=dry_run + ): + created.append((repo_id, "-b" in command)) _write_line(config, line, dry_run=dry_run) except Exception as exc: if created: @@ -774,6 +826,103 @@ def spawn_line( return line +def add_line_repository( + config: Config, + line_id: str, + repo_id: str, + *, + base: str | None = None, + storage: str | None = None, + dry_run: bool = False, +) -> Line: + """Add one already-registered repository to one existing line. + + Child lines of this line are not modified. The worktree is created before + the manifest rewrite; a later failure removes only that new destination. + """ + with line_identity_lock(config): + with exclusive_lock( + merge_lock_path(config, line_id), + timeout_seconds=MERGE_LOCK_TIMEOUT_SECONDS, + ): + line = get_line(config, line_id) + require_no_unfinished_op(config, line.id) + if repo_id not in config.repositories: + raise ValidationError(f"未配置的仓库:{repo_id}") + if repo_id in line.repositories: + raise DyroError(f"仓库 {repo_id} 已包含在开发线 {line.id} 中") + if line.parent: + parent = get_line(config, line.parent) + if repo_id not in parent.repositories: + raise ValidationError( + f"子线仓库必须是父线 {parent.id} 仓库的子集:{repo_id};" + f"请先把该仓库加入父线 {parent.id}" + ) + if base is not None or storage is not None: + raise ValidationError( + f"子线 {line.id} 的仓库基线与存储方式必须从父线 {parent.id} 派生," + "不能指定 --base 或 --storage" + ) + resolved_base = _spawn_base_for(config, parent, repo_id) + resolved_storage = parent.storage_for(repo_id) + else: + resolved_base = (base or line.base).strip() + if not resolved_base: + raise ValidationError(f"{repo_id} 的基线不能为空") + resolved_storage = storage or "linked-worktree" + if resolved_storage not in STORAGE_MODES: + raise ValidationError( + f"{repo_id} 的存储方式必须是:{', '.join(sorted(STORAGE_MODES))}" + ) + updated = replace( + line, + repositories=line.repositories + (repo_id,), + repository_bases=( + {**line.repository_bases, repo_id: resolved_base} + if resolved_base != line.base + else dict(line.repository_bases) + ), + storage_modes=( + {**line.storage_modes, repo_id: resolved_storage} + if resolved_storage != "linked-worktree" + else dict(line.storage_modes) + ), + ) + with anchor_locks(config, [repo_id]): + _repo_id, destination, command = _plan_repository_creation( + config, updated, repo_id + ) + created = False + try: + created = _create_repository_worktree( + config, + updated, + repo_id, + destination, + command, + dry_run=dry_run, + ) + _write_line(config, updated, dry_run=dry_run) + except Exception as exc: + if created: + failures: list[str] = [] + failure = _remove_line_worktree( + config, updated, repo_id, destination, new_branch="-b" in command + ) + if failure: + failures.append(failure) + parent_failure = _remove_empty_parents( + destination, line_root(config, line) + ) + if parent_failure: + failures.append(parent_failure) + if failures: + detail = "; ".join(failures) + raise DyroError(f"{exc}\n自动清理未完全成功:{detail}") from exc + raise + return updated + + @dataclass(frozen=True) class _LineMergePlan: repository: str diff --git a/tests/test_line_add_repo.py b/tests/test_line_add_repo.py new file mode 100644 index 0000000..8fc20b6 --- /dev/null +++ b/tests/test_line_add_repo.py @@ -0,0 +1,402 @@ +from contextlib import redirect_stderr, redirect_stdout +from dataclasses import replace +from io import StringIO +from pathlib import Path +import subprocess +from types import SimpleNamespace +from unittest.mock import patch + +from dyro import line_ops, workspace +from dyro.cli import main +from dyro.config import load +from dyro.errors import DyroError, ValidationError +from dyro.workspace import ( + _write_line, + add_line_repository, + create_line, + get_line, + line_repository_path, + line_root, + spawn_line, +) + +from .support import WorkspaceCase, shell + + +def git_stdout(*args: str, cwd: Path) -> str: + completed = subprocess.run( + ["git", *args], + cwd=cwd, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + return completed.stdout.strip() + + +def branch_names(repo: Path) -> set[str]: + text = git_stdout("branch", "--list", "--format=%(refname:short)", cwd=repo) + return set(filter(None, text.splitlines())) + + +class LineAddRepoTests(WorkspaceCase): + def _register_web(self) -> Path: + web = self.root / "repositories/web" + web.mkdir(parents=True) + shell("git", "init", "-b", "main", cwd=web) + shell("git", "config", "user.name", "Test User", cwd=web) + shell("git", "config", "user.email", "test@example.com", cwd=web) + shell("git", "config", "commit.gpgsign", "false", cwd=web) + (web / "README.md").write_text("web\n", encoding="utf-8") + shell("git", "add", "README.md", cwd=web) + shell("git", "commit", "-m", "chore: initial", cwd=web) + config_path = self.root / "dyro.toml" + config_path.write_text( + config_path.read_text(encoding="utf-8") + + '\n[repositories.web]\npath = "repositories/web"\nmount = "clients/web"\n', + encoding="utf-8", + ) + return web + + def _line_with_api(self, line_id: str = "alpha"): + config = load(self.root) + line = create_line( + config, + line_id=line_id, + branch=f"feat/{line_id}", + base="main", + repositories=["api"], + ) + return config, line + + def _manifest(self, config, line_id: str) -> Path: + return config.lines_state_dir / f"{line_id}.toml" + + def test_top_level_line_adds_registered_repo_from_base(self) -> None: + config, line = self._line_with_api() + api_worktree = line_repository_path(config, line, "api") + marker = api_worktree / "keep.txt" + marker.write_text("untouched\n", encoding="utf-8") + api_head = git_stdout("rev-parse", "HEAD", cwd=api_worktree) + web = self._register_web() + config = load(self.root) + base_sha = git_stdout("rev-parse", "main^{commit}", cwd=web) + + updated = add_line_repository(config, "alpha", "web") + + destination = line_repository_path(config, updated, "web") + self.assertTrue((destination / ".git").exists()) + self.assertFalse(destination.is_symlink()) + self.assertEqual(git_stdout("branch", "--show-current", cwd=destination), line.branch) + self.assertEqual(git_stdout("rev-parse", "HEAD", cwd=destination), base_sha) + self.assertEqual(get_line(config, "alpha").repositories, ("api", "web")) + self.assertEqual(marker.read_text(encoding="utf-8"), "untouched\n") + self.assertEqual(git_stdout("rev-parse", "HEAD", cwd=api_worktree), api_head) + self.assertTrue(api_worktree.is_dir()) + + def test_custom_base_is_persisted_and_default_base_is_not(self) -> None: + config, _line = self._line_with_api() + web = self._register_web() + shell("git", "checkout", "-b", "release", cwd=web) + (web / "release.txt").write_text("rel\n", encoding="utf-8") + shell("git", "add", "release.txt", cwd=web) + shell("git", "commit", "-m", "release", cwd=web) + release_sha = git_stdout("rev-parse", "HEAD", cwd=web) + shell("git", "checkout", "main", cwd=web) + config = load(self.root) + + updated = add_line_repository(config, "alpha", "web", base="release") + + destination = line_repository_path(config, updated, "web") + manifest = self._manifest(config, "alpha").read_text(encoding="utf-8") + self.assertEqual(updated.repository_bases["web"], "release") + self.assertIn("[repository_bases]", manifest) + self.assertIn('"web" = "release"', manifest) + self.assertEqual(git_stdout("rev-parse", "HEAD", cwd=destination), release_sha) + self.assertTrue((destination / "release.txt").is_file()) + + create_line( + config, + line_id="beta", + branch="feat/beta", + base="main", + repositories=["api"], + ) + defaulted = add_line_repository(config, "beta", "web") + beta_manifest = self._manifest(config, "beta").read_text(encoding="utf-8") + self.assertNotIn("web", defaulted.repository_bases) + self.assertNotIn("[repository_bases]", beta_manifest) + self.assertEqual(defaulted.base_for("web"), "main") + + def test_existing_local_branch_is_reused(self) -> None: + config, line = self._line_with_api() + web = self._register_web() + shell("git", "checkout", "-b", line.branch, cwd=web) + (web / "extra.txt").write_text("extra\n", encoding="utf-8") + shell("git", "add", "extra.txt", cwd=web) + shell("git", "commit", "-m", "extra", cwd=web) + tip = git_stdout("rev-parse", "HEAD", cwd=web) + main_sha = git_stdout("rev-parse", "main", cwd=web) + shell("git", "checkout", "main", cwd=web) + before = branch_names(web) + config = load(self.root) + + updated = add_line_repository(config, "alpha", "web") + + destination = line_repository_path(config, updated, "web") + self.assertEqual(git_stdout("rev-parse", "HEAD", cwd=destination), tip) + self.assertNotEqual(tip, main_sha) + self.assertEqual(branch_names(web), before) + self.assertTrue((destination / "extra.txt").is_file()) + + def test_already_included_and_unregistered_repo_write_nothing(self) -> None: + config, line = self._line_with_api() + manifest = self._manifest(config, "alpha") + before = manifest.read_bytes() + root = line_root(config, line) + before_tree = sorted(path.relative_to(root).as_posix() for path in root.rglob("*")) + + with self.assertRaisesRegex(DyroError, "已包含"): + add_line_repository(config, "alpha", "api") + with self.assertRaisesRegex(ValidationError, "未配置的仓库:missing"): + add_line_repository(config, "alpha", "missing") + + self.assertEqual(manifest.read_bytes(), before) + self.assertEqual( + sorted(path.relative_to(root).as_posix() for path in root.rglob("*")), + before_tree, + ) + + def test_child_derives_base_and_storage_and_rejects_overrides(self) -> None: + config, parent = self._line_with_api("onboard") + child = spawn_line(config, parent.id, "tryon") + web = self._register_web() + config = load(self.root) + child_manifest = self._manifest(config, child.id) + before = child_manifest.read_bytes() + child_destination = self.root / "versions" / child.id / "clients" / "web" + + with self.assertRaisesRegex(ValidationError, parent.id): + add_line_repository(config, child.id, "web") + self.assertEqual(child_manifest.read_bytes(), before) + self.assertFalse(child_destination.exists()) + + shell("git", "checkout", "-b", parent.branch, cwd=web) + add_line_repository(config, parent.id, "web", storage="anchor-reference") + config = load(self.root) + parent = get_line(config, parent.id) + self.assertEqual(child_manifest.read_bytes(), before) + + with self.assertRaisesRegex(ValidationError, "--base"): + add_line_repository(config, child.id, "web", base="main") + with self.assertRaisesRegex(ValidationError, "--storage"): + add_line_repository(config, child.id, "web", storage="linked-worktree") + self.assertEqual(child_manifest.read_bytes(), before) + self.assertFalse(child_destination.exists()) + + shell("git", "checkout", "-b", child.branch, cwd=web) + updated = add_line_repository(config, child.id, "web") + self.assertEqual(updated.base_for("web"), parent.branch) + self.assertEqual(updated.storage_for("web"), parent.storage_for("web")) + self.assertEqual(updated.storage_for("web"), "anchor-reference") + self.assertTrue(child_destination.is_symlink()) + reloaded = get_line(config, child.id) + self.assertEqual(reloaded.repositories, ("api", "web")) + self.assertEqual(reloaded.base_for("web"), parent.branch) + + def test_adding_to_parent_leaves_child_manifest_unchanged(self) -> None: + config, parent = self._line_with_api("onboard") + child = spawn_line(config, parent.id, "tryon") + self._register_web() + config = load(self.root) + child_manifest = self._manifest(config, child.id) + before = child_manifest.read_bytes() + child_web = self.root / "versions" / child.id / "clients" / "web" + + add_line_repository(config, parent.id, "web") + + self.assertEqual(child_manifest.read_bytes(), before) + self.assertFalse(child_web.exists()) + self.assertEqual(get_line(config, child.id).repositories, ("api",)) + self.assertIn("web", get_line(config, parent.id).repositories) + + def test_unfinished_op_refuses_without_creating_a_worktree(self) -> None: + config, _line = self._line_with_api() + self._register_web() + config = load(self.root) + line_ops.create_op( + config, + kind="merge", + subject_line_ids=["alpha"], + manifest_snapshot={"id": "alpha", "repositories": ["api"]}, + repos_ordered=["api"], + effective_options={}, + ) + manifest = self._manifest(config, "alpha") + before = manifest.read_bytes() + destination = self.root / "versions/alpha/clients/web" + + with self.assertRaisesRegex(DyroError, "未完成操作"): + add_line_repository(config, "alpha", "web") + + self.assertEqual(manifest.read_bytes(), before) + self.assertFalse(destination.exists()) + + def test_write_failure_removes_only_the_new_worktree(self) -> None: + config, line = self._line_with_api() + empty_keep = line_repository_path(config, line, "api") / "empty-keep" + empty_keep.mkdir() + web = self._register_web() + shell("git", "checkout", "-b", "release", cwd=web) + (web / "release.txt").write_text("rel\n", encoding="utf-8") + shell("git", "add", "release.txt", cwd=web) + shell("git", "commit", "-m", "release", cwd=web) + shell("git", "checkout", "main", cwd=web) + config = load(self.root) + manifest = self._manifest(config, "alpha") + before = manifest.read_bytes() + destination = self.root / "versions/alpha/clients/web" + + with patch("dyro.workspace._write_line", side_effect=RuntimeError("write failed")): + with self.assertRaisesRegex(RuntimeError, "write failed"): + add_line_repository(config, "alpha", "web", base="release") + + self.assertFalse(destination.exists()) + self.assertFalse(destination.parent.exists()) + self.assertTrue(empty_keep.is_dir()) + self.assertEqual(manifest.read_bytes(), before) + self.assertTrue(line_repository_path(config, line, "api").is_dir()) + self.assertNotIn(line.branch, branch_names(web)) + + # Retry with the default base must start from main, not the failed release tip. + updated = add_line_repository(config, "alpha", "web") + self.assertEqual( + git_stdout("rev-parse", "HEAD", cwd=line_repository_path(config, updated, "web")), + git_stdout("rev-parse", "main", cwd=web), + ) + + def test_write_failure_keeps_a_preexisting_branch(self) -> None: + config, line = self._line_with_api() + web = self._register_web() + shell("git", "branch", line.branch, cwd=web) + config = load(self.root) + + with patch("dyro.workspace._write_line", side_effect=RuntimeError("write failed")): + with self.assertRaisesRegex(RuntimeError, "write failed"): + add_line_repository(config, "alpha", "web") + + self.assertIn(line.branch, branch_names(web)) + self.assertFalse((self.root / "versions/alpha/clients/web").exists()) + + def test_anchor_reference_write_failure_removes_symlink(self) -> None: + config, line = self._line_with_api() + web = self._register_web() + shell("git", "checkout", "-b", line.branch, cwd=web) + config = load(self.root) + destination = self.root / "versions/alpha/clients/web" + + with patch("dyro.workspace._write_line", side_effect=RuntimeError("write failed")): + with self.assertRaisesRegex(RuntimeError, "write failed"): + add_line_repository(config, "alpha", "web", storage="anchor-reference") + + self.assertFalse(destination.is_symlink() or destination.exists()) + self.assertFalse(destination.parent.exists()) + self.assertTrue(web.is_dir()) + self.assertIn(line.branch, branch_names(web)) + + def test_path_cleanup_failure_never_silently_keeps_self_created_branch(self) -> None: + config, line = self._line_with_api() + web = self._register_web() + config = load(self.root) + real_git = workspace.git + + def flaky_git(path, *args, **kwargs): + if args[:2] in (("worktree", "remove"), ("worktree", "prune")): + return SimpleNamespace(code=1, stdout="boom") + return real_git(path, *args, **kwargs) + + with patch("dyro.workspace._write_line", side_effect=RuntimeError("write failed")): + with patch("dyro.workspace.git", side_effect=flaky_git): + with self.assertRaisesRegex(DyroError, "worktree remove failed") as caught: + add_line_repository(config, "alpha", "web") + + # Either the branch is gone, or the error names it so it is never left silently. + self.assertTrue( + line.branch not in branch_names(web) or line.branch in str(caught.exception) + ) + + def test_create_line_rollback_deletes_only_branches_it_created(self) -> None: + web = self._register_web() + shell("git", "branch", "feat/gamma", cwd=web) + config = load(self.root) + + with patch("dyro.workspace._write_line", side_effect=RuntimeError("write failed")): + with self.assertRaisesRegex(RuntimeError, "write failed"): + create_line( + config, + line_id="gamma", + branch="feat/gamma", + base="main", + repositories=["api", "web"], + ) + + self.assertNotIn("feat/gamma", branch_names(self.anchor)) + self.assertIn("feat/gamma", branch_names(web)) + self.assertFalse((self.root / "versions/gamma").exists()) + + def test_dry_run_plans_without_writing(self) -> None: + config, _line = self._line_with_api() + self._register_web() + config = load(self.root) + manifest = self._manifest(config, "alpha") + before = manifest.read_bytes() + destination = self.root / "versions/alpha/clients/web" + + updated = add_line_repository(config, "alpha", "web", dry_run=True) + + self.assertEqual(updated.repositories, ("api", "web")) + self.assertFalse(destination.exists()) + self.assertEqual(manifest.read_bytes(), before) + self.assertEqual(get_line(config, "alpha").repositories, ("api",)) + + def test_remote_anchors_survive_add_repo(self) -> None: + config, line = self._line_with_api() + anchor_sha = "a" * 40 + _write_line(config, replace(get_line(config, line.id), remote_anchors={"api": anchor_sha})) + self._register_web() + config = load(self.root) + + add_line_repository(config, "alpha", "web") + + text = self._manifest(config, "alpha").read_text(encoding="utf-8") + reloaded = get_line(config, "alpha") + self.assertIn("schema_version = 4", text) + self.assertIn("[remote_anchors]", text) + self.assertIn(f'"api" = "{anchor_sha}"', text) + self.assertEqual(reloaded.remote_anchors["api"], anchor_sha) + self.assertEqual(reloaded.repositories, ("api", "web")) + self.assertNotIn("web", reloaded.remote_anchors) + + def test_cli_refuses_without_yes_and_adds_with_yes(self) -> None: + self._line_with_api() + self._register_web() + destination = self.root / "versions/alpha/clients/web" + stderr = StringIO() + with redirect_stderr(stderr): + with self.assertRaises(SystemExit) as raised: + main(["--root", str(self.root), "line", "add-repo", "alpha", "web"]) + self.assertEqual(raised.exception.code, 2) + self.assertIn("--yes", stderr.getvalue()) + self.assertIn("--dry-run", stderr.getvalue()) + self.assertFalse(destination.exists()) + + stdout = StringIO() + with redirect_stdout(stdout): + main(["--root", str(self.root), "line", "add-repo", "alpha", "web", "--yes"]) + self.assertIn( + "已为 line alpha 加入仓库 web,分支 feat/alpha,基线 main,存储 linked-worktree", + stdout.getvalue(), + ) + self.assertTrue((destination / ".git").exists()) + self.assertEqual(get_line(load(self.root), "alpha").repositories, ("api", "web"))