{"thread":{"id":"66320","subject":"[PATCH 0/2] worktree repair: avoid breaking unrelated .git file and gitdir","startedAt":"2026-09-13T03:20:15Z","lastAt":"2026-10-17T12:55:02Z","messageCount":23,"participants":["Yoichi NAKAYAMA via GitGitGadget","Yoichi NAKAYAMA","Junio C Hamano"],"isPatch":true,"patchVersion":1,"patchTotal":2},"messages":[{"id":"552632","messageId":"pull.2225.git.1789269613.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":null,"subject":"[PATCH 0/2] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-09-13T03:20:11Z","receivedAt":"2026-09-13T03:20:15Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"'git worktree repair' does not sufficiently validate the cross-references\nbetween a linked working tree and its administrative data before repairing\nthem. This can cause the repair to modify the wrong .git file or gitdir in\ncertain situations.\n\nThis series first refactors the code to read the .git file once and extract\nthe worktree ID, then uses that information to validate the repair target\nbefore modifying the cross-references.\n\n * [1/2] Refactor the code without changing functionality before making the\n   fix\n * [2/2] Validate the worktree ID and inferred gitdir path before repairing\n\nYoichi NAKAYAMA (2):\n  worktree repair: refactor and reduce .git file reads\n  worktree repair: avoid breaking unrelated .git file and gitdir\n\n t/t2406-worktree-repair.sh |  33 +++++++++---\n worktree.c                 | 105 ++++++++++++++++++++-----------------\n 2 files changed, 83 insertions(+), 55 deletions(-)\n\n\nbase-commit: 47ce80527c56f462cb97db4ca8125342204d3783\nPublished-As: https://github.com/gitgitgadget/git/releases/tag/pr-2225%2Fyoichi%2Fworktree-repair-keep-unrelated-gitfile-v1\nFetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2225/yoichi/worktree-repair-keep-unrelated-gitfile-v1\nPull-Request: https://github.com/gitgitgadget/git/pull/2225\n-- \ngitgitgadget\n"},{"id":"552633","messageId":"dc7ebb427bedc7318ebbf84c05ecd02063408353.1789269613.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.git.1789269613.gitgitgadget@gmail.com","subject":"[PATCH 1/2] worktree repair: refactor and reduce .git file reads","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-09-13T03:20:12Z","receivedAt":"2026-09-13T03:20:17Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nRemove the file reading and trimming logic from `infer_backlink()`,\nand instead read the .git file once in its caller,\n`repair_worktree_at_path()`, using `read_gitfile_raw()`. Since\n`read_gitfile_gently()` is replaced with `read_gitfile_raw()`, restore\nthe logic for constructing the absolute path and replace the\nREAD_GITFILE_ERR_NOT_A_REPO handling with a check using\n`is_git_directory()`. Simplify the logic for prioritizing\n'inferred_backlink' over 'backlink'.\n\nExtract `get_worktree_id()` to get the worktree ID from the contents\nof the .git file. We are going to modify and use this function in\nsubsequent commits.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 89 ++++++++++++++++++++++++++----------------------------\n 1 file changed, 43 insertions(+), 46 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex 8cb8637b18..7af13898d0 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -637,6 +637,14 @@ int other_head_refs(struct repository *repo,\n \treturn ret;\n }\n \n+static const char *get_worktree_id(const char *dotgit_contents)\n+{\n+\tconst char *slash = find_last_dir_sep(dotgit_contents);\n+\tif (!slash)\n+\t\treturn \"\";\n+\treturn slash + 1;\n+}\n+\n /*\n  * Repair worktree's /path/to/worktree/.git file if missing, corrupt, or not\n  * pointing at <repo>/worktrees/<id>.\n@@ -798,30 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n  * Returns -1 on failure and strbuf.len on success.\n  */\n static ssize_t infer_backlink(struct repository *repo,\n-\t\t\t      const char *gitfile,\n+\t\t\t      const char *dotgit_contents,\n \t\t\t      struct strbuf *inferred)\n {\n-\tstruct strbuf actual = STRBUF_INIT;\n \tconst char *id;\n \n-\tif (strbuf_read_file(&actual, gitfile, 0) < 0)\n-\t\tgoto error;\n-\tif (!starts_with(actual.buf, \"gitdir:\"))\n-\t\tgoto error;\n-\tif (!(id = find_last_dir_sep(actual.buf)))\n-\t\tgoto error;\n-\tstrbuf_trim(&actual);\n-\tid++; /* advance past '/' to point at <id> */\n+\tid = get_worktree_id(dotgit_contents);\n \tif (!*id)\n \t\tgoto error;\n \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n \tif (!is_directory(inferred->buf))\n \t\tgoto error;\n \n-\tstrbuf_release(&actual);\n \treturn inferred->len;\n error:\n-\tstrbuf_release(&actual);\n \tstrbuf_reset(inferred); /* clear invalid path */\n \treturn -1;\n }\n@@ -840,7 +838,8 @@ void repair_worktree_at_path(struct repository *repo,\n \tstruct strbuf inferred_backlink = STRBUF_INIT;\n \tstruct strbuf gitdir = STRBUF_INIT;\n \tstruct strbuf olddotgit = STRBUF_INIT;\n-\tchar *dotgit_contents = NULL;\n+\tstruct strbuf contents = STRBUF_INIT;\n+\tconst char *dotgit_contents = NULL;\n \tconst char *repair = NULL;\n \tint err;\n \n@@ -856,51 +855,49 @@ void repair_worktree_at_path(struct repository *repo,\n \t\tgoto done;\n \t}\n \n-\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n-\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n-\tdotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));\n-\tif (dotgit_contents) {\n-\t\tstrbuf_addstr(&backlink, dotgit_contents);\n-\t} else if (err == READ_GITFILE_ERR_NOT_A_FILE ||\n-\t\t\terr == READ_GITFILE_ERR_IS_A_DIR) {\n+\terr = read_gitfile_raw(&contents, dotgit.buf);\n+\tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n+\t    err == READ_GITFILE_ERR_IS_A_DIR) {\n \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git is not a file\"), cb_data);\n \t\tgoto done;\n-\t} else if (err == READ_GITFILE_ERR_NOT_A_REPO) {\n-\t\tif (inferred_backlink.len) {\n-\t\t\t/*\n-\t\t\t * Worktree's .git file does not point at a repository\n-\t\t\t * but we found a .git/worktrees/<id> in this\n-\t\t\t * repository with the same <id> as recorded in the\n-\t\t\t * worktree's .git file so make the worktree point at\n-\t\t\t * the discovered .git/worktrees/<id>.\n-\t\t\t */\n-\t\t\tstrbuf_swap(&backlink, &inferred_backlink);\n-\t\t} else {\n-\t\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n-\t\t\tgoto done;\n-\t\t}\n-\t} else {\n+\t} else if (err) {\n \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file broken\"), cb_data);\n \t\tgoto done;\n \t}\n \n+\tdotgit_contents = contents.buf;\n+\tinfer_backlink(repo, dotgit_contents, &inferred_backlink);\n+\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n+\n+\tif (is_absolute_path(dotgit_contents)) {\n+\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t} else {\n+\t\tstrbuf_addbuf(&backlink, &dotgit);\n+\t\tstrbuf_strip_suffix(&backlink, \".git\");\n+\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n+\t}\n+\n+\tif (!is_git_directory(backlink.buf) && !inferred_backlink.len) {\n+\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n+\t\tgoto done;\n+\t}\n+\n \t/*\n \t * If we got this far, either the worktree's .git file pointed at a\n-\t * valid repository (i.e. read_gitfile_gently() returned success) or\n+\t * valid repository (i.e. is_git_directory() returned true) or\n \t * the .git file did not point at a repository but we were able to\n \t * infer a suitable new value for the .git file by locating a\n \t * .git/worktrees/<id> in *this* repository corresponding to the <id>\n \t * recorded in the worktree's .git file.\n \t *\n-\t * However, if, at this point, inferred_backlink is non-NULL (i.e. we\n-\t * found a suitable .git/worktrees/<id> in *this* repository) *and* the\n-\t * worktree's .git file points at a valid repository *and* those two\n-\t * paths differ, then that indicates that the user probably *copied*\n-\t * the main and linked worktrees to a new location as a unit rather\n-\t * than *moving* them. Thus, the copied worktree's .git file actually\n-\t * points at the .git/worktrees/<id> in the *original* repository, not\n-\t * in the \"copy\" repository. In this case, point the \"copy\" worktree's\n-\t * .git file at the \"copy\" repository.\n+\t * Even if the worktree's .git file pointed at a valid repository,\n+\t * it doesn't always mean that the backlink is correct. For example,\n+\t * the user might have *copied* the main and linked worktrees to a\n+\t * new location as a unit rather than *moving* them (the copied\n+\t * worktree's .git file actually points at the .git/worktrees/<id>\n+\t * in the *original* repository, not in the \"copy\" repository).\n+\t * Therefore, we prioritize inferred_backlink over backlink.\n \t */\n \tif (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))\n \t\tstrbuf_swap(&backlink, &inferred_backlink);\n@@ -926,12 +923,12 @@ void repair_worktree_at_path(struct repository *repo,\n \t\t\t\t\t     gitdir.buf, use_relative_paths);\n \t}\n done:\n-\tfree(dotgit_contents);\n \tstrbuf_release(&olddotgit);\n \tstrbuf_release(&backlink);\n \tstrbuf_release(&inferred_backlink);\n \tstrbuf_release(&gitdir);\n \tstrbuf_release(&dotgit);\n+\tstrbuf_release(&contents);\n }\n \n int should_prune_worktree(struct repository *repo,\n-- \ngitgitgadget\n\n"},{"id":"552634","messageId":"99aa34135c481e7cd7605788408055157d09fa19.1789269613.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.git.1789269613.gitgitgadget@gmail.com","subject":"[PATCH 2/2] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-09-13T03:20:13Z","receivedAt":"2026-09-13T03:20:18Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nCurrently, `repair_gitfile()` does not verify whether the worktree ID\nrecorded in the .git file matches the worktree being repaired, which\ncan result in an unrelated .git file being corrupted. For instance,\nif two worktree directories are swapped without using 'git worktree\nmove', running 'git worktree repair' in the main worktree accidentally\nswaps the links between their .git files and gitdirs.\n\n`repair_worktree_at_path()` proceeds even if it fails to infer the\ngitdir path. This can result in the corruption of an unrelated\ngitdir. For instance, if we copied a linked worktree to a new location\nX, running 'git worktree repair X' in a working tree which does not\nbelong to the original repository can accidentally overwrite the\ngitdir in the original repository (the scope of impact should be\nlimited to the repository where the command was executed).\n\nResolve these issues by validating the worktree ID and stopping the\nrepair when the ID does not match or the gitdir path cannot be\ninferred.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n t/t2406-worktree-repair.sh | 33 +++++++++++++++++++++++++++------\n worktree.c                 | 18 ++++++++++++++----\n 2 files changed, 41 insertions(+), 10 deletions(-)\n\ndiff --git a/t/t2406-worktree-repair.sh b/t/t2406-worktree-repair.sh\nindex d4e53d492b..2ffa123f42 100755\n--- a/t/t2406-worktree-repair.sh\n+++ b/t/t2406-worktree-repair.sh\n@@ -56,15 +56,12 @@ test_expect_success 'repair missing .git file' '\n '\n \n test_expect_success 'repair bogus .git file' '\n-\ttest_corrupt_gitfile \"echo \\\"gitdir: /nowhere\\\" >corrupt/.git\" \\\n+\ttest_corrupt_gitfile \"echo \\\"contents not started with gitdir:\\\" >corrupt/.git\" \\\n \t\t\".git file broken\"\n '\n \n-test_expect_success 'repair incorrect .git file' '\n-\ttest_when_finished \"rm -rf other && git worktree prune\" &&\n-\ttest_create_repo other &&\n-\tother=$(git -C other rev-parse --absolute-git-dir) &&\n-\ttest_corrupt_gitfile \"echo \\\"gitdir: $other\\\" >corrupt/.git\" \\\n+test_expect_success 'repair unlinked .git file' '\n+\ttest_corrupt_gitfile \"echo \\\"gitdir: /nowhere/worktrees/corrupt\\\" >corrupt/.git\" \\\n \t\t\".git file incorrect\"\n '\n \n@@ -89,6 +86,18 @@ test_expect_success 'repair .git file from bare.git' '\n \ttest_cmp expect actual\n '\n \n+test_expect_success 'skip unrelated .git file' '\n+\ttest_when_finished \"rm -rf corrupt other && git worktree prune\" &&\n+\tgit worktree add --detach corrupt &&\n+\trm -rf corrupt &&\n+\tgit worktree add --detach other &&\n+\tmv other corrupt &&\n+\tcat corrupt/.git >expect &&\n+\ttest_must_fail git worktree repair 2>err &&\n+\ttest_cmp expect corrupt/.git &&\n+\ttest_grep \"unrelated .git file\" err\n+'\n+\n test_expect_success 'invalid worktree path' '\n \ttest_must_fail git worktree repair /notvalid >out 2>err &&\n \ttest_must_be_empty out &&\n@@ -113,6 +122,18 @@ test_expect_success 'repo not found; .git not referencing repo' '\n \ttest_grep \".git file does not reference a repository\" err\n '\n \n+test_expect_success 'repo not found; .git not for worktree' '\n+\ttest_when_finished \"rm -rf side other-repo && git worktree prune\" &&\n+\ttest_create_repo other-repo &&\n+\tgit worktree add --detach side &&\n+\tcat .git/worktrees/side/gitdir >expect &&\n+\tcp -R side other-repo/side &&\n+\ttest_must_fail git -C other-repo worktree repair side >out 2>err &&\n+\ttest_cmp expect .git/worktrees/side/gitdir &&\n+\ttest_must_be_empty out &&\n+\ttest_grep \".git file is not for a linked worktree\" err\n+'\n+\n test_expect_success 'repo not found; .git file broken' '\n \ttest_when_finished \"rm -rf orig moved && git worktree prune\" &&\n \tgit worktree add --detach orig &&\ndiff --git a/worktree.c b/worktree.c\nindex 7af13898d0..88da599ab6 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -640,7 +640,11 @@ int other_head_refs(struct repository *repo,\n static const char *get_worktree_id(const char *dotgit_contents)\n {\n \tconst char *slash = find_last_dir_sep(dotgit_contents);\n-\tif (!slash)\n+\tconst char *prefix = \"/worktrees\";\n+\tint prefixlen = strlen(prefix);\n+\tif (!slash ||\n+\t    slash - dotgit_contents < prefixlen ||\n+\t    strncmp(slash - prefixlen, prefix, prefixlen))\n \t\treturn \"\";\n \treturn slash + 1;\n }\n@@ -692,8 +696,10 @@ static void repair_gitfile(struct worktree *wt,\n \tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n \t\terr == READ_GITFILE_ERR_IS_A_DIR)\n \t\tfn(1, wt->path, _(\".git is not a file\"), cb_data);\n-\telse if (err || !is_git_directory(backlink.buf))\n+\telse if (err)\n \t\trepair = _(\".git file broken\");\n+\telse if (strcmp(get_worktree_id(dotgit_contents), wt->id))\n+\t\tfn(1, wt->path, _(\"unrelated .git file\"), cb_data);\n \telse if (fspathcmp(backlink.buf, repo.buf))\n \t\trepair = _(\".git file incorrect\");\n \telse if (use_relative_paths == is_absolute_path(dotgit_contents))\n@@ -815,7 +821,7 @@ static ssize_t infer_backlink(struct repository *repo,\n \tif (!*id)\n \t\tgoto error;\n \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n-\tif (!is_directory(inferred->buf))\n+\tif (!is_git_directory(inferred->buf))\n \t\tgoto error;\n \n \treturn inferred->len;\n@@ -882,6 +888,10 @@ void repair_worktree_at_path(struct repository *repo,\n \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n \t\tgoto done;\n \t}\n+\tif (!inferred_backlink.len) {\n+\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file is not for a linked worktree\"), cb_data);\n+\t\tgoto done;\n+\t}\n \n \t/*\n \t * If we got this far, either the worktree's .git file pointed at a\n@@ -899,7 +909,7 @@ void repair_worktree_at_path(struct repository *repo,\n \t * in the *original* repository, not in the \"copy\" repository).\n \t * Therefore, we prioritize inferred_backlink over backlink.\n \t */\n-\tif (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))\n+\tif (fspathcmp(backlink.buf, inferred_backlink.buf))\n \t\tstrbuf_swap(&backlink, &inferred_backlink);\n \n \tstrbuf_addf(&gitdir, \"%s/gitdir\", backlink.buf);\n-- \ngitgitgadget\n"},{"id":"554435","messageId":"CAF5D8-u60aRV5rKoLQYRghh1YUFK=p1QqTe02WtsxSdyBL_e4Q@mail.gmail.com","threadId":"66320","inReplyTo":"pull.2225.git.1789269613.gitgitgadget@gmail.com","subject":"Re: [PATCH 0/2] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA","fromEmail":"yoichi.nakayama@gmail.com","sentAt":"2026-10-08T03:50:35Z","receivedAt":"2026-10-08T03:50:35Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"Friendly ping on this :)\n\n"},{"id":"554537","messageId":"xmqqh5ivyks1.fsf@gitster.g","threadId":"66320","inReplyTo":"dc7ebb427bedc7318ebbf84c05ecd02063408353.1789269613.git.gitgitgadget@gmail.com","subject":"Re: [PATCH 1/2] worktree repair: refactor and reduce .git file reads","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2026-10-08T20:55:42Z","receivedAt":"2026-10-08T20:55:42Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"\"Yoichi NAKAYAMA via GitGitGadget\" <gitgitgadget@gmail.com> writes:\n\n> +static const char *get_worktree_id(const char *dotgit_contents)\n> +{\n> +\tconst char *slash = find_last_dir_sep(dotgit_contents);\n> +\tif (!slash)\n> +\t\treturn \"\";\n> +\treturn slash + 1;\n> +}\n\nThis returns a pointer into dotgit_contents; it is the last\ncomponent of a pathname, similar to what basename(3) gives us.\n\n> @@ -798,30 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n\nThe unified diff is a bit hard to follow, so let's see if we can\ncompare preimage and postimage more easily.\n\n>  static ssize_t infer_backlink(struct repository *repo,\n> -\t\t\t      const char *gitfile,\n>  \t\t\t      struct strbuf *inferred)\n>  {\n> -\tstruct strbuf actual = STRBUF_INIT;\n>  \tconst char *id;\n>  \n> -\tif (strbuf_read_file(&actual, gitfile, 0) < 0)\n> -\t\tgoto error;\n> -\tif (!starts_with(actual.buf, \"gitdir:\"))\n> -\t\tgoto error;\n> -\tif (!(id = find_last_dir_sep(actual.buf)))\n> -\t\tgoto error;\n> -\tstrbuf_trim(&actual);\n> -\tid++; /* advance past '/' to point at <id> */\n>  \tif (!*id)\n>  \t\tgoto error;\n>  \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n>  \tif (!is_directory(inferred->buf))\n>  \t\tgoto error;\n>  \n> -\tstrbuf_release(&actual);\n>  \treturn inferred->len;\n>  error:\n> -\tstrbuf_release(&actual);\n>  \tstrbuf_reset(inferred); /* clear invalid path */\n>  \treturn -1;\n\nWe used to receive the filename of \".git\", read it and made sure we\nhave \"gitdir:\" prefix, and find the last component, but then trimmed\nthe actual buffer.  Which means a few things.\n\n - If the contents of the gitfile were \"gitdir:foo/bar/baz \\n\", our\n   id pointer found the slash after \"foo/bar\", trimmed the buffer to\n   have \"gitdir:foo/bar/baz\", and then incremented id, which now\n   points at \"baz\".\n\n - If the contents of the gitfile were \"gitdir: foo/bar/   \\n\", then\n   after triming, the buffer would have \"gitdir: foo/bar/\" and id\n   would be pointing at the NUL at the end, which would have lead us\n   to error.\n\nNow let's look at the new code.\n\n> @@ -798,30 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n>   * Returns -1 on failure and strbuf.len on success.\n>   */\n>  static ssize_t infer_backlink(struct repository *repo,\n> +\t\t\t      const char *dotgit_contents,\n>  \t\t\t      struct strbuf *inferred)\n>  {\n>  \tconst char *id;\n>  \n> +\tid = get_worktree_id(dotgit_contents);\n>  \tif (!*id)\n>  \t\tgoto error;\n>  \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n>  \tif (!is_directory(inferred->buf))\n>  \t\tgoto error;\n>  \n>  \treturn inferred->len;\n>  error:\n>  \tstrbuf_reset(inferred); /* clear invalid path */\n>  \treturn -1;\n\nThe caller is expected to give us the contents of gitfile read by\nsetup.c:read_gitfile_raw(), which reads the file in full, validates\nthat the file begins with \"gitdir: \" (notice the trailing space),\nremoves arbitrary run of CR or LF from the end, and then returns\nthe string after skipping \"gitdir: \" prefix (8 bytes).\n\nIn the normal case, read_gitfile_raw() would see \"gitdir: foo/bar/baz\\n\" \nin the file and returns \"foo/bar/baz\" to our caller.  In fishy cases\nwe examined for the preimage above:\n\n - If the contents of the gitfile were \"gitdir:foo/bar/baz \\n\", our\n   caller would have received an error from read_gitfile_raw() and\n   wouldn't have called us.\n\n - If the contents of the gitfile were \"gitdir: foo/bar/   \\n\", our\n   caller would have given us \"foo/bar/   \".\n\nget_worktree_id() will give us \"baz\" in the normal case, and \"   \"\nin the last case.  We fail to error out in the latter with \"*id\"\ncheck, but is_directory() check will catch us, as the inferred\ndirectory is \"worktrees/   \" in that bad case.\n\nSo there are certain differences in error cases, but they behave the\nsame in the most basic cases.\n\n\nNow, this is the caller in the preimage (i.e., what we used to do).\n\n> @@ -856,51 +855,49 @@ void repair_worktree_at_path(struct repository *repo,\n>  \t\tgoto done;\n>  \t}\n>  \n> -\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n> -\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n> -\tdotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));\n\nWe used to have infer_backlink() read the .git file to compute \"worktree/$id\",\nthen again called read_gitfile_gently() to read it again.\n\n> -\tif (dotgit_contents) {\n> -\t\tstrbuf_addstr(&backlink, dotgit_contents);\n\nThis is the happy path.  We successfully read from .git and use it.\n\n> -\t} else if (err == READ_GITFILE_ERR_NOT_A_FILE ||\n> -\t\t\terr == READ_GITFILE_ERR_IS_A_DIR) {\n>  \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git is not a file\"), cb_data);\n>  \t\tgoto done;\n\nThis is inherited badness, but overly long lines like this one needs\nto be fixed.\n\n> -\t} else if (err == READ_GITFILE_ERR_NOT_A_REPO) {\n\nThe _gently() did read something, but that does not point at a git\ndirectory.\n\n> -\t\tif (inferred_backlink.len) {\n> -\t\t\t/*\n> -\t\t\t * Worktree's .git file does not point at a repository\n> -\t\t\t * but we found a .git/worktrees/<id> in this\n> -\t\t\t * repository with the same <id> as recorded in the\n> -\t\t\t * worktree's .git file so make the worktree point at\n> -\t\t\t * the discovered .git/worktrees/<id>.\n> -\t\t\t */\n> -\t\t\tstrbuf_swap(&backlink, &inferred_backlink);\n\nIf we had the \"worktree/$id\" thing, we use it.\n\n> -\t\t} else {\n> -\t\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n> -\t\t\tgoto done;\n> -\t\t}\n> -\t} else {\n>  \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file broken\"), cb_data);\n>  \t\tgoto done;\n>  \t}\n\nThese lines to show error messages should also be folded to avoid\noverly long lines.\n\nSo, what does the updated code in the postimage do?\n\n> @@ -856,51 +855,49 @@ void repair_worktree_at_path(struct repository *repo,\n>  \t\tgoto done;\n>  \t}\n>  \n> +\terr = read_gitfile_raw(&contents, dotgit.buf);\n\nWe use read_gitfile_raw() just once.\n\n> +\tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n> +\t    err == READ_GITFILE_ERR_IS_A_DIR) {\n>  \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git is not a file\"), cb_data);\n>  \t\tgoto done;\n> +\t} else if (err) {\n>  \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file broken\"), cb_data);\n>  \t\tgoto done;\n>  \t}\n\nThe original code handled the happy case that read_gitfile_gently()\nsuccessfully returned first.  Underlying read_gitfile_raw() would\nnot have given any of these errors when read_gitfile_gently()\nsucceeded, so handling the error cases first would not affect the\nbehaviour of the code in these cases.  Again, these overlong lines\nare annoying.\n\nNow the simplest error cases are behind us.  How would we do in the\nhappy case?\n\n> +\tdotgit_contents = contents.buf;\n> +\tinfer_backlink(repo, dotgit_contents, &inferred_backlink);\n> +\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n\nWe reuse what we already read with read_gitfile_raw(), which\nprepared \"worktrees/$id\", and do the same realpath_forgiving()\nthe original used to do a bit earlier.\n\n> +\tif (is_absolute_path(dotgit_contents)) {\n> +\t\tstrbuf_addstr(&backlink, dotgit_contents);\n\nI am not sure which part of the original this logic corresponds to.\nIf the result from read_gitfile_raw() is an absolute path, even if\nit later turns out not to be is_git_directory(), the inferred backlink\nis not given a chance to act as a fallback.  The original made a\ncall to read_gitfile_gently() which checked is_git_directory() to\ngive us an error, and that is how it allowed inferred backlink to\nsubstitute for a bad contents stored in .git file.  Now we do not\nallow that fallback if .git file has an absolute path?\n\nAh, outside the context of this patch, before we barf for \"unable to\nlocate repository\" when we complain backlink.buf is not naming a git\ndirectory, there is the fallback logic, and in order to reach there,\nwe have \"if (!is_git_directory(backlink.buf) && !inferred_backlink.len)\"\nthere.  OK, so this may be doing the same thing as the original, but\nit is rather hard to follow and convince readers that this is a\nno-op conversion.\n\n> +\t} else {\n> +\t\tstrbuf_addbuf(&backlink, &dotgit);\n> +\t\tstrbuf_strip_suffix(&backlink, \".git\");\n> +\t\tstrbuf_addstr(&backlink, dotgit_contents);\n> +\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n\nThis converts dotgit_contents relative to the computed backlink,\nwhich needs to be done here because read_gitfile_gently() used to do\nthat for us, which we no longer use.\n\n> +\t}\n> +\n> +\tif (!is_git_directory(backlink.buf) && !inferred_backlink.len) {\n> +\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n> +\t\tgoto done;\n> +\t}\n\nI'll stop here.\n\n"},{"id":"554718","messageId":"CAF5D8-vFCwDjNMRwk4Vkjz9SrRgkQKFW_yYVFLiTNM_sXnMHLA@mail.gmail.com","threadId":"66320","inReplyTo":"xmqqh5ivyks1.fsf@gitster.g","subject":"Re: [PATCH 1/2] worktree repair: refactor and reduce .git file reads","fromName":"Yoichi NAKAYAMA","fromEmail":"yoichi.nakayama@gmail.com","sentAt":"2026-10-11T16:16:34Z","receivedAt":"2026-10-11T16:16:34Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"On Fri, Oct 9, 2026 at 5:55 AM Junio C Hamano <gitster@pobox.com> wrote:\n>\n> \"Yoichi NAKAYAMA via GitGitGadget\" <gitgitgadget@gmail.com> writes:\n>\n> > +static const char *get_worktree_id(const char *dotgit_contents)\n> > +{\n> > +     const char *slash = find_last_dir_sep(dotgit_contents);\n> > +     if (!slash)\n> > +             return \"\";\n> > +     return slash + 1;\n> > +}\n>\n> This returns a pointer into dotgit_contents; it is the last\n> component of a pathname, similar to what basename(3) gives us.\n>\n> > @@ -798,30 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n>\n> The unified diff is a bit hard to follow, so let's see if we can\n> compare preimage and postimage more easily.\n>\n> >  static ssize_t infer_backlink(struct repository *repo,\n> > -                           const char *gitfile,\n> >                             struct strbuf *inferred)\n> >  {\n> > -     struct strbuf actual = STRBUF_INIT;\n> >       const char *id;\n> >\n> > -     if (strbuf_read_file(&actual, gitfile, 0) < 0)\n> > -             goto error;\n> > -     if (!starts_with(actual.buf, \"gitdir:\"))\n> > -             goto error;\n> > -     if (!(id = find_last_dir_sep(actual.buf)))\n> > -             goto error;\n> > -     strbuf_trim(&actual);\n> > -     id++; /* advance past '/' to point at <id> */\n> >       if (!*id)\n> >               goto error;\n> >       repo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n> >       if (!is_directory(inferred->buf))\n> >               goto error;\n> >\n> > -     strbuf_release(&actual);\n> >       return inferred->len;\n> >  error:\n> > -     strbuf_release(&actual);\n> >       strbuf_reset(inferred); /* clear invalid path */\n> >       return -1;\n>\n> We used to receive the filename of \".git\", read it and made sure we\n> have \"gitdir:\" prefix, and find the last component, but then trimmed\n> the actual buffer.  Which means a few things.\n>\n>  - If the contents of the gitfile were \"gitdir:foo/bar/baz \\n\", our\n>    id pointer found the slash after \"foo/bar\", trimmed the buffer to\n>    have \"gitdir:foo/bar/baz\", and then incremented id, which now\n>    points at \"baz\".\n>\n>  - If the contents of the gitfile were \"gitdir: foo/bar/   \\n\", then\n>    after triming, the buffer would have \"gitdir: foo/bar/\" and id\n>    would be pointing at the NUL at the end, which would have lead us\n>    to error.\n>\n> Now let's look at the new code.\n>\n> > @@ -798,30 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n> >   * Returns -1 on failure and strbuf.len on success.\n> >   */\n> >  static ssize_t infer_backlink(struct repository *repo,\n> > +                           const char *dotgit_contents,\n> >                             struct strbuf *inferred)\n> >  {\n> >       const char *id;\n> >\n> > +     id = get_worktree_id(dotgit_contents);\n> >       if (!*id)\n> >               goto error;\n> >       repo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n> >       if (!is_directory(inferred->buf))\n> >               goto error;\n> >\n> >       return inferred->len;\n> >  error:\n> >       strbuf_reset(inferred); /* clear invalid path */\n> >       return -1;\n>\n> The caller is expected to give us the contents of gitfile read by\n> setup.c:read_gitfile_raw(), which reads the file in full, validates\n> that the file begins with \"gitdir: \" (notice the trailing space),\n> removes arbitrary run of CR or LF from the end, and then returns\n> the string after skipping \"gitdir: \" prefix (8 bytes).\n>\n> In the normal case, read_gitfile_raw() would see \"gitdir: foo/bar/baz\\n\"\n> in the file and returns \"foo/bar/baz\" to our caller.  In fishy cases\n> we examined for the preimage above:\n>\n>  - If the contents of the gitfile were \"gitdir:foo/bar/baz \\n\", our\n>    caller would have received an error from read_gitfile_raw() and\n>    wouldn't have called us.\n>\n>  - If the contents of the gitfile were \"gitdir: foo/bar/   \\n\", our\n>    caller would have given us \"foo/bar/   \".\n>\n> get_worktree_id() will give us \"baz\" in the normal case, and \"   \"\n> in the last case.  We fail to error out in the latter with \"*id\"\n> check, but is_directory() check will catch us, as the inferred\n> directory is \"worktrees/   \" in that bad case.\n>\n> So there are certain differences in error cases, but they behave the\n> same in the most basic cases.\n\ninfer_backlink() in the preimage accepts the \"gitdir:\" prefix without requiring\na following space and uses strbuf_trim(), which does more than just remove\ntrailing newlines. This is more lenient than `read_gitfile_gently()`, which is\ncalled when other Git commands are used.\nI believe the primary purpose of `worktree repair` is to fix common issues\nlike worktree relocation, with repairing cases where the `.git` file's contents\nwere manually modified being a secondary concern.\nTherefore, I have adjusted the behavior for error cases: if the file deviates\nfrom the standard `.git` file format, it is treated as \".git file\nbroken\"; if there\nare trailing whitespaces, they are interpreted as part of the path and treated\nas \".git file does not reference a repository.\"\nI would like to split the commits and provide a detailed explanation for this.\n\n> > -     } else if (err == READ_GITFILE_ERR_NOT_A_FILE ||\n> > -                     err == READ_GITFILE_ERR_IS_A_DIR) {\n> >               fn(1, dotgit.buf, _(\"unable to locate repository; .git is not a file\"), cb_data);\n> >               goto done;\n>\n> This is inherited badness, but overly long lines like this one needs\n> to be fixed.\n\nI'll fold long lines near the changes.\n\n> Ah, outside the context of this patch, before we barf for \"unable to\n> locate repository\" when we complain backlink.buf is not naming a git\n> directory, there is the fallback logic, and in order to reach there,\n> we have \"if (!is_git_directory(backlink.buf) && !inferred_backlink.len)\"\n> there.  OK, so this may be doing the same thing as the original, but\n> it is rather hard to follow and convince readers that this is a\n> no-op conversion.\n\nThe first commit contained multiple changes, making it difficult to follow.\nI will split the commit to distinguish between the parts where the behavior\nis modified and those where it remains unchanged, making it easier to\nverify that no changes were made to the latter.\n\nThanks,\n-- \nYoichi NAKAYAMA\n\n"},{"id":"554805","messageId":"CAF5D8-siz_USPuW=GEc3LNvSGD_8HXjVcFgr_zUNdYkeRu7Fzg@mail.gmail.com","threadId":"66320","inReplyTo":"CAF5D8-vFCwDjNMRwk4Vkjz9SrRgkQKFW_yYVFLiTNM_sXnMHLA@mail.gmail.com","subject":"Re: [PATCH 1/2] worktree repair: refactor and reduce .git file reads","fromName":"Yoichi NAKAYAMA","fromEmail":"yoichi.nakayama@gmail.com","sentAt":"2026-10-12T19:57:06Z","receivedAt":"2026-10-12T19:57:06Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"On Mon, Oct 12, 2026 at 1:16 AM Yoichi NAKAYAMA\n<yoichi.nakayama@gmail.com> wrote:\n>\n> On Fri, Oct 9, 2026 at 5:55 AM Junio C Hamano <gitster@pobox.com> wrote:\n> >\n> > \"Yoichi NAKAYAMA via GitGitGadget\" <gitgitgadget@gmail.com> writes:\n> >\n> > > +static const char *get_worktree_id(const char *dotgit_contents)\n> > > +{\n> > > +     const char *slash = find_last_dir_sep(dotgit_contents);\n> > > +     if (!slash)\n> > > +             return \"\";\n> > > +     return slash + 1;\n> > > +}\n> >\n> > This returns a pointer into dotgit_contents; it is the last\n> > component of a pathname, similar to what basename(3) gives us.\n> >\n> > > @@ -798,30 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n> >\n> > The unified diff is a bit hard to follow, so let's see if we can\n> > compare preimage and postimage more easily.\n> >\n> > >  static ssize_t infer_backlink(struct repository *repo,\n> > > -                           const char *gitfile,\n> > >                             struct strbuf *inferred)\n> > >  {\n> > > -     struct strbuf actual = STRBUF_INIT;\n> > >       const char *id;\n> > >\n> > > -     if (strbuf_read_file(&actual, gitfile, 0) < 0)\n> > > -             goto error;\n> > > -     if (!starts_with(actual.buf, \"gitdir:\"))\n> > > -             goto error;\n> > > -     if (!(id = find_last_dir_sep(actual.buf)))\n> > > -             goto error;\n> > > -     strbuf_trim(&actual);\n> > > -     id++; /* advance past '/' to point at <id> */\n> > >       if (!*id)\n> > >               goto error;\n> > >       repo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n> > >       if (!is_directory(inferred->buf))\n> > >               goto error;\n> > >\n> > > -     strbuf_release(&actual);\n> > >       return inferred->len;\n> > >  error:\n> > > -     strbuf_release(&actual);\n> > >       strbuf_reset(inferred); /* clear invalid path */\n> > >       return -1;\n> >\n> > We used to receive the filename of \".git\", read it and made sure we\n> > have \"gitdir:\" prefix, and find the last component, but then trimmed\n> > the actual buffer.  Which means a few things.\n> >\n> >  - If the contents of the gitfile were \"gitdir:foo/bar/baz \\n\", our\n> >    id pointer found the slash after \"foo/bar\", trimmed the buffer to\n> >    have \"gitdir:foo/bar/baz\", and then incremented id, which now\n> >    points at \"baz\".\n> >\n> >  - If the contents of the gitfile were \"gitdir: foo/bar/   \\n\", then\n> >    after triming, the buffer would have \"gitdir: foo/bar/\" and id\n> >    would be pointing at the NUL at the end, which would have lead us\n> >    to error.\n> >\n> > Now let's look at the new code.\n> >\n> > > @@ -798,30 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n> > >   * Returns -1 on failure and strbuf.len on success.\n> > >   */\n> > >  static ssize_t infer_backlink(struct repository *repo,\n> > > +                           const char *dotgit_contents,\n> > >                             struct strbuf *inferred)\n> > >  {\n> > >       const char *id;\n> > >\n> > > +     id = get_worktree_id(dotgit_contents);\n> > >       if (!*id)\n> > >               goto error;\n> > >       repo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n> > >       if (!is_directory(inferred->buf))\n> > >               goto error;\n> > >\n> > >       return inferred->len;\n> > >  error:\n> > >       strbuf_reset(inferred); /* clear invalid path */\n> > >       return -1;\n> >\n> > The caller is expected to give us the contents of gitfile read by\n> > setup.c:read_gitfile_raw(), which reads the file in full, validates\n> > that the file begins with \"gitdir: \" (notice the trailing space),\n> > removes arbitrary run of CR or LF from the end, and then returns\n> > the string after skipping \"gitdir: \" prefix (8 bytes).\n> >\n> > In the normal case, read_gitfile_raw() would see \"gitdir: foo/bar/baz\\n\"\n> > in the file and returns \"foo/bar/baz\" to our caller.  In fishy cases\n> > we examined for the preimage above:\n> >\n> >  - If the contents of the gitfile were \"gitdir:foo/bar/baz \\n\", our\n> >    caller would have received an error from read_gitfile_raw() and\n> >    wouldn't have called us.\n> >\n> >  - If the contents of the gitfile were \"gitdir: foo/bar/   \\n\", our\n> >    caller would have given us \"foo/bar/   \".\n> >\n> > get_worktree_id() will give us \"baz\" in the normal case, and \"   \"\n> > in the last case.  We fail to error out in the latter with \"*id\"\n> > check, but is_directory() check will catch us, as the inferred\n> > directory is \"worktrees/   \" in that bad case.\n> >\n> > So there are certain differences in error cases, but they behave the\n> > same in the most basic cases.\n>\n> infer_backlink() in the preimage accepts the \"gitdir:\" prefix without requiring\n> a following space and uses strbuf_trim(), which does more than just remove\n> trailing newlines. This is more lenient than `read_gitfile_gently()`, which is\n> called when other Git commands are used.\n> I believe the primary purpose of `worktree repair` is to fix common issues\n> like worktree relocation, with repairing cases where the `.git` file's contents\n> were manually modified being a secondary concern.\n> Therefore, I have adjusted the behavior for error cases: if the file deviates\n> from the standard `.git` file format, it is treated as \".git file\n> broken\"; if there\n> are trailing whitespaces, they are interpreted as part of the path and treated\n> as \".git file does not reference a repository.\"\n\nThe former case (where there is no space after \"gitdir:\") behaved this way\neven before the change. repair_worktree_at_path() calls read_gitfile_gently()\nand returns `err = READ_GITFILE_ERR_INVALID_FORMAT`; this behavior\nremains unchanged.\n\nThanks,\n-- \nYoichi NAKAYAMA\n\n"},{"id":"555072","messageId":"pull.2225.v2.git.1792012836.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.git.1789269613.gitgitgadget@gmail.com","subject":"[PATCH v2 0/5] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-14T21:20:31Z","receivedAt":"2026-10-14T21:20:31Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"'git worktree repair' does not sufficiently validate the cross-references\nbetween a linked working tree and its administrative data before repairing\nthem. This can cause the repair to modify the wrong .git file or gitdir in\ncertain situations.\n\n\nv2 (0156021)\n============\n\nSplit the first commit of v1 to make the changes easier to understand. Fold\nlong lines.\n\n * [1/5] align .git file handling with repair_gitfile()\n * [2/5] centralize inferred backlink selection\n * [3/5] use read_gitfile_raw() in infer_backlink()\n * [4/5] reduce .git file reads\n * [5/5] avoid breaking unrelated .git file and gitdir\n\n\nv1 (99aa341)\n============\n\nThis series first refactors the code to read the .git file once and extract\nthe worktree ID, then uses that information to validate the repair target\nbefore modifying the cross-references.\n\n * [1/2] Refactor the code without changing functionality before making the\n   fix\n * [2/2] Validate the worktree ID and inferred gitdir path before repairing\n\nYoichi NAKAYAMA (5):\n  worktree repair: align .git file handling with repair_gitfile()\n  worktree repair: centralize inferred backlink selection\n  worktree repair: use read_gitfile_raw() in infer_backlink()\n  worktree repair: reduce .git file reads\n  worktree repair: avoid breaking unrelated .git file and gitdir\n\n t/t2406-worktree-repair.sh |  33 +++++++++--\n worktree.c                 | 113 +++++++++++++++++++++----------------\n 2 files changed, 91 insertions(+), 55 deletions(-)\n\n\nbase-commit: 6de20f6092dcf9bdb1c8efe03db4b70c82b423dd\nPublished-As: https://github.com/gitgitgadget/git/releases/tag/pr-2225%2Fyoichi%2Fworktree-repair-keep-unrelated-gitfile-v2\nFetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2225/yoichi/worktree-repair-keep-unrelated-gitfile-v2\nPull-Request: https://github.com/gitgitgadget/git/pull/2225\n\nRange-diff vs v1:\n\n -:  ---------- > 1:  21b2878aa5 worktree repair: align .git file handling with repair_gitfile()\n 1:  dc7ebb427b ! 2:  30ac7acad3 worktree repair: refactor and reduce .git file reads\n     @@ Metadata\n      Author: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n      \n       ## Commit message ##\n     -    worktree repair: refactor and reduce .git file reads\n     +    worktree repair: centralize inferred backlink selection\n      \n     -    Remove the file reading and trimming logic from `infer_backlink()`,\n     -    and instead read the .git file once in its caller,\n     -    `repair_worktree_at_path()`, using `read_gitfile_raw()`. Since\n     -    `read_gitfile_gently()` is replaced with `read_gitfile_raw()`, restore\n     -    the logic for constructing the absolute path and replace the\n     -    READ_GITFILE_ERR_NOT_A_REPO handling with a check using\n     -    `is_git_directory()`. Simplify the logic for prioritizing\n     -    'inferred_backlink' over 'backlink'.\n     -\n     -    Extract `get_worktree_id()` to get the worktree ID from the contents\n     -    of the .git file. We are going to modify and use this function in\n     -    subsequent commits.\n     +    Reorder the processing steps to centralize the logic for preferring\n     +    the inferred_backlink.\n      \n          Signed-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n      \n       ## worktree.c ##\n     -@@ worktree.c: int other_head_refs(struct repository *repo,\n     - \treturn ret;\n     - }\n     - \n     -+static const char *get_worktree_id(const char *dotgit_contents)\n     -+{\n     -+\tconst char *slash = find_last_dir_sep(dotgit_contents);\n     -+\tif (!slash)\n     -+\t\treturn \"\";\n     -+\treturn slash + 1;\n     -+}\n     -+\n     - /*\n     -  * Repair worktree's /path/to/worktree/.git file if missing, corrupt, or not\n     -  * pointing at <repo>/worktrees/<id>.\n     -@@ worktree.c: static int is_main_worktree_path(struct repository *repo, const char *path)\n     -  * Returns -1 on failure and strbuf.len on success.\n     -  */\n     - static ssize_t infer_backlink(struct repository *repo,\n     --\t\t\t      const char *gitfile,\n     -+\t\t\t      const char *dotgit_contents,\n     - \t\t\t      struct strbuf *inferred)\n     - {\n     --\tstruct strbuf actual = STRBUF_INIT;\n     - \tconst char *id;\n     - \n     --\tif (strbuf_read_file(&actual, gitfile, 0) < 0)\n     --\t\tgoto error;\n     --\tif (!starts_with(actual.buf, \"gitdir:\"))\n     --\t\tgoto error;\n     --\tif (!(id = find_last_dir_sep(actual.buf)))\n     --\t\tgoto error;\n     --\tstrbuf_trim(&actual);\n     --\tid++; /* advance past '/' to point at <id> */\n     -+\tid = get_worktree_id(dotgit_contents);\n     - \tif (!*id)\n     - \t\tgoto error;\n     - \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n     - \tif (!is_directory(inferred->buf))\n     - \t\tgoto error;\n     - \n     --\tstrbuf_release(&actual);\n     - \treturn inferred->len;\n     - error:\n     --\tstrbuf_release(&actual);\n     - \tstrbuf_reset(inferred); /* clear invalid path */\n     - \treturn -1;\n     - }\n      @@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n     - \tstruct strbuf inferred_backlink = STRBUF_INIT;\n       \tstruct strbuf gitdir = STRBUF_INIT;\n       \tstruct strbuf olddotgit = STRBUF_INIT;\n     --\tchar *dotgit_contents = NULL;\n     -+\tstruct strbuf contents = STRBUF_INIT;\n     + \tstruct strbuf contents = STRBUF_INIT;\n      +\tconst char *dotgit_contents = NULL;\n       \tconst char *repair = NULL;\n       \tint err;\n     @@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n       \n      -\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n      -\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n     --\tdotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));\n     --\tif (dotgit_contents) {\n     --\t\tstrbuf_addstr(&backlink, dotgit_contents);\n     --\t} else if (err == READ_GITFILE_ERR_NOT_A_FILE ||\n     --\t\t\terr == READ_GITFILE_ERR_IS_A_DIR) {\n     -+\terr = read_gitfile_raw(&contents, dotgit.buf);\n     -+\tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n     -+\t    err == READ_GITFILE_ERR_IS_A_DIR) {\n     - \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git is not a file\"), cb_data);\n     + \terr = read_gitfile_raw(&contents, dotgit.buf);\n     +-\tif (!err) {\n     +-\t\tconst char *dotgit_contents = contents.buf;\n     +-\t\tif (is_absolute_path(dotgit_contents)) {\n     +-\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n     +-\t\t} else {\n     +-\t\t\tstrbuf_addbuf(&backlink, &dotgit);\n     +-\t\t\tstrbuf_strip_suffix(&backlink, \".git\");\n     +-\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n     +-\t\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n     +-\t\t}\n     +-\t}\n     + \tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n     + \t    err == READ_GITFILE_ERR_IS_A_DIR) {\n     + \t\tfn(1, dotgit.buf,\n     + \t\t   _(\"unable to locate repository; .git is not a file\"),\n     + \t\t   cb_data);\n       \t\tgoto done;\n     --\t} else if (err == READ_GITFILE_ERR_NOT_A_REPO) {\n     +-\t} else if (!err && !is_git_directory(backlink.buf)) {\n     +-\t\tstrbuf_release(&backlink);\n      -\t\tif (inferred_backlink.len) {\n      -\t\t\t/*\n      -\t\t\t * Worktree's .git file does not point at a repository\n     @@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n      -\t\t\t */\n      -\t\t\tstrbuf_swap(&backlink, &inferred_backlink);\n      -\t\t} else {\n     --\t\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n     +-\t\t\tfn(1, dotgit.buf,\n     +-\t\t\t   _(\"unable to locate repository; .git file does not reference a repository\"),\n     +-\t\t\t   cb_data);\n      -\t\t\tgoto done;\n      -\t\t}\n     --\t} else {\n     -+\t} else if (err) {\n     - \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file broken\"), cb_data);\n     + \t} else if (err) {\n     + \t\tfn(1, dotgit.buf,\n     + \t\t   _(\"unable to locate repository; .git file broken\"),\n     +@@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n       \t\tgoto done;\n       \t}\n       \n      +\tdotgit_contents = contents.buf;\n     -+\tinfer_backlink(repo, dotgit_contents, &inferred_backlink);\n     ++\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n      +\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n      +\n      +\tif (is_absolute_path(dotgit_contents)) {\n     @@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n      +\t}\n      +\n      +\tif (!is_git_directory(backlink.buf) && !inferred_backlink.len) {\n     -+\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n     ++\t\tfn(1, dotgit.buf,\n     ++\t\t   _(\"unable to locate repository; .git file does not reference a repository\"),\n     ++\t\t   cb_data);\n      +\t\tgoto done;\n      +\t}\n      +\n     @@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n       \t */\n       \tif (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))\n       \t\tstrbuf_swap(&backlink, &inferred_backlink);\n     -@@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n     - \t\t\t\t\t     gitdir.buf, use_relative_paths);\n     - \t}\n     - done:\n     --\tfree(dotgit_contents);\n     - \tstrbuf_release(&olddotgit);\n     - \tstrbuf_release(&backlink);\n     - \tstrbuf_release(&inferred_backlink);\n     - \tstrbuf_release(&gitdir);\n     - \tstrbuf_release(&dotgit);\n     -+\tstrbuf_release(&contents);\n     - }\n     - \n     - int should_prune_worktree(struct repository *repo,\n -:  ---------- > 3:  2cc7b817ee worktree repair: use read_gitfile_raw() in infer_backlink()\n -:  ---------- > 4:  8c80b9ae05 worktree repair: reduce .git file reads\n 2:  99aa34135c ! 5:  015602168c worktree repair: avoid breaking unrelated .git file and gitdir\n     @@ worktree.c: static ssize_t infer_backlink(struct repository *repo,\n       \n       \treturn inferred->len;\n      @@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n     - \t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n     + \t\t   cb_data);\n       \t\tgoto done;\n       \t}\n      +\tif (!inferred_backlink.len) {\n     -+\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file is not for a linked worktree\"), cb_data);\n     ++\t\tfn(1, dotgit.buf,\n     ++\t\t   _(\"unable to locate repository; .git file is not for a linked worktree\"),\n     ++\t\t   cb_data);\n      +\t\tgoto done;\n      +\t}\n       \n\n-- \ngitgitgadget\n\n"},{"id":"555073","messageId":"21b2878aa552a931788aa7bb14720b24e7809c75.1792012836.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v2.git.1792012836.gitgitgadget@gmail.com","subject":"[PATCH v2 1/5] worktree repair: align .git file handling with repair_gitfile()","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-14T21:20:32Z","receivedAt":"2026-10-14T21:20:32Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nUse read_gitfile_raw() instead of read_gitfile_gently() in\nrepair_worktree_at_path(), moving path resolution and repository\nvalidation to the caller. This makes .git file handling consistent\nwith repair_gitfile() and avoids using the non-reentrant\nread_gitfile_gently().\n\nA subsequent commit will update infer_backlink() to use\nread_gitfile_raw() as well.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 40 ++++++++++++++++++++++++++++------------\n 1 file changed, 28 insertions(+), 12 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex 8cb8637b18..4492ca835d 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -840,7 +840,7 @@ void repair_worktree_at_path(struct repository *repo,\n \tstruct strbuf inferred_backlink = STRBUF_INIT;\n \tstruct strbuf gitdir = STRBUF_INIT;\n \tstruct strbuf olddotgit = STRBUF_INIT;\n-\tchar *dotgit_contents = NULL;\n+\tstruct strbuf contents = STRBUF_INIT;\n \tconst char *repair = NULL;\n \tint err;\n \n@@ -858,14 +858,26 @@ void repair_worktree_at_path(struct repository *repo,\n \n \tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n \tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n-\tdotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));\n-\tif (dotgit_contents) {\n-\t\tstrbuf_addstr(&backlink, dotgit_contents);\n-\t} else if (err == READ_GITFILE_ERR_NOT_A_FILE ||\n-\t\t\terr == READ_GITFILE_ERR_IS_A_DIR) {\n-\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git is not a file\"), cb_data);\n+\terr = read_gitfile_raw(&contents, dotgit.buf);\n+\tif (!err) {\n+\t\tconst char *dotgit_contents = contents.buf;\n+\t\tif (is_absolute_path(dotgit_contents)) {\n+\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t\t} else {\n+\t\t\tstrbuf_addbuf(&backlink, &dotgit);\n+\t\t\tstrbuf_strip_suffix(&backlink, \".git\");\n+\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n+\t\t}\n+\t}\n+\tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n+\t    err == READ_GITFILE_ERR_IS_A_DIR) {\n+\t\tfn(1, dotgit.buf,\n+\t\t   _(\"unable to locate repository; .git is not a file\"),\n+\t\t   cb_data);\n \t\tgoto done;\n-\t} else if (err == READ_GITFILE_ERR_NOT_A_REPO) {\n+\t} else if (!err && !is_git_directory(backlink.buf)) {\n+\t\tstrbuf_release(&backlink);\n \t\tif (inferred_backlink.len) {\n \t\t\t/*\n \t\t\t * Worktree's .git file does not point at a repository\n@@ -876,11 +888,15 @@ void repair_worktree_at_path(struct repository *repo,\n \t\t\t */\n \t\t\tstrbuf_swap(&backlink, &inferred_backlink);\n \t\t} else {\n-\t\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n+\t\t\tfn(1, dotgit.buf,\n+\t\t\t   _(\"unable to locate repository; .git file does not reference a repository\"),\n+\t\t\t   cb_data);\n \t\t\tgoto done;\n \t\t}\n-\t} else {\n-\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file broken\"), cb_data);\n+\t} else if (err) {\n+\t\tfn(1, dotgit.buf,\n+\t\t   _(\"unable to locate repository; .git file broken\"),\n+\t\t   cb_data);\n \t\tgoto done;\n \t}\n \n@@ -926,12 +942,12 @@ void repair_worktree_at_path(struct repository *repo,\n \t\t\t\t\t     gitdir.buf, use_relative_paths);\n \t}\n done:\n-\tfree(dotgit_contents);\n \tstrbuf_release(&olddotgit);\n \tstrbuf_release(&backlink);\n \tstrbuf_release(&inferred_backlink);\n \tstrbuf_release(&gitdir);\n \tstrbuf_release(&dotgit);\n+\tstrbuf_release(&contents);\n }\n \n int should_prune_worktree(struct repository *repo,\n-- \ngitgitgadget\n\n\n"},{"id":"555074","messageId":"30ac7acad32750609befc3049c0f4174f6ec2f2e.1792012836.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v2.git.1792012836.gitgitgadget@gmail.com","subject":"[PATCH v2 2/5] worktree repair: centralize inferred backlink selection","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-14T21:20:33Z","receivedAt":"2026-10-14T21:20:33Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nReorder the processing steps to centralize the logic for preferring\nthe inferred_backlink.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 69 +++++++++++++++++++++++-------------------------------\n 1 file changed, 29 insertions(+), 40 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex 4492ca835d..f8e9850f6f 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -841,6 +841,7 @@ void repair_worktree_at_path(struct repository *repo,\n \tstruct strbuf gitdir = STRBUF_INIT;\n \tstruct strbuf olddotgit = STRBUF_INIT;\n \tstruct strbuf contents = STRBUF_INIT;\n+\tconst char *dotgit_contents = NULL;\n \tconst char *repair = NULL;\n \tint err;\n \n@@ -856,43 +857,13 @@ void repair_worktree_at_path(struct repository *repo,\n \t\tgoto done;\n \t}\n \n-\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n-\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n \terr = read_gitfile_raw(&contents, dotgit.buf);\n-\tif (!err) {\n-\t\tconst char *dotgit_contents = contents.buf;\n-\t\tif (is_absolute_path(dotgit_contents)) {\n-\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n-\t\t} else {\n-\t\t\tstrbuf_addbuf(&backlink, &dotgit);\n-\t\t\tstrbuf_strip_suffix(&backlink, \".git\");\n-\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n-\t\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n-\t\t}\n-\t}\n \tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n \t    err == READ_GITFILE_ERR_IS_A_DIR) {\n \t\tfn(1, dotgit.buf,\n \t\t   _(\"unable to locate repository; .git is not a file\"),\n \t\t   cb_data);\n \t\tgoto done;\n-\t} else if (!err && !is_git_directory(backlink.buf)) {\n-\t\tstrbuf_release(&backlink);\n-\t\tif (inferred_backlink.len) {\n-\t\t\t/*\n-\t\t\t * Worktree's .git file does not point at a repository\n-\t\t\t * but we found a .git/worktrees/<id> in this\n-\t\t\t * repository with the same <id> as recorded in the\n-\t\t\t * worktree's .git file so make the worktree point at\n-\t\t\t * the discovered .git/worktrees/<id>.\n-\t\t\t */\n-\t\t\tstrbuf_swap(&backlink, &inferred_backlink);\n-\t\t} else {\n-\t\t\tfn(1, dotgit.buf,\n-\t\t\t   _(\"unable to locate repository; .git file does not reference a repository\"),\n-\t\t\t   cb_data);\n-\t\t\tgoto done;\n-\t\t}\n \t} else if (err) {\n \t\tfn(1, dotgit.buf,\n \t\t   _(\"unable to locate repository; .git file broken\"),\n@@ -900,23 +871,41 @@ void repair_worktree_at_path(struct repository *repo,\n \t\tgoto done;\n \t}\n \n+\tdotgit_contents = contents.buf;\n+\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n+\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n+\n+\tif (is_absolute_path(dotgit_contents)) {\n+\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t} else {\n+\t\tstrbuf_addbuf(&backlink, &dotgit);\n+\t\tstrbuf_strip_suffix(&backlink, \".git\");\n+\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n+\t}\n+\n+\tif (!is_git_directory(backlink.buf) && !inferred_backlink.len) {\n+\t\tfn(1, dotgit.buf,\n+\t\t   _(\"unable to locate repository; .git file does not reference a repository\"),\n+\t\t   cb_data);\n+\t\tgoto done;\n+\t}\n+\n \t/*\n \t * If we got this far, either the worktree's .git file pointed at a\n-\t * valid repository (i.e. read_gitfile_gently() returned success) or\n+\t * valid repository (i.e. is_git_directory() returned true) or\n \t * the .git file did not point at a repository but we were able to\n \t * infer a suitable new value for the .git file by locating a\n \t * .git/worktrees/<id> in *this* repository corresponding to the <id>\n \t * recorded in the worktree's .git file.\n \t *\n-\t * However, if, at this point, inferred_backlink is non-NULL (i.e. we\n-\t * found a suitable .git/worktrees/<id> in *this* repository) *and* the\n-\t * worktree's .git file points at a valid repository *and* those two\n-\t * paths differ, then that indicates that the user probably *copied*\n-\t * the main and linked worktrees to a new location as a unit rather\n-\t * than *moving* them. Thus, the copied worktree's .git file actually\n-\t * points at the .git/worktrees/<id> in the *original* repository, not\n-\t * in the \"copy\" repository. In this case, point the \"copy\" worktree's\n-\t * .git file at the \"copy\" repository.\n+\t * Even if the worktree's .git file pointed at a valid repository,\n+\t * it doesn't always mean that the backlink is correct. For example,\n+\t * the user might have *copied* the main and linked worktrees to a\n+\t * new location as a unit rather than *moving* them (the copied\n+\t * worktree's .git file actually points at the .git/worktrees/<id>\n+\t * in the *original* repository, not in the \"copy\" repository).\n+\t * Therefore, we prioritize inferred_backlink over backlink.\n \t */\n \tif (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))\n \t\tstrbuf_swap(&backlink, &inferred_backlink);\n-- \ngitgitgadget\n\n\n"},{"id":"555075","messageId":"2cc7b817ee4105b57450ed80d80cfa224f2ed431.1792012836.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v2.git.1792012836.gitgitgadget@gmail.com","subject":"[PATCH v2 3/5] worktree repair: use read_gitfile_raw() in infer_backlink()","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-14T21:20:34Z","receivedAt":"2026-10-14T21:20:34Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nUse read_gitfile_raw() in infer_backlink() to parse .git files\nconsistently with repair_gitfile(). Unlike strbuf_trim(),\nread_gitfile_raw() does not silently discard trailing whitespace. Such\nwhitespace is treated as part of the path and may cause the path to be\ntreated as not referencing a repository.\n\nExtract get_worktree_id() for use in a subsequent commit.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 25 +++++++++++++++----------\n 1 file changed, 15 insertions(+), 10 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex f8e9850f6f..3627dbc044 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -637,6 +637,14 @@ int other_head_refs(struct repository *repo,\n \treturn ret;\n }\n \n+static const char *get_worktree_id(const char *dotgit_contents)\n+{\n+\tconst char *slash = find_last_dir_sep(dotgit_contents);\n+\tif (!slash)\n+\t\treturn \"\";\n+\treturn slash + 1;\n+}\n+\n /*\n  * Repair worktree's /path/to/worktree/.git file if missing, corrupt, or not\n  * pointing at <repo>/worktrees/<id>.\n@@ -801,27 +809,24 @@ static ssize_t infer_backlink(struct repository *repo,\n \t\t\t      const char *gitfile,\n \t\t\t      struct strbuf *inferred)\n {\n-\tstruct strbuf actual = STRBUF_INIT;\n+\tstruct strbuf contents = STRBUF_INIT;\n \tconst char *id;\n+\tint err;\n \n-\tif (strbuf_read_file(&actual, gitfile, 0) < 0)\n+\terr = read_gitfile_raw(&contents, gitfile);\n+\tif (err)\n \t\tgoto error;\n-\tif (!starts_with(actual.buf, \"gitdir:\"))\n-\t\tgoto error;\n-\tif (!(id = find_last_dir_sep(actual.buf)))\n-\t\tgoto error;\n-\tstrbuf_trim(&actual);\n-\tid++; /* advance past '/' to point at <id> */\n+\tid = get_worktree_id(contents.buf);\n \tif (!*id)\n \t\tgoto error;\n \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n \tif (!is_directory(inferred->buf))\n \t\tgoto error;\n \n-\tstrbuf_release(&actual);\n+\tstrbuf_release(&contents);\n \treturn inferred->len;\n error:\n-\tstrbuf_release(&actual);\n+\tstrbuf_release(&contents);\n \tstrbuf_reset(inferred); /* clear invalid path */\n \treturn -1;\n }\n-- \ngitgitgadget\n\n\n"},{"id":"555076","messageId":"8c80b9ae05035b3bb864e17e08be9604447dd0e5.1792012836.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v2.git.1792012836.gitgitgadget@gmail.com","subject":"[PATCH v2 4/5] worktree repair: reduce .git file reads","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-14T21:20:35Z","receivedAt":"2026-10-14T21:20:35Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nPass the loaded contents of the .git file to infer_backlink().\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 13 +++----------\n 1 file changed, 3 insertions(+), 10 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex 3627dbc044..879941a977 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -806,27 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n  * Returns -1 on failure and strbuf.len on success.\n  */\n static ssize_t infer_backlink(struct repository *repo,\n-\t\t\t      const char *gitfile,\n+\t\t\t      const char *dotgit_contents,\n \t\t\t      struct strbuf *inferred)\n {\n-\tstruct strbuf contents = STRBUF_INIT;\n \tconst char *id;\n-\tint err;\n \n-\terr = read_gitfile_raw(&contents, gitfile);\n-\tif (err)\n-\t\tgoto error;\n-\tid = get_worktree_id(contents.buf);\n+\tid = get_worktree_id(dotgit_contents);\n \tif (!*id)\n \t\tgoto error;\n \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n \tif (!is_directory(inferred->buf))\n \t\tgoto error;\n \n-\tstrbuf_release(&contents);\n \treturn inferred->len;\n error:\n-\tstrbuf_release(&contents);\n \tstrbuf_reset(inferred); /* clear invalid path */\n \treturn -1;\n }\n@@ -877,7 +870,7 @@ void repair_worktree_at_path(struct repository *repo,\n \t}\n \n \tdotgit_contents = contents.buf;\n-\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n+\tinfer_backlink(repo, dotgit_contents, &inferred_backlink);\n \tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n \n \tif (is_absolute_path(dotgit_contents)) {\n-- \ngitgitgadget\n\n\n"},{"id":"555077","messageId":"015602168c8532c07b94c9f50925bf5d5a2ef7c8.1792012836.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v2.git.1792012836.gitgitgadget@gmail.com","subject":"[PATCH v2 5/5] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-14T21:20:36Z","receivedAt":"2026-10-14T21:20:36Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nCurrently, `repair_gitfile()` does not verify whether the worktree ID\nrecorded in the .git file matches the worktree being repaired, which\ncan result in an unrelated .git file being corrupted. For instance,\nif two worktree directories are swapped without using 'git worktree\nmove', running 'git worktree repair' in the main worktree accidentally\nswaps the links between their .git files and gitdirs.\n\n`repair_worktree_at_path()` proceeds even if it fails to infer the\ngitdir path. This can result in the corruption of an unrelated\ngitdir. For instance, if we copied a linked worktree to a new location\nX, running 'git worktree repair X' in a working tree which does not\nbelong to the original repository can accidentally overwrite the\ngitdir in the original repository (the scope of impact should be\nlimited to the repository where the command was executed).\n\nResolve these issues by validating the worktree ID and stopping the\nrepair when the ID does not match or the gitdir path cannot be\ninferred.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n t/t2406-worktree-repair.sh | 33 +++++++++++++++++++++++++++------\n worktree.c                 | 20 ++++++++++++++++----\n 2 files changed, 43 insertions(+), 10 deletions(-)\n\ndiff --git a/t/t2406-worktree-repair.sh b/t/t2406-worktree-repair.sh\nindex d4e53d492b..2ffa123f42 100755\n--- a/t/t2406-worktree-repair.sh\n+++ b/t/t2406-worktree-repair.sh\n@@ -56,15 +56,12 @@ test_expect_success 'repair missing .git file' '\n '\n \n test_expect_success 'repair bogus .git file' '\n-\ttest_corrupt_gitfile \"echo \\\"gitdir: /nowhere\\\" >corrupt/.git\" \\\n+\ttest_corrupt_gitfile \"echo \\\"contents not started with gitdir:\\\" >corrupt/.git\" \\\n \t\t\".git file broken\"\n '\n \n-test_expect_success 'repair incorrect .git file' '\n-\ttest_when_finished \"rm -rf other && git worktree prune\" &&\n-\ttest_create_repo other &&\n-\tother=$(git -C other rev-parse --absolute-git-dir) &&\n-\ttest_corrupt_gitfile \"echo \\\"gitdir: $other\\\" >corrupt/.git\" \\\n+test_expect_success 'repair unlinked .git file' '\n+\ttest_corrupt_gitfile \"echo \\\"gitdir: /nowhere/worktrees/corrupt\\\" >corrupt/.git\" \\\n \t\t\".git file incorrect\"\n '\n \n@@ -89,6 +86,18 @@ test_expect_success 'repair .git file from bare.git' '\n \ttest_cmp expect actual\n '\n \n+test_expect_success 'skip unrelated .git file' '\n+\ttest_when_finished \"rm -rf corrupt other && git worktree prune\" &&\n+\tgit worktree add --detach corrupt &&\n+\trm -rf corrupt &&\n+\tgit worktree add --detach other &&\n+\tmv other corrupt &&\n+\tcat corrupt/.git >expect &&\n+\ttest_must_fail git worktree repair 2>err &&\n+\ttest_cmp expect corrupt/.git &&\n+\ttest_grep \"unrelated .git file\" err\n+'\n+\n test_expect_success 'invalid worktree path' '\n \ttest_must_fail git worktree repair /notvalid >out 2>err &&\n \ttest_must_be_empty out &&\n@@ -113,6 +122,18 @@ test_expect_success 'repo not found; .git not referencing repo' '\n \ttest_grep \".git file does not reference a repository\" err\n '\n \n+test_expect_success 'repo not found; .git not for worktree' '\n+\ttest_when_finished \"rm -rf side other-repo && git worktree prune\" &&\n+\ttest_create_repo other-repo &&\n+\tgit worktree add --detach side &&\n+\tcat .git/worktrees/side/gitdir >expect &&\n+\tcp -R side other-repo/side &&\n+\ttest_must_fail git -C other-repo worktree repair side >out 2>err &&\n+\ttest_cmp expect .git/worktrees/side/gitdir &&\n+\ttest_must_be_empty out &&\n+\ttest_grep \".git file is not for a linked worktree\" err\n+'\n+\n test_expect_success 'repo not found; .git file broken' '\n \ttest_when_finished \"rm -rf orig moved && git worktree prune\" &&\n \tgit worktree add --detach orig &&\ndiff --git a/worktree.c b/worktree.c\nindex 879941a977..86094307b1 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -640,7 +640,11 @@ int other_head_refs(struct repository *repo,\n static const char *get_worktree_id(const char *dotgit_contents)\n {\n \tconst char *slash = find_last_dir_sep(dotgit_contents);\n-\tif (!slash)\n+\tconst char *prefix = \"/worktrees\";\n+\tint prefixlen = strlen(prefix);\n+\tif (!slash ||\n+\t    slash - dotgit_contents < prefixlen ||\n+\t    strncmp(slash - prefixlen, prefix, prefixlen))\n \t\treturn \"\";\n \treturn slash + 1;\n }\n@@ -692,8 +696,10 @@ static void repair_gitfile(struct worktree *wt,\n \tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n \t\terr == READ_GITFILE_ERR_IS_A_DIR)\n \t\tfn(1, wt->path, _(\".git is not a file\"), cb_data);\n-\telse if (err || !is_git_directory(backlink.buf))\n+\telse if (err)\n \t\trepair = _(\".git file broken\");\n+\telse if (strcmp(get_worktree_id(dotgit_contents), wt->id))\n+\t\tfn(1, wt->path, _(\"unrelated .git file\"), cb_data);\n \telse if (fspathcmp(backlink.buf, repo.buf))\n \t\trepair = _(\".git file incorrect\");\n \telse if (use_relative_paths == is_absolute_path(dotgit_contents))\n@@ -815,7 +821,7 @@ static ssize_t infer_backlink(struct repository *repo,\n \tif (!*id)\n \t\tgoto error;\n \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n-\tif (!is_directory(inferred->buf))\n+\tif (!is_git_directory(inferred->buf))\n \t\tgoto error;\n \n \treturn inferred->len;\n@@ -888,6 +894,12 @@ void repair_worktree_at_path(struct repository *repo,\n \t\t   cb_data);\n \t\tgoto done;\n \t}\n+\tif (!inferred_backlink.len) {\n+\t\tfn(1, dotgit.buf,\n+\t\t   _(\"unable to locate repository; .git file is not for a linked worktree\"),\n+\t\t   cb_data);\n+\t\tgoto done;\n+\t}\n \n \t/*\n \t * If we got this far, either the worktree's .git file pointed at a\n@@ -905,7 +917,7 @@ void repair_worktree_at_path(struct repository *repo,\n \t * in the *original* repository, not in the \"copy\" repository).\n \t * Therefore, we prioritize inferred_backlink over backlink.\n \t */\n-\tif (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))\n+\tif (fspathcmp(backlink.buf, inferred_backlink.buf))\n \t\tstrbuf_swap(&backlink, &inferred_backlink);\n \n \tstrbuf_addf(&gitdir, \"%s/gitdir\", backlink.buf);\n-- \ngitgitgadget\n\n"},{"id":"555085","messageId":"xmqqmrsfq4rm.fsf@gitster.g","threadId":"66320","inReplyTo":"pull.2225.v2.git.1792012836.gitgitgadget@gmail.com","subject":"Re: [PATCH v2 0/5] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2026-10-14T22:46:53Z","receivedAt":"2026-10-14T22:46:53Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"\"Yoichi NAKAYAMA via GitGitGadget\" <gitgitgadget@gmail.com> writes:\n\n> 'git worktree repair' does not sufficiently validate the cross-references\n> between a linked working tree and its administrative data before repairing\n> them. This can cause the repair to modify the wrong .git file or gitdir in\n> certain situations.\n>\n>\n> v2 (0156021)\n> ============\n>\n> Split the first commit of v1 to make the changes easier to understand. Fold\n> long lines.\n>\n>  * [1/5] align .git file handling with repair_gitfile()\n>  * [2/5] centralize inferred backlink selection\n>  * [3/5] use read_gitfile_raw() in infer_backlink()\n>  * [4/5] reduce .git file reads\n>  * [5/5] avoid breaking unrelated .git file and gitdir\n\nMakes more sense to have this series as a logical progression of\nsmaller pieces compared to v1.\n\nWhat is \"0156021\" by the way?\n\nThanks.\n\n>  t/t2406-worktree-repair.sh |  33 +++++++++--\n>  worktree.c                 | 113 +++++++++++++++++++++----------------\n>  2 files changed, 91 insertions(+), 55 deletions(-)\n\n\n"},{"id":"555145","messageId":"CAF5D8-uzTe2qm8MdoADkSunrKhc_qSLzjBG9CGR5tDAS32Xh5A@mail.gmail.com","threadId":"66320","inReplyTo":"xmqqmrsfq4rm.fsf@gitster.g","subject":"Re: [PATCH v2 0/5] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA","fromEmail":"yoichi.nakayama@gmail.com","sentAt":"2026-10-15T13:41:02Z","receivedAt":"2026-10-15T13:41:02Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"Sorry, I sent the previous email in HTML. I'm resending it as plain text.\n\nOn Thu, Oct 15, 2026 at 7:46 AM Junio C Hamano <gitster@pobox.com> wrote:\n>\n> \"Yoichi NAKAYAMA via GitGitGadget\" <gitgitgadget@gmail.com> writes:\n>\n> > 'git worktree repair' does not sufficiently validate the cross-references\n> > between a linked working tree and its administrative data before repairing\n> > them. This can cause the repair to modify the wrong .git file or gitdir in\n> > certain situations.\n> >\n> >\n> > v2 (0156021)\n> > ============\n> >\n> > Split the first commit of v1 to make the changes easier to understand. Fold\n> > long lines.\n> >\n> >  * [1/5] align .git file handling with repair_gitfile()\n> >  * [2/5] centralize inferred backlink selection\n> >  * [3/5] use read_gitfile_raw() in infer_backlink()\n> >  * [4/5] reduce .git file reads\n> >  * [5/5] avoid breaking unrelated .git file and gitdir\n>\n> Makes more sense to have this series as a logical progression of\n> smaller pieces compared to v1.\n>\n> What is \"0156021\" by the way?\n\nIt is the first 7 characters of the commit hash\nin https://github.com/gitgitgadget/git/\n(Creating a commit from an email changes the\ncommit hash, so the identifier was meaningless.)\n\nThanks,\n--\nYoichi NAKAYAMA\n\n"},{"id":"555178","messageId":"xmqq8q3yon7p.fsf@gitster.g","threadId":"66320","inReplyTo":"015602168c8532c07b94c9f50925bf5d5a2ef7c8.1792012836.git.gitgitgadget@gmail.com","subject":"Re: [PATCH v2 5/5] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2026-10-15T18:03:38Z","receivedAt":"2026-10-15T18:03:38Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"\"Yoichi NAKAYAMA via GitGitGadget\" <gitgitgadget@gmail.com> writes:\n\n> diff --git a/worktree.c b/worktree.c\n> index 879941a977..86094307b1 100644\n> --- a/worktree.c\n> +++ b/worktree.c\n> @@ -640,7 +640,11 @@ int other_head_refs(struct repository *repo,\n>  static const char *get_worktree_id(const char *dotgit_contents)\n>  {\n>  \tconst char *slash = find_last_dir_sep(dotgit_contents);\n> -\tif (!slash)\n> +\tconst char *prefix = \"/worktrees\";\n> +\tint prefixlen = strlen(prefix);\n> +\tif (!slash ||\n> +\t    slash - dotgit_contents < prefixlen ||\n> +\t    strncmp(slash - prefixlen, prefix, prefixlen))\n>  \t\treturn \"\";\n>  \treturn slash + 1;\n\nJust being curious, but slash is found by scanning dotgit_contents\nfor either '/' or '\\'.  We make sure what comes before the slash\nis \"/worktree\".\n\nCould there be situations where this code needs to accept \n\n\t\"...\\worktrees\\my-worktree\"\n\nwhere slash points at the backslash before \"my-worktree\"?  Because\nsomebody wrote the pathname with backslash before the worktree name,\nit would be natural to expect another backslash before the \"worktrees\"\nconstant, no?  For that matter, would this code need to also accept\n\n\t\".../worktrees//my-worktree\"\n\nwhere three are extra/duplicated slashes (or backslashes)?  The\nnormal code paths to create these directories and records the path\nto these directories should hopefully be using the canonical '/'\nwithout unnecessary duplicate slashes, but (1) existing use of\nfind_last_dir_sep() might be a sign that we may have to deal with\nbackslashes, and (2) since this is about reparing a broken set-up,\nit does not seem too far-fetched to attempt dealing with the above\ntwo sample input, hence this question.\n\nThanks.\n\n"},{"id":"555294","messageId":"CAF5D8-tTmruFLpCY4WpCkMU+3ng9pHp22MrTcUrKbXfWmhzoow@mail.gmail.com","threadId":"66320","inReplyTo":"xmqq8q3yon7p.fsf@gitster.g","subject":"Re: [PATCH v2 5/5] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA","fromEmail":"yoichi.nakayama@gmail.com","sentAt":"2026-10-17T02:40:03Z","receivedAt":"2026-10-17T02:40:03Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"On Fri, Oct 16, 2026 at 3:03 AM Junio C Hamano <gitster@pobox.com> wrote:\n>\n> \"Yoichi NAKAYAMA via GitGitGadget\" <gitgitgadget@gmail.com> writes:\n>\n> > diff --git a/worktree.c b/worktree.c\n> > index 879941a977..86094307b1 100644\n> > --- a/worktree.c\n> > +++ b/worktree.c\n> > @@ -640,7 +640,11 @@ int other_head_refs(struct repository *repo,\n> >  static const char *get_worktree_id(const char *dotgit_contents)\n> >  {\n> >       const char *slash = find_last_dir_sep(dotgit_contents);\n> > -     if (!slash)\n> > +     const char *prefix = \"/worktrees\";\n> > +     int prefixlen = strlen(prefix);\n> > +     if (!slash ||\n> > +         slash - dotgit_contents < prefixlen ||\n> > +         strncmp(slash - prefixlen, prefix, prefixlen))\n> >               return \"\";\n> >       return slash + 1;\n>\n> Just being curious, but slash is found by scanning dotgit_contents\n> for either '/' or '\\'.  We make sure what comes before the slash\n> is \"/worktree\".\n>\n> Could there be situations where this code needs to accept\n>\n>         \"...\\worktrees\\my-worktree\"\n>\n> where slash points at the backslash before \"my-worktree\"?  Because\n> somebody wrote the pathname with backslash before the worktree name,\n> it would be natural to expect another backslash before the \"worktrees\"\n> constant, no?  For that matter, would this code need to also accept\n>\n>         \".../worktrees//my-worktree\"\n>\n> where three are extra/duplicated slashes (or backslashes)?  The\n> normal code paths to create these directories and records the path\n> to these directories should hopefully be using the canonical '/'\n> without unnecessary duplicate slashes, but (1) existing use of\n> find_last_dir_sep() might be a sign that we may have to deal with\n> backslashes, and (2) since this is about reparing a broken set-up,\n> it does not seem too far-fetched to attempt dealing with the above\n> two sample input, hence this question.\n\nWhile Git doesn't create a .git file with backslash separators,\nit can find the repository from such .git file on Windows.\nSo I think 'worktree repair' should handle it.\n\nI will also add handling for duplicated separators.\n\nThanks,\n-- \nYoichi NAKAYAMA\n\n"},{"id":"555320","messageId":"pull.2225.v3.git.1792241702.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.git.1789269613.gitgitgadget@gmail.com","subject":"[PATCH v3 0/5] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-17T12:54:57Z","receivedAt":"2026-10-17T12:54:57Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"'git worktree repair' does not sufficiently validate the cross-references\nbetween a linked working tree and its administrative data before repairing\nthem. This can cause the repair to modify the wrong .git file or gitdir in\ncertain situations.\n\n\nv3\n==\n\nMake the separator check in get_worktree_id() more lenient.\n\n * [1/5] align .git file handling with repair_gitfile()\n * [2/5] centralize inferred backlink selection\n * [3/5] use read_gitfile_raw() in infer_backlink()\n * [4/5] reduce .git file reads\n * [5/5] avoid breaking unrelated .git file and gitdir\n\n\nv2\n==\n\nSplit the first commit of v1 to make the changes easier to understand. Fold\nlong lines.\n\n * [1/5] align .git file handling with repair_gitfile()\n * [2/5] centralize inferred backlink selection\n * [3/5] use read_gitfile_raw() in infer_backlink()\n * [4/5] reduce .git file reads\n * [5/5] avoid breaking unrelated .git file and gitdir\n\n\nv1\n==\n\nThis series first refactors the code to read the .git file once and extract\nthe worktree ID, then uses that information to validate the repair target\nbefore modifying the cross-references.\n\n * [1/2] Refactor the code without changing functionality before making the\n   fix\n * [2/2] Validate the worktree ID and inferred gitdir path before repairing\n\nYoichi NAKAYAMA (5):\n  worktree repair: align .git file handling with repair_gitfile()\n  worktree repair: centralize inferred backlink selection\n  worktree repair: use read_gitfile_raw() in infer_backlink()\n  worktree repair: reduce .git file reads\n  worktree repair: avoid breaking unrelated .git file and gitdir\n\n t/t2406-worktree-repair.sh |  57 ++++++++++++--\n worktree.c                 | 153 ++++++++++++++++++++++++-------------\n 2 files changed, 152 insertions(+), 58 deletions(-)\n\n\nbase-commit: c51408889c3b372814bc20b9431c3b74d0d268eb\nPublished-As: https://github.com/gitgitgadget/git/releases/tag/pr-2225%2Fyoichi%2Fworktree-repair-keep-unrelated-gitfile-v3\nFetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2225/yoichi/worktree-repair-keep-unrelated-gitfile-v3\nPull-Request: https://github.com/gitgitgadget/git/pull/2225\n\nRange-diff vs v2:\n\n 1:  21b2878aa5 = 1:  e336afa029 worktree repair: align .git file handling with repair_gitfile()\n 2:  30ac7acad3 = 2:  86021f31af worktree repair: centralize inferred backlink selection\n 3:  2cc7b817ee = 3:  7087e829bb worktree repair: use read_gitfile_raw() in infer_backlink()\n 4:  8c80b9ae05 = 4:  e35285a4ea worktree repair: reduce .git file reads\n 5:  015602168c ! 5:  f1d5c7b5f7 worktree repair: avoid breaking unrelated .git file and gitdir\n     @@ t/t2406-worktree-repair.sh: test_expect_success 'repair .git file from bare.git'\n      +\ttest_cmp expect corrupt/.git &&\n      +\ttest_grep \"unrelated .git file\" err\n      +'\n     ++\n     ++test_expect_success 'repair moved worktree whose .git file has extra separators' '\n     ++\ttest_when_finished \"rm -rf side sidemoved && git worktree prune\" &&\n     ++\tgit worktree add --detach side &&\n     ++\tmv side sidemoved &&\n     ++\tcat sidemoved/.git >expect &&\n     ++\tsed s,/,//,g sidemoved/.git | sed s,$,//, >sidemoved/.newgit &&\n     ++\tmv sidemoved/.newgit sidemoved/.git &&\n     ++\tgit worktree repair sidemoved 2>err &&\n     ++\ttest_cmp expect sidemoved/.git &&\n     ++\ttest_grep \"gitdir incorrect\" err\n     ++'\n     ++\n     ++test_expect_success WINDOWS 'repair moved worktree whose .git file uses backslash' '\n     ++\ttest_when_finished \"rm -rf side sidemoved && git worktree prune\" &&\n     ++\tgit worktree add --detach side &&\n     ++\tmv side sidemoved &&\n     ++\tcat sidemoved/.git >expect &&\n     ++\tsed s,\\/,\\\\\\\\,g sidemoved/.git >sidemoved/.newgit &&\n     ++\tmv sidemoved/.newgit sidemoved/.git &&\n     ++\tgit worktree repair sidemoved 2>err &&\n     ++\ttest_cmp expect sidemoved/.git &&\n     ++\ttest_grep \"gitdir incorrect\" err\n     ++'\n      +\n       test_expect_success 'invalid worktree path' '\n       \ttest_must_fail git worktree repair /notvalid >out 2>err &&\n     @@ t/t2406-worktree-repair.sh: test_expect_success 'repo not found; .git not refere\n      \n       ## worktree.c ##\n      @@ worktree.c: int other_head_refs(struct repository *repo,\n     - static const char *get_worktree_id(const char *dotgit_contents)\n     + \treturn ret;\n     + }\n     + \n     +-static const char *get_worktree_id(const char *dotgit_contents)\n     ++static int get_worktree_id(struct strbuf *worktree_id,\n     ++\t\t\t   const char *dotgit_contents)\n       {\n     - \tconst char *slash = find_last_dir_sep(dotgit_contents);\n     +-\tconst char *slash = find_last_dir_sep(dotgit_contents);\n      -\tif (!slash)\n     -+\tconst char *prefix = \"/worktrees\";\n     +-\t\treturn \"\";\n     +-\treturn slash + 1;\n     ++\tconst char *id_end;\n     ++\tconst char *id;\n     ++\tconst char *prefix_end;\n     ++\tconst char *prefix = \"worktrees\";\n      +\tint prefixlen = strlen(prefix);\n     -+\tif (!slash ||\n     -+\t    slash - dotgit_contents < prefixlen ||\n     -+\t    strncmp(slash - prefixlen, prefix, prefixlen))\n     - \t\treturn \"\";\n     - \treturn slash + 1;\n     ++\n     ++\tid_end = dotgit_contents + strlen(dotgit_contents);\n     ++\n     ++\t/* skip trailing separators */\n     ++\twhile (dotgit_contents < id_end && is_dir_sep(*(id_end - 1)))\n     ++\t\tid_end--;\n     ++\tif (id_end == dotgit_contents)\n     ++\t\treturn 1;\n     ++\n     ++\tid = id_end;\n     ++\n     ++\t/* find the last separator */\n     ++\twhile (dotgit_contents < id && !is_dir_sep(*(id - 1)))\n     ++\t\tid--;\n     ++\tif (id == dotgit_contents || id == id_end)\n     ++\t\treturn 1;\n     ++\n     ++\tprefix_end = id - 1;\n     ++\n     ++\t/* skip repeated separators */\n     ++\twhile (dotgit_contents < prefix_end && is_dir_sep(*(prefix_end - 1)))\n     ++\t\tprefix_end--;\n     ++\n     ++\t/* check for \"/worktrees\" */\n     ++\tif (prefix_end - dotgit_contents < prefixlen + 1 ||\n     ++\t    strncmp(prefix_end - prefixlen, prefix, prefixlen) ||\n     ++\t    !is_dir_sep(*(prefix_end - prefixlen - 1)))\n     ++\t\treturn 1;\n     ++\n     ++\tstrbuf_add(worktree_id, id, id_end - id);\n     ++\treturn 0;\n       }\n     + \n     + /*\n     +@@ worktree.c: static void repair_gitfile(struct worktree *wt,\n     + \tstruct strbuf repo = STRBUF_INIT;\n     + \tstruct strbuf backlink = STRBUF_INIT;\n     + \tstruct strbuf contents = STRBUF_INIT;\n     ++\tstruct strbuf worktree_id = STRBUF_INIT;\n     + \tconst char *dotgit_contents = NULL;\n     + \tconst char *repair = NULL;\n     + \tchar *path = NULL;\n      @@ worktree.c: static void repair_gitfile(struct worktree *wt,\n       \tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n       \t\terr == READ_GITFILE_ERR_IS_A_DIR)\n     @@ worktree.c: static void repair_gitfile(struct worktree *wt,\n      -\telse if (err || !is_git_directory(backlink.buf))\n      +\telse if (err)\n       \t\trepair = _(\".git file broken\");\n     -+\telse if (strcmp(get_worktree_id(dotgit_contents), wt->id))\n     ++\telse if (get_worktree_id(&worktree_id, dotgit_contents) ||\n     ++\t\t strcmp(worktree_id.buf, wt->id))\n      +\t\tfn(1, wt->path, _(\"unrelated .git file\"), cb_data);\n       \telse if (fspathcmp(backlink.buf, repo.buf))\n       \t\trepair = _(\".git file incorrect\");\n       \telse if (use_relative_paths == is_absolute_path(dotgit_contents))\n     +@@ worktree.c: done:\n     + \tstrbuf_release(&gitdir);\n     + \tstrbuf_release(&backlink);\n     + \tstrbuf_release(&contents);\n     ++\tstrbuf_release(&worktree_id);\n     + }\n     + \n     + static void repair_noop(int iserr UNUSED,\n      @@ worktree.c: static ssize_t infer_backlink(struct repository *repo,\n     - \tif (!*id)\n     + \t\t\t      const char *dotgit_contents,\n     + \t\t\t      struct strbuf *inferred)\n     + {\n     +-\tconst char *id;\n     ++\tstruct strbuf worktree_id = STRBUF_INIT;\n     + \n     +-\tid = get_worktree_id(dotgit_contents);\n     +-\tif (!*id)\n     ++\tif (get_worktree_id(&worktree_id, dotgit_contents))\n       \t\tgoto error;\n     - \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n     +-\trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n      -\tif (!is_directory(inferred->buf))\n     ++\trepo_common_path_replace(repo, inferred,\n     ++\t\t\t\t \"worktrees/%s\", worktree_id.buf);\n      +\tif (!is_git_directory(inferred->buf))\n       \t\tgoto error;\n       \n     ++\tstrbuf_release(&worktree_id);\n       \treturn inferred->len;\n     + error:\n     + \tstrbuf_reset(inferred); /* clear invalid path */\n     ++\tstrbuf_release(&worktree_id);\n     + \treturn -1;\n     + }\n     + \n      @@ worktree.c: void repair_worktree_at_path(struct repository *repo,\n       \t\t   cb_data);\n       \t\tgoto done;\n\n-- \ngitgitgadget\n\n"},{"id":"555321","messageId":"e336afa0296abd3e7e7e0e99b4e6b1b33649e274.1792241702.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v3.git.1792241702.gitgitgadget@gmail.com","subject":"[PATCH v3 1/5] worktree repair: align .git file handling with repair_gitfile()","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-17T12:54:58Z","receivedAt":"2026-10-17T12:54:58Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nUse read_gitfile_raw() instead of read_gitfile_gently() in\nrepair_worktree_at_path(), moving path resolution and repository\nvalidation to the caller. This makes .git file handling consistent\nwith repair_gitfile() and avoids using the non-reentrant\nread_gitfile_gently().\n\nA subsequent commit will update infer_backlink() to use\nread_gitfile_raw() as well.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 40 ++++++++++++++++++++++++++++------------\n 1 file changed, 28 insertions(+), 12 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex 8cb8637b18..4492ca835d 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -840,7 +840,7 @@ void repair_worktree_at_path(struct repository *repo,\n \tstruct strbuf inferred_backlink = STRBUF_INIT;\n \tstruct strbuf gitdir = STRBUF_INIT;\n \tstruct strbuf olddotgit = STRBUF_INIT;\n-\tchar *dotgit_contents = NULL;\n+\tstruct strbuf contents = STRBUF_INIT;\n \tconst char *repair = NULL;\n \tint err;\n \n@@ -858,14 +858,26 @@ void repair_worktree_at_path(struct repository *repo,\n \n \tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n \tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n-\tdotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));\n-\tif (dotgit_contents) {\n-\t\tstrbuf_addstr(&backlink, dotgit_contents);\n-\t} else if (err == READ_GITFILE_ERR_NOT_A_FILE ||\n-\t\t\terr == READ_GITFILE_ERR_IS_A_DIR) {\n-\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git is not a file\"), cb_data);\n+\terr = read_gitfile_raw(&contents, dotgit.buf);\n+\tif (!err) {\n+\t\tconst char *dotgit_contents = contents.buf;\n+\t\tif (is_absolute_path(dotgit_contents)) {\n+\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t\t} else {\n+\t\t\tstrbuf_addbuf(&backlink, &dotgit);\n+\t\t\tstrbuf_strip_suffix(&backlink, \".git\");\n+\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n+\t\t}\n+\t}\n+\tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n+\t    err == READ_GITFILE_ERR_IS_A_DIR) {\n+\t\tfn(1, dotgit.buf,\n+\t\t   _(\"unable to locate repository; .git is not a file\"),\n+\t\t   cb_data);\n \t\tgoto done;\n-\t} else if (err == READ_GITFILE_ERR_NOT_A_REPO) {\n+\t} else if (!err && !is_git_directory(backlink.buf)) {\n+\t\tstrbuf_release(&backlink);\n \t\tif (inferred_backlink.len) {\n \t\t\t/*\n \t\t\t * Worktree's .git file does not point at a repository\n@@ -876,11 +888,15 @@ void repair_worktree_at_path(struct repository *repo,\n \t\t\t */\n \t\t\tstrbuf_swap(&backlink, &inferred_backlink);\n \t\t} else {\n-\t\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file does not reference a repository\"), cb_data);\n+\t\t\tfn(1, dotgit.buf,\n+\t\t\t   _(\"unable to locate repository; .git file does not reference a repository\"),\n+\t\t\t   cb_data);\n \t\t\tgoto done;\n \t\t}\n-\t} else {\n-\t\tfn(1, dotgit.buf, _(\"unable to locate repository; .git file broken\"), cb_data);\n+\t} else if (err) {\n+\t\tfn(1, dotgit.buf,\n+\t\t   _(\"unable to locate repository; .git file broken\"),\n+\t\t   cb_data);\n \t\tgoto done;\n \t}\n \n@@ -926,12 +942,12 @@ void repair_worktree_at_path(struct repository *repo,\n \t\t\t\t\t     gitdir.buf, use_relative_paths);\n \t}\n done:\n-\tfree(dotgit_contents);\n \tstrbuf_release(&olddotgit);\n \tstrbuf_release(&backlink);\n \tstrbuf_release(&inferred_backlink);\n \tstrbuf_release(&gitdir);\n \tstrbuf_release(&dotgit);\n+\tstrbuf_release(&contents);\n }\n \n int should_prune_worktree(struct repository *repo,\n-- \ngitgitgadget\n\n\n"},{"id":"555322","messageId":"86021f31af4985d9c2a42e2b96031605652837bf.1792241702.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v3.git.1792241702.gitgitgadget@gmail.com","subject":"[PATCH v3 2/5] worktree repair: centralize inferred backlink selection","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-17T12:54:59Z","receivedAt":"2026-10-17T12:54:59Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nReorder the processing steps to centralize the logic for preferring\nthe inferred_backlink.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 69 +++++++++++++++++++++++-------------------------------\n 1 file changed, 29 insertions(+), 40 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex 4492ca835d..f8e9850f6f 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -841,6 +841,7 @@ void repair_worktree_at_path(struct repository *repo,\n \tstruct strbuf gitdir = STRBUF_INIT;\n \tstruct strbuf olddotgit = STRBUF_INIT;\n \tstruct strbuf contents = STRBUF_INIT;\n+\tconst char *dotgit_contents = NULL;\n \tconst char *repair = NULL;\n \tint err;\n \n@@ -856,43 +857,13 @@ void repair_worktree_at_path(struct repository *repo,\n \t\tgoto done;\n \t}\n \n-\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n-\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n \terr = read_gitfile_raw(&contents, dotgit.buf);\n-\tif (!err) {\n-\t\tconst char *dotgit_contents = contents.buf;\n-\t\tif (is_absolute_path(dotgit_contents)) {\n-\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n-\t\t} else {\n-\t\t\tstrbuf_addbuf(&backlink, &dotgit);\n-\t\t\tstrbuf_strip_suffix(&backlink, \".git\");\n-\t\t\tstrbuf_addstr(&backlink, dotgit_contents);\n-\t\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n-\t\t}\n-\t}\n \tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n \t    err == READ_GITFILE_ERR_IS_A_DIR) {\n \t\tfn(1, dotgit.buf,\n \t\t   _(\"unable to locate repository; .git is not a file\"),\n \t\t   cb_data);\n \t\tgoto done;\n-\t} else if (!err && !is_git_directory(backlink.buf)) {\n-\t\tstrbuf_release(&backlink);\n-\t\tif (inferred_backlink.len) {\n-\t\t\t/*\n-\t\t\t * Worktree's .git file does not point at a repository\n-\t\t\t * but we found a .git/worktrees/<id> in this\n-\t\t\t * repository with the same <id> as recorded in the\n-\t\t\t * worktree's .git file so make the worktree point at\n-\t\t\t * the discovered .git/worktrees/<id>.\n-\t\t\t */\n-\t\t\tstrbuf_swap(&backlink, &inferred_backlink);\n-\t\t} else {\n-\t\t\tfn(1, dotgit.buf,\n-\t\t\t   _(\"unable to locate repository; .git file does not reference a repository\"),\n-\t\t\t   cb_data);\n-\t\t\tgoto done;\n-\t\t}\n \t} else if (err) {\n \t\tfn(1, dotgit.buf,\n \t\t   _(\"unable to locate repository; .git file broken\"),\n@@ -900,23 +871,41 @@ void repair_worktree_at_path(struct repository *repo,\n \t\tgoto done;\n \t}\n \n+\tdotgit_contents = contents.buf;\n+\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n+\tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n+\n+\tif (is_absolute_path(dotgit_contents)) {\n+\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t} else {\n+\t\tstrbuf_addbuf(&backlink, &dotgit);\n+\t\tstrbuf_strip_suffix(&backlink, \".git\");\n+\t\tstrbuf_addstr(&backlink, dotgit_contents);\n+\t\tstrbuf_realpath_forgiving(&backlink, backlink.buf, 0);\n+\t}\n+\n+\tif (!is_git_directory(backlink.buf) && !inferred_backlink.len) {\n+\t\tfn(1, dotgit.buf,\n+\t\t   _(\"unable to locate repository; .git file does not reference a repository\"),\n+\t\t   cb_data);\n+\t\tgoto done;\n+\t}\n+\n \t/*\n \t * If we got this far, either the worktree's .git file pointed at a\n-\t * valid repository (i.e. read_gitfile_gently() returned success) or\n+\t * valid repository (i.e. is_git_directory() returned true) or\n \t * the .git file did not point at a repository but we were able to\n \t * infer a suitable new value for the .git file by locating a\n \t * .git/worktrees/<id> in *this* repository corresponding to the <id>\n \t * recorded in the worktree's .git file.\n \t *\n-\t * However, if, at this point, inferred_backlink is non-NULL (i.e. we\n-\t * found a suitable .git/worktrees/<id> in *this* repository) *and* the\n-\t * worktree's .git file points at a valid repository *and* those two\n-\t * paths differ, then that indicates that the user probably *copied*\n-\t * the main and linked worktrees to a new location as a unit rather\n-\t * than *moving* them. Thus, the copied worktree's .git file actually\n-\t * points at the .git/worktrees/<id> in the *original* repository, not\n-\t * in the \"copy\" repository. In this case, point the \"copy\" worktree's\n-\t * .git file at the \"copy\" repository.\n+\t * Even if the worktree's .git file pointed at a valid repository,\n+\t * it doesn't always mean that the backlink is correct. For example,\n+\t * the user might have *copied* the main and linked worktrees to a\n+\t * new location as a unit rather than *moving* them (the copied\n+\t * worktree's .git file actually points at the .git/worktrees/<id>\n+\t * in the *original* repository, not in the \"copy\" repository).\n+\t * Therefore, we prioritize inferred_backlink over backlink.\n \t */\n \tif (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))\n \t\tstrbuf_swap(&backlink, &inferred_backlink);\n-- \ngitgitgadget\n\n\n"},{"id":"555323","messageId":"7087e829bbfafe22b665364d8ee56526fd12e783.1792241702.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v3.git.1792241702.gitgitgadget@gmail.com","subject":"[PATCH v3 3/5] worktree repair: use read_gitfile_raw() in infer_backlink()","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-17T12:55:00Z","receivedAt":"2026-10-17T12:55:00Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nUse read_gitfile_raw() in infer_backlink() to parse .git files\nconsistently with repair_gitfile(). Unlike strbuf_trim(),\nread_gitfile_raw() does not silently discard trailing whitespace. Such\nwhitespace is treated as part of the path and may cause the path to be\ntreated as not referencing a repository.\n\nExtract get_worktree_id() for use in a subsequent commit.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 25 +++++++++++++++----------\n 1 file changed, 15 insertions(+), 10 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex f8e9850f6f..3627dbc044 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -637,6 +637,14 @@ int other_head_refs(struct repository *repo,\n \treturn ret;\n }\n \n+static const char *get_worktree_id(const char *dotgit_contents)\n+{\n+\tconst char *slash = find_last_dir_sep(dotgit_contents);\n+\tif (!slash)\n+\t\treturn \"\";\n+\treturn slash + 1;\n+}\n+\n /*\n  * Repair worktree's /path/to/worktree/.git file if missing, corrupt, or not\n  * pointing at <repo>/worktrees/<id>.\n@@ -801,27 +809,24 @@ static ssize_t infer_backlink(struct repository *repo,\n \t\t\t      const char *gitfile,\n \t\t\t      struct strbuf *inferred)\n {\n-\tstruct strbuf actual = STRBUF_INIT;\n+\tstruct strbuf contents = STRBUF_INIT;\n \tconst char *id;\n+\tint err;\n \n-\tif (strbuf_read_file(&actual, gitfile, 0) < 0)\n+\terr = read_gitfile_raw(&contents, gitfile);\n+\tif (err)\n \t\tgoto error;\n-\tif (!starts_with(actual.buf, \"gitdir:\"))\n-\t\tgoto error;\n-\tif (!(id = find_last_dir_sep(actual.buf)))\n-\t\tgoto error;\n-\tstrbuf_trim(&actual);\n-\tid++; /* advance past '/' to point at <id> */\n+\tid = get_worktree_id(contents.buf);\n \tif (!*id)\n \t\tgoto error;\n \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n \tif (!is_directory(inferred->buf))\n \t\tgoto error;\n \n-\tstrbuf_release(&actual);\n+\tstrbuf_release(&contents);\n \treturn inferred->len;\n error:\n-\tstrbuf_release(&actual);\n+\tstrbuf_release(&contents);\n \tstrbuf_reset(inferred); /* clear invalid path */\n \treturn -1;\n }\n-- \ngitgitgadget\n\n\n"},{"id":"555324","messageId":"e35285a4ea5a5f7b11cd112df841948e9a0a3ab9.1792241702.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v3.git.1792241702.gitgitgadget@gmail.com","subject":"[PATCH v3 4/5] worktree repair: reduce .git file reads","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-17T12:55:01Z","receivedAt":"2026-10-17T12:55:01Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nPass the loaded contents of the .git file to infer_backlink().\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n worktree.c | 13 +++----------\n 1 file changed, 3 insertions(+), 10 deletions(-)\n\ndiff --git a/worktree.c b/worktree.c\nindex 3627dbc044..879941a977 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -806,27 +806,20 @@ static int is_main_worktree_path(struct repository *repo, const char *path)\n  * Returns -1 on failure and strbuf.len on success.\n  */\n static ssize_t infer_backlink(struct repository *repo,\n-\t\t\t      const char *gitfile,\n+\t\t\t      const char *dotgit_contents,\n \t\t\t      struct strbuf *inferred)\n {\n-\tstruct strbuf contents = STRBUF_INIT;\n \tconst char *id;\n-\tint err;\n \n-\terr = read_gitfile_raw(&contents, gitfile);\n-\tif (err)\n-\t\tgoto error;\n-\tid = get_worktree_id(contents.buf);\n+\tid = get_worktree_id(dotgit_contents);\n \tif (!*id)\n \t\tgoto error;\n \trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n \tif (!is_directory(inferred->buf))\n \t\tgoto error;\n \n-\tstrbuf_release(&contents);\n \treturn inferred->len;\n error:\n-\tstrbuf_release(&contents);\n \tstrbuf_reset(inferred); /* clear invalid path */\n \treturn -1;\n }\n@@ -877,7 +870,7 @@ void repair_worktree_at_path(struct repository *repo,\n \t}\n \n \tdotgit_contents = contents.buf;\n-\tinfer_backlink(repo, dotgit.buf, &inferred_backlink);\n+\tinfer_backlink(repo, dotgit_contents, &inferred_backlink);\n \tstrbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);\n \n \tif (is_absolute_path(dotgit_contents)) {\n-- \ngitgitgadget\n\n\n"},{"id":"555325","messageId":"f1d5c7b5f76b8f7bcdb34b38410f15bcc9178290.1792241702.git.gitgitgadget@gmail.com","threadId":"66320","inReplyTo":"pull.2225.v3.git.1792241702.gitgitgadget@gmail.com","subject":"[PATCH v3 5/5] worktree repair: avoid breaking unrelated .git file and gitdir","fromName":"Yoichi NAKAYAMA via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-17T12:55:02Z","receivedAt":"2026-10-17T12:55:02Z","isPatch":true,"sender":{"key":"yoichi.nakayama@gmail.com","avatar":"https://avatars.githubusercontent.com/u/107537?v=4"},"body":"From: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n\nCurrently, `repair_gitfile()` does not verify whether the worktree ID\nrecorded in the .git file matches the worktree being repaired, which\ncan result in an unrelated .git file being corrupted. For instance,\nif two worktree directories are swapped without using 'git worktree\nmove', running 'git worktree repair' in the main worktree accidentally\nswaps the links between their .git files and gitdirs.\n\n`repair_worktree_at_path()` proceeds even if it fails to infer the\ngitdir path. This can result in the corruption of an unrelated\ngitdir. For instance, if we copied a linked worktree to a new location\nX, running 'git worktree repair X' in a working tree which does not\nbelong to the original repository can accidentally overwrite the\ngitdir in the original repository (the scope of impact should be\nlimited to the repository where the command was executed).\n\nResolve these issues by validating the worktree ID and stopping the\nrepair when the ID does not match or the gitdir path cannot be\ninferred.\n\nSigned-off-by: Yoichi NAKAYAMA <yoichi.nakayama@gmail.com>\n---\n t/t2406-worktree-repair.sh | 57 +++++++++++++++++++++++++++----\n worktree.c                 | 70 +++++++++++++++++++++++++++++++-------\n 2 files changed, 109 insertions(+), 18 deletions(-)\n\ndiff --git a/t/t2406-worktree-repair.sh b/t/t2406-worktree-repair.sh\nindex d4e53d492b..fa26565d0a 100755\n--- a/t/t2406-worktree-repair.sh\n+++ b/t/t2406-worktree-repair.sh\n@@ -56,15 +56,12 @@ test_expect_success 'repair missing .git file' '\n '\n \n test_expect_success 'repair bogus .git file' '\n-\ttest_corrupt_gitfile \"echo \\\"gitdir: /nowhere\\\" >corrupt/.git\" \\\n+\ttest_corrupt_gitfile \"echo \\\"contents not started with gitdir:\\\" >corrupt/.git\" \\\n \t\t\".git file broken\"\n '\n \n-test_expect_success 'repair incorrect .git file' '\n-\ttest_when_finished \"rm -rf other && git worktree prune\" &&\n-\ttest_create_repo other &&\n-\tother=$(git -C other rev-parse --absolute-git-dir) &&\n-\ttest_corrupt_gitfile \"echo \\\"gitdir: $other\\\" >corrupt/.git\" \\\n+test_expect_success 'repair unlinked .git file' '\n+\ttest_corrupt_gitfile \"echo \\\"gitdir: /nowhere/worktrees/corrupt\\\" >corrupt/.git\" \\\n \t\t\".git file incorrect\"\n '\n \n@@ -89,6 +86,42 @@ test_expect_success 'repair .git file from bare.git' '\n \ttest_cmp expect actual\n '\n \n+test_expect_success 'skip unrelated .git file' '\n+\ttest_when_finished \"rm -rf corrupt other && git worktree prune\" &&\n+\tgit worktree add --detach corrupt &&\n+\trm -rf corrupt &&\n+\tgit worktree add --detach other &&\n+\tmv other corrupt &&\n+\tcat corrupt/.git >expect &&\n+\ttest_must_fail git worktree repair 2>err &&\n+\ttest_cmp expect corrupt/.git &&\n+\ttest_grep \"unrelated .git file\" err\n+'\n+\n+test_expect_success 'repair moved worktree whose .git file has extra separators' '\n+\ttest_when_finished \"rm -rf side sidemoved && git worktree prune\" &&\n+\tgit worktree add --detach side &&\n+\tmv side sidemoved &&\n+\tcat sidemoved/.git >expect &&\n+\tsed s,/,//,g sidemoved/.git | sed s,$,//, >sidemoved/.newgit &&\n+\tmv sidemoved/.newgit sidemoved/.git &&\n+\tgit worktree repair sidemoved 2>err &&\n+\ttest_cmp expect sidemoved/.git &&\n+\ttest_grep \"gitdir incorrect\" err\n+'\n+\n+test_expect_success WINDOWS 'repair moved worktree whose .git file uses backslash' '\n+\ttest_when_finished \"rm -rf side sidemoved && git worktree prune\" &&\n+\tgit worktree add --detach side &&\n+\tmv side sidemoved &&\n+\tcat sidemoved/.git >expect &&\n+\tsed s,\\/,\\\\\\\\,g sidemoved/.git >sidemoved/.newgit &&\n+\tmv sidemoved/.newgit sidemoved/.git &&\n+\tgit worktree repair sidemoved 2>err &&\n+\ttest_cmp expect sidemoved/.git &&\n+\ttest_grep \"gitdir incorrect\" err\n+'\n+\n test_expect_success 'invalid worktree path' '\n \ttest_must_fail git worktree repair /notvalid >out 2>err &&\n \ttest_must_be_empty out &&\n@@ -113,6 +146,18 @@ test_expect_success 'repo not found; .git not referencing repo' '\n \ttest_grep \".git file does not reference a repository\" err\n '\n \n+test_expect_success 'repo not found; .git not for worktree' '\n+\ttest_when_finished \"rm -rf side other-repo && git worktree prune\" &&\n+\ttest_create_repo other-repo &&\n+\tgit worktree add --detach side &&\n+\tcat .git/worktrees/side/gitdir >expect &&\n+\tcp -R side other-repo/side &&\n+\ttest_must_fail git -C other-repo worktree repair side >out 2>err &&\n+\ttest_cmp expect .git/worktrees/side/gitdir &&\n+\ttest_must_be_empty out &&\n+\ttest_grep \".git file is not for a linked worktree\" err\n+'\n+\n test_expect_success 'repo not found; .git file broken' '\n \ttest_when_finished \"rm -rf orig moved && git worktree prune\" &&\n \tgit worktree add --detach orig &&\ndiff --git a/worktree.c b/worktree.c\nindex 879941a977..31137018d9 100644\n--- a/worktree.c\n+++ b/worktree.c\n@@ -637,12 +637,45 @@ int other_head_refs(struct repository *repo,\n \treturn ret;\n }\n \n-static const char *get_worktree_id(const char *dotgit_contents)\n+static int get_worktree_id(struct strbuf *worktree_id,\n+\t\t\t   const char *dotgit_contents)\n {\n-\tconst char *slash = find_last_dir_sep(dotgit_contents);\n-\tif (!slash)\n-\t\treturn \"\";\n-\treturn slash + 1;\n+\tconst char *id_end;\n+\tconst char *id;\n+\tconst char *prefix_end;\n+\tconst char *prefix = \"worktrees\";\n+\tint prefixlen = strlen(prefix);\n+\n+\tid_end = dotgit_contents + strlen(dotgit_contents);\n+\n+\t/* skip trailing separators */\n+\twhile (dotgit_contents < id_end && is_dir_sep(*(id_end - 1)))\n+\t\tid_end--;\n+\tif (id_end == dotgit_contents)\n+\t\treturn 1;\n+\n+\tid = id_end;\n+\n+\t/* find the last separator */\n+\twhile (dotgit_contents < id && !is_dir_sep(*(id - 1)))\n+\t\tid--;\n+\tif (id == dotgit_contents || id == id_end)\n+\t\treturn 1;\n+\n+\tprefix_end = id - 1;\n+\n+\t/* skip repeated separators */\n+\twhile (dotgit_contents < prefix_end && is_dir_sep(*(prefix_end - 1)))\n+\t\tprefix_end--;\n+\n+\t/* check for \"/worktrees\" */\n+\tif (prefix_end - dotgit_contents < prefixlen + 1 ||\n+\t    strncmp(prefix_end - prefixlen, prefix, prefixlen) ||\n+\t    !is_dir_sep(*(prefix_end - prefixlen - 1)))\n+\t\treturn 1;\n+\n+\tstrbuf_add(worktree_id, id, id_end - id);\n+\treturn 0;\n }\n \n /*\n@@ -658,6 +691,7 @@ static void repair_gitfile(struct worktree *wt,\n \tstruct strbuf repo = STRBUF_INIT;\n \tstruct strbuf backlink = STRBUF_INIT;\n \tstruct strbuf contents = STRBUF_INIT;\n+\tstruct strbuf worktree_id = STRBUF_INIT;\n \tconst char *dotgit_contents = NULL;\n \tconst char *repair = NULL;\n \tchar *path = NULL;\n@@ -692,8 +726,11 @@ static void repair_gitfile(struct worktree *wt,\n \tif (err == READ_GITFILE_ERR_NOT_A_FILE ||\n \t\terr == READ_GITFILE_ERR_IS_A_DIR)\n \t\tfn(1, wt->path, _(\".git is not a file\"), cb_data);\n-\telse if (err || !is_git_directory(backlink.buf))\n+\telse if (err)\n \t\trepair = _(\".git file broken\");\n+\telse if (get_worktree_id(&worktree_id, dotgit_contents) ||\n+\t\t strcmp(worktree_id.buf, wt->id))\n+\t\tfn(1, wt->path, _(\"unrelated .git file\"), cb_data);\n \telse if (fspathcmp(backlink.buf, repo.buf))\n \t\trepair = _(\".git file incorrect\");\n \telse if (use_relative_paths == is_absolute_path(dotgit_contents))\n@@ -712,6 +749,7 @@ done:\n \tstrbuf_release(&gitdir);\n \tstrbuf_release(&backlink);\n \tstrbuf_release(&contents);\n+\tstrbuf_release(&worktree_id);\n }\n \n static void repair_noop(int iserr UNUSED,\n@@ -809,18 +847,20 @@ static ssize_t infer_backlink(struct repository *repo,\n \t\t\t      const char *dotgit_contents,\n \t\t\t      struct strbuf *inferred)\n {\n-\tconst char *id;\n+\tstruct strbuf worktree_id = STRBUF_INIT;\n \n-\tid = get_worktree_id(dotgit_contents);\n-\tif (!*id)\n+\tif (get_worktree_id(&worktree_id, dotgit_contents))\n \t\tgoto error;\n-\trepo_common_path_replace(repo, inferred, \"worktrees/%s\", id);\n-\tif (!is_directory(inferred->buf))\n+\trepo_common_path_replace(repo, inferred,\n+\t\t\t\t \"worktrees/%s\", worktree_id.buf);\n+\tif (!is_git_directory(inferred->buf))\n \t\tgoto error;\n \n+\tstrbuf_release(&worktree_id);\n \treturn inferred->len;\n error:\n \tstrbuf_reset(inferred); /* clear invalid path */\n+\tstrbuf_release(&worktree_id);\n \treturn -1;\n }\n \n@@ -888,6 +928,12 @@ void repair_worktree_at_path(struct repository *repo,\n \t\t   cb_data);\n \t\tgoto done;\n \t}\n+\tif (!inferred_backlink.len) {\n+\t\tfn(1, dotgit.buf,\n+\t\t   _(\"unable to locate repository; .git file is not for a linked worktree\"),\n+\t\t   cb_data);\n+\t\tgoto done;\n+\t}\n \n \t/*\n \t * If we got this far, either the worktree's .git file pointed at a\n@@ -905,7 +951,7 @@ void repair_worktree_at_path(struct repository *repo,\n \t * in the *original* repository, not in the \"copy\" repository).\n \t * Therefore, we prioritize inferred_backlink over backlink.\n \t */\n-\tif (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))\n+\tif (fspathcmp(backlink.buf, inferred_backlink.buf))\n \t\tstrbuf_swap(&backlink, &inferred_backlink);\n \n \tstrbuf_addf(&gitdir, \"%s/gitdir\", backlink.buf);\n-- \ngitgitgadget\n\n"}]}