{"thread":{"id":"65762","subject":"[PATCH 0/2] worktree: copy-on-write creation and shared-branch worktrees","startedAt":"2026-06-05T18:49:30Z","lastAt":"2026-10-22T22:31:06Z","messageCount":23,"participants":["Jason Newton via GitGitGadget","brian m. carlson","Junio C Hamano","Eric Sunshine","Jason Newton","Phillip Wood"],"isPatch":true,"patchVersion":1,"patchTotal":2},"messages":[{"id":"544820","messageId":"pull.2317.git.git.1780685368.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":null,"subject":"[PATCH 0/2] worktree: copy-on-write creation and shared-branch worktrees","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-06-05T18:49:26Z","receivedAt":"2026-06-05T18:49:30Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"When many worktrees share one repository -- e .g. a fleet of agents each\nneeding an isolated checkout -- \"git worktree add\" is costly at scale.\nObjects are shared via the common dir, but the working tree is not: each add\nrewrites every tracked file, so N worktrees cost N full checkouts of disk\nand I/O. And a branch can only be checked out in one worktree.\n\nPatch 1 adds \"git worktree add --reflink\": on a copy-on-write filesystem it\npopulates the new worktree by reflinking the current worktree's files and\nindex, then \"git reset --hard\" rewrites only the paths that differ from . A\nreflink_file() helper in copy.c uses FICLONE (Linux) and clonefile()\n(macOS); elsewhere (other filesystems, Windows) it is probed up front and\nfalls back to a normal checkout. Defaulting is via the worktree.reflink\nconfig (true/false/auto); --no-reflink overrides.\n\nPatch 2 lets a branch be checked out in several worktrees, for parallel work\non one checkout. A branch mid-rebase or mid-bisect elsewhere is still\nrefused.\n\nBenchmark (Linux-kernel fork, 93k files, ~33 GB tree incl. build output,\nbtrfs): a normal add allocates ~0.9 GB of real disk per worktree (~5.3 GB\nfor four, linear); --reflink allocates ~0 at any count and also carries the\nuntracked build tree. (\"Real disk\" = btrfs exclusive bytes.)\n\nworktree-reflink-bench\n[https://github.com/user-attachments/assets/e3e721c8-2206-4b78-ad08-21677ef30753]\n\nNote: patch 2 changes a default (same-branch checkout now allowed); two\nt2400 assertions were updated accordingly.\n\nJason Newton (2):\n  worktree: add --reflink for copy-on-write worktree creation\n  worktree: allow sharing a checked-out branch across worktrees\n\n Documentation/config/worktree.adoc |  10 ++\n Documentation/git-worktree.adoc    |  47 +++++-\n builtin/worktree.c                 | 257 ++++++++++++++++++++++++++++-\n copy.c                             |  65 ++++++++\n copy.h                             |  13 ++\n t/t2400-worktree-add.sh            | 119 ++++++++++++-\n 6 files changed, 493 insertions(+), 18 deletions(-)\n\n\nbase-commit: c69baaf57ba26cf117c2b6793802877f19738b0d\nPublished-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2317%2Fnevion%2Fworktree-reflink-cow-v1\nFetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2317/nevion/worktree-reflink-cow-v1\nPull-Request: https://github.com/git/git/pull/2317\n-- \ngitgitgadget\n"},{"id":"544822","messageId":"7dbd9ca94f3c25f34fe76e6d0c4ff034075cda1c.1780685368.git.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.git.git.1780685368.gitgitgadget@gmail.com","subject":"[PATCH 1/2] worktree: add --reflink for copy-on-write worktree creation","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-06-05T18:49:27Z","receivedAt":"2026-06-05T18:49:31Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"From: Jason Newton <nevion@gmail.com>\n\nCreating many worktrees from the same base -- for example to run a\nfleet of automated agents in parallel -- is expensive today: every\n\"git worktree add\" materializes the entire working tree by writing\neach tracked file out from the object store. The objects are shared\nvia the common directory, but the working tree is not: N worktrees\nmean N full checkouts on disk and N times the file I/O.\n\nAdd a \"--reflink\" option that, on copy-on-write filesystems, populates\nthe new worktree by reflinking the current worktree's files and index\ninstead. The subsequent \"git reset --hard\" then only rewrites the\npaths that actually differ between the current worktree and\n<commit-ish>; everything else (including untracked files such as build\noutputs) keeps sharing storage with the source until modified. Because\nthe cloned index still carries the source files' stat data, it is\nrefreshed against the reflinked files first so that reset recognizes\nthe unchanged paths as up to date and leaves them sharing extents\nrather than rewriting them.\n\nThe clones are made by a new reflink_file() helper in copy.c, which\nuses the FICLONE ioctl on Linux and clonefile() on macOS and reports\nan error otherwise so callers fall back to a normal copy. Support is\nprobed up front; when unavailable -- including on filesystems without\ncopy-on-write and on platforms such as Windows that lack a reflink\nprimitive -- \"--reflink\" transparently falls back to an ordinary\ncheckout, so the worst case is no slower than today rather than a\nbyte-for-byte copy of the source tree. The directory walk skips the\nnew worktree itself when it lives inside the source one, and preserves\nsymlinks and modes.\n\nThe behavior can be made the default with the worktree.reflink\nconfiguration (\"true\", \"false\" or \"auto\", the last suppressing the\nunsupported-filesystem warning), and turned off per-invocation with\n--no-reflink. A configured default degrades quietly in modes that\ncannot reflink (--orphan, --no-checkout) instead of erroring, so\nenabling it never breaks those commands. The checkout step continues\nto honor checkout.workers, so parallel checkout composes with\n--reflink for the paths that do need rewriting.\n\nSigned-off-by: Jason Newton <nevion@gmail.com>\n---\n Documentation/config/worktree.adoc |  10 ++\n Documentation/git-worktree.adoc    |  30 +++-\n builtin/worktree.c                 | 227 ++++++++++++++++++++++++++++-\n copy.c                             |  65 +++++++++\n copy.h                             |  13 ++\n t/t2400-worktree-add.sh            |  88 +++++++++++\n 6 files changed, 431 insertions(+), 2 deletions(-)\n\ndiff --git a/Documentation/config/worktree.adoc b/Documentation/config/worktree.adoc\nindex a248076ea5..d3a03c86d4 100644\n--- a/Documentation/config/worktree.adoc\n+++ b/Documentation/config/worktree.adoc\n@@ -17,3 +17,13 @@\n Note that setting `worktree.useRelativePaths` to \"`true`\" implies enabling the\n `extensions.relativeWorktrees` config (see linkgit:git-config[1]),\n thus making it incompatible with older versions of Git.\n+\n+`worktree.reflink`::\n+\tControls whether `git worktree add` populates new worktrees with\n+\tcopy-on-write (reflink) clones, as if `--reflink` had been given\n+\t(see linkgit:git-worktree[1]). May be set to \"`true`\", \"`false`\"\n+\t(the default), or \"`auto`\". With \"`true`\", a filesystem that does\n+\tnot support reflinks produces a warning before falling back to an\n+\tordinary checkout; with \"`auto`\", the fallback is silent. An\n+\texplicit `--reflink` or `--no-reflink` on the command line\n+\toverrides this setting.\ndiff --git a/Documentation/git-worktree.adoc b/Documentation/git-worktree.adoc\nindex fbf8426cd9..1ca81718b7 100644\n--- a/Documentation/git-worktree.adoc\n+++ b/Documentation/git-worktree.adoc\n@@ -10,7 +10,7 @@ SYNOPSIS\n --------\n [synopsis]\n git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n-\t\t [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]\n+\t\t [--orphan] [--reflink] [(-b | -B) <new-branch>] <path> [<commit-ish>]\n git worktree list [-v | --porcelain [-z]]\n git worktree lock [--reason <string>] <worktree>\n git worktree move <worktree> <new-path>\n@@ -213,6 +213,34 @@ To remove a locked worktree, specify `--force` twice.\n \tsuch as configuring sparse-checkout. See \"Sparse checkout\"\n \tin linkgit:git-read-tree[1].\n \n+`--reflink`::\n+`--no-reflink`::\n+\tPopulate the new worktree by creating copy-on-write (reflink)\n+\tclones of the current worktree's files and index instead of\n+\twriting every file out from the object store. The checkout that\n+\tfollows then only has to rewrite the paths that actually differ\n+\tbetween the current worktree and _<commit-ish>_; everything else\n+\t(including untracked files such as build outputs) keeps sharing\n+\tstorage with the source worktree until modified. This makes\n+\t`add` much faster and far cheaper on disk when creating many\n+\tworktrees from the same base. `--no-reflink` forces an ordinary\n+\tcheckout, overriding the `worktree.reflink` configuration.\n++\n+Reflinks require a copy-on-write filesystem (for example btrfs, XFS,\n+bcachefs or ZFS on Linux, or APFS on macOS). On filesystems or platforms\n+that do not support reflinks, `--reflink` transparently falls back to an\n+ordinary checkout. Because the source worktree's untracked and ignored\n+files are cloned as well, only use `--reflink` when that is acceptable.\n++\n+This option cannot be combined with `--no-checkout` or `--orphan`. It can\n+be enabled by default with the `worktree.reflink` configuration; see\n+linkgit:git-config[1].\n++\n+The checkout that populates a new worktree also honors the\n+`checkout.workers` configuration (see linkgit:git-config[1]), so setting it\n+parallelizes the file writes and can further speed up `add`, with or\n+without `--reflink`.\n+\n `--guess-remote`::\n `--no-guess-remote`::\n \tWith `worktree add <path>`, without _<commit-ish>_, instead\ndiff --git a/builtin/worktree.c b/builtin/worktree.c\nindex d21c43fde3..973da33051 100644\n--- a/builtin/worktree.c\n+++ b/builtin/worktree.c\n@@ -30,7 +30,7 @@\n \n #define BUILTIN_WORKTREE_ADD_USAGE \\\n \tN_(\"git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\\n\" \\\n-\t   \"                 [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]\")\n+\t   \"                 [--orphan] [--reflink] [(-b | -B) <new-branch>] <path> [<commit-ish>]\")\n \n #define BUILTIN_WORKTREE_LIST_USAGE \\\n \tN_(\"git worktree list [-v | --porcelain [-z]]\")\n@@ -47,6 +47,11 @@\n #define BUILTIN_WORKTREE_UNLOCK_USAGE \\\n \tN_(\"git worktree unlock <worktree>\")\n \n+/* values for add_opts.reflink and the worktree.reflink config */\n+#define REFLINK_OFF\t0\n+#define REFLINK_ON\t1\t/* warn and fall back if unsupported */\n+#define REFLINK_AUTO\t2\t/* silently fall back if unsupported */\n+\n #define WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT \\\n \t_(\"No possible source branch, inferring '--orphan'\")\n \n@@ -123,6 +128,7 @@ struct add_opts {\n \tint checkout;\n \tint orphan;\n \tint relative_paths;\n+\tint reflink;\n \tconst char *keep_locked;\n };\n \n@@ -130,6 +136,7 @@ static int show_only;\n static int verbose;\n static int guess_remote;\n static int use_relative_paths;\n+static int reflink_config = REFLINK_OFF;\n static timestamp_t expire;\n \n static int git_worktree_config(const char *var, const char *value,\n@@ -141,6 +148,13 @@ static int git_worktree_config(const char *var, const char *value,\n \t} else if (!strcmp(var, \"worktree.userelativepaths\")) {\n \t\tuse_relative_paths = git_config_bool(var, value);\n \t\treturn 0;\n+\t} else if (!strcmp(var, \"worktree.reflink\")) {\n+\t\tif (value && !strcmp(value, \"auto\"))\n+\t\t\treflink_config = REFLINK_AUTO;\n+\t\telse\n+\t\t\treflink_config = git_config_bool(var, value) ?\n+\t\t\t\tREFLINK_ON : REFLINK_OFF;\n+\t\treturn 0;\n \t}\n \n \treturn git_default_config(var, value, ctx, cb);\n@@ -397,6 +411,182 @@ worktree_copy_cleanup:\n \tfree(to_file);\n }\n \n+/*\n+ * Probe whether the filesystem backing \"dir\" supports reflinks. We do this\n+ * once up front so that, on filesystems without copy-on-write support (or on\n+ * platforms such as Windows that lack a reflink primitive entirely), we can\n+ * fall back to a normal checkout instead of byte-copying the whole source\n+ * working tree -- which would include untracked files and be slower than the\n+ * checkout we are trying to avoid.\n+ */\n+static int reflink_supported(const char *dir)\n+{\n+\tstruct strbuf src = STRBUF_INIT, dst = STRBUF_INIT;\n+\tint fd, ok = 0;\n+\n+\tstrbuf_addf(&src, \"%s/.git-reflink-probe-src\", dir);\n+\tstrbuf_addf(&dst, \"%s/.git-reflink-probe-dst\", dir);\n+\n+\tfd = open(src.buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);\n+\tif (fd >= 0) {\n+\t\twrite_in_full(fd, \"x\", 1);\n+\t\tclose(fd);\n+\t\tif (!reflink_file(dst.buf, src.buf, 0600))\n+\t\t\tok = 1;\n+\t\tunlink(dst.buf);\n+\t}\n+\tunlink(src.buf);\n+\n+\tstrbuf_release(&src);\n+\tstrbuf_release(&dst);\n+\treturn ok;\n+}\n+\n+/*\n+ * Reflink a single regular file, falling back to a regular copy when the\n+ * clone fails for this particular file (for example across mount points).\n+ */\n+static int reflink_or_copy(const char *dst, const char *src, int mode)\n+{\n+\tif (!reflink_file(dst, src, mode))\n+\t\treturn 0;\n+\treturn copy_file(dst, src, mode);\n+}\n+\n+/*\n+ * Recursively copy the working-tree directory \"src\" into \"dst\" using reflinks\n+ * for regular files. Directory entries that resolve to the destination\n+ * worktree itself (identified by skip_dev/skip_ino, which matters when the new\n+ * worktree lives inside the source one) and the top-level \".git\" gitfile are\n+ * skipped.\n+ */\n+static int reflink_tree(const char *src, const char *dst,\n+\t\t\tdev_t skip_dev, ino_t skip_ino, int top)\n+{\n+\tstruct strbuf s = STRBUF_INIT, d = STRBUF_INIT;\n+\tDIR *dir;\n+\tstruct dirent *de;\n+\tint ret = 0;\n+\n+\tdir = opendir(src);\n+\tif (!dir)\n+\t\treturn error_errno(_(\"could not open directory '%s'\"), src);\n+\n+\twhile (!ret && (de = readdir(dir))) {\n+\t\tstruct stat st;\n+\n+\t\tif (is_dot_or_dotdot(de->d_name))\n+\t\t\tcontinue;\n+\t\tif (top && !strcmp(de->d_name, \".git\"))\n+\t\t\tcontinue;\n+\n+\t\tstrbuf_reset(&s);\n+\t\tstrbuf_addf(&s, \"%s/%s\", src, de->d_name);\n+\t\tstrbuf_reset(&d);\n+\t\tstrbuf_addf(&d, \"%s/%s\", dst, de->d_name);\n+\n+\t\tif (lstat(s.buf, &st)) {\n+\t\t\tret = error_errno(_(\"could not stat '%s'\"), s.buf);\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tif (S_ISDIR(st.st_mode)) {\n+\t\t\t/* never recurse into the new worktree itself */\n+\t\t\tif (st.st_dev == skip_dev && st.st_ino == skip_ino)\n+\t\t\t\tcontinue;\n+\t\t\tif (mkdir(d.buf, st.st_mode & 07777) && errno != EEXIST) {\n+\t\t\t\tret = error_errno(_(\"could not create directory '%s'\"), d.buf);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tret = reflink_tree(s.buf, d.buf, skip_dev, skip_ino, 0);\n+\t\t} else if (S_ISLNK(st.st_mode)) {\n+\t\t\tstruct strbuf link = STRBUF_INIT;\n+\n+\t\t\tif (strbuf_readlink(&link, s.buf, st.st_size))\n+\t\t\t\tret = error_errno(_(\"could not read symlink '%s'\"), s.buf);\n+\t\t\telse if (symlink(link.buf, d.buf))\n+\t\t\t\tret = error_errno(_(\"could not create symlink '%s'\"), d.buf);\n+\t\t\tstrbuf_release(&link);\n+\t\t} else if (S_ISREG(st.st_mode)) {\n+\t\t\tif (reflink_or_copy(d.buf, s.buf, st.st_mode))\n+\t\t\t\tret = error_errno(_(\"could not copy '%s' to '%s'\"),\n+\t\t\t\t\t\t  s.buf, d.buf);\n+\t\t}\n+\t\t/* silently skip fifos, sockets and device nodes */\n+\t}\n+\n+\tclosedir(dir);\n+\tstrbuf_release(&s);\n+\tstrbuf_release(&d);\n+\treturn ret;\n+}\n+\n+/*\n+ * Populate the new worktree at \"path\" by reflinking the current worktree's\n+ * files and index. The subsequent \"git reset --hard\" then only has to rewrite\n+ * the paths that actually differ between the source and <commit-ish>, leaving\n+ * everything else sharing storage with the source. Returns 1 when reflinks are\n+ * unavailable so the caller can fall back to a plain checkout.\n+ */\n+static int reflink_worktree(const char *path, const char *wt_git_dir,\n+\t\t\t    const struct add_opts *opts, struct strvec *child_env)\n+{\n+\tconst char *src_wt = the_repository->worktree;\n+\tchar *src_index = NULL, *dst_index = NULL;\n+\tstruct stat dst_st;\n+\tint ret = 0;\n+\n+\tif (!src_wt)\n+\t\treturn error(_(\"--reflink needs a source working tree, but this \"\n+\t\t\t       \"repository does not have one\"));\n+\n+\tif (!reflink_supported(path)) {\n+\t\t/* In auto mode the fallback is expected, so stay quiet. */\n+\t\tif (!opts->quiet && opts->reflink != REFLINK_AUTO)\n+\t\t\twarning(_(\"the filesystem at '%s' does not support reflinks; \"\n+\t\t\t\t  \"falling back to a regular checkout\"), path);\n+\t\treturn 1;\n+\t}\n+\n+\tif (stat(path, &dst_st))\n+\t\treturn error_errno(_(\"could not stat '%s'\"), path);\n+\n+\tif ((ret = reflink_tree(src_wt, path, dst_st.st_dev, dst_st.st_ino, 1)))\n+\t\treturn ret;\n+\n+\t/*\n+\t * Clone the source index so the following reset sees the source's\n+\t * state and only materializes the differences to <commit-ish>.\n+\t */\n+\tsrc_index = repo_git_path(the_repository, \"index\");\n+\tdst_index = xstrfmt(\"%s/index\", wt_git_dir);\n+\tif (!access(src_index, F_OK) &&\n+\t    reflink_or_copy(dst_index, src_index, 0666)) {\n+\t\tret = error_errno(_(\"could not copy index to '%s'\"), dst_index);\n+\t\tgoto out;\n+\t}\n+\n+\t/*\n+\t * The cloned index still carries the source files' stat information.\n+\t * Refresh it against the freshly reflinked files so that \"git reset\"\n+\t * recognizes unchanged paths as up to date and leaves them sharing\n+\t * storage instead of rewriting (and thus un-sharing) them.\n+\t */\n+\tif (!access(dst_index, F_OK)) {\n+\t\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\t\tcp.git_cmd = 1;\n+\t\tstrvec_pushl(&cp.args, \"update-index\", \"-q\", \"--refresh\", NULL);\n+\t\tstrvec_pushv(&cp.env, child_env->v);\n+\t\t/* a dirty working tree is not an error here */\n+\t\trun_command(&cp);\n+\t}\n+\n+out:\n+\tfree(src_index);\n+\tfree(dst_index);\n+\treturn ret;\n+}\n+\n static int checkout_worktree(const struct add_opts *opts,\n \t\t\t     struct strvec *child_env)\n {\n@@ -589,6 +779,20 @@ static int add_worktree(const char *path, const char *refname,\n \t    (ret = make_worktree_orphan(refname, opts, &child_env)))\n \t\tgoto done;\n \n+\t/*\n+\t * When --reflink is requested and the filesystem supports it, copy the\n+\t * current worktree (and its index) into the new one using copy-on-write\n+\t * clones. checkout_worktree() then only rewrites the paths that differ\n+\t * from <commit-ish>. reflink_worktree() returns 1 when reflinks are not\n+\t * available, in which case we just do an ordinary checkout below.\n+\t */\n+\tif (opts->checkout && opts->reflink) {\n+\t\tret = reflink_worktree(path, sb_repo.buf, opts, &child_env);\n+\t\tif (ret < 0)\n+\t\t\tgoto done;\n+\t\tret = 0;\n+\t}\n+\n \tif (opts->checkout &&\n \t    (ret = checkout_worktree(opts, &child_env)))\n \t\tgoto done;\n@@ -801,6 +1005,7 @@ static int add(int ac, const char **av, const char *prefix,\n \tconst char *lock_reason = NULL;\n \tint keep_locked = 0;\n \tint used_new_branch_options;\n+\tint reflink_cli = -1;\n \tstruct option options[] = {\n \t\tOPT__FORCE(&opts.force,\n \t\t\t   N_(\"checkout <branch> even if already checked out in other worktree\"),\n@@ -823,6 +1028,8 @@ static int add(int ac, const char **av, const char *prefix,\n \t\t\t N_(\"try to match the new branch name with a remote-tracking branch\")),\n \t\tOPT_BOOL(0, \"relative-paths\", &opts.relative_paths,\n \t\t\t N_(\"use relative paths for worktrees\")),\n+\t\tOPT_BOOL(0, \"reflink\", &reflink_cli,\n+\t\t\t N_(\"populate the worktree using copy-on-write clones when supported\")),\n \t\tOPT_END()\n \t};\n \tint ret;\n@@ -842,6 +1049,24 @@ static int add(int ac, const char **av, const char *prefix,\n \tif (opts.orphan && !opts.checkout)\n \t\tdie(_(\"options '%s' and '%s' cannot be used together\"),\n \t\t    \"--orphan\", \"--no-checkout\");\n+\n+\t/*\n+\t * Resolve whether to reflink: an explicit --reflink/--no-reflink on\n+\t * the command line wins, otherwise fall back to the worktree.reflink\n+\t * configuration (which may select the \"auto\" mode).\n+\t */\n+\topts.reflink = (reflink_cli != -1) ? reflink_cli : reflink_config;\n+\tif (opts.reflink && (opts.orphan || !opts.checkout)) {\n+\t\t/*\n+\t\t * Reflinking is incompatible with these; only complain when it\n+\t\t * was explicitly requested, otherwise quietly do a plain\n+\t\t * checkout so a configured default does not break these modes.\n+\t\t */\n+\t\tif (reflink_cli == REFLINK_ON)\n+\t\t\tdie(_(\"options '%s' and '%s' cannot be used together\"),\n+\t\t\t    \"--reflink\", opts.orphan ? \"--orphan\" : \"--no-checkout\");\n+\t\topts.reflink = REFLINK_OFF;\n+\t}\n \tif (opts.orphan && ac == 2)\n \t\tdie(_(\"option '%s' and commit-ish cannot be used together\"),\n \t\t    \"--orphan\");\ndiff --git a/copy.c b/copy.c\nindex b668209b6c..d2c8ce5209 100644\n--- a/copy.c\n+++ b/copy.c\n@@ -7,6 +7,21 @@\n #include \"strbuf.h\"\n #include \"abspath.h\"\n \n+#if defined(__linux__)\n+#include <sys/ioctl.h>\n+/*\n+ * FICLONE lives in <linux/fs.h>, but including that header tends to clash\n+ * with the libc headers git already pulls in, so define it ourselves if it\n+ * is missing. The value is part of the stable kernel uapi.\n+ */\n+#ifndef FICLONE\n+#define FICLONE _IOW(0x94, 9, int)\n+#endif\n+#elif defined(__APPLE__)\n+#include <sys/attr.h>\n+#include <sys/clonefile.h>\n+#endif\n+\n int copy_fd(int ifd, int ofd)\n {\n \twhile (1) {\n@@ -72,3 +87,53 @@ int copy_file_with_time(const char *dst, const char *src, int mode)\n \t\treturn copy_times(dst, src);\n \treturn status;\n }\n+\n+int reflink_file(const char *dst, const char *src, int mode)\n+{\n+#if defined(__APPLE__)\n+\t/*\n+\t * clonefile() refuses to operate when the destination exists and\n+\t * copies the source's permissions for us, so \"mode\" is unused here.\n+\t */\n+\t(void)mode;\n+\tif (clonefile(src, dst, 0) < 0)\n+\t\treturn -1;\n+\tif (adjust_shared_perm(the_repository, dst))\n+\t\treturn -1;\n+\treturn 0;\n+#elif defined(__linux__)\n+\tint fdi, fdo, status;\n+\n+\tmode = (mode & 0111) ? 0777 : 0666;\n+\tif ((fdi = open(src, O_RDONLY)) < 0)\n+\t\treturn -1;\n+\tif ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) {\n+\t\tint saved = errno;\n+\t\tclose(fdi);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\tstatus = ioctl(fdo, FICLONE, fdi);\n+\tclose(fdi);\n+\tif (status < 0) {\n+\t\tint saved = errno;\n+\t\tclose(fdo);\n+\t\t/* we created an empty file above; do not leave it behind */\n+\t\tunlink(dst);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\tif (close(fdo) != 0)\n+\t\treturn -1;\n+\tif (adjust_shared_perm(the_repository, dst))\n+\t\treturn -1;\n+\treturn 0;\n+#else\n+\t/* No reflink support on this platform (e.g. Windows). */\n+\t(void)dst;\n+\t(void)src;\n+\t(void)mode;\n+\terrno = ENOSYS;\n+\treturn -1;\n+#endif\n+}\ndiff --git a/copy.h b/copy.h\nindex 2af77cba86..a8646f7ff5 100644\n--- a/copy.h\n+++ b/copy.h\n@@ -7,4 +7,17 @@ int copy_fd(int ifd, int ofd);\n int copy_file(const char *dst, const char *src, int mode);\n int copy_file_with_time(const char *dst, const char *src, int mode);\n \n+/*\n+ * Create \"dst\" as a copy-on-write (reflink) clone of the regular file\n+ * \"src\", so that the two files share their data blocks until one of\n+ * them is modified. \"dst\" must not already exist.\n+ *\n+ * This only succeeds on filesystems that support block cloning (e.g.\n+ * btrfs, XFS or bcachefs on Linux, APFS on macOS). When the platform or\n+ * filesystem does not support reflinks, -1 is returned with errno set to\n+ * ENOSYS (or the underlying error). Callers are expected to fall back to\n+ * copy_file() in that case. Returns 0 on success.\n+ */\n+int reflink_file(const char *dst, const char *src, int mode);\n+\n #endif /* COPY_H */\ndiff --git a/t/t2400-worktree-add.sh b/t/t2400-worktree-add.sh\nindex 58b4445cc4..56fb79179a 100755\n--- a/t/t2400-worktree-add.sh\n+++ b/t/t2400-worktree-add.sh\n@@ -1248,4 +1248,92 @@ test_expect_success 'relative worktree sets extension config' '\n \ttest_cmp_config -C repo true extensions.relativeworktrees\n '\n \n+test_expect_success '--reflink produces a correct checkout on any filesystem' '\n+\ttest_when_finished \"rm -rf reflinkrepo\" &&\n+\tgit init reflinkrepo &&\n+\t(\n+\t\tcd reflinkrepo &&\n+\t\ttest_commit base file.txt base &&\n+\t\ttest_commit next file.txt next &&\n+\t\tgit worktree add --reflink wt -b reflinkbr base &&\n+\t\techo base >expect &&\n+\t\ttest_cmp expect wt/file.txt &&\n+\t\tgit -C wt status --porcelain >status &&\n+\t\ttest_must_be_empty status\n+\t)\n+'\n+\n+test_expect_success '--reflink rejects incompatible options' '\n+\ttest_must_fail git worktree add --reflink --no-checkout wt-bad HEAD 2>err &&\n+\ttest_grep \"cannot be used together\" err &&\n+\ttest_must_fail git worktree add --reflink --orphan wt-bad2 2>err &&\n+\ttest_grep \"cannot be used together\" err\n+'\n+\n+test_expect_success 'worktree.reflink config drives a correct checkout' '\n+\ttest_when_finished \"rm -rf reflinkcfg\" &&\n+\tgit init reflinkcfg &&\n+\t(\n+\t\tcd reflinkcfg &&\n+\t\ttest_commit cfg file.txt value &&\n+\t\tgit -c worktree.reflink=true worktree add wt HEAD &&\n+\t\techo value >expect &&\n+\t\ttest_cmp expect wt/file.txt\n+\t)\n+'\n+\n+test_expect_success 'worktree.reflink=auto does not break --orphan' '\n+\ttest_when_finished \"rm -rf reflinkorphan\" &&\n+\tgit init reflinkorphan &&\n+\t(\n+\t\tcd reflinkorphan &&\n+\t\ttest_commit base file.txt value &&\n+\t\tgit -c worktree.reflink=auto worktree add --orphan wt &&\n+\t\tgit -C wt symbolic-ref --short HEAD >actual &&\n+\t\techo wt >expect &&\n+\t\ttest_cmp expect actual\n+\t)\n+'\n+\n+test_expect_success '--no-reflink overrides worktree.reflink' '\n+\ttest_when_finished \"rm -rf reflinkoff\" &&\n+\tgit init reflinkoff &&\n+\t(\n+\t\tcd reflinkoff &&\n+\t\ttest_commit base file.txt value &&\n+\t\tgit -c worktree.reflink=true worktree add --no-reflink wt HEAD &&\n+\t\techo value >expect &&\n+\t\ttest_cmp expect wt/file.txt\n+\t)\n+'\n+\n+# Reflinks are only available on copy-on-write filesystems (btrfs, XFS,\n+# bcachefs, APFS, ...). Where they are unavailable, --reflink transparently\n+# falls back to a regular checkout, which the test above already covers.\n+test_lazy_prereq REFLINK '\n+\techo probe >reflink-src &&\n+\tcp --reflink=always reflink-src reflink-dst 2>/dev/null\n+'\n+\n+test_expect_success REFLINK '--reflink carries untracked files and reconciles changes' '\n+\ttest_when_finished \"rm -rf cowrepo\" &&\n+\tgit init cowrepo &&\n+\t(\n+\t\tcd cowrepo &&\n+\t\ttest_commit same same.txt content &&\n+\t\ttest_commit old change.txt old-value &&\n+\t\ttest_commit new change.txt new-value &&\n+\t\techo artifact >untracked.bin &&\n+\t\tgit worktree add --reflink wt -b cowbr old &&\n+\t\techo content >expect &&\n+\t\ttest_cmp expect wt/same.txt &&\n+\t\techo old-value >expect &&\n+\t\ttest_cmp expect wt/change.txt &&\n+\t\techo artifact >expect &&\n+\t\ttest_cmp expect wt/untracked.bin &&\n+\t\tgit -C wt status --porcelain >status &&\n+\t\tgrep \"?? untracked.bin\" status\n+\t)\n+'\n+\n test_done\n-- \ngitgitgadget\n\n"},{"id":"544821","messageId":"97f0fdad9bd32aa5eeb6fc2d524823df55e5b61e.1780685368.git.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.git.git.1780685368.gitgitgadget@gmail.com","subject":"[PATCH 2/2] worktree: allow sharing a checked-out branch across worktrees","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-06-05T18:49:28Z","receivedAt":"2026-06-05T18:49:32Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"From: Jason Newton <nevion@gmail.com>\n\nWhen spinning up several worktrees on the same checkout for parallel\nwork (for example a fleet of agents working from one branch), git's\nrefusal to check out a branch that is already checked out elsewhere is\njust in the way. The restriction exists to stop two worktrees from\nmoving the same branch underneath each other, but plain parallel\ncheckouts do not need that protection.\n\nDrop the restriction: \"git worktree add <branch>\" now checks out a\nbranch even if it is in use by another worktree. The genuinely\ndangerous case is kept -- a branch that another worktree is in the\nmiddle of rebasing or bisecting is still refused, because a second\ncheckout could corrupt that operation. die_if_branch_busy() performs\nthat narrower check in place of the old die_if_checked_out(). The\nseparate guard against force-updating (e.g. with -B) a branch in use\nelsewhere is left untouched.\n\nSigned-off-by: Jason Newton <nevion@gmail.com>\n---\n Documentation/git-worktree.adoc | 17 +++++++++--------\n builtin/worktree.c              | 30 +++++++++++++++++++++++++++++-\n t/t2400-worktree-add.sh         | 31 ++++++++++++++++++++++++-------\n 3 files changed, 62 insertions(+), 16 deletions(-)\n\ndiff --git a/Documentation/git-worktree.adoc b/Documentation/git-worktree.adoc\nindex 1ca81718b7..cc4c91b787 100644\n--- a/Documentation/git-worktree.adoc\n+++ b/Documentation/git-worktree.adoc\n@@ -93,8 +93,9 @@ then, as a convenience, the new worktree is associated with a branch (call\n it _<branch>_) named after `$(basename <path>)`.  If _<branch>_ doesn't\n exist, a new branch based on `HEAD` is automatically created as if\n `-b <branch>` was given.  If _<branch>_ does exist, it will be checked out\n-in the new worktree, if it's not checked out anywhere else, otherwise the\n-command will refuse to create the worktree (unless `--force` is used).\n+in the new worktree, even if it is already checked out in another worktree.\n+(A branch that another worktree is in the middle of rebasing or bisecting is\n+refused unless `--force` is used.)\n +\n If _<commit-ish>_ is omitted, neither `--detach`, or `--orphan` is\n used, and there are no valid local branches (or remote branches if\n@@ -177,12 +178,12 @@ OPTIONS\n \n `-f`::\n `--force`::\n-\tBy default, `add` refuses to create a new worktree when\n-\t_<commit-ish>_ is a branch name and is already checked out by\n-\tanother worktree, or if _<path>_ is already assigned to some\n-\tworktree but is missing (for instance, if _<path>_ was deleted\n-\tmanually). This option overrides these safeguards. To add a missing but\n-\tlocked worktree path, specify `--force` twice.\n+\t`add` refuses to create a new worktree when _<commit-ish>_ is a\n+\tbranch that another worktree is in the middle of rebasing or\n+\tbisecting, or if _<path>_ is already assigned to some worktree but\n+\tis missing (for instance, if _<path>_ was deleted manually). This\n+\toption overrides these safeguards. To add a missing but locked\n+\tworktree path, specify `--force` twice.\n +\n `move` refuses to move a locked worktree unless `--force` is specified\n twice. If the destination is already assigned to some other worktree but is\ndiff --git a/builtin/worktree.c b/builtin/worktree.c\nindex 973da33051..b457b015d1 100644\n--- a/builtin/worktree.c\n+++ b/builtin/worktree.c\n@@ -648,6 +648,34 @@ static void setup_alternate_ref_dir(struct worktree *wt, const char *wt_git_path\n \tstrbuf_release(&sb);\n }\n \n+/*\n+ * Checking out a branch that is already checked out in another worktree is\n+ * fine -- it is exactly what you want when spinning up several worktrees on\n+ * the same checkout for parallel work. The one case that is still unsafe is a\n+ * branch that another worktree is in the middle of rebasing or bisecting,\n+ * since a second checkout could corrupt that operation, so refuse only that.\n+ */\n+static void die_if_branch_busy(const char *branch)\n+{\n+\tstruct worktree **worktrees = get_worktrees();\n+\tint i;\n+\n+\tfor (i = 0; worktrees[i]; i++) {\n+\t\tconst struct worktree *wt = worktrees[i];\n+\n+\t\tif (is_worktree_being_rebased(wt, branch) ||\n+\t\t    is_worktree_being_bisected(wt, branch)) {\n+\t\t\tconst char *shortname = branch;\n+\n+\t\t\tskip_prefix(branch, \"refs/heads/\", &shortname);\n+\t\t\tdie(_(\"'%s' is already used by worktree at '%s'\"),\n+\t\t\t    shortname, wt->path);\n+\t\t}\n+\t}\n+\n+\tfree_worktrees(worktrees);\n+}\n+\n static int add_worktree(const char *path, const char *refname,\n \t\t\tconst struct add_opts *opts)\n {\n@@ -675,7 +703,7 @@ static int add_worktree(const char *path, const char *refname,\n \t    refs_ref_exists(get_main_ref_store(the_repository), symref.buf)) {\n \t\tis_branch = 1;\n \t\tif (!opts->force)\n-\t\t\tdie_if_checked_out(symref.buf, 0);\n+\t\t\tdie_if_branch_busy(symref.buf);\n \t}\n \tcommit = lookup_commit_reference_by_name(refname);\n \tif (!commit && !opts->orphan)\ndiff --git a/t/t2400-worktree-add.sh b/t/t2400-worktree-add.sh\nindex 56fb79179a..6a1eb72ac7 100755\n--- a/t/t2400-worktree-add.sh\n+++ b/t/t2400-worktree-add.sh\n@@ -40,10 +40,24 @@ test_expect_success '\"add\" using - shorthand' '\n \ttest_cmp expect actual\n '\n \n-test_expect_success '\"add\" refuses to checkout locked branch' '\n-\ttest_must_fail git worktree add zere main &&\n-\ttest_path_is_missing zere &&\n-\ttest_path_is_missing .git/worktrees/zere\n+test_expect_success '\"add\" can check out a branch in use by another worktree' '\n+\ttest_when_finished \"git worktree remove -f zere || :\" &&\n+\tgit worktree add zere main &&\n+\techo refs/heads/main >expect &&\n+\tgit -C zere symbolic-ref HEAD >actual &&\n+\ttest_cmp expect actual\n+'\n+\n+test_expect_success 'the same branch can be checked out in several worktrees' '\n+\ttest_when_finished \"git worktree remove -f shared1 || :; git worktree remove -f shared2 || :\" &&\n+\tgit branch -f sharedbr main &&\n+\tgit worktree add shared1 sharedbr &&\n+\tgit worktree add shared2 sharedbr &&\n+\techo refs/heads/sharedbr >expect &&\n+\tgit -C shared1 symbolic-ref HEAD >actual &&\n+\ttest_cmp expect actual &&\n+\tgit -C shared2 symbolic-ref HEAD >actual &&\n+\ttest_cmp expect actual\n '\n \n test_expect_success 'checking out paths not complaining about linked checkouts' '\n@@ -304,10 +318,13 @@ test_expect_success '\"add\" checks out existing branch of dwimd name' '\n \t)\n '\n \n-test_expect_success '\"add <path>\" dwim fails with checked out branch' '\n+test_expect_success '\"add <path>\" dwim shares a checked out branch' '\n \tgit checkout -b test-branch &&\n-\ttest_must_fail git worktree add test-branch &&\n-\ttest_path_is_missing test-branch\n+\tgit worktree add test-branch &&\n+\techo refs/heads/test-branch >expect &&\n+\tgit -C test-branch symbolic-ref HEAD >actual &&\n+\ttest_cmp expect actual &&\n+\tgit worktree remove test-branch\n '\n \n test_expect_success '\"add --force\" with existing dwimd name doesnt die' '\n-- \ngitgitgadget\n"},{"id":"544823","messageId":"aiMqrVQ6NRl4gImh@fruit.crustytoothpaste.net","threadId":"65762","inReplyTo":"pull.2317.git.git.1780685368.gitgitgadget@gmail.com","subject":"Re: [PATCH 0/2] worktree: copy-on-write creation and shared-branch worktrees","fromName":"brian m. carlson","fromEmail":"sandals@crustytoothpaste.net","sentAt":"2026-06-05T19:59:41Z","receivedAt":"2026-06-05T20:08:34Z","isPatch":true,"sender":{"key":"sandals@crustytoothpaste.net","avatar":"https://avatars.githubusercontent.com/u/497054?v=4"},"body":"On 2026-06-05 at 18:49:26, Jason Newton via GitGitGadget wrote:\n> When many worktrees share one repository -- e .g. a fleet of agents each\n> needing an isolated checkout -- \"git worktree add\" is costly at scale.\n> Objects are shared via the common dir, but the working tree is not: each add\n> rewrites every tracked file, so N worktrees cost N full checkouts of disk\n> and I/O. And a branch can only be checked out in one worktree.\n> \n> Patch 1 adds \"git worktree add --reflink\": on a copy-on-write filesystem it\n> populates the new worktree by reflinking the current worktree's files and\n> index, then \"git reset --hard\" rewrites only the paths that differ from . A\n> reflink_file() helper in copy.c uses FICLONE (Linux) and clonefile()\n> (macOS); elsewhere (other filesystems, Windows) it is probed up front and\n> falls back to a normal checkout. Defaulting is via the worktree.reflink\n> config (true/false/auto); --no-reflink overrides.\n\nWindows apparently has CoW functionality if you use ReFS.  I believe Git\nLFS has code to do this and you may be interested in checking it out.\n\nAlso, how does this work if worktree A is dirty (but `git update-index`\nand `git status` have not been run) when the reflink occurs?  Does B\nhave stale files from the working tree?  If not, how do we plan on\ndetecting that?  (While I'm curious, this should also be explained in\nyour commit message because we want to know that you have thought about\nthis problem and have a good answer for it.)\n\nI was curious as to how this would work with containers, which typically\nuse overlayfs, but some searching reveals that overlayfs does indeed\nsupport reflinks.  Thanks for the opportunity to learn something new\ntoday.\n\n> Patch 2 lets a branch be checked out in several worktrees, for parallel work\n> on one checkout. A branch mid-rebase or mid-bisect elsewhere is still\n> refused.\n\nSo how does this work if you have two worktrees for the same branch, A\nand B, and A commits, and then B does?  What we don't want to happen is\nthat because B's worktree is not up to date, it effectively reverts the\nchanges that A made when adding objects to the index to commit.  (Again,\nthis is a good thing to explain in your commit message, since reviewers\nwill be curious.)\n\nMy personal approach, if I needed many worktrees of the same commit,\nwould be to create many refs pointing to the same object ID and check\nthose out.  `git update-ref` can perform a single ref transaction with\nmany refs, which is especially efficient with reftable.  That would\navoid the need for multiple checkout support, although I could still see\nthe utility of reflinking if it can be done safely.  If that's a\nsolution that you think would be valuable, you could propose it as a FAQ\nentry or an edit to the manual page, since I'm sure there are other\npeople with your use case.\n-- \nbrian m. carlson (they/them)\nToronto, Ontario, CA\n"},{"id":"544933","messageId":"xmqq8q8pxfny.fsf@gitster.g","threadId":"65762","inReplyTo":"pull.2317.git.git.1780685368.gitgitgadget@gmail.com","subject":"Re: [PATCH 0/2] worktree: copy-on-write creation and shared-branch worktrees","fromName":"Junio C Hamano","fromEmail":"gitster@pobox.com","sentAt":"2026-06-08T14:36:33Z","receivedAt":"2026-06-08T14:36:35Z","isPatch":true,"sender":{"key":"gitster@pobox.com","avatar":"https://avatars.githubusercontent.com/u/54884?v=4"},"body":"\"Jason Newton via GitGitGadget\" <gitgitgadget@gmail.com> writes:\n\n> When many worktrees share one repository -- e .g. a fleet of agents each\n> needing an isolated checkout -- \"git worktree add\" is costly at scale.\n> Objects are shared via the common dir, but the working tree is not: each add\n> rewrites every tracked file, so N worktrees cost N full checkouts of disk\n> and I/O.\n\nAre the \"CoW\" semantics offered by these underlying mechanisms,\nwhich may differ per operating system and possibly filesystem type,\nall meant as mere storage-space optimization, or do some of them\ntrade potential space saving with some limitation of the features,\ni.e., what you can do in the CoW copy and original, or increased\nruntime cost, either at the clone time or the time of first\nmodification?\n\nWhat I am trying to get at is why should this be even an opt-in\nfeature.  If \"cp treeA treeB\" at the shell level would make all the\nfiles in treeA under identical names and contents in treeB, and let\nyou edit/update/delete copies in either tree without affecting the\nother tree, then in practice you would not even be able to _tell_ if\nCoW is in use, no?\n\nIt may tilt the scale if there is a downside associated with the use\nof CoW, like at the first modification of one copy, the system may\nneed to do real copies of other copies, but even such a cost should\nnot be outrageously worse than the cost of copying everything once\nat the worktree creation time.\n\nSo I would understand \"whenever we say git_copy_file(A, B), we\nalways use CoW facility under the hood if available, regardless of\nthe purpose of the operation to copy one file to another location---\nit may include, but does not have to be limited to, populating\nworking file trees in a new worktree\", and I think it is a welcome\nchange.\n\nBut I do not quite get \"... only if the user gives --reflink\noption\".  Why is it even necessary to offer a choice?  Especially\nsince you seem to have auto-probe, we should be able to implement a\nlow-level operation to materialize contents identified by a_hash at\na_path in the working tree in two different ways, switching on the\navailablity of CoW, e.g.,\n\n\tif (CoW available && we can find existing path with a_hash) {\n\t        copy-cow the found path to a_path;\n\t} else {\n\t\twrite object identified by a_hash to a_path;\n\t}\n\n>  And a branch can only be checked out in one worktree.\n\nThis is a safety feature that has nothing to do with shared files\nacross worktrees, no?  Your two worktrees may think they have a\ncheckout of the same branch (thus the same commit), one worktree\nmakes changes and commits, the other worktree suddenly starts seeing\na totally different output from its \"git diff HEAD\" that mixes what\nit did relative to where it started (which is what we want) plus the\nreversion of what was done in the other worktree (which is definitely\nnot what we want).\n"},{"id":"555574","messageId":"pull.2317.v2.git.git.1792512249.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.git.git.1780685368.gitgitgadget@gmail.com","subject":"[PATCH v2 0/2] worktree: copy-on-write creation and ephemeral branches","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-20T16:04:07Z","receivedAt":"2026-10-20T16:04:07Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"When many worktrees share one repository -- for example a fleet of agents\neach needing an isolated checkout -- \"git worktree add\" is costly at scale.\nObjects are shared via the common directory, but the working tree is not:\neach add rewrites every tracked file, so N worktrees cost N full checkouts\nof disk and I/O. A branch created only to back one of those worktrees is\nalso left behind when the worktree is removed.\n\nPatch 1 adds \"git worktree add --reflink\". On a copy-on-write filesystem it\npopulates the new worktree by reflinking the current worktree's files and\nindex, then \"git reset --hard\" rewrites only the paths that differ from .\nreflink_file() in copy.c uses FICLONE (Linux), clonefile() (macOS), and ReFS\nblock cloning (FSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does). Elsewhere\nit is probed up front and falls back to a normal checkout. worktree.reflink\n(true/false/auto) sets the default; --no-reflink overrides.\n\nUncommitted edits to tracked files in the source do not leak into the new\nworktree. The copied index is refreshed before reset, and because every\nreflinked file is a new inode the refresh re-validates by content. Only\nuntracked files are carried over. The option stays opt-in for that reason:\nit copies the source's untracked and ignored files, which a plain checkout\ndoes not.\n\nFor many worktrees at one commit, the series does not share a branch.\ngit-worktree(1) shows a single update-ref transaction that creates a ref per\nworktree (or a detached HEAD). A shared branch still lets a stale index in\none worktree silently revert a commit made in another.\n\nPatch 2 treats a branch that \"git worktree add \" created itself as owned by\nthat worktree. \"git worktree remove\" deletes it. Branches named with -b/-B,\nor that already existed, are left alone. --keep-branch keeps an owned\nbranch.\n\nChanges since v1:\n\n * Dropped the patch that allowed one branch to be checked out in several\n   worktrees. Documented the per-ref / detached-HEAD pattern instead (brian\n   m. carlson, Junio).\n * Explained, in the commit message and the manual, why a dirty source\n   worktree does not leak tracked content (brian m. carlson).\n * Added the ReFS block-cloning arm (brian m. carlson).\n * Noted overlayfs as a supported setup when the lower filesystem supports\n   reflinks (brian m. carlson).\n * Kept --reflink opt-in. A whole-tree reflink is not invisible: it carries\n   untracked files, and cloning every file can be slower than checkout when\n   the files are small (Junio; qub1n on the ReFS work).\n * Rebased onto 47fdf2208c (\"The 7th batch\"). reflink_file() now takes a\n   repository argument, matching copy_file().\n * Added ephemeral-branch reaping for the auto-named branch that \"worktree\n   add \" creates.\n\nJason Newton (2):\n  worktree: add --reflink for copy-on-write worktree creation\n  worktree: reap ephemeral branches created by \"worktree add\"\n\n Documentation/config/worktree.adoc |  10 +\n Documentation/git-worktree.adoc    |  71 ++++++-\n builtin/branch.c                   |  28 +++\n builtin/worktree.c                 | 301 ++++++++++++++++++++++++++++-\n copy.c                             | 190 ++++++++++++++++++\n copy.h                             |  14 ++\n t/t2400-worktree-add.sh            | 143 ++++++++++++++\n t/t3200-branch.sh                  |   2 +-\n t/t3400-rebase.sh                  |   2 +-\n t/t5516-fetch-push.sh              |   2 +-\n 10 files changed, 754 insertions(+), 9 deletions(-)\n\n\nbase-commit: 47fdf2208c5b94c8cc01c106b8f7c85efb91c926\nPublished-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2317%2Fnevion%2Fworktree-reflink-cow-v2\nFetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2317/nevion/worktree-reflink-cow-v2\nPull-Request: https://github.com/git/git/pull/2317\n\nRange-diff vs v1:\n\n 1:  7dbd9ca94f ! 1:  83841020f4 worktree: add --reflink for copy-on-write worktree creation\n     @@ Commit message\n          via the common directory, but the working tree is not: N worktrees\n          mean N full checkouts on disk and N times the file I/O.\n      \n     -    Add a \"--reflink\" option that, on copy-on-write filesystems, populates\n     +    Add a \"--reflink\" option that, on a copy-on-write filesystem, populates\n          the new worktree by reflinking the current worktree's files and index\n          instead. The subsequent \"git reset --hard\" then only rewrites the\n          paths that actually differ between the current worktree and\n          <commit-ish>; everything else (including untracked files such as build\n     -    outputs) keeps sharing storage with the source until modified. Because\n     -    the cloned index still carries the source files' stat data, it is\n     -    refreshed against the reflinked files first so that reset recognizes\n     -    the unchanged paths as up to date and leaves them sharing extents\n     -    rather than rewriting them.\n     +    outputs) keeps sharing storage with the source until modified.\n      \n     -    The clones are made by a new reflink_file() helper in copy.c, which\n     -    uses the FICLONE ioctl on Linux and clonefile() on macOS and reports\n     -    an error otherwise so callers fall back to a normal copy. Support is\n     -    probed up front; when unavailable -- including on filesystems without\n     -    copy-on-write and on platforms such as Windows that lack a reflink\n     -    primitive -- \"--reflink\" transparently falls back to an ordinary\n     -    checkout, so the worst case is no slower than today rather than a\n     -    byte-for-byte copy of the source tree. The directory walk skips the\n     -    new worktree itself when it lives inside the source one, and preserves\n     -    symlinks and modes.\n     +    A new reflink_file() helper in copy.c clones every regular file. There\n     +    is no size cutoff.\n     +\n     +    On Linux it uses the FICLONE ioctl. That is the primitive btrfs, XFS\n     +    and bcachefs implement, and the one overlayfs forwards when the lower\n     +    filesystem can clone. This path has been tested on btrfs.\n     +\n     +    On macOS it uses clonefile(), the APFS primitive. That path is\n     +    implemented and has not been run here.\n     +\n     +    On Windows it uses ReFS block cloning,\n     +    FSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does. The destination is\n     +    sized to the source, extents are cloned in chunks of at most 1GiB, and\n     +    the tail is rounded up to a cluster (64K, then 4K) and cloned; Windows\n     +    ignores the range past EOF. The tail is not byte-copied, and small\n     +    files are not skipped. That path is implemented and has not been run\n     +    on ReFS. A volume that rejects the control code, including NTFS, fails\n     +    the probe.\n     +\n     +    Anywhere else there is no reflink primitive. Support is probed up front\n     +    by cloning a one-byte file, and where that fails \"--reflink\" falls back\n     +    to an ordinary checkout instead of byte-copying the source tree. The\n     +    directory walk skips the new worktree itself when it lives inside the\n     +    source one, and preserves symlinks and modes.\n     +\n     +    Uncommitted changes in the source do not leak into the new worktree.\n     +    After reflinking the source's files we copy its index and run\n     +    \"update-index --refresh\" before \"reset --hard\": because every reflinked\n     +    file is a fresh inode, the cached stat never matches, so the refresh is\n     +    forced to re-validate by content rather than by stat. A tracked path is\n     +    therefore only left sharing extents when its content equals the indexed\n     +    object; any path whose content differs from <commit-ish> -- which\n     +    includes every uncommitted modification in the source -- is rewritten\n     +    by the reset. The new worktree is thus always a faithful checkout of\n     +    <commit-ish> for tracked paths, and only untracked files are carried\n     +    over.\n      \n          The behavior can be made the default with the worktree.reflink\n          configuration (\"true\", \"false\" or \"auto\", the last suppressing the\n          unsupported-filesystem warning), and turned off per-invocation with\n          --no-reflink. A configured default degrades quietly in modes that\n          cannot reflink (--orphan, --no-checkout) instead of erroring, so\n     -    enabling it never breaks those commands. The checkout step continues\n     -    to honor checkout.workers, so parallel checkout composes with\n     -    --reflink for the paths that do need rewriting.\n     +    enabling it never breaks those commands. The checkout step continues to\n     +    honor checkout.workers, so parallel checkout composes with --reflink for\n     +    the paths that do need rewriting.\n     +\n     +    To check out many worktrees at the same commit safely, give each its\n     +    own ref (or a detached HEAD) rather than sharing one branch; a\n     +    git-worktree(1) example shows the one-shot \"update-ref\" transaction\n     +    that pairs with --reflink.\n      \n          Signed-off-by: Jason Newton <nevion@gmail.com>\n      \n     @@ Documentation/git-worktree.adoc: To remove a locked worktree, specify `--force`\n      +\tworktrees from the same base. `--no-reflink` forces an ordinary\n      +\tcheckout, overriding the `worktree.reflink` configuration.\n      ++\n     -+Reflinks require a copy-on-write filesystem (for example btrfs, XFS,\n     -+bcachefs or ZFS on Linux, or APFS on macOS). On filesystems or platforms\n     -+that do not support reflinks, `--reflink` transparently falls back to an\n     -+ordinary checkout. Because the source worktree's untracked and ignored\n     -+files are cloned as well, only use `--reflink` when that is acceptable.\n     ++Reflinks require a copy-on-write filesystem: for example btrfs, XFS,\n     ++bcachefs or ZFS on Linux (and overlayfs on top of one of these, as used by\n     ++containers), APFS on macOS, or ReFS on Windows. On a filesystem that does\n     ++not support reflinks, `--reflink` transparently falls back to an ordinary\n     ++checkout. Because the source worktree's untracked and ignored files are\n     ++cloned as well, only use `--reflink` when that is acceptable.\n      ++\n      +This option cannot be combined with `--no-checkout` or `--orphan`. It can\n      +be enabled by default with the `worktree.reflink` configuration; see\n     @@ Documentation/git-worktree.adoc: To remove a locked worktree, specify `--force`\n       `--guess-remote`::\n       `--no-guess-remote`::\n       \tWith `worktree add <path>`, without _<commit-ish>_, instead\n     +@@ Documentation/git-worktree.adoc: $ popd\n     + $ git worktree remove ../temp\n     + ------------\n     + \n     ++To run several independent worktrees from the same starting commit -- for\n     ++example a pool of automated agents -- give each one its own branch rather than\n     ++sharing a single branch between them. A shared branch is unsafe here: if one\n     ++worktree commits and another then commits from its now-stale index, the second\n     ++commit silently drops the first one's changes. Create the branches in a single\n     ++ref transaction and check each out in its own (optionally reflinked) worktree:\n     ++\n     ++------------\n     ++$ oid=$(git rev-parse HEAD)\n     ++$ printf 'create refs/heads/agent-%s %s\\n' 1 \"$oid\" 2 \"$oid\" 3 \"$oid\" |\n     ++\tgit update-ref --stdin\n     ++$ for n in 1 2 3; do git worktree add --reflink ../agent-$n agent-$n; done\n     ++------------\n     ++\n     ++The single linkgit:git-update-ref[1] transaction is cheap and is especially\n     ++efficient with the `reftable` backend. If a worktree does not need to advance a\n     ++branch at all, use a detached `HEAD` (`git worktree add --detach`) instead.\n     ++\n     + CONFIGURATION\n     + -------------\n     + \n      \n       ## builtin/worktree.c ##\n      @@\n     @@ builtin/worktree.c: worktree_copy_cleanup:\n       \n      +/*\n      + * Probe whether the filesystem backing \"dir\" supports reflinks. We do this\n     -+ * once up front so that, on filesystems without copy-on-write support (or on\n     -+ * platforms such as Windows that lack a reflink primitive entirely), we can\n     ++ * once up front so that, on filesystems without copy-on-write support (and on\n     ++ * platforms that lack a reflink primitive entirely), we can\n      + * fall back to a normal checkout instead of byte-copying the whole source\n      + * working tree -- which would include untracked files and be slower than the\n      + * checkout we are trying to avoid.\n     @@ builtin/worktree.c: worktree_copy_cleanup:\n      +\tif (fd >= 0) {\n      +\t\twrite_in_full(fd, \"x\", 1);\n      +\t\tclose(fd);\n     -+\t\tif (!reflink_file(dst.buf, src.buf, 0600))\n     ++\t\tif (!reflink_file(the_repository, dst.buf, src.buf, 0600))\n      +\t\t\tok = 1;\n      +\t\tunlink(dst.buf);\n      +\t}\n     @@ builtin/worktree.c: worktree_copy_cleanup:\n      + */\n      +static int reflink_or_copy(const char *dst, const char *src, int mode)\n      +{\n     -+\tif (!reflink_file(dst, src, mode))\n     ++\tif (!reflink_file(the_repository, dst, src, mode))\n      +\t\treturn 0;\n     -+\treturn copy_file(dst, src, mode);\n     ++\treturn copy_file(the_repository, dst, src, mode);\n      +}\n      +\n      +/*\n     @@ copy.c\n      +#elif defined(__APPLE__)\n      +#include <sys/attr.h>\n      +#include <sys/clonefile.h>\n     ++#elif defined(GIT_WINDOWS_NATIVE)\n     ++#include <winioctl.h>\n     ++/*\n     ++ * Block cloning on ReFS uses FSCTL_DUPLICATE_EXTENTS_TO_FILE. Older Windows\n     ++ * SDK headers may lack the control code and its payload struct, so define\n     ++ * them ourselves when missing (the values are part of the stable Win32 API).\n     ++ */\n     ++#ifndef FSCTL_DUPLICATE_EXTENTS_TO_FILE\n     ++#define FSCTL_DUPLICATE_EXTENTS_TO_FILE \\\n     ++\tCTL_CODE(FILE_DEVICE_FILE_SYSTEM, 209, METHOD_BUFFERED, FILE_WRITE_DATA)\n     ++typedef struct _DUPLICATE_EXTENTS_DATA {\n     ++\tHANDLE FileHandle;\n     ++\tLARGE_INTEGER SourceFileOffset;\n     ++\tLARGE_INTEGER TargetFileOffset;\n     ++\tLARGE_INTEGER ByteCount;\n     ++} DUPLICATE_EXTENTS_DATA, *PDUPLICATE_EXTENTS_DATA;\n     ++#endif\n      +#endif\n      +\n       int copy_fd(int ifd, int ofd)\n       {\n       \twhile (1) {\n     -@@ copy.c: int copy_file_with_time(const char *dst, const char *src, int mode)\n     +@@ copy.c: int copy_file_with_time(struct repository *repo,\n       \t\treturn copy_times(dst, src);\n       \treturn status;\n       }\n      +\n     -+int reflink_file(const char *dst, const char *src, int mode)\n     ++#ifdef GIT_WINDOWS_NATIVE\n     ++/*\n     ++ * Clone [offset, offset+count) of \"src\" onto \"dst\" via ReFS block cloning.\n     ++ * \"count\" is rounded up to a cluster boundary by the caller; a range that\n     ++ * runs past the source's end of file is harmless and ignored by Windows.\n     ++ */\n     ++static int clone_extent_windows(HANDLE dst, HANDLE src,\n     ++\t\t\t\tuint64_t offset, uint64_t count)\n     ++{\n     ++\tDUPLICATE_EXTENTS_DATA dup;\n     ++\tDWORD bytes;\n     ++\n     ++\tdup.FileHandle = src;\n     ++\tdup.SourceFileOffset.QuadPart = offset;\n     ++\tdup.TargetFileOffset.QuadPart = offset;\n     ++\tdup.ByteCount.QuadPart = count;\n     ++\tif (!DeviceIoControl(dst, FSCTL_DUPLICATE_EXTENTS_TO_FILE,\n     ++\t\t\t     &dup, sizeof(dup), NULL, 0, &bytes, NULL))\n     ++\t\treturn -1;\n     ++\treturn 0;\n     ++}\n     ++#endif\n     ++\n     ++int reflink_file(struct repository *repo,\n     ++\t\t const char *dst, const char *src, int mode)\n      +{\n      +#if defined(__APPLE__)\n      +\t/*\n     @@ copy.c: int copy_file_with_time(const char *dst, const char *src, int mode)\n      +\t(void)mode;\n      +\tif (clonefile(src, dst, 0) < 0)\n      +\t\treturn -1;\n     -+\tif (adjust_shared_perm(the_repository, dst))\n     ++\tif (adjust_shared_perm(repo, dst))\n      +\t\treturn -1;\n      +\treturn 0;\n      +#elif defined(__linux__)\n     @@ copy.c: int copy_file_with_time(const char *dst, const char *src, int mode)\n      +\t}\n      +\tif (close(fdo) != 0)\n      +\t\treturn -1;\n     -+\tif (adjust_shared_perm(the_repository, dst))\n     ++\tif (adjust_shared_perm(repo, dst))\n     ++\t\treturn -1;\n     ++\treturn 0;\n     ++#elif defined(GIT_WINDOWS_NATIVE)\n     ++\t/*\n     ++\t * ReFS supports copy-on-write block cloning via\n     ++\t * FSCTL_DUPLICATE_EXTENTS_TO_FILE, the same mechanism Git LFS uses.\n     ++\t * Cloned ranges must start and end on a cluster boundary (ReFS uses\n     ++\t * 64K or 4K clusters) and span less than 4GiB, so clone in <=1GiB\n     ++\t * chunks and round the final chunk up to a cluster; the destination is\n     ++\t * sized to the source's exact length and an over-long final range past\n     ++\t * the source's EOF is ignored.\n     ++\t */\n     ++\tconst uint64_t GiB = (uint64_t)1 << 30;\n     ++\tconst uint64_t clusters[] = { 64 * 1024, 4 * 1024 };\n     ++\tint fdi, fdo, ret = -1;\n     ++\tHANDLE hi, ho;\n     ++\tLARGE_INTEGER size;\n     ++\tuint64_t off;\n     ++\tsize_t i;\n     ++\n     ++\tmode = (mode & 0111) ? 0777 : 0666;\n     ++\tif ((fdi = open(src, O_RDONLY | O_BINARY)) < 0)\n     ++\t\treturn -1;\n     ++\tif ((fdo = open(dst, O_RDWR | O_CREAT | O_EXCL | O_BINARY, mode)) < 0) {\n     ++\t\tint saved = errno;\n     ++\t\tclose(fdi);\n     ++\t\terrno = saved;\n     ++\t\treturn -1;\n     ++\t}\n     ++\thi = (HANDLE)_get_osfhandle(fdi);\n     ++\tho = (HANDLE)_get_osfhandle(fdo);\n     ++\tif (hi == INVALID_HANDLE_VALUE || ho == INVALID_HANDLE_VALUE ||\n     ++\t    !GetFileSizeEx(hi, &size)) {\n     ++\t\terrno = EINVAL;\n     ++\t\tgoto cleanup;\n     ++\t}\n     ++\n     ++\t/* the destination must be the source's exact size before cloning */\n     ++\tif (!SetFilePointerEx(ho, size, NULL, FILE_BEGIN) || !SetEndOfFile(ho)) {\n     ++\t\terrno = EIO;\n     ++\t\tgoto cleanup;\n     ++\t}\n     ++\n     ++\tret = 0;\n     ++\t/* clone whole 1GiB regions (already cluster aligned) */\n     ++\tfor (off = 0; (uint64_t)size.QuadPart > off &&\n     ++\t\t      (uint64_t)size.QuadPart - off > GiB; off += GiB) {\n     ++\t\tif (clone_extent_windows(ho, hi, off, GiB)) {\n     ++\t\t\terrno = ENOSYS;\n     ++\t\t\tret = -1;\n     ++\t\t\tgoto cleanup;\n     ++\t\t}\n     ++\t}\n     ++\t/* clone the tail, rounding its length up to a cluster (64K then 4K) */\n     ++\tif (!ret && (uint64_t)size.QuadPart > off) {\n     ++\t\tuint64_t rem = (uint64_t)size.QuadPart - off;\n     ++\n     ++\t\tret = -1;\n     ++\t\tfor (i = 0; i < ARRAY_SIZE(clusters); i++) {\n     ++\t\t\tuint64_t count = (rem + clusters[i] - 1) &\n     ++\t\t\t\t\t ~(clusters[i] - 1);\n     ++\t\t\tif (!clone_extent_windows(ho, hi, off, count)) {\n     ++\t\t\t\tret = 0;\n     ++\t\t\t\tbreak;\n     ++\t\t\t}\n     ++\t\t}\n     ++\t\tif (ret)\n     ++\t\t\terrno = ENOSYS;\t/* not a CoW volume */\n     ++\t}\n     ++\n     ++cleanup:\n     ++\tclose(fdi);\n     ++\tif (close(fdo) && !ret) {\n     ++\t\terrno = EIO;\n     ++\t\tret = -1;\n     ++\t}\n     ++\tif (ret) {\n     ++\t\tint saved = errno;\n     ++\t\tunlink(dst);\n     ++\t\terrno = saved;\n     ++\t\treturn -1;\n     ++\t}\n     ++\tif (adjust_shared_perm(repo, dst))\n      +\t\treturn -1;\n      +\treturn 0;\n      +#else\n     -+\t/* No reflink support on this platform (e.g. Windows). */\n     ++\t/* No reflink primitive on this platform. */\n     ++\t(void)repo;\n      +\t(void)dst;\n      +\t(void)src;\n      +\t(void)mode;\n     @@ copy.c: int copy_file_with_time(const char *dst, const char *src, int mode)\n      +}\n      \n       ## copy.h ##\n     -@@ copy.h: int copy_fd(int ifd, int ofd);\n     - int copy_file(const char *dst, const char *src, int mode);\n     - int copy_file_with_time(const char *dst, const char *src, int mode);\n     +@@ copy.h: int copy_file(struct repository *repo,\n     + int copy_file_with_time(struct repository *repo,\n     + \t\t\tconst char *dst, const char *src, int mode);\n       \n      +/*\n      + * Create \"dst\" as a copy-on-write (reflink) clone of the regular file\n     @@ copy.h: int copy_fd(int ifd, int ofd);\n      + * ENOSYS (or the underlying error). Callers are expected to fall back to\n      + * copy_file() in that case. Returns 0 on success.\n      + */\n     -+int reflink_file(const char *dst, const char *src, int mode);\n     ++int reflink_file(struct repository *repo,\n     ++\t\t const char *dst, const char *src, int mode);\n      +\n       #endif /* COPY_H */\n      \n     @@ t/t2400-worktree-add.sh: test_expect_success 'relative worktree sets extension c\n      +\t\techo artifact >expect &&\n      +\t\ttest_cmp expect wt/untracked.bin &&\n      +\t\tgit -C wt status --porcelain >status &&\n     -+\t\tgrep \"?? untracked.bin\" status\n     ++\t\ttest_grep \"?? untracked.bin\" status\n      +\t)\n      +'\n      +\n 2:  97f0fdad9b < -:  ---------- worktree: allow sharing a checked-out branch across worktrees\n -:  ---------- > 2:  6e2acdc5e2 worktree: reap ephemeral branches created by \"worktree add\"\n\n-- \ngitgitgadget\n\n"},{"id":"555575","messageId":"83841020f43f9f8989371117075ebf089888d619.1792512249.git.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.v2.git.git.1792512249.gitgitgadget@gmail.com","subject":"[PATCH v2 1/2] worktree: add --reflink for copy-on-write worktree creation","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-20T16:04:08Z","receivedAt":"2026-10-20T16:04:08Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"From: Jason Newton <nevion@gmail.com>\n\nCreating many worktrees from the same base -- for example to run a\nfleet of automated agents in parallel -- is expensive today: every\n\"git worktree add\" materializes the entire working tree by writing\neach tracked file out from the object store. The objects are shared\nvia the common directory, but the working tree is not: N worktrees\nmean N full checkouts on disk and N times the file I/O.\n\nAdd a \"--reflink\" option that, on a copy-on-write filesystem, populates\nthe new worktree by reflinking the current worktree's files and index\ninstead. The subsequent \"git reset --hard\" then only rewrites the\npaths that actually differ between the current worktree and\n<commit-ish>; everything else (including untracked files such as build\noutputs) keeps sharing storage with the source until modified.\n\nA new reflink_file() helper in copy.c clones every regular file. There\nis no size cutoff.\n\nOn Linux it uses the FICLONE ioctl. That is the primitive btrfs, XFS\nand bcachefs implement, and the one overlayfs forwards when the lower\nfilesystem can clone. This path has been tested on btrfs.\n\nOn macOS it uses clonefile(), the APFS primitive. That path is\nimplemented and has not been run here.\n\nOn Windows it uses ReFS block cloning,\nFSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does. The destination is\nsized to the source, extents are cloned in chunks of at most 1GiB, and\nthe tail is rounded up to a cluster (64K, then 4K) and cloned; Windows\nignores the range past EOF. The tail is not byte-copied, and small\nfiles are not skipped. That path is implemented and has not been run\non ReFS. A volume that rejects the control code, including NTFS, fails\nthe probe.\n\nAnywhere else there is no reflink primitive. Support is probed up front\nby cloning a one-byte file, and where that fails \"--reflink\" falls back\nto an ordinary checkout instead of byte-copying the source tree. The\ndirectory walk skips the new worktree itself when it lives inside the\nsource one, and preserves symlinks and modes.\n\nUncommitted changes in the source do not leak into the new worktree.\nAfter reflinking the source's files we copy its index and run\n\"update-index --refresh\" before \"reset --hard\": because every reflinked\nfile is a fresh inode, the cached stat never matches, so the refresh is\nforced to re-validate by content rather than by stat. A tracked path is\ntherefore only left sharing extents when its content equals the indexed\nobject; any path whose content differs from <commit-ish> -- which\nincludes every uncommitted modification in the source -- is rewritten\nby the reset. The new worktree is thus always a faithful checkout of\n<commit-ish> for tracked paths, and only untracked files are carried\nover.\n\nThe behavior can be made the default with the worktree.reflink\nconfiguration (\"true\", \"false\" or \"auto\", the last suppressing the\nunsupported-filesystem warning), and turned off per-invocation with\n--no-reflink. A configured default degrades quietly in modes that\ncannot reflink (--orphan, --no-checkout) instead of erroring, so\nenabling it never breaks those commands. The checkout step continues to\nhonor checkout.workers, so parallel checkout composes with --reflink for\nthe paths that do need rewriting.\n\nTo check out many worktrees at the same commit safely, give each its\nown ref (or a detached HEAD) rather than sharing one branch; a\ngit-worktree(1) example shows the one-shot \"update-ref\" transaction\nthat pairs with --reflink.\n\nSigned-off-by: Jason Newton <nevion@gmail.com>\n---\n Documentation/config/worktree.adoc |  10 ++\n Documentation/git-worktree.adoc    |  49 ++++++-\n builtin/worktree.c                 | 227 ++++++++++++++++++++++++++++-\n copy.c                             | 190 ++++++++++++++++++++++++\n copy.h                             |  14 ++\n t/t2400-worktree-add.sh            |  88 +++++++++++\n 6 files changed, 576 insertions(+), 2 deletions(-)\n\ndiff --git a/Documentation/config/worktree.adoc b/Documentation/config/worktree.adoc\nindex 0930183b91..aa849c08d2 100644\n--- a/Documentation/config/worktree.adoc\n+++ b/Documentation/config/worktree.adoc\n@@ -18,3 +18,13 @@\n Note that setting `worktree.useRelativePaths` to \"`true`\" implies enabling the\n `extensions.relativeWorktrees` config (see linkgit:git-config[1]),\n thus making it incompatible with older versions of Git.\n+\n+`worktree.reflink`::\n+\tControls whether `git worktree add` populates new worktrees with\n+\tcopy-on-write (reflink) clones, as if `--reflink` had been given\n+\t(see linkgit:git-worktree[1]). May be set to \"`true`\", \"`false`\"\n+\t(the default), or \"`auto`\". With \"`true`\", a filesystem that does\n+\tnot support reflinks produces a warning before falling back to an\n+\tordinary checkout; with \"`auto`\", the fallback is silent. An\n+\texplicit `--reflink` or `--no-reflink` on the command line\n+\toverrides this setting.\ndiff --git a/Documentation/git-worktree.adoc b/Documentation/git-worktree.adoc\nindex e6e77252ab..4264ee753a 100644\n--- a/Documentation/git-worktree.adoc\n+++ b/Documentation/git-worktree.adoc\n@@ -10,7 +10,7 @@ SYNOPSIS\n --------\n [synopsis]\n git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n-\t\t [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]\n+\t\t [--orphan] [--reflink] [(-b | -B) <new-branch>] <path> [<commit-ish>]\n git worktree list [-v | --porcelain [-z]]\n git worktree lock [--reason <string>] <worktree>\n git worktree move <worktree> <new-path>\n@@ -213,6 +213,35 @@ To remove a locked worktree, specify `--force` twice.\n \tsuch as configuring sparse-checkout. See \"Sparse checkout\"\n \tin linkgit:git-read-tree[1].\n \n+`--reflink`::\n+`--no-reflink`::\n+\tPopulate the new worktree by creating copy-on-write (reflink)\n+\tclones of the current worktree's files and index instead of\n+\twriting every file out from the object store. The checkout that\n+\tfollows then only has to rewrite the paths that actually differ\n+\tbetween the current worktree and _<commit-ish>_; everything else\n+\t(including untracked files such as build outputs) keeps sharing\n+\tstorage with the source worktree until modified. This makes\n+\t`add` much faster and far cheaper on disk when creating many\n+\tworktrees from the same base. `--no-reflink` forces an ordinary\n+\tcheckout, overriding the `worktree.reflink` configuration.\n++\n+Reflinks require a copy-on-write filesystem: for example btrfs, XFS,\n+bcachefs or ZFS on Linux (and overlayfs on top of one of these, as used by\n+containers), APFS on macOS, or ReFS on Windows. On a filesystem that does\n+not support reflinks, `--reflink` transparently falls back to an ordinary\n+checkout. Because the source worktree's untracked and ignored files are\n+cloned as well, only use `--reflink` when that is acceptable.\n++\n+This option cannot be combined with `--no-checkout` or `--orphan`. It can\n+be enabled by default with the `worktree.reflink` configuration; see\n+linkgit:git-config[1].\n++\n+The checkout that populates a new worktree also honors the\n+`checkout.workers` configuration (see linkgit:git-config[1]), so setting it\n+parallelizes the file writes and can further speed up `add`, with or\n+without `--reflink`.\n+\n `--guess-remote`::\n `--no-guess-remote`::\n \tWith `worktree add <path>`, without _<commit-ish>_, instead\n@@ -531,6 +560,24 @@ $ popd\n $ git worktree remove ../temp\n ------------\n \n+To run several independent worktrees from the same starting commit -- for\n+example a pool of automated agents -- give each one its own branch rather than\n+sharing a single branch between them. A shared branch is unsafe here: if one\n+worktree commits and another then commits from its now-stale index, the second\n+commit silently drops the first one's changes. Create the branches in a single\n+ref transaction and check each out in its own (optionally reflinked) worktree:\n+\n+------------\n+$ oid=$(git rev-parse HEAD)\n+$ printf 'create refs/heads/agent-%s %s\\n' 1 \"$oid\" 2 \"$oid\" 3 \"$oid\" |\n+\tgit update-ref --stdin\n+$ for n in 1 2 3; do git worktree add --reflink ../agent-$n agent-$n; done\n+------------\n+\n+The single linkgit:git-update-ref[1] transaction is cheap and is especially\n+efficient with the `reftable` backend. If a worktree does not need to advance a\n+branch at all, use a detached `HEAD` (`git worktree add --detach`) instead.\n+\n CONFIGURATION\n -------------\n \ndiff --git a/builtin/worktree.c b/builtin/worktree.c\nindex 77ecd0f71f..9d4b51305e 100644\n--- a/builtin/worktree.c\n+++ b/builtin/worktree.c\n@@ -30,7 +30,7 @@\n \n #define BUILTIN_WORKTREE_ADD_USAGE \\\n \tN_(\"git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\\n\" \\\n-\t   \"                 [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]\")\n+\t   \"                 [--orphan] [--reflink] [(-b | -B) <new-branch>] <path> [<commit-ish>]\")\n \n #define BUILTIN_WORKTREE_LIST_USAGE \\\n \tN_(\"git worktree list [-v | --porcelain [-z]]\")\n@@ -47,6 +47,11 @@\n #define BUILTIN_WORKTREE_UNLOCK_USAGE \\\n \tN_(\"git worktree unlock <worktree>\")\n \n+/* values for add_opts.reflink and the worktree.reflink config */\n+#define REFLINK_OFF\t0\n+#define REFLINK_ON\t1\t/* warn and fall back if unsupported */\n+#define REFLINK_AUTO\t2\t/* silently fall back if unsupported */\n+\n #define WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT \\\n \t_(\"No possible source branch, inferring '--orphan'\")\n \n@@ -123,6 +128,7 @@ struct add_opts {\n \tint checkout;\n \tint orphan;\n \tint relative_paths;\n+\tint reflink;\n \tconst char *keep_locked;\n };\n \n@@ -130,6 +136,7 @@ static int show_only;\n static int verbose;\n static int guess_remote;\n static int use_relative_paths;\n+static int reflink_config = REFLINK_OFF;\n static timestamp_t expire;\n \n static int git_worktree_config(const char *var, const char *value,\n@@ -141,6 +148,13 @@ static int git_worktree_config(const char *var, const char *value,\n \t} else if (!strcmp(var, \"worktree.userelativepaths\")) {\n \t\tuse_relative_paths = git_config_bool(var, value);\n \t\treturn 0;\n+\t} else if (!strcmp(var, \"worktree.reflink\")) {\n+\t\tif (value && !strcmp(value, \"auto\"))\n+\t\t\treflink_config = REFLINK_AUTO;\n+\t\telse\n+\t\t\treflink_config = git_config_bool(var, value) ?\n+\t\t\t\tREFLINK_ON : REFLINK_OFF;\n+\t\treturn 0;\n \t}\n \n \treturn git_default_config(var, value, ctx, cb);\n@@ -394,6 +408,182 @@ worktree_copy_cleanup:\n \tfree(to_file);\n }\n \n+/*\n+ * Probe whether the filesystem backing \"dir\" supports reflinks. We do this\n+ * once up front so that, on filesystems without copy-on-write support (and on\n+ * platforms that lack a reflink primitive entirely), we can\n+ * fall back to a normal checkout instead of byte-copying the whole source\n+ * working tree -- which would include untracked files and be slower than the\n+ * checkout we are trying to avoid.\n+ */\n+static int reflink_supported(const char *dir)\n+{\n+\tstruct strbuf src = STRBUF_INIT, dst = STRBUF_INIT;\n+\tint fd, ok = 0;\n+\n+\tstrbuf_addf(&src, \"%s/.git-reflink-probe-src\", dir);\n+\tstrbuf_addf(&dst, \"%s/.git-reflink-probe-dst\", dir);\n+\n+\tfd = open(src.buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);\n+\tif (fd >= 0) {\n+\t\twrite_in_full(fd, \"x\", 1);\n+\t\tclose(fd);\n+\t\tif (!reflink_file(the_repository, dst.buf, src.buf, 0600))\n+\t\t\tok = 1;\n+\t\tunlink(dst.buf);\n+\t}\n+\tunlink(src.buf);\n+\n+\tstrbuf_release(&src);\n+\tstrbuf_release(&dst);\n+\treturn ok;\n+}\n+\n+/*\n+ * Reflink a single regular file, falling back to a regular copy when the\n+ * clone fails for this particular file (for example across mount points).\n+ */\n+static int reflink_or_copy(const char *dst, const char *src, int mode)\n+{\n+\tif (!reflink_file(the_repository, dst, src, mode))\n+\t\treturn 0;\n+\treturn copy_file(the_repository, dst, src, mode);\n+}\n+\n+/*\n+ * Recursively copy the working-tree directory \"src\" into \"dst\" using reflinks\n+ * for regular files. Directory entries that resolve to the destination\n+ * worktree itself (identified by skip_dev/skip_ino, which matters when the new\n+ * worktree lives inside the source one) and the top-level \".git\" gitfile are\n+ * skipped.\n+ */\n+static int reflink_tree(const char *src, const char *dst,\n+\t\t\tdev_t skip_dev, ino_t skip_ino, int top)\n+{\n+\tstruct strbuf s = STRBUF_INIT, d = STRBUF_INIT;\n+\tDIR *dir;\n+\tstruct dirent *de;\n+\tint ret = 0;\n+\n+\tdir = opendir(src);\n+\tif (!dir)\n+\t\treturn error_errno(_(\"could not open directory '%s'\"), src);\n+\n+\twhile (!ret && (de = readdir(dir))) {\n+\t\tstruct stat st;\n+\n+\t\tif (is_dot_or_dotdot(de->d_name))\n+\t\t\tcontinue;\n+\t\tif (top && !strcmp(de->d_name, \".git\"))\n+\t\t\tcontinue;\n+\n+\t\tstrbuf_reset(&s);\n+\t\tstrbuf_addf(&s, \"%s/%s\", src, de->d_name);\n+\t\tstrbuf_reset(&d);\n+\t\tstrbuf_addf(&d, \"%s/%s\", dst, de->d_name);\n+\n+\t\tif (lstat(s.buf, &st)) {\n+\t\t\tret = error_errno(_(\"could not stat '%s'\"), s.buf);\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tif (S_ISDIR(st.st_mode)) {\n+\t\t\t/* never recurse into the new worktree itself */\n+\t\t\tif (st.st_dev == skip_dev && st.st_ino == skip_ino)\n+\t\t\t\tcontinue;\n+\t\t\tif (mkdir(d.buf, st.st_mode & 07777) && errno != EEXIST) {\n+\t\t\t\tret = error_errno(_(\"could not create directory '%s'\"), d.buf);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tret = reflink_tree(s.buf, d.buf, skip_dev, skip_ino, 0);\n+\t\t} else if (S_ISLNK(st.st_mode)) {\n+\t\t\tstruct strbuf link = STRBUF_INIT;\n+\n+\t\t\tif (strbuf_readlink(&link, s.buf, st.st_size))\n+\t\t\t\tret = error_errno(_(\"could not read symlink '%s'\"), s.buf);\n+\t\t\telse if (symlink(link.buf, d.buf))\n+\t\t\t\tret = error_errno(_(\"could not create symlink '%s'\"), d.buf);\n+\t\t\tstrbuf_release(&link);\n+\t\t} else if (S_ISREG(st.st_mode)) {\n+\t\t\tif (reflink_or_copy(d.buf, s.buf, st.st_mode))\n+\t\t\t\tret = error_errno(_(\"could not copy '%s' to '%s'\"),\n+\t\t\t\t\t\t  s.buf, d.buf);\n+\t\t}\n+\t\t/* silently skip fifos, sockets and device nodes */\n+\t}\n+\n+\tclosedir(dir);\n+\tstrbuf_release(&s);\n+\tstrbuf_release(&d);\n+\treturn ret;\n+}\n+\n+/*\n+ * Populate the new worktree at \"path\" by reflinking the current worktree's\n+ * files and index. The subsequent \"git reset --hard\" then only has to rewrite\n+ * the paths that actually differ between the source and <commit-ish>, leaving\n+ * everything else sharing storage with the source. Returns 1 when reflinks are\n+ * unavailable so the caller can fall back to a plain checkout.\n+ */\n+static int reflink_worktree(const char *path, const char *wt_git_dir,\n+\t\t\t    const struct add_opts *opts, struct strvec *child_env)\n+{\n+\tconst char *src_wt = the_repository->worktree;\n+\tchar *src_index = NULL, *dst_index = NULL;\n+\tstruct stat dst_st;\n+\tint ret = 0;\n+\n+\tif (!src_wt)\n+\t\treturn error(_(\"--reflink needs a source working tree, but this \"\n+\t\t\t       \"repository does not have one\"));\n+\n+\tif (!reflink_supported(path)) {\n+\t\t/* In auto mode the fallback is expected, so stay quiet. */\n+\t\tif (!opts->quiet && opts->reflink != REFLINK_AUTO)\n+\t\t\twarning(_(\"the filesystem at '%s' does not support reflinks; \"\n+\t\t\t\t  \"falling back to a regular checkout\"), path);\n+\t\treturn 1;\n+\t}\n+\n+\tif (stat(path, &dst_st))\n+\t\treturn error_errno(_(\"could not stat '%s'\"), path);\n+\n+\tif ((ret = reflink_tree(src_wt, path, dst_st.st_dev, dst_st.st_ino, 1)))\n+\t\treturn ret;\n+\n+\t/*\n+\t * Clone the source index so the following reset sees the source's\n+\t * state and only materializes the differences to <commit-ish>.\n+\t */\n+\tsrc_index = repo_git_path(the_repository, \"index\");\n+\tdst_index = xstrfmt(\"%s/index\", wt_git_dir);\n+\tif (!access(src_index, F_OK) &&\n+\t    reflink_or_copy(dst_index, src_index, 0666)) {\n+\t\tret = error_errno(_(\"could not copy index to '%s'\"), dst_index);\n+\t\tgoto out;\n+\t}\n+\n+\t/*\n+\t * The cloned index still carries the source files' stat information.\n+\t * Refresh it against the freshly reflinked files so that \"git reset\"\n+\t * recognizes unchanged paths as up to date and leaves them sharing\n+\t * storage instead of rewriting (and thus un-sharing) them.\n+\t */\n+\tif (!access(dst_index, F_OK)) {\n+\t\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\t\tcp.git_cmd = 1;\n+\t\tstrvec_pushl(&cp.args, \"update-index\", \"-q\", \"--refresh\", NULL);\n+\t\tstrvec_pushv(&cp.env, child_env->v);\n+\t\t/* a dirty working tree is not an error here */\n+\t\trun_command(&cp);\n+\t}\n+\n+out:\n+\tfree(src_index);\n+\tfree(dst_index);\n+\treturn ret;\n+}\n+\n static int checkout_worktree(const struct add_opts *opts,\n \t\t\t     struct strvec *child_env)\n {\n@@ -588,6 +778,20 @@ static int add_worktree(const char *path, const char *refname,\n \t    (ret = make_worktree_orphan(refname, opts, &child_env)))\n \t\tgoto done;\n \n+\t/*\n+\t * When --reflink is requested and the filesystem supports it, copy the\n+\t * current worktree (and its index) into the new one using copy-on-write\n+\t * clones. checkout_worktree() then only rewrites the paths that differ\n+\t * from <commit-ish>. reflink_worktree() returns 1 when reflinks are not\n+\t * available, in which case we just do an ordinary checkout below.\n+\t */\n+\tif (opts->checkout && opts->reflink) {\n+\t\tret = reflink_worktree(path, sb_repo.buf, opts, &child_env);\n+\t\tif (ret < 0)\n+\t\t\tgoto done;\n+\t\tret = 0;\n+\t}\n+\n \tif (opts->checkout &&\n \t    (ret = checkout_worktree(opts, &child_env)))\n \t\tgoto done;\n@@ -832,6 +1036,7 @@ static int add(int ac, const char **av, const char *prefix,\n \tconst char *lock_reason = NULL;\n \tint keep_locked = 0;\n \tint used_new_branch_options;\n+\tint reflink_cli = -1;\n \tstruct option options[] = {\n \t\tOPT__FORCE(&opts.force,\n \t\t\t   N_(\"checkout <branch> even if already checked out in other worktree\"),\n@@ -854,6 +1059,8 @@ static int add(int ac, const char **av, const char *prefix,\n \t\t\t N_(\"try to match the new branch name with a remote-tracking branch\")),\n \t\tOPT_BOOL(0, \"relative-paths\", &opts.relative_paths,\n \t\t\t N_(\"use relative paths for worktrees\")),\n+\t\tOPT_BOOL(0, \"reflink\", &reflink_cli,\n+\t\t\t N_(\"populate the worktree using copy-on-write clones when supported\")),\n \t\tOPT_END()\n \t};\n \tint ret;\n@@ -873,6 +1080,24 @@ static int add(int ac, const char **av, const char *prefix,\n \tif (opts.orphan && !opts.checkout)\n \t\tdie(_(\"options '%s' and '%s' cannot be used together\"),\n \t\t    \"--orphan\", \"--no-checkout\");\n+\n+\t/*\n+\t * Resolve whether to reflink: an explicit --reflink/--no-reflink on\n+\t * the command line wins, otherwise fall back to the worktree.reflink\n+\t * configuration (which may select the \"auto\" mode).\n+\t */\n+\topts.reflink = (reflink_cli != -1) ? reflink_cli : reflink_config;\n+\tif (opts.reflink && (opts.orphan || !opts.checkout)) {\n+\t\t/*\n+\t\t * Reflinking is incompatible with these; only complain when it\n+\t\t * was explicitly requested, otherwise quietly do a plain\n+\t\t * checkout so a configured default does not break these modes.\n+\t\t */\n+\t\tif (reflink_cli == REFLINK_ON)\n+\t\t\tdie(_(\"options '%s' and '%s' cannot be used together\"),\n+\t\t\t    \"--reflink\", opts.orphan ? \"--orphan\" : \"--no-checkout\");\n+\t\topts.reflink = REFLINK_OFF;\n+\t}\n \tif (opts.orphan && ac == 2)\n \t\tdie(_(\"option '%s' and commit-ish cannot be used together\"),\n \t\t    \"--orphan\");\ndiff --git a/copy.c b/copy.c\nindex 6074132050..e6dfe33f6a 100644\n--- a/copy.c\n+++ b/copy.c\n@@ -5,6 +5,38 @@\n #include \"strbuf.h\"\n #include \"abspath.h\"\n \n+#if defined(__linux__)\n+#include <sys/ioctl.h>\n+/*\n+ * FICLONE lives in <linux/fs.h>, but including that header tends to clash\n+ * with the libc headers git already pulls in, so define it ourselves if it\n+ * is missing. The value is part of the stable kernel uapi.\n+ */\n+#ifndef FICLONE\n+#define FICLONE _IOW(0x94, 9, int)\n+#endif\n+#elif defined(__APPLE__)\n+#include <sys/attr.h>\n+#include <sys/clonefile.h>\n+#elif defined(GIT_WINDOWS_NATIVE)\n+#include <winioctl.h>\n+/*\n+ * Block cloning on ReFS uses FSCTL_DUPLICATE_EXTENTS_TO_FILE. Older Windows\n+ * SDK headers may lack the control code and its payload struct, so define\n+ * them ourselves when missing (the values are part of the stable Win32 API).\n+ */\n+#ifndef FSCTL_DUPLICATE_EXTENTS_TO_FILE\n+#define FSCTL_DUPLICATE_EXTENTS_TO_FILE \\\n+\tCTL_CODE(FILE_DEVICE_FILE_SYSTEM, 209, METHOD_BUFFERED, FILE_WRITE_DATA)\n+typedef struct _DUPLICATE_EXTENTS_DATA {\n+\tHANDLE FileHandle;\n+\tLARGE_INTEGER SourceFileOffset;\n+\tLARGE_INTEGER TargetFileOffset;\n+\tLARGE_INTEGER ByteCount;\n+} DUPLICATE_EXTENTS_DATA, *PDUPLICATE_EXTENTS_DATA;\n+#endif\n+#endif\n+\n int copy_fd(int ifd, int ofd)\n {\n \twhile (1) {\n@@ -72,3 +104,161 @@ int copy_file_with_time(struct repository *repo,\n \t\treturn copy_times(dst, src);\n \treturn status;\n }\n+\n+#ifdef GIT_WINDOWS_NATIVE\n+/*\n+ * Clone [offset, offset+count) of \"src\" onto \"dst\" via ReFS block cloning.\n+ * \"count\" is rounded up to a cluster boundary by the caller; a range that\n+ * runs past the source's end of file is harmless and ignored by Windows.\n+ */\n+static int clone_extent_windows(HANDLE dst, HANDLE src,\n+\t\t\t\tuint64_t offset, uint64_t count)\n+{\n+\tDUPLICATE_EXTENTS_DATA dup;\n+\tDWORD bytes;\n+\n+\tdup.FileHandle = src;\n+\tdup.SourceFileOffset.QuadPart = offset;\n+\tdup.TargetFileOffset.QuadPart = offset;\n+\tdup.ByteCount.QuadPart = count;\n+\tif (!DeviceIoControl(dst, FSCTL_DUPLICATE_EXTENTS_TO_FILE,\n+\t\t\t     &dup, sizeof(dup), NULL, 0, &bytes, NULL))\n+\t\treturn -1;\n+\treturn 0;\n+}\n+#endif\n+\n+int reflink_file(struct repository *repo,\n+\t\t const char *dst, const char *src, int mode)\n+{\n+#if defined(__APPLE__)\n+\t/*\n+\t * clonefile() refuses to operate when the destination exists and\n+\t * copies the source's permissions for us, so \"mode\" is unused here.\n+\t */\n+\t(void)mode;\n+\tif (clonefile(src, dst, 0) < 0)\n+\t\treturn -1;\n+\tif (adjust_shared_perm(repo, dst))\n+\t\treturn -1;\n+\treturn 0;\n+#elif defined(__linux__)\n+\tint fdi, fdo, status;\n+\n+\tmode = (mode & 0111) ? 0777 : 0666;\n+\tif ((fdi = open(src, O_RDONLY)) < 0)\n+\t\treturn -1;\n+\tif ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) {\n+\t\tint saved = errno;\n+\t\tclose(fdi);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\tstatus = ioctl(fdo, FICLONE, fdi);\n+\tclose(fdi);\n+\tif (status < 0) {\n+\t\tint saved = errno;\n+\t\tclose(fdo);\n+\t\t/* we created an empty file above; do not leave it behind */\n+\t\tunlink(dst);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\tif (close(fdo) != 0)\n+\t\treturn -1;\n+\tif (adjust_shared_perm(repo, dst))\n+\t\treturn -1;\n+\treturn 0;\n+#elif defined(GIT_WINDOWS_NATIVE)\n+\t/*\n+\t * ReFS supports copy-on-write block cloning via\n+\t * FSCTL_DUPLICATE_EXTENTS_TO_FILE, the same mechanism Git LFS uses.\n+\t * Cloned ranges must start and end on a cluster boundary (ReFS uses\n+\t * 64K or 4K clusters) and span less than 4GiB, so clone in <=1GiB\n+\t * chunks and round the final chunk up to a cluster; the destination is\n+\t * sized to the source's exact length and an over-long final range past\n+\t * the source's EOF is ignored.\n+\t */\n+\tconst uint64_t GiB = (uint64_t)1 << 30;\n+\tconst uint64_t clusters[] = { 64 * 1024, 4 * 1024 };\n+\tint fdi, fdo, ret = -1;\n+\tHANDLE hi, ho;\n+\tLARGE_INTEGER size;\n+\tuint64_t off;\n+\tsize_t i;\n+\n+\tmode = (mode & 0111) ? 0777 : 0666;\n+\tif ((fdi = open(src, O_RDONLY | O_BINARY)) < 0)\n+\t\treturn -1;\n+\tif ((fdo = open(dst, O_RDWR | O_CREAT | O_EXCL | O_BINARY, mode)) < 0) {\n+\t\tint saved = errno;\n+\t\tclose(fdi);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\thi = (HANDLE)_get_osfhandle(fdi);\n+\tho = (HANDLE)_get_osfhandle(fdo);\n+\tif (hi == INVALID_HANDLE_VALUE || ho == INVALID_HANDLE_VALUE ||\n+\t    !GetFileSizeEx(hi, &size)) {\n+\t\terrno = EINVAL;\n+\t\tgoto cleanup;\n+\t}\n+\n+\t/* the destination must be the source's exact size before cloning */\n+\tif (!SetFilePointerEx(ho, size, NULL, FILE_BEGIN) || !SetEndOfFile(ho)) {\n+\t\terrno = EIO;\n+\t\tgoto cleanup;\n+\t}\n+\n+\tret = 0;\n+\t/* clone whole 1GiB regions (already cluster aligned) */\n+\tfor (off = 0; (uint64_t)size.QuadPart > off &&\n+\t\t      (uint64_t)size.QuadPart - off > GiB; off += GiB) {\n+\t\tif (clone_extent_windows(ho, hi, off, GiB)) {\n+\t\t\terrno = ENOSYS;\n+\t\t\tret = -1;\n+\t\t\tgoto cleanup;\n+\t\t}\n+\t}\n+\t/* clone the tail, rounding its length up to a cluster (64K then 4K) */\n+\tif (!ret && (uint64_t)size.QuadPart > off) {\n+\t\tuint64_t rem = (uint64_t)size.QuadPart - off;\n+\n+\t\tret = -1;\n+\t\tfor (i = 0; i < ARRAY_SIZE(clusters); i++) {\n+\t\t\tuint64_t count = (rem + clusters[i] - 1) &\n+\t\t\t\t\t ~(clusters[i] - 1);\n+\t\t\tif (!clone_extent_windows(ho, hi, off, count)) {\n+\t\t\t\tret = 0;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tif (ret)\n+\t\t\terrno = ENOSYS;\t/* not a CoW volume */\n+\t}\n+\n+cleanup:\n+\tclose(fdi);\n+\tif (close(fdo) && !ret) {\n+\t\terrno = EIO;\n+\t\tret = -1;\n+\t}\n+\tif (ret) {\n+\t\tint saved = errno;\n+\t\tunlink(dst);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\tif (adjust_shared_perm(repo, dst))\n+\t\treturn -1;\n+\treturn 0;\n+#else\n+\t/* No reflink primitive on this platform. */\n+\t(void)repo;\n+\t(void)dst;\n+\t(void)src;\n+\t(void)mode;\n+\terrno = ENOSYS;\n+\treturn -1;\n+#endif\n+}\ndiff --git a/copy.h b/copy.h\nindex 1059b118d6..b9168a24f1 100644\n--- a/copy.h\n+++ b/copy.h\n@@ -11,4 +11,18 @@ int copy_file(struct repository *repo,\n int copy_file_with_time(struct repository *repo,\n \t\t\tconst char *dst, const char *src, int mode);\n \n+/*\n+ * Create \"dst\" as a copy-on-write (reflink) clone of the regular file\n+ * \"src\", so that the two files share their data blocks until one of\n+ * them is modified. \"dst\" must not already exist.\n+ *\n+ * This only succeeds on filesystems that support block cloning (e.g.\n+ * btrfs, XFS or bcachefs on Linux, APFS on macOS). When the platform or\n+ * filesystem does not support reflinks, -1 is returned with errno set to\n+ * ENOSYS (or the underlying error). Callers are expected to fall back to\n+ * copy_file() in that case. Returns 0 on success.\n+ */\n+int reflink_file(struct repository *repo,\n+\t\t const char *dst, const char *src, int mode);\n+\n #endif /* COPY_H */\ndiff --git a/t/t2400-worktree-add.sh b/t/t2400-worktree-add.sh\nindex bdcca97633..4f62360a78 100755\n--- a/t/t2400-worktree-add.sh\n+++ b/t/t2400-worktree-add.sh\n@@ -1288,4 +1288,92 @@ test_expect_success 'relative worktree sets extension config' '\n \ttest_cmp_config -C repo true extensions.relativeworktrees\n '\n \n+test_expect_success '--reflink produces a correct checkout on any filesystem' '\n+\ttest_when_finished \"rm -rf reflinkrepo\" &&\n+\tgit init reflinkrepo &&\n+\t(\n+\t\tcd reflinkrepo &&\n+\t\ttest_commit base file.txt base &&\n+\t\ttest_commit next file.txt next &&\n+\t\tgit worktree add --reflink wt -b reflinkbr base &&\n+\t\techo base >expect &&\n+\t\ttest_cmp expect wt/file.txt &&\n+\t\tgit -C wt status --porcelain >status &&\n+\t\ttest_must_be_empty status\n+\t)\n+'\n+\n+test_expect_success '--reflink rejects incompatible options' '\n+\ttest_must_fail git worktree add --reflink --no-checkout wt-bad HEAD 2>err &&\n+\ttest_grep \"cannot be used together\" err &&\n+\ttest_must_fail git worktree add --reflink --orphan wt-bad2 2>err &&\n+\ttest_grep \"cannot be used together\" err\n+'\n+\n+test_expect_success 'worktree.reflink config drives a correct checkout' '\n+\ttest_when_finished \"rm -rf reflinkcfg\" &&\n+\tgit init reflinkcfg &&\n+\t(\n+\t\tcd reflinkcfg &&\n+\t\ttest_commit cfg file.txt value &&\n+\t\tgit -c worktree.reflink=true worktree add wt HEAD &&\n+\t\techo value >expect &&\n+\t\ttest_cmp expect wt/file.txt\n+\t)\n+'\n+\n+test_expect_success 'worktree.reflink=auto does not break --orphan' '\n+\ttest_when_finished \"rm -rf reflinkorphan\" &&\n+\tgit init reflinkorphan &&\n+\t(\n+\t\tcd reflinkorphan &&\n+\t\ttest_commit base file.txt value &&\n+\t\tgit -c worktree.reflink=auto worktree add --orphan wt &&\n+\t\tgit -C wt symbolic-ref --short HEAD >actual &&\n+\t\techo wt >expect &&\n+\t\ttest_cmp expect actual\n+\t)\n+'\n+\n+test_expect_success '--no-reflink overrides worktree.reflink' '\n+\ttest_when_finished \"rm -rf reflinkoff\" &&\n+\tgit init reflinkoff &&\n+\t(\n+\t\tcd reflinkoff &&\n+\t\ttest_commit base file.txt value &&\n+\t\tgit -c worktree.reflink=true worktree add --no-reflink wt HEAD &&\n+\t\techo value >expect &&\n+\t\ttest_cmp expect wt/file.txt\n+\t)\n+'\n+\n+# Reflinks are only available on copy-on-write filesystems (btrfs, XFS,\n+# bcachefs, APFS, ...). Where they are unavailable, --reflink transparently\n+# falls back to a regular checkout, which the test above already covers.\n+test_lazy_prereq REFLINK '\n+\techo probe >reflink-src &&\n+\tcp --reflink=always reflink-src reflink-dst 2>/dev/null\n+'\n+\n+test_expect_success REFLINK '--reflink carries untracked files and reconciles changes' '\n+\ttest_when_finished \"rm -rf cowrepo\" &&\n+\tgit init cowrepo &&\n+\t(\n+\t\tcd cowrepo &&\n+\t\ttest_commit same same.txt content &&\n+\t\ttest_commit old change.txt old-value &&\n+\t\ttest_commit new change.txt new-value &&\n+\t\techo artifact >untracked.bin &&\n+\t\tgit worktree add --reflink wt -b cowbr old &&\n+\t\techo content >expect &&\n+\t\ttest_cmp expect wt/same.txt &&\n+\t\techo old-value >expect &&\n+\t\ttest_cmp expect wt/change.txt &&\n+\t\techo artifact >expect &&\n+\t\ttest_cmp expect wt/untracked.bin &&\n+\t\tgit -C wt status --porcelain >status &&\n+\t\ttest_grep \"?? untracked.bin\" status\n+\t)\n+'\n+\n test_done\n-- \ngitgitgadget\n\n\n"},{"id":"555576","messageId":"6e2acdc5e2578da4e915fd2ac541a776349fb23e.1792512249.git.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.v2.git.git.1792512249.gitgitgadget@gmail.com","subject":"[PATCH v2 2/2] worktree: reap ephemeral branches created by \"worktree add\"","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-20T16:04:09Z","receivedAt":"2026-10-20T16:04:09Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"From: Jason Newton <nevion@gmail.com>\n\nWhen \"git worktree add <path>\" is given no branch to check out, it\nauto-creates one named after the path. Such a branch exists only to back\nthe new worktree, yet it outlives it: removing the worktree leaves the\nbranch behind, so a fleet of throwaway worktrees fills refs/heads/ with\ndead branches that have to be cleaned up by hand.\n\nTreat an auto-created branch as owned by the worktree. Record it in the\nworktree's administrative directory (worktrees/<id>/owned-branch) at\ncreation time -- the one moment we can know for certain the branch is\nworktree-private, since we are the one that created it. \"git worktree\nremove\" then deletes the owned branch once the worktree is gone and it\nis no longer checked out.\n\nOwnership is recorded only when \"worktree add\" itself creates the branch\nvia DWIM auto-naming; a branch named explicitly with -b/-B, or one that\nalready existed, is never owned and never reaped. Deletion is\nunconditional (even for unmerged commits) because an ephemeral branch is\ndisposable by contract: to keep the work, pass --keep-branch, or anchor\nthe commits with an ordinary branch beforehand -- a normal branch can\npoint at the same commits, after which reaping the ephemeral ref loses\nnothing. \"git branch -m\" updates the marker so ownership follows a\nrename, and the branch stays ephemeral.\n\nThe marker is just another per-worktree administrative file, so older\nversions of Git simply ignore it (they keep the branch on removal, as\ntoday).\n\nSigned-off-by: Jason Newton <nevion@gmail.com>\n---\n Documentation/git-worktree.adoc | 22 ++++++++--\n builtin/branch.c                | 28 +++++++++++++\n builtin/worktree.c              | 74 ++++++++++++++++++++++++++++++++-\n t/t2400-worktree-add.sh         | 55 ++++++++++++++++++++++++\n t/t3200-branch.sh               |  2 +-\n t/t3400-rebase.sh               |  2 +-\n t/t5516-fetch-push.sh           |  2 +-\n 7 files changed, 178 insertions(+), 7 deletions(-)\n\ndiff --git a/Documentation/git-worktree.adoc b/Documentation/git-worktree.adoc\nindex 4264ee753a..99e6e55be4 100644\n--- a/Documentation/git-worktree.adoc\n+++ b/Documentation/git-worktree.adoc\n@@ -15,7 +15,7 @@ git worktree list [-v | --porcelain [-z]]\n git worktree lock [--reason <string>] <worktree>\n git worktree move <worktree> <new-path>\n git worktree prune [-n] [-v] [--expire <expire>]\n-git worktree remove [-f] <worktree>\n+git worktree remove [-f] [--keep-branch] <worktree>\n git worktree repair [<path>...]\n git worktree unlock <worktree>\n \n@@ -40,8 +40,11 @@ In its simplest form, `git worktree add <path>` automatically creates a\n new branch whose name is the final component of _<path>_, which is\n convenient if you plan to work on a new topic. For instance, `git\n worktree add ../hotfix` creates new branch `hotfix` and checks it out at\n-path `../hotfix`. To instead work on an existing branch in a new worktree,\n-use `git worktree add <path> <branch>`. On the other hand, if you just\n+path `../hotfix`. Such an automatically-created branch is _ephemeral_: it\n+is owned by the worktree and is deleted again when the worktree is removed\n+with `git worktree remove` (see that command and `--keep-branch`). To\n+instead work on an existing branch in a new worktree, use\n+`git worktree add <path> <branch>`. On the other hand, if you just\n plan to make some experimental changes or do testing without disturbing\n existing development, it is often convenient to create a 'throwaway'\n worktree not associated with any branch. For instance,\n@@ -145,6 +148,14 @@ Remove a worktree. Only clean worktrees (no untracked files and no\n modification in tracked files) can be removed. Unclean worktrees or ones\n with submodules can be removed with `--force`. The main worktree cannot be\n removed.\n++\n+If the worktree owns an _ephemeral_ branch -- one that `git worktree add`\n+created itself because no branch was named (the auto-naming case above) --\n+that branch is deleted along with the worktree, even if it has unmerged\n+commits, since it was created solely to back this worktree. To keep it, use\n+`--keep-branch`, or anchor the commits with an ordinary branch\n+(`git branch <name>`) beforehand. A branch you named explicitly (`-b`/`-B`)\n+or one that existed before the worktree is never deleted.\n \n `repair [<path>...]`::\n \n@@ -192,6 +203,11 @@ allows the move to proceed; use `--force` twice if the destination is locked.\n `remove` refuses to remove an unclean worktree unless `--force` is used.\n To remove a locked worktree, specify `--force` twice.\n \n+`--keep-branch`::\n+\tWith `remove`, do not delete the worktree's ephemeral (owned) branch;\n+\tkeep it as an ordinary branch. Has no effect on worktrees that do not\n+\town a branch.\n+\n `-b <new-branch>`::\n `-B <new-branch>`::\n \tWith `add`, create a new branch named _<new-branch>_ starting at\ndiff --git a/builtin/branch.c b/builtin/branch.c\nindex a613148fc7..ca2e25df03 100644\n--- a/builtin/branch.c\n+++ b/builtin/branch.c\n@@ -607,6 +607,32 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,\n #define IS_HEAD 1\n #define IS_ORPHAN 2\n \n+/*\n+ * When a branch that a worktree owns (its ephemeral branch, recorded in\n+ * worktrees/<id>/owned-branch) is renamed, update the marker so ownership\n+ * follows the new name -- it stays ephemeral.\n+ */\n+static void rename_owned_branch_markers(struct worktree **worktrees,\n+\t\t\t\t\tconst char *oldref, const char *newref)\n+{\n+\tfor (int i = 0; worktrees[i]; i++) {\n+\t\tstruct strbuf path = STRBUF_INIT, buf = STRBUF_INIT;\n+\n+\t\tif (!worktrees[i]->id)\n+\t\t\tcontinue;\t/* the main worktree keeps no marker */\n+\t\trepo_common_path_append(the_repository, &path,\n+\t\t\t\t\t\"worktrees/%s/owned-branch\",\n+\t\t\t\t\tworktrees[i]->id);\n+\t\tif (strbuf_read_file(&buf, path.buf, 64) > 0) {\n+\t\t\tstrbuf_trim(&buf);\n+\t\t\tif (!strcmp(buf.buf, oldref))\n+\t\t\t\twrite_file(path.buf, \"%s\", newref);\n+\t\t}\n+\t\tstrbuf_release(&path);\n+\t\tstrbuf_release(&buf);\n+\t}\n+}\n+\n static void copy_or_rename_branch(const char *oldname, const char *newname, int copy, int force)\n {\n \tstruct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;\n@@ -675,6 +701,8 @@ static void copy_or_rename_branch(const char *oldname, const char *newname, int\n \tif (!copy && !(oldref_usage & IS_ORPHAN) &&\n \t    refs_rename_ref(get_main_ref_store(the_repository), oldref.buf, newref.buf, logmsg.buf))\n \t\tdie(_(\"branch rename failed\"));\n+\tif (!copy && !(oldref_usage & IS_ORPHAN))\n+\t\trename_owned_branch_markers(worktrees, oldref.buf, newref.buf);\n \tif (copy && refs_copy_existing_ref(get_main_ref_store(the_repository), oldref.buf, newref.buf, logmsg.buf))\n \t\tdie(_(\"branch copy failed\"));\n \ndiff --git a/builtin/worktree.c b/builtin/worktree.c\nindex 9d4b51305e..1059429cbb 100644\n--- a/builtin/worktree.c\n+++ b/builtin/worktree.c\n@@ -41,7 +41,7 @@\n #define BUILTIN_WORKTREE_PRUNE_USAGE \\\n \tN_(\"git worktree prune [-n] [-v] [--expire <expire>]\")\n #define BUILTIN_WORKTREE_REMOVE_USAGE \\\n-\tN_(\"git worktree remove [-f] <worktree>\")\n+\tN_(\"git worktree remove [-f] [--keep-branch] <worktree>\")\n #define BUILTIN_WORKTREE_REPAIR_USAGE \\\n \tN_(\"git worktree repair [<path>...]\")\n #define BUILTIN_WORKTREE_UNLOCK_USAGE \\\n@@ -130,8 +130,34 @@ struct add_opts {\n \tint relative_paths;\n \tint reflink;\n \tconst char *keep_locked;\n+\tconst char *owned_branch;\n };\n \n+/*\n+ * An \"owned\" (ephemeral) branch is one that \"git worktree add\" created itself\n+ * because the user did not name a branch (the DWIM auto-name case). Its\n+ * lifetime is bound to the worktree: it is recorded in the worktree's\n+ * administrative directory at creation and reaped when the worktree is\n+ * removed. A pre-existing branch, or one named explicitly with -b/-B, is never\n+ * owned.\n+ */\n+static char *read_owned_branch(const char *id)\n+{\n+\tstruct strbuf path = STRBUF_INIT, buf = STRBUF_INIT;\n+\tchar *ret = NULL;\n+\n+\trepo_common_path_append(the_repository, &path,\n+\t\t\t\t\"worktrees/%s/owned-branch\", id);\n+\tif (strbuf_read_file(&buf, path.buf, 64) > 0) {\n+\t\tstrbuf_trim(&buf);\n+\t\tif (buf.len)\n+\t\t\tret = strbuf_detach(&buf, NULL);\n+\t}\n+\tstrbuf_release(&path);\n+\tstrbuf_release(&buf);\n+\treturn ret;\n+}\n+\n static int show_only;\n static int verbose;\n static int guess_remote;\n@@ -771,6 +797,16 @@ static int add_worktree(const char *path, const char *refname,\n \tif (the_repository->repository_format_worktree_config)\n \t\tcopy_filtered_worktree_config(sb_repo.buf);\n \n+\t/*\n+\t * Record an owned (ephemeral) branch so that \"git worktree remove\" can\n+\t * reap it. Only DWIM-created branches are owned (see read_owned_branch()).\n+\t */\n+\tif (opts->owned_branch) {\n+\t\tstrbuf_reset(&sb);\n+\t\tstrbuf_addf(&sb, \"%s/owned-branch\", sb_repo.buf);\n+\t\twrite_file(sb.buf, \"refs/heads/%s\", opts->owned_branch);\n+\t}\n+\n \tstrvec_pushf(&child_env, \"%s=%s\", GIT_DIR_ENVIRONMENT, sb_git.buf);\n \tstrvec_pushf(&child_env, \"%s=%s\", GIT_WORK_TREE_ENVIRONMENT, path);\n \n@@ -1148,6 +1184,13 @@ static int add(int ac, const char **av, const char *prefix,\n \t\t\tbranch = branch_to_free = s;\n \t\tnew_branch = new_branch_to_free;\n \n+\t\t/*\n+\t\t * A branch auto-created from the path (the user named no\n+\t\t * branch) is owned by this worktree and reaped on removal.\n+\t\t */\n+\t\tif (new_branch_to_free)\n+\t\t\topts.owned_branch = new_branch_to_free;\n+\n \t\t/* DWIM: Infer --orphan when repo has no refs. */\n \t\topts.orphan = (!s) && dwim_orphan(&opts, !!opt_track, 1);\n \t} else if (ac == 2 && new_branch) {\n@@ -1651,15 +1694,19 @@ static int remove_worktree(int ac, const char **av, const char *prefix,\n \t\t\t   struct repository *repo UNUSED)\n {\n \tint force = 0;\n+\tint keep_branch = 0;\n \tstruct option options[] = {\n \t\tOPT__FORCE(&force,\n \t\t\t N_(\"force removal even if worktree is dirty or locked\"),\n \t\t\t PARSE_OPT_NOCOMPLETE),\n+\t\tOPT_BOOL(0, \"keep-branch\", &keep_branch,\n+\t\t\t N_(\"keep the worktree's owned (ephemeral) branch\")),\n \t\tOPT_END()\n \t};\n \tstruct worktree **worktrees, *wt;\n \tstruct strbuf errmsg = STRBUF_INIT;\n \tconst char *reason = NULL;\n+\tchar *owned = NULL;\n \tint ret = 0;\n \n \tac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);\n@@ -1685,6 +1732,10 @@ static int remove_worktree(int ac, const char **av, const char *prefix,\n \t\t    errmsg.buf);\n \tstrbuf_release(&errmsg);\n \n+\t/* read the owned-branch marker before the admin dir is deleted */\n+\tif (!keep_branch)\n+\t\towned = read_owned_branch(wt->id);\n+\n \tif (file_exists(wt->path)) {\n \t\tif (!force)\n \t\t\tcheck_clean_worktree(wt, av[0]);\n@@ -1698,6 +1749,27 @@ static int remove_worktree(int ac, const char **av, const char *prefix,\n \tret |= delete_git_dir(wt->id);\n \tdelete_worktrees_dir_if_empty();\n \n+\t/*\n+\t * Reap the worktree's owned (ephemeral) branch now that the worktree\n+\t * is gone and the branch is no longer checked out. This is\n+\t * unconditional by design: the branch was created for this worktree\n+\t * and is disposable. To keep the work, anchor it with an ordinary\n+\t * branch (or pass --keep-branch) before removing the worktree.\n+\t */\n+\tif (owned) {\n+\t\tstruct ref_store *refs = get_main_ref_store(the_repository);\n+\t\tif (refs_ref_exists(refs, owned)) {\n+\t\t\tif (refs_delete_ref(refs, NULL, owned, NULL, 0))\n+\t\t\t\tret = error(_(\"failed to reap branch '%s'\"), owned);\n+\t\t\telse {\n+\t\t\t\tconst char *name = owned;\n+\t\t\t\tskip_prefix(owned, \"refs/heads/\", &name);\n+\t\t\t\tfprintf_ln(stderr, _(\"Removed branch '%s'\"), name);\n+\t\t\t}\n+\t\t}\n+\t\tfree(owned);\n+\t}\n+\n \tfree_worktrees(worktrees);\n \treturn ret;\n }\ndiff --git a/t/t2400-worktree-add.sh b/t/t2400-worktree-add.sh\nindex 4f62360a78..d083a871eb 100755\n--- a/t/t2400-worktree-add.sh\n+++ b/t/t2400-worktree-add.sh\n@@ -1376,4 +1376,59 @@ test_expect_success REFLINK '--reflink carries untracked files and reconciles ch\n \t)\n '\n \n+test_expect_success 'ephemeral: DWIM-created branch is owned and reaped on remove' '\n+\ttest_when_finished \"git worktree remove -f eph || :; git branch -D eph 2>/dev/null || :\" &&\n+\tgit worktree add eph &&\n+\techo refs/heads/eph >expect &&\n+\ttest_cmp expect .git/worktrees/eph/owned-branch &&\n+\tgit rev-parse --verify refs/heads/eph &&\n+\tgit worktree remove eph &&\n+\ttest_must_fail git rev-parse --verify --quiet refs/heads/eph\n+'\n+\n+test_expect_success 'ephemeral: -b branch is not owned and is kept on remove' '\n+\ttest_when_finished \"git worktree remove -f nb || :; git branch -D named 2>/dev/null || :\" &&\n+\tgit worktree add -b named nb &&\n+\ttest_path_is_missing .git/worktrees/nb/owned-branch &&\n+\tgit worktree remove nb &&\n+\tgit rev-parse --verify refs/heads/named\n+'\n+\n+test_expect_success 'ephemeral: pre-existing branch is not owned' '\n+\ttest_when_finished \"git worktree remove -f pe || :; git branch -D pre 2>/dev/null || :\" &&\n+\tgit branch pre &&\n+\tgit worktree add pe pre &&\n+\ttest_path_is_missing .git/worktrees/pe/owned-branch &&\n+\tgit worktree remove pe &&\n+\tgit rev-parse --verify refs/heads/pre\n+'\n+\n+test_expect_success 'ephemeral: --keep-branch keeps an owned branch' '\n+\ttest_when_finished \"git branch -D keepme 2>/dev/null || :\" &&\n+\tgit worktree add keepme &&\n+\tgit worktree remove --keep-branch keepme &&\n+\tgit rev-parse --verify refs/heads/keepme\n+'\n+\n+test_expect_success 'ephemeral: branch -m follows the marker and stays ephemeral' '\n+\ttest_when_finished \"git worktree remove -f mv || :; git branch -D mv2 2>/dev/null || :\" &&\n+\tgit worktree add mv &&\n+\tgit -C mv branch -m mv mv2 &&\n+\techo refs/heads/mv2 >expect &&\n+\ttest_cmp expect .git/worktrees/mv/owned-branch &&\n+\tgit worktree remove mv &&\n+\ttest_must_fail git rev-parse --verify --quiet refs/heads/mv2\n+'\n+\n+test_expect_success 'ephemeral: commits survive the reap when anchored by a normal branch' '\n+\ttest_when_finished \"git worktree remove -f anc || :; git branch -D anchored 2>/dev/null || :\" &&\n+\tgit worktree add anc &&\n+\ttest_commit -C anc agentwork &&\n+\ttip=$(git -C anc rev-parse HEAD) &&\n+\tgit branch anchored \"$tip\" &&\n+\tgit worktree remove anc &&\n+\ttest_must_fail git rev-parse --verify --quiet refs/heads/anc &&\n+\ttest \"$(git rev-parse anchored)\" = \"$tip\"\n+'\n+\n test_done\ndiff --git a/t/t3200-branch.sh b/t/t3200-branch.sh\nindex cdb6c6a634..67c7c67853 100755\n--- a/t/t3200-branch.sh\n+++ b/t/t3200-branch.sh\n@@ -190,7 +190,7 @@ test_expect_success 'git branch -M foo bar should fail when bar is checked out'\n \n test_expect_success 'git branch -M foo bar should fail when bar is checked out in worktree' '\n \tgit branch -f bar &&\n-\ttest_when_finished \"git worktree remove wt && git branch -D wt\" &&\n+\ttest_when_finished \"git worktree remove --keep-branch wt && git branch -D wt\" &&\n \tgit worktree add wt &&\n \ttest_must_fail git branch -M bar wt\n '\ndiff --git a/t/t3400-rebase.sh b/t/t3400-rebase.sh\nindex accaaba4d4..9c0c80f113 100755\n--- a/t/t3400-rebase.sh\n+++ b/t/t3400-rebase.sh\n@@ -471,7 +471,7 @@ test_expect_success 'git rebase --update-ref with core.commentChar and branch on\n \ttest_when_finished git branch -D base topic2 &&\n \ttest_when_finished git checkout main &&\n \ttest_when_finished git branch -D wt-topic &&\n-\ttest_when_finished git worktree remove wt-topic &&\n+\ttest_when_finished git worktree remove --keep-branch wt-topic &&\n \tgit checkout main &&\n \tgit checkout -b base &&\n \tgit checkout -b topic2 &&\ndiff --git a/t/t5516-fetch-push.sh b/t/t5516-fetch-push.sh\nindex b982b209bf..6ffeb064fa 100755\n--- a/t/t5516-fetch-push.sh\n+++ b/t/t5516-fetch-push.sh\n@@ -1873,7 +1873,7 @@ test_expect_success 'updateInstead with bare repository worktree and unborn bare\n '\n \n test_expect_success 'refuse fetch to current branch of worktree' '\n-\ttest_when_finished \"git worktree remove --force wt && git branch -D wt\" &&\n+\ttest_when_finished \"git worktree remove --force --keep-branch wt && git branch -D wt\" &&\n \tgit worktree add wt &&\n \ttest_commit apple &&\n \ttest_must_fail git fetch . HEAD:wt &&\n-- \ngitgitgadget\n\n"},{"id":"555626","messageId":"atfbDXhTUmPtv5pE@fruit.crustytoothpaste.net","threadId":"65762","inReplyTo":"83841020f43f9f8989371117075ebf089888d619.1792512249.git.gitgitgadget@gmail.com","subject":"Re: [PATCH v2 1/2] worktree: add --reflink for copy-on-write worktree creation","fromName":"brian m. carlson","fromEmail":"sandals@crustytoothpaste.net","sentAt":"2026-10-20T21:20:14Z","receivedAt":"2026-10-20T21:20:14Z","isPatch":true,"sender":{"key":"sandals@crustytoothpaste.net","avatar":"https://avatars.githubusercontent.com/u/497054?v=4"},"body":"On 2026-10-20 at 16:04:08, Jason Newton via GitGitGadget wrote:\n> Creating many worktrees from the same base -- for example to run a\n> fleet of automated agents in parallel -- is expensive today: every\n> \"git worktree add\" materializes the entire working tree by writing\n> each tracked file out from the object store. The objects are shared\n> via the common directory, but the working tree is not: N worktrees\n> mean N full checkouts on disk and N times the file I/O.\n> \n> Add a \"--reflink\" option that, on a copy-on-write filesystem, populates\n> the new worktree by reflinking the current worktree's files and index\n> instead. The subsequent \"git reset --hard\" then only rewrites the\n> paths that actually differ between the current worktree and\n> <commit-ish>; everything else (including untracked files such as build\n> outputs) keeps sharing storage with the source until modified.\n> \n> A new reflink_file() helper in copy.c clones every regular file. There\n> is no size cutoff.\n> \n> On Linux it uses the FICLONE ioctl. That is the primitive btrfs, XFS\n> and bcachefs implement, and the one overlayfs forwards when the lower\n> filesystem can clone. This path has been tested on btrfs.\n> \n> On macOS it uses clonefile(), the APFS primitive. That path is\n> implemented and has not been run here.\n> \n> On Windows it uses ReFS block cloning,\n> FSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does. The destination is\n> sized to the source, extents are cloned in chunks of at most 1GiB, and\n> the tail is rounded up to a cluster (64K, then 4K) and cloned; Windows\n> ignores the range past EOF. The tail is not byte-copied, and small\n> files are not skipped. That path is implemented and has not been run\n> on ReFS. A volume that rejects the control code, including NTFS, fails\n> the probe.\n\nThat functionality is defective; see\nhttps://github.com/git-lfs/git-lfs/issues/6312.  We should not implement\nthis on Windows because there's no reasonable way to avoid corruption.\nIt's quite shocking that that bug exists, but it does.  Unless we can\nguarantee a fixed version of Windows (which does not exist yet), we\nshould skip reflinking there.\n\nI'd also like to see us limit this to platforms where it _has_ been\nmanually tested or is guaranteed to be automatically tested in CI.  That\nmeans we should make sure this runs in CI on APFS for macOS (see below).\n\n> +# Reflinks are only available on copy-on-write filesystems (btrfs, XFS,\n> +# bcachefs, APFS, ...). Where they are unavailable, --reflink transparently\n> +# falls back to a regular checkout, which the test above already covers.\n> +test_lazy_prereq REFLINK '\n> +\techo probe >reflink-src &&\n> +\tcp --reflink=always reflink-src reflink-dst 2>/dev/null\n> +'\n\nDoes this work properly on macOS?  That is, does the macOS `cp` binary\ncontain support for `--reflink=always`?  If not, we won't be testing\nthis case properly on macOS.\n-- \nbrian m. carlson (they/them)\nToronto, Ontario, CA\n"},{"id":"555677","messageId":"CAPig+cRsSN9gY405MGsCQzLuxzBKcfHo2Oc8Z4WB-U3BGd6m_Q@mail.gmail.com","threadId":"65762","inReplyTo":"6e2acdc5e2578da4e915fd2ac541a776349fb23e.1792512249.git.gitgitgadget@gmail.com","subject":"Re: [PATCH v2 2/2] worktree: reap ephemeral branches created by \"worktree add\"","fromName":"Eric Sunshine","fromEmail":"sunshine@sunshineco.com","sentAt":"2026-10-21T06:52:28Z","receivedAt":"2026-10-21T06:52:28Z","isPatch":true,"sender":{"key":"sunshine@sunshineco.com","avatar":"https://avatars.githubusercontent.com/u/163641?v=4"},"body":"On Tue, Oct 20, 2026 at 12:09 PM Jason Newton via GitGitGadget\n<gitgitgadget@gmail.com> wrote:\n> When \"git worktree add <path>\" is given no branch to check out, it\n> auto-creates one named after the path. Such a branch exists only to back\n> the new worktree, yet it outlives it: removing the worktree leaves the\n> branch behind, so a fleet of throwaway worktrees fills refs/heads/ with\n> dead branches that have to be cleaned up by hand.\n>\n> Treat an auto-created branch as owned by the worktree. Record it in the\n> worktree's administrative directory (worktrees/<id>/owned-branch) at\n> creation time -- the one moment we can know for certain the branch is\n> worktree-private, since we are the one that created it. \"git worktree\n> remove\" then deletes the owned branch once the worktree is gone and it\n> is no longer checked out.\n>\n> Ownership is recorded only when \"worktree add\" itself creates the branch\n> via DWIM auto-naming; a branch named explicitly with -b/-B, or one that\n> already existed, is never owned and never reaped. Deletion is\n> unconditional (even for unmerged commits) because an ephemeral branch is\n> disposable by contract: to keep the work, pass --keep-branch, or anchor\n> the commits with an ordinary branch beforehand -- a normal branch can\n> point at the same commits, after which reaping the ephemeral ref loses\n> nothing. \"git branch -m\" updates the marker so ownership follows a\n> rename, and the branch stays ephemeral.\n>\n> The marker is just another per-worktree administrative file, so older\n> versions of Git simply ignore it (they keep the branch on removal, as\n> today).\n>\n> Signed-off-by: Jason Newton <nevion@gmail.com>\n\nSorry, I may be missing something obvious, but this message never\nexplains why we should add all this additional complexity for a\nuse-case already directly supported by `git worktree add -d <path>`.\nSpecifically, worktree's --detach option is exactly what you want when\ncreating throwaway worktrees, even \"fleets\" of them (using terminology\nfrom this apparently fully or partially LLM-generated message). If\nyour tooling or agent is not using -d/--detach for throwaway\nworktrees, then the problem is fixable by modifying the tooling or by\nteaching the agent about --detach, without bulking up the git-worktree\nimplementation unnecessarily.\n\nMoreover, a change like this which makes the new behavior\nunconditional is certainly going to break existing tooling and\nworkflows, thus it will not go over well, even with the --keep-branch\nescape-hatch. At minimum, to be acceptable, assuming such new\nfunctionality is even desirable, to avoid breaking existing setups, it\nwould have to be opt-in, not opt-out (via --keep-branch). But if it's\ngoing to be opt-in, then you may as well just use --detach to achieve\nthe same effect.\n\n"},{"id":"555682","messageId":"CAPig+cRtMkJb6Y-b9M8JP5pmZXuHZf7Y+3-0mFVP2N4Zd+KpjA@mail.gmail.com","threadId":"65762","inReplyTo":"pull.2317.v2.git.git.1792512249.gitgitgadget@gmail.com","subject":"Re: [PATCH v2 0/2] worktree: copy-on-write creation and ephemeral branches","fromName":"Eric Sunshine","fromEmail":"sunshine@sunshineco.com","sentAt":"2026-10-21T07:08:18Z","receivedAt":"2026-10-21T07:08:18Z","isPatch":true,"sender":{"key":"sunshine@sunshineco.com","avatar":"https://avatars.githubusercontent.com/u/163641?v=4"},"body":"On Tue, Oct 20, 2026 at 12:08 PM Jason Newton via GitGitGadget\n<gitgitgadget@gmail.com> wrote:\n> When many worktrees share one repository -- for example a fleet of agents\n> each needing an isolated checkout -- \"git worktree add\" is costly at scale.\n> Objects are shared via the common directory, but the working tree is not:\n> each add rewrites every tracked file, so N worktrees cost N full checkouts\n> of disk and I/O. A branch created only to back one of those worktrees is\n> also left behind when the worktree is removed.\n>\n> Patch 1 adds \"git worktree add --reflink\". On a copy-on-write filesystem it\n> populates the new worktree by reflinking the current worktree's files and\n> index, then \"git reset --hard\" rewrites only the paths that differ from .\n> reflink_file() in copy.c uses FICLONE (Linux), clonefile() (macOS), and ReFS\n> block cloning (FSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does). Elsewhere\n> it is probed up front and falls back to a normal checkout. worktree.reflink\n> (true/false/auto) sets the default; --no-reflink overrides.\n>\n> Changes since v1:\n> [...]\n>  * Kept --reflink opt-in. A whole-tree reflink is not invisible: it carries\n>    untracked files, and cloning every file can be slower than checkout when\n>    the files are small (Junio; qub1n on the ReFS work).\n\nI may be missing something, but it's still not clear from this\nexplanation why --reflink must be opt-in rather than default behavior.\nThe above only seems to be touching on Junio's superficial \"cp treeA\ntreeB\" example[*], but doesn't answer the deeper question he asked\nabout why this can't be the default behavior for individual tracked\nresources in the worktree (his \"a_hash at a_path\" example).\n\n[*]: https://lore.kernel.org/git/xmqq8q8pxfny.fsf@gitster.g/\n\n"},{"id":"555683","messageId":"CAGou9MhkmSZs3ViSj6qqkZY6LLLQQ+5RzjLG5EhM-AXx+d7h=A@mail.gmail.com","threadId":"65762","inReplyTo":"atfbDXhTUmPtv5pE@fruit.crustytoothpaste.net","subject":"Re: [PATCH v2 1/2] worktree: add --reflink for copy-on-write worktree creation","fromName":"Jason Newton","fromEmail":"nevion@gmail.com","sentAt":"2026-10-21T07:15:50Z","receivedAt":"2026-10-21T07:15:50Z","isPatch":true,"sender":{"key":"nevion@gmail.com","avatar":null},"body":"Brian,\n\nmacOS cp has no --reflink=always. The clone option is -c, which is\nclonefile(2). t/t2400-worktree-add.sh already probes that way. The\nREFLINK prerequisite runs \"cp -c\" when the MACOS prerequisite is set,\nand \"cp --reflink=always\" otherwise. The test that depends on REFLINK\nis \"--reflink carries untracked files and reconciles changes\".\n\nThat is in 042485f0e9cd8cf1765b811ea7334247aec44971. The pull request\nCI for that commit is the APFS run:\n\nhttps://github.com/git/git/pull/2317\nhttps://github.com/git/git/actions/runs/39502233266\n\nAll four macos-14 jobs succeeded. The runners were macOS 14.8.9\n(23J631), image macos-14-arm64 20260831.0302.1. \"print test failures\"\nwas skipped on each job, which is the step that runs only when a test\nscript fails.\n\nosx-clang:\nhttps://github.com/git/git/actions/runs/39502233266/job/118902393415\nt2400-worktree-add.sh ok, 55208 ms\n\nosx-gcc:\nhttps://github.com/git/git/actions/runs/39502233266/job/118902393588\nt2400-worktree-add.sh ok, 45173 ms\n\nosx-meson:\nhttps://github.com/git/git/actions/runs/39502233266/job/118902393644\n\nosx-reftable:\nhttps://github.com/git/git/actions/runs/39502233266/job/118902393664\n\nThe macOS evidence is those jobs.\n\nReflink is disabled on Windows in \"worktree: disable reflink on\nWindows\" (91806975a6909265b1325206ef2f33a169393920). The pull request\nhead is 876fb541a8e1d43731bb72ddbbf1c49da8760775, which keeps that\ndisable and leaves the filesystem probe compiled so the mingw build\ndoes not fail with -Werror=unused-function. The CI run linked above\nis the previous tip, 042485f. The warning names the build from the\ngit-lfs report,\nWindows 11 build 26200. A later note on that report reproduced the\nzero-fill on build 26200.9448 with git-lfs 3.6.1. No fixed build is\nidentified, so every Windows version refuses the ioctl and falls back\nto a regular checkout. \"git worktree add --reflink\" and\nworktree.reflink=true warn with \"Windows build 26200\".\nworktree.reflink=auto stays silent. t2400 checks that warning under\nMINGW.\n\nOn the git-lfs report, the failure mode is real and documented here:\n\nhttps://github.com/git-lfs/git-lfs/issues/6312\nhttps://github.com/git-lfs/git-lfs/pull/6323\n\nFSCTL_DUPLICATE_EXTENTS_TO_FILE can publish zeros when the source\ndata is still cached. FlushFileBuffers on the read-only handle a\ncheckout uses fails with ERROR_ACCESS_DENIED (win32 5). The change in\n6323 reopens the source writable, flushes, and skips that flush when\nthe volume does not advertise FILE_SUPPORTS_BLOCK_REFCOUNTING.\n\nThe numbers below are from the ioctl path before that disable, on\nthis machine, Windows build 26300.9457. The read-only flush failed\nwith win32 5, the same error the git-lfs report describes. The clones\nkept the original bytes.\n\nNTFS rejects the ioctl: win32 1 on a USB NTFS partition, win32 50 on\nC:. The fallback there is a normal write. The USB disk would not\nformat as ReFS. The ReFS volume was a 32 GiB Dev Drive, stored as a\nVHD on that disk, with block refcounting set. The clone path did not\nflush.\n\nContent check, every clone, unbuffered SHA-256:\n\n4000 files, 8,388,608 bytes each\n(33,554,432,000 bytes, 31.25 GiB of clone names).\nCreated with FSCTL_DUPLICATE_EXTENTS_TO_FILE only.\n\nSource before rewrite:\n106640827aa82610080b1e4c676e2028230b841fa4642faaa292046833950714\nPass 1: old=4000 new=0 other=0 errors=0\n\nSource rewritten to a different pattern, still no flush:\ne58408ac406d407257cd3a2474b8bba7b615e76bd4ce03e8ec3df9b42a02bc89\nPass 2: old=4000 new=0 other=0 errors=0\n\nFlushFileBuffers on the read-only handle: FAIL win32=5\nReopen writable and flush: OK\nSource hash stayed on the rewritten pattern.\nPass 3, after that flush: old=4000 new=0 other=0 errors=0\n\nAll 4000 clones still hashed to the original source. After they\nsettled, free space was 30,462,386,176 bytes and the backing VHD was\nstill 4,164,943,872 bytes. The volume stayed Healthy. Deleting the\nclones freed nothing further.\n\nThis is one Windows build, alongside the version described in\ngit-lfs #6312.\n\n\nOn Tue, Oct 20, 2026 at 2:20 PM brian m. carlson\n<sandals@crustytoothpaste.net> wrote:\n>\n> On 2026-10-20 at 16:04:08, Jason Newton via GitGitGadget wrote:\n> > Creating many worktrees from the same base -- for example to run a\n> > fleet of automated agents in parallel -- is expensive today: every\n> > \"git worktree add\" materializes the entire working tree by writing\n> > each tracked file out from the object store. The objects are shared\n> > via the common directory, but the working tree is not: N worktrees\n> > mean N full checkouts on disk and N times the file I/O.\n> >\n> > Add a \"--reflink\" option that, on a copy-on-write filesystem, populates\n> > the new worktree by reflinking the current worktree's files and index\n> > instead. The subsequent \"git reset --hard\" then only rewrites the\n> > paths that actually differ between the current worktree and\n> > <commit-ish>; everything else (including untracked files such as build\n> > outputs) keeps sharing storage with the source until modified.\n> >\n> > A new reflink_file() helper in copy.c clones every regular file. There\n> > is no size cutoff.\n> >\n> > On Linux it uses the FICLONE ioctl. That is the primitive btrfs, XFS\n> > and bcachefs implement, and the one overlayfs forwards when the lower\n> > filesystem can clone. This path has been tested on btrfs.\n> >\n> > On macOS it uses clonefile(), the APFS primitive. That path is\n> > implemented and has not been run here.\n> >\n> > On Windows it uses ReFS block cloning,\n> > FSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does. The destination is\n> > sized to the source, extents are cloned in chunks of at most 1GiB, and\n> > the tail is rounded up to a cluster (64K, then 4K) and cloned; Windows\n> > ignores the range past EOF. The tail is not byte-copied, and small\n> > files are not skipped. That path is implemented and has not been run\n> > on ReFS. A volume that rejects the control code, including NTFS, fails\n> > the probe.\n>\n> That functionality is defective; see\n> https://github.com/git-lfs/git-lfs/issues/6312.  We should not implement\n> this on Windows because there's no reasonable way to avoid corruption.\n> It's quite shocking that that bug exists, but it does.  Unless we can\n> guarantee a fixed version of Windows (which does not exist yet), we\n> should skip reflinking there.\n>\n> I'd also like to see us limit this to platforms where it _has_ been\n> manually tested or is guaranteed to be automatically tested in CI.  That\n> means we should make sure this runs in CI on APFS for macOS (see below).\n>\n> > +# Reflinks are only available on copy-on-write filesystems (btrfs, XFS,\n> > +# bcachefs, APFS, ...). Where they are unavailable, --reflink transparently\n> > +# falls back to a regular checkout, which the test above already covers.\n> > +test_lazy_prereq REFLINK '\n> > +     echo probe >reflink-src &&\n> > +     cp --reflink=always reflink-src reflink-dst 2>/dev/null\n> > +'\n>\n> Does this work properly on macOS?  That is, does the macOS `cp` binary\n> contain support for `--reflink=always`?  If not, we won't be testing\n> this case properly on macOS.\n> --\n> brian m. carlson (they/them)\n> Toronto, Ontario, CA\n\n"},{"id":"555684","messageId":"pull.2317.v3.git.git.1792567061.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.git.git.1780685368.gitgitgadget@gmail.com","subject":"[PATCH v3 0/4] worktree: copy-on-write creation and ephemeral branches","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-21T07:17:37Z","receivedAt":"2026-10-21T07:17:37Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"When many worktrees share one repository -- for example a fleet of agents\neach needing an isolated checkout -- \"git worktree add\" is costly at scale.\nObjects are shared via the common directory, but the working tree is not:\neach add rewrites every tracked file, so N worktrees cost N full checkouts\nof disk and I/O. A branch created only to back one of those worktrees is\nalso left behind when the worktree is removed.\n\nPatch 1 adds \"git worktree add --reflink\". On a copy-on-write filesystem it\npopulates the new worktree by reflinking the current worktree's files and\nindex, then \"git reset --hard\" rewrites only the paths that differ from .\nreflink_file() in copy.c uses FICLONE (Linux), clonefile() (macOS), and ReFS\nblock cloning (FSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does). Elsewhere\nit is probed up front and falls back to a normal checkout. worktree.reflink\n(true/false/auto) sets the default; --no-reflink overrides.\n\nUncommitted edits to tracked files in the source do not leak into the new\nworktree. The copied index is refreshed before reset, and because every\nreflinked file is a new inode the refresh re-validates by content. Only\nuntracked files are carried over. The option stays opt-in for that reason:\nit copies the source's untracked and ignored files, which a plain checkout\ndoes not.\n\nFor many worktrees at one commit, the series does not share a branch.\ngit-worktree(1) shows a single update-ref transaction that creates a ref per\nworktree (or a detached HEAD). A shared branch still lets a stale index in\none worktree silently revert a commit made in another.\n\nPatch 2 treats a branch that \"git worktree add \" created itself as owned by\nthat worktree. \"git worktree remove\" deletes it. Branches named with -b/-B,\nor that already existed, are left alone. --keep-branch keeps an owned\nbranch.\n\nChanges since v1:\n\n * Dropped the patch that allowed one branch to be checked out in several\n   worktrees. Documented the per-ref / detached-HEAD pattern instead (brian\n   m. carlson, Junio).\n * Explained, in the commit message and the manual, why a dirty source\n   worktree does not leak tracked content (brian m. carlson).\n * Added the ReFS block-cloning arm (brian m. carlson).\n * Noted overlayfs as a supported setup when the lower filesystem supports\n   reflinks (brian m. carlson).\n * Kept --reflink opt-in. A whole-tree reflink is not invisible: it carries\n   untracked files, and cloning every file can be slower than checkout when\n   the files are small (Junio; qub1n on the ReFS work).\n * Rebased onto 47fdf2208c (\"The 7th batch\"). reflink_file() now takes a\n   repository argument, matching copy_file().\n * Added ephemeral-branch reaping for the auto-named branch that \"worktree\n   add \" creates.\n\nReFS measurements (32 GiB Dev Drive, Windows build 26300). The USB disk\nitself would not format as ReFS, so the volume is a Dev Drive VHD on an NTFS\npartition of that disk. NTFS rejects the clone ioctl (win32 error 1 there,\nerror 50 on C:) and falls back to a full write.\n\nThe clone shares the source clusters and does not flush. Four thousand\nclones of one 8 MiB file, 31.3 GiB of logical names, were read back\nunbuffered and SHA-256'd in full: 4000 of 4000 matched the source. The\nsource was then overwritten with a different pattern. A read-only\nFlushFileBuffers failed with win32 error 5; a writable reopen succeeded.\nAfter that flush, 4000 of 4000 clones still hashed to the original contents\nand none hashed to the new source. While the clones were created the\nfree-space counter fell to about 1 GiB, then returned to 28.38 GiB with the\nclones still present. The backing VHD did not grow. Deleting the clones\nfreed nothing further.\n\nJason Newton (4):\n  worktree: add --reflink for copy-on-write worktree creation\n  worktree: reap ephemeral branches created by \"worktree add\"\n  worktree: disable reflink on Windows\n  worktree: keep the reflink probe referenced on Windows\n\n Documentation/config/worktree.adoc |  12 ++\n Documentation/git-worktree.adoc    |  75 ++++++-\n builtin/branch.c                   |  28 +++\n builtin/worktree.c                 | 315 ++++++++++++++++++++++++++++-\n copy.c                             |  83 ++++++++\n copy.h                             |  14 ++\n t/t2400-worktree-add.sh            | 166 +++++++++++++++\n t/t3200-branch.sh                  |   2 +-\n t/t3400-rebase.sh                  |   2 +-\n t/t5516-fetch-push.sh              |   2 +-\n 10 files changed, 690 insertions(+), 9 deletions(-)\n\n\nbase-commit: 47fdf2208c5b94c8cc01c106b8f7c85efb91c926\nPublished-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2317%2Fnevion%2Fworktree-reflink-cow-v3\nFetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2317/nevion/worktree-reflink-cow-v3\nPull-Request: https://github.com/git/git/pull/2317\n\nRange-diff vs v2:\n\n 1:  83841020f4 ! 1:  a163f737af worktree: add --reflink for copy-on-write worktree creation\n     @@ Commit message\n          and bcachefs implement, and the one overlayfs forwards when the lower\n          filesystem can clone. This path has been tested on btrfs.\n      \n     -    On macOS it uses clonefile(), the APFS primitive. That path is\n     -    implemented and has not been run here.\n     +    On macOS it uses clonefile(), the APFS primitive. The t2400\n     +    REFLINK prerequisite probes that with \"cp -c\", because BSD cp has no\n     +    --reflink=always, so the macOS CI jobs exercise this path on APFS.\n      \n          On Windows it uses ReFS block cloning,\n          FSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does. The destination is\n     @@ t/t2400-worktree-add.sh: test_expect_success 'relative worktree sets extension c\n      +# Reflinks are only available on copy-on-write filesystems (btrfs, XFS,\n      +# bcachefs, APFS, ...). Where they are unavailable, --reflink transparently\n      +# falls back to a regular checkout, which the test above already covers.\n     ++#\n     ++# GNU cp probes with --reflink=always. macOS cp has no such option; -c\n     ++# is clonefile(2), which is what the APFS CI jobs exercise.\n      +test_lazy_prereq REFLINK '\n      +\techo probe >reflink-src &&\n     -+\tcp --reflink=always reflink-src reflink-dst 2>/dev/null\n     ++\tif test_have_prereq MACOS\n     ++\tthen\n     ++\t\tcp -c reflink-src reflink-dst 2>/dev/null\n     ++\telse\n     ++\t\tcp --reflink=always reflink-src reflink-dst 2>/dev/null\n     ++\tfi\n      +'\n      +\n      +test_expect_success REFLINK '--reflink carries untracked files and reconciles changes' '\n 2:  6e2acdc5e2 = 2:  042485f0e9 worktree: reap ephemeral branches created by \"worktree add\"\n -:  ---------- > 3:  91806975a6 worktree: disable reflink on Windows\n -:  ---------- > 4:  876fb541a8 worktree: keep the reflink probe referenced on Windows\n\n-- \ngitgitgadget\n\n"},{"id":"555685","messageId":"a163f737af090cc00e4c93a068df54d6a6ecd7ec.1792567061.git.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.v3.git.git.1792567061.gitgitgadget@gmail.com","subject":"[PATCH v3 1/4] worktree: add --reflink for copy-on-write worktree creation","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-21T07:17:38Z","receivedAt":"2026-10-21T07:17:38Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"From: Jason Newton <nevion@gmail.com>\n\nCreating many worktrees from the same base -- for example to run a\nfleet of automated agents in parallel -- is expensive today: every\n\"git worktree add\" materializes the entire working tree by writing\neach tracked file out from the object store. The objects are shared\nvia the common directory, but the working tree is not: N worktrees\nmean N full checkouts on disk and N times the file I/O.\n\nAdd a \"--reflink\" option that, on a copy-on-write filesystem, populates\nthe new worktree by reflinking the current worktree's files and index\ninstead. The subsequent \"git reset --hard\" then only rewrites the\npaths that actually differ between the current worktree and\n<commit-ish>; everything else (including untracked files such as build\noutputs) keeps sharing storage with the source until modified.\n\nA new reflink_file() helper in copy.c clones every regular file. There\nis no size cutoff.\n\nOn Linux it uses the FICLONE ioctl. That is the primitive btrfs, XFS\nand bcachefs implement, and the one overlayfs forwards when the lower\nfilesystem can clone. This path has been tested on btrfs.\n\nOn macOS it uses clonefile(), the APFS primitive. The t2400\nREFLINK prerequisite probes that with \"cp -c\", because BSD cp has no\n--reflink=always, so the macOS CI jobs exercise this path on APFS.\n\nOn Windows it uses ReFS block cloning,\nFSCTL_DUPLICATE_EXTENTS_TO_FILE, as Git LFS does. The destination is\nsized to the source, extents are cloned in chunks of at most 1GiB, and\nthe tail is rounded up to a cluster (64K, then 4K) and cloned; Windows\nignores the range past EOF. The tail is not byte-copied, and small\nfiles are not skipped. That path is implemented and has not been run\non ReFS. A volume that rejects the control code, including NTFS, fails\nthe probe.\n\nAnywhere else there is no reflink primitive. Support is probed up front\nby cloning a one-byte file, and where that fails \"--reflink\" falls back\nto an ordinary checkout instead of byte-copying the source tree. The\ndirectory walk skips the new worktree itself when it lives inside the\nsource one, and preserves symlinks and modes.\n\nUncommitted changes in the source do not leak into the new worktree.\nAfter reflinking the source's files we copy its index and run\n\"update-index --refresh\" before \"reset --hard\": because every reflinked\nfile is a fresh inode, the cached stat never matches, so the refresh is\nforced to re-validate by content rather than by stat. A tracked path is\ntherefore only left sharing extents when its content equals the indexed\nobject; any path whose content differs from <commit-ish> -- which\nincludes every uncommitted modification in the source -- is rewritten\nby the reset. The new worktree is thus always a faithful checkout of\n<commit-ish> for tracked paths, and only untracked files are carried\nover.\n\nThe behavior can be made the default with the worktree.reflink\nconfiguration (\"true\", \"false\" or \"auto\", the last suppressing the\nunsupported-filesystem warning), and turned off per-invocation with\n--no-reflink. A configured default degrades quietly in modes that\ncannot reflink (--orphan, --no-checkout) instead of erroring, so\nenabling it never breaks those commands. The checkout step continues to\nhonor checkout.workers, so parallel checkout composes with --reflink for\nthe paths that do need rewriting.\n\nTo check out many worktrees at the same commit safely, give each its\nown ref (or a detached HEAD) rather than sharing one branch; a\ngit-worktree(1) example shows the one-shot \"update-ref\" transaction\nthat pairs with --reflink.\n\nSigned-off-by: Jason Newton <nevion@gmail.com>\n---\n Documentation/config/worktree.adoc |  10 ++\n Documentation/git-worktree.adoc    |  49 ++++++-\n builtin/worktree.c                 | 227 ++++++++++++++++++++++++++++-\n copy.c                             | 190 ++++++++++++++++++++++++\n copy.h                             |  14 ++\n t/t2400-worktree-add.sh            |  96 ++++++++++++\n 6 files changed, 584 insertions(+), 2 deletions(-)\n\ndiff --git a/Documentation/config/worktree.adoc b/Documentation/config/worktree.adoc\nindex 0930183b91..aa849c08d2 100644\n--- a/Documentation/config/worktree.adoc\n+++ b/Documentation/config/worktree.adoc\n@@ -18,3 +18,13 @@\n Note that setting `worktree.useRelativePaths` to \"`true`\" implies enabling the\n `extensions.relativeWorktrees` config (see linkgit:git-config[1]),\n thus making it incompatible with older versions of Git.\n+\n+`worktree.reflink`::\n+\tControls whether `git worktree add` populates new worktrees with\n+\tcopy-on-write (reflink) clones, as if `--reflink` had been given\n+\t(see linkgit:git-worktree[1]). May be set to \"`true`\", \"`false`\"\n+\t(the default), or \"`auto`\". With \"`true`\", a filesystem that does\n+\tnot support reflinks produces a warning before falling back to an\n+\tordinary checkout; with \"`auto`\", the fallback is silent. An\n+\texplicit `--reflink` or `--no-reflink` on the command line\n+\toverrides this setting.\ndiff --git a/Documentation/git-worktree.adoc b/Documentation/git-worktree.adoc\nindex e6e77252ab..4264ee753a 100644\n--- a/Documentation/git-worktree.adoc\n+++ b/Documentation/git-worktree.adoc\n@@ -10,7 +10,7 @@ SYNOPSIS\n --------\n [synopsis]\n git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\n-\t\t [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]\n+\t\t [--orphan] [--reflink] [(-b | -B) <new-branch>] <path> [<commit-ish>]\n git worktree list [-v | --porcelain [-z]]\n git worktree lock [--reason <string>] <worktree>\n git worktree move <worktree> <new-path>\n@@ -213,6 +213,35 @@ To remove a locked worktree, specify `--force` twice.\n \tsuch as configuring sparse-checkout. See \"Sparse checkout\"\n \tin linkgit:git-read-tree[1].\n \n+`--reflink`::\n+`--no-reflink`::\n+\tPopulate the new worktree by creating copy-on-write (reflink)\n+\tclones of the current worktree's files and index instead of\n+\twriting every file out from the object store. The checkout that\n+\tfollows then only has to rewrite the paths that actually differ\n+\tbetween the current worktree and _<commit-ish>_; everything else\n+\t(including untracked files such as build outputs) keeps sharing\n+\tstorage with the source worktree until modified. This makes\n+\t`add` much faster and far cheaper on disk when creating many\n+\tworktrees from the same base. `--no-reflink` forces an ordinary\n+\tcheckout, overriding the `worktree.reflink` configuration.\n++\n+Reflinks require a copy-on-write filesystem: for example btrfs, XFS,\n+bcachefs or ZFS on Linux (and overlayfs on top of one of these, as used by\n+containers), APFS on macOS, or ReFS on Windows. On a filesystem that does\n+not support reflinks, `--reflink` transparently falls back to an ordinary\n+checkout. Because the source worktree's untracked and ignored files are\n+cloned as well, only use `--reflink` when that is acceptable.\n++\n+This option cannot be combined with `--no-checkout` or `--orphan`. It can\n+be enabled by default with the `worktree.reflink` configuration; see\n+linkgit:git-config[1].\n++\n+The checkout that populates a new worktree also honors the\n+`checkout.workers` configuration (see linkgit:git-config[1]), so setting it\n+parallelizes the file writes and can further speed up `add`, with or\n+without `--reflink`.\n+\n `--guess-remote`::\n `--no-guess-remote`::\n \tWith `worktree add <path>`, without _<commit-ish>_, instead\n@@ -531,6 +560,24 @@ $ popd\n $ git worktree remove ../temp\n ------------\n \n+To run several independent worktrees from the same starting commit -- for\n+example a pool of automated agents -- give each one its own branch rather than\n+sharing a single branch between them. A shared branch is unsafe here: if one\n+worktree commits and another then commits from its now-stale index, the second\n+commit silently drops the first one's changes. Create the branches in a single\n+ref transaction and check each out in its own (optionally reflinked) worktree:\n+\n+------------\n+$ oid=$(git rev-parse HEAD)\n+$ printf 'create refs/heads/agent-%s %s\\n' 1 \"$oid\" 2 \"$oid\" 3 \"$oid\" |\n+\tgit update-ref --stdin\n+$ for n in 1 2 3; do git worktree add --reflink ../agent-$n agent-$n; done\n+------------\n+\n+The single linkgit:git-update-ref[1] transaction is cheap and is especially\n+efficient with the `reftable` backend. If a worktree does not need to advance a\n+branch at all, use a detached `HEAD` (`git worktree add --detach`) instead.\n+\n CONFIGURATION\n -------------\n \ndiff --git a/builtin/worktree.c b/builtin/worktree.c\nindex 77ecd0f71f..9d4b51305e 100644\n--- a/builtin/worktree.c\n+++ b/builtin/worktree.c\n@@ -30,7 +30,7 @@\n \n #define BUILTIN_WORKTREE_ADD_USAGE \\\n \tN_(\"git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]]\\n\" \\\n-\t   \"                 [--orphan] [(-b | -B) <new-branch>] <path> [<commit-ish>]\")\n+\t   \"                 [--orphan] [--reflink] [(-b | -B) <new-branch>] <path> [<commit-ish>]\")\n \n #define BUILTIN_WORKTREE_LIST_USAGE \\\n \tN_(\"git worktree list [-v | --porcelain [-z]]\")\n@@ -47,6 +47,11 @@\n #define BUILTIN_WORKTREE_UNLOCK_USAGE \\\n \tN_(\"git worktree unlock <worktree>\")\n \n+/* values for add_opts.reflink and the worktree.reflink config */\n+#define REFLINK_OFF\t0\n+#define REFLINK_ON\t1\t/* warn and fall back if unsupported */\n+#define REFLINK_AUTO\t2\t/* silently fall back if unsupported */\n+\n #define WORKTREE_ADD_DWIM_ORPHAN_INFER_TEXT \\\n \t_(\"No possible source branch, inferring '--orphan'\")\n \n@@ -123,6 +128,7 @@ struct add_opts {\n \tint checkout;\n \tint orphan;\n \tint relative_paths;\n+\tint reflink;\n \tconst char *keep_locked;\n };\n \n@@ -130,6 +136,7 @@ static int show_only;\n static int verbose;\n static int guess_remote;\n static int use_relative_paths;\n+static int reflink_config = REFLINK_OFF;\n static timestamp_t expire;\n \n static int git_worktree_config(const char *var, const char *value,\n@@ -141,6 +148,13 @@ static int git_worktree_config(const char *var, const char *value,\n \t} else if (!strcmp(var, \"worktree.userelativepaths\")) {\n \t\tuse_relative_paths = git_config_bool(var, value);\n \t\treturn 0;\n+\t} else if (!strcmp(var, \"worktree.reflink\")) {\n+\t\tif (value && !strcmp(value, \"auto\"))\n+\t\t\treflink_config = REFLINK_AUTO;\n+\t\telse\n+\t\t\treflink_config = git_config_bool(var, value) ?\n+\t\t\t\tREFLINK_ON : REFLINK_OFF;\n+\t\treturn 0;\n \t}\n \n \treturn git_default_config(var, value, ctx, cb);\n@@ -394,6 +408,182 @@ worktree_copy_cleanup:\n \tfree(to_file);\n }\n \n+/*\n+ * Probe whether the filesystem backing \"dir\" supports reflinks. We do this\n+ * once up front so that, on filesystems without copy-on-write support (and on\n+ * platforms that lack a reflink primitive entirely), we can\n+ * fall back to a normal checkout instead of byte-copying the whole source\n+ * working tree -- which would include untracked files and be slower than the\n+ * checkout we are trying to avoid.\n+ */\n+static int reflink_supported(const char *dir)\n+{\n+\tstruct strbuf src = STRBUF_INIT, dst = STRBUF_INIT;\n+\tint fd, ok = 0;\n+\n+\tstrbuf_addf(&src, \"%s/.git-reflink-probe-src\", dir);\n+\tstrbuf_addf(&dst, \"%s/.git-reflink-probe-dst\", dir);\n+\n+\tfd = open(src.buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);\n+\tif (fd >= 0) {\n+\t\twrite_in_full(fd, \"x\", 1);\n+\t\tclose(fd);\n+\t\tif (!reflink_file(the_repository, dst.buf, src.buf, 0600))\n+\t\t\tok = 1;\n+\t\tunlink(dst.buf);\n+\t}\n+\tunlink(src.buf);\n+\n+\tstrbuf_release(&src);\n+\tstrbuf_release(&dst);\n+\treturn ok;\n+}\n+\n+/*\n+ * Reflink a single regular file, falling back to a regular copy when the\n+ * clone fails for this particular file (for example across mount points).\n+ */\n+static int reflink_or_copy(const char *dst, const char *src, int mode)\n+{\n+\tif (!reflink_file(the_repository, dst, src, mode))\n+\t\treturn 0;\n+\treturn copy_file(the_repository, dst, src, mode);\n+}\n+\n+/*\n+ * Recursively copy the working-tree directory \"src\" into \"dst\" using reflinks\n+ * for regular files. Directory entries that resolve to the destination\n+ * worktree itself (identified by skip_dev/skip_ino, which matters when the new\n+ * worktree lives inside the source one) and the top-level \".git\" gitfile are\n+ * skipped.\n+ */\n+static int reflink_tree(const char *src, const char *dst,\n+\t\t\tdev_t skip_dev, ino_t skip_ino, int top)\n+{\n+\tstruct strbuf s = STRBUF_INIT, d = STRBUF_INIT;\n+\tDIR *dir;\n+\tstruct dirent *de;\n+\tint ret = 0;\n+\n+\tdir = opendir(src);\n+\tif (!dir)\n+\t\treturn error_errno(_(\"could not open directory '%s'\"), src);\n+\n+\twhile (!ret && (de = readdir(dir))) {\n+\t\tstruct stat st;\n+\n+\t\tif (is_dot_or_dotdot(de->d_name))\n+\t\t\tcontinue;\n+\t\tif (top && !strcmp(de->d_name, \".git\"))\n+\t\t\tcontinue;\n+\n+\t\tstrbuf_reset(&s);\n+\t\tstrbuf_addf(&s, \"%s/%s\", src, de->d_name);\n+\t\tstrbuf_reset(&d);\n+\t\tstrbuf_addf(&d, \"%s/%s\", dst, de->d_name);\n+\n+\t\tif (lstat(s.buf, &st)) {\n+\t\t\tret = error_errno(_(\"could not stat '%s'\"), s.buf);\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tif (S_ISDIR(st.st_mode)) {\n+\t\t\t/* never recurse into the new worktree itself */\n+\t\t\tif (st.st_dev == skip_dev && st.st_ino == skip_ino)\n+\t\t\t\tcontinue;\n+\t\t\tif (mkdir(d.buf, st.st_mode & 07777) && errno != EEXIST) {\n+\t\t\t\tret = error_errno(_(\"could not create directory '%s'\"), d.buf);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tret = reflink_tree(s.buf, d.buf, skip_dev, skip_ino, 0);\n+\t\t} else if (S_ISLNK(st.st_mode)) {\n+\t\t\tstruct strbuf link = STRBUF_INIT;\n+\n+\t\t\tif (strbuf_readlink(&link, s.buf, st.st_size))\n+\t\t\t\tret = error_errno(_(\"could not read symlink '%s'\"), s.buf);\n+\t\t\telse if (symlink(link.buf, d.buf))\n+\t\t\t\tret = error_errno(_(\"could not create symlink '%s'\"), d.buf);\n+\t\t\tstrbuf_release(&link);\n+\t\t} else if (S_ISREG(st.st_mode)) {\n+\t\t\tif (reflink_or_copy(d.buf, s.buf, st.st_mode))\n+\t\t\t\tret = error_errno(_(\"could not copy '%s' to '%s'\"),\n+\t\t\t\t\t\t  s.buf, d.buf);\n+\t\t}\n+\t\t/* silently skip fifos, sockets and device nodes */\n+\t}\n+\n+\tclosedir(dir);\n+\tstrbuf_release(&s);\n+\tstrbuf_release(&d);\n+\treturn ret;\n+}\n+\n+/*\n+ * Populate the new worktree at \"path\" by reflinking the current worktree's\n+ * files and index. The subsequent \"git reset --hard\" then only has to rewrite\n+ * the paths that actually differ between the source and <commit-ish>, leaving\n+ * everything else sharing storage with the source. Returns 1 when reflinks are\n+ * unavailable so the caller can fall back to a plain checkout.\n+ */\n+static int reflink_worktree(const char *path, const char *wt_git_dir,\n+\t\t\t    const struct add_opts *opts, struct strvec *child_env)\n+{\n+\tconst char *src_wt = the_repository->worktree;\n+\tchar *src_index = NULL, *dst_index = NULL;\n+\tstruct stat dst_st;\n+\tint ret = 0;\n+\n+\tif (!src_wt)\n+\t\treturn error(_(\"--reflink needs a source working tree, but this \"\n+\t\t\t       \"repository does not have one\"));\n+\n+\tif (!reflink_supported(path)) {\n+\t\t/* In auto mode the fallback is expected, so stay quiet. */\n+\t\tif (!opts->quiet && opts->reflink != REFLINK_AUTO)\n+\t\t\twarning(_(\"the filesystem at '%s' does not support reflinks; \"\n+\t\t\t\t  \"falling back to a regular checkout\"), path);\n+\t\treturn 1;\n+\t}\n+\n+\tif (stat(path, &dst_st))\n+\t\treturn error_errno(_(\"could not stat '%s'\"), path);\n+\n+\tif ((ret = reflink_tree(src_wt, path, dst_st.st_dev, dst_st.st_ino, 1)))\n+\t\treturn ret;\n+\n+\t/*\n+\t * Clone the source index so the following reset sees the source's\n+\t * state and only materializes the differences to <commit-ish>.\n+\t */\n+\tsrc_index = repo_git_path(the_repository, \"index\");\n+\tdst_index = xstrfmt(\"%s/index\", wt_git_dir);\n+\tif (!access(src_index, F_OK) &&\n+\t    reflink_or_copy(dst_index, src_index, 0666)) {\n+\t\tret = error_errno(_(\"could not copy index to '%s'\"), dst_index);\n+\t\tgoto out;\n+\t}\n+\n+\t/*\n+\t * The cloned index still carries the source files' stat information.\n+\t * Refresh it against the freshly reflinked files so that \"git reset\"\n+\t * recognizes unchanged paths as up to date and leaves them sharing\n+\t * storage instead of rewriting (and thus un-sharing) them.\n+\t */\n+\tif (!access(dst_index, F_OK)) {\n+\t\tstruct child_process cp = CHILD_PROCESS_INIT;\n+\t\tcp.git_cmd = 1;\n+\t\tstrvec_pushl(&cp.args, \"update-index\", \"-q\", \"--refresh\", NULL);\n+\t\tstrvec_pushv(&cp.env, child_env->v);\n+\t\t/* a dirty working tree is not an error here */\n+\t\trun_command(&cp);\n+\t}\n+\n+out:\n+\tfree(src_index);\n+\tfree(dst_index);\n+\treturn ret;\n+}\n+\n static int checkout_worktree(const struct add_opts *opts,\n \t\t\t     struct strvec *child_env)\n {\n@@ -588,6 +778,20 @@ static int add_worktree(const char *path, const char *refname,\n \t    (ret = make_worktree_orphan(refname, opts, &child_env)))\n \t\tgoto done;\n \n+\t/*\n+\t * When --reflink is requested and the filesystem supports it, copy the\n+\t * current worktree (and its index) into the new one using copy-on-write\n+\t * clones. checkout_worktree() then only rewrites the paths that differ\n+\t * from <commit-ish>. reflink_worktree() returns 1 when reflinks are not\n+\t * available, in which case we just do an ordinary checkout below.\n+\t */\n+\tif (opts->checkout && opts->reflink) {\n+\t\tret = reflink_worktree(path, sb_repo.buf, opts, &child_env);\n+\t\tif (ret < 0)\n+\t\t\tgoto done;\n+\t\tret = 0;\n+\t}\n+\n \tif (opts->checkout &&\n \t    (ret = checkout_worktree(opts, &child_env)))\n \t\tgoto done;\n@@ -832,6 +1036,7 @@ static int add(int ac, const char **av, const char *prefix,\n \tconst char *lock_reason = NULL;\n \tint keep_locked = 0;\n \tint used_new_branch_options;\n+\tint reflink_cli = -1;\n \tstruct option options[] = {\n \t\tOPT__FORCE(&opts.force,\n \t\t\t   N_(\"checkout <branch> even if already checked out in other worktree\"),\n@@ -854,6 +1059,8 @@ static int add(int ac, const char **av, const char *prefix,\n \t\t\t N_(\"try to match the new branch name with a remote-tracking branch\")),\n \t\tOPT_BOOL(0, \"relative-paths\", &opts.relative_paths,\n \t\t\t N_(\"use relative paths for worktrees\")),\n+\t\tOPT_BOOL(0, \"reflink\", &reflink_cli,\n+\t\t\t N_(\"populate the worktree using copy-on-write clones when supported\")),\n \t\tOPT_END()\n \t};\n \tint ret;\n@@ -873,6 +1080,24 @@ static int add(int ac, const char **av, const char *prefix,\n \tif (opts.orphan && !opts.checkout)\n \t\tdie(_(\"options '%s' and '%s' cannot be used together\"),\n \t\t    \"--orphan\", \"--no-checkout\");\n+\n+\t/*\n+\t * Resolve whether to reflink: an explicit --reflink/--no-reflink on\n+\t * the command line wins, otherwise fall back to the worktree.reflink\n+\t * configuration (which may select the \"auto\" mode).\n+\t */\n+\topts.reflink = (reflink_cli != -1) ? reflink_cli : reflink_config;\n+\tif (opts.reflink && (opts.orphan || !opts.checkout)) {\n+\t\t/*\n+\t\t * Reflinking is incompatible with these; only complain when it\n+\t\t * was explicitly requested, otherwise quietly do a plain\n+\t\t * checkout so a configured default does not break these modes.\n+\t\t */\n+\t\tif (reflink_cli == REFLINK_ON)\n+\t\t\tdie(_(\"options '%s' and '%s' cannot be used together\"),\n+\t\t\t    \"--reflink\", opts.orphan ? \"--orphan\" : \"--no-checkout\");\n+\t\topts.reflink = REFLINK_OFF;\n+\t}\n \tif (opts.orphan && ac == 2)\n \t\tdie(_(\"option '%s' and commit-ish cannot be used together\"),\n \t\t    \"--orphan\");\ndiff --git a/copy.c b/copy.c\nindex 6074132050..e6dfe33f6a 100644\n--- a/copy.c\n+++ b/copy.c\n@@ -5,6 +5,38 @@\n #include \"strbuf.h\"\n #include \"abspath.h\"\n \n+#if defined(__linux__)\n+#include <sys/ioctl.h>\n+/*\n+ * FICLONE lives in <linux/fs.h>, but including that header tends to clash\n+ * with the libc headers git already pulls in, so define it ourselves if it\n+ * is missing. The value is part of the stable kernel uapi.\n+ */\n+#ifndef FICLONE\n+#define FICLONE _IOW(0x94, 9, int)\n+#endif\n+#elif defined(__APPLE__)\n+#include <sys/attr.h>\n+#include <sys/clonefile.h>\n+#elif defined(GIT_WINDOWS_NATIVE)\n+#include <winioctl.h>\n+/*\n+ * Block cloning on ReFS uses FSCTL_DUPLICATE_EXTENTS_TO_FILE. Older Windows\n+ * SDK headers may lack the control code and its payload struct, so define\n+ * them ourselves when missing (the values are part of the stable Win32 API).\n+ */\n+#ifndef FSCTL_DUPLICATE_EXTENTS_TO_FILE\n+#define FSCTL_DUPLICATE_EXTENTS_TO_FILE \\\n+\tCTL_CODE(FILE_DEVICE_FILE_SYSTEM, 209, METHOD_BUFFERED, FILE_WRITE_DATA)\n+typedef struct _DUPLICATE_EXTENTS_DATA {\n+\tHANDLE FileHandle;\n+\tLARGE_INTEGER SourceFileOffset;\n+\tLARGE_INTEGER TargetFileOffset;\n+\tLARGE_INTEGER ByteCount;\n+} DUPLICATE_EXTENTS_DATA, *PDUPLICATE_EXTENTS_DATA;\n+#endif\n+#endif\n+\n int copy_fd(int ifd, int ofd)\n {\n \twhile (1) {\n@@ -72,3 +104,161 @@ int copy_file_with_time(struct repository *repo,\n \t\treturn copy_times(dst, src);\n \treturn status;\n }\n+\n+#ifdef GIT_WINDOWS_NATIVE\n+/*\n+ * Clone [offset, offset+count) of \"src\" onto \"dst\" via ReFS block cloning.\n+ * \"count\" is rounded up to a cluster boundary by the caller; a range that\n+ * runs past the source's end of file is harmless and ignored by Windows.\n+ */\n+static int clone_extent_windows(HANDLE dst, HANDLE src,\n+\t\t\t\tuint64_t offset, uint64_t count)\n+{\n+\tDUPLICATE_EXTENTS_DATA dup;\n+\tDWORD bytes;\n+\n+\tdup.FileHandle = src;\n+\tdup.SourceFileOffset.QuadPart = offset;\n+\tdup.TargetFileOffset.QuadPart = offset;\n+\tdup.ByteCount.QuadPart = count;\n+\tif (!DeviceIoControl(dst, FSCTL_DUPLICATE_EXTENTS_TO_FILE,\n+\t\t\t     &dup, sizeof(dup), NULL, 0, &bytes, NULL))\n+\t\treturn -1;\n+\treturn 0;\n+}\n+#endif\n+\n+int reflink_file(struct repository *repo,\n+\t\t const char *dst, const char *src, int mode)\n+{\n+#if defined(__APPLE__)\n+\t/*\n+\t * clonefile() refuses to operate when the destination exists and\n+\t * copies the source's permissions for us, so \"mode\" is unused here.\n+\t */\n+\t(void)mode;\n+\tif (clonefile(src, dst, 0) < 0)\n+\t\treturn -1;\n+\tif (adjust_shared_perm(repo, dst))\n+\t\treturn -1;\n+\treturn 0;\n+#elif defined(__linux__)\n+\tint fdi, fdo, status;\n+\n+\tmode = (mode & 0111) ? 0777 : 0666;\n+\tif ((fdi = open(src, O_RDONLY)) < 0)\n+\t\treturn -1;\n+\tif ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) {\n+\t\tint saved = errno;\n+\t\tclose(fdi);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\tstatus = ioctl(fdo, FICLONE, fdi);\n+\tclose(fdi);\n+\tif (status < 0) {\n+\t\tint saved = errno;\n+\t\tclose(fdo);\n+\t\t/* we created an empty file above; do not leave it behind */\n+\t\tunlink(dst);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\tif (close(fdo) != 0)\n+\t\treturn -1;\n+\tif (adjust_shared_perm(repo, dst))\n+\t\treturn -1;\n+\treturn 0;\n+#elif defined(GIT_WINDOWS_NATIVE)\n+\t/*\n+\t * ReFS supports copy-on-write block cloning via\n+\t * FSCTL_DUPLICATE_EXTENTS_TO_FILE, the same mechanism Git LFS uses.\n+\t * Cloned ranges must start and end on a cluster boundary (ReFS uses\n+\t * 64K or 4K clusters) and span less than 4GiB, so clone in <=1GiB\n+\t * chunks and round the final chunk up to a cluster; the destination is\n+\t * sized to the source's exact length and an over-long final range past\n+\t * the source's EOF is ignored.\n+\t */\n+\tconst uint64_t GiB = (uint64_t)1 << 30;\n+\tconst uint64_t clusters[] = { 64 * 1024, 4 * 1024 };\n+\tint fdi, fdo, ret = -1;\n+\tHANDLE hi, ho;\n+\tLARGE_INTEGER size;\n+\tuint64_t off;\n+\tsize_t i;\n+\n+\tmode = (mode & 0111) ? 0777 : 0666;\n+\tif ((fdi = open(src, O_RDONLY | O_BINARY)) < 0)\n+\t\treturn -1;\n+\tif ((fdo = open(dst, O_RDWR | O_CREAT | O_EXCL | O_BINARY, mode)) < 0) {\n+\t\tint saved = errno;\n+\t\tclose(fdi);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\thi = (HANDLE)_get_osfhandle(fdi);\n+\tho = (HANDLE)_get_osfhandle(fdo);\n+\tif (hi == INVALID_HANDLE_VALUE || ho == INVALID_HANDLE_VALUE ||\n+\t    !GetFileSizeEx(hi, &size)) {\n+\t\terrno = EINVAL;\n+\t\tgoto cleanup;\n+\t}\n+\n+\t/* the destination must be the source's exact size before cloning */\n+\tif (!SetFilePointerEx(ho, size, NULL, FILE_BEGIN) || !SetEndOfFile(ho)) {\n+\t\terrno = EIO;\n+\t\tgoto cleanup;\n+\t}\n+\n+\tret = 0;\n+\t/* clone whole 1GiB regions (already cluster aligned) */\n+\tfor (off = 0; (uint64_t)size.QuadPart > off &&\n+\t\t      (uint64_t)size.QuadPart - off > GiB; off += GiB) {\n+\t\tif (clone_extent_windows(ho, hi, off, GiB)) {\n+\t\t\terrno = ENOSYS;\n+\t\t\tret = -1;\n+\t\t\tgoto cleanup;\n+\t\t}\n+\t}\n+\t/* clone the tail, rounding its length up to a cluster (64K then 4K) */\n+\tif (!ret && (uint64_t)size.QuadPart > off) {\n+\t\tuint64_t rem = (uint64_t)size.QuadPart - off;\n+\n+\t\tret = -1;\n+\t\tfor (i = 0; i < ARRAY_SIZE(clusters); i++) {\n+\t\t\tuint64_t count = (rem + clusters[i] - 1) &\n+\t\t\t\t\t ~(clusters[i] - 1);\n+\t\t\tif (!clone_extent_windows(ho, hi, off, count)) {\n+\t\t\t\tret = 0;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tif (ret)\n+\t\t\terrno = ENOSYS;\t/* not a CoW volume */\n+\t}\n+\n+cleanup:\n+\tclose(fdi);\n+\tif (close(fdo) && !ret) {\n+\t\terrno = EIO;\n+\t\tret = -1;\n+\t}\n+\tif (ret) {\n+\t\tint saved = errno;\n+\t\tunlink(dst);\n+\t\terrno = saved;\n+\t\treturn -1;\n+\t}\n+\tif (adjust_shared_perm(repo, dst))\n+\t\treturn -1;\n+\treturn 0;\n+#else\n+\t/* No reflink primitive on this platform. */\n+\t(void)repo;\n+\t(void)dst;\n+\t(void)src;\n+\t(void)mode;\n+\terrno = ENOSYS;\n+\treturn -1;\n+#endif\n+}\ndiff --git a/copy.h b/copy.h\nindex 1059b118d6..b9168a24f1 100644\n--- a/copy.h\n+++ b/copy.h\n@@ -11,4 +11,18 @@ int copy_file(struct repository *repo,\n int copy_file_with_time(struct repository *repo,\n \t\t\tconst char *dst, const char *src, int mode);\n \n+/*\n+ * Create \"dst\" as a copy-on-write (reflink) clone of the regular file\n+ * \"src\", so that the two files share their data blocks until one of\n+ * them is modified. \"dst\" must not already exist.\n+ *\n+ * This only succeeds on filesystems that support block cloning (e.g.\n+ * btrfs, XFS or bcachefs on Linux, APFS on macOS). When the platform or\n+ * filesystem does not support reflinks, -1 is returned with errno set to\n+ * ENOSYS (or the underlying error). Callers are expected to fall back to\n+ * copy_file() in that case. Returns 0 on success.\n+ */\n+int reflink_file(struct repository *repo,\n+\t\t const char *dst, const char *src, int mode);\n+\n #endif /* COPY_H */\ndiff --git a/t/t2400-worktree-add.sh b/t/t2400-worktree-add.sh\nindex bdcca97633..4aa63c5d3f 100755\n--- a/t/t2400-worktree-add.sh\n+++ b/t/t2400-worktree-add.sh\n@@ -1288,4 +1288,100 @@ test_expect_success 'relative worktree sets extension config' '\n \ttest_cmp_config -C repo true extensions.relativeworktrees\n '\n \n+test_expect_success '--reflink produces a correct checkout on any filesystem' '\n+\ttest_when_finished \"rm -rf reflinkrepo\" &&\n+\tgit init reflinkrepo &&\n+\t(\n+\t\tcd reflinkrepo &&\n+\t\ttest_commit base file.txt base &&\n+\t\ttest_commit next file.txt next &&\n+\t\tgit worktree add --reflink wt -b reflinkbr base &&\n+\t\techo base >expect &&\n+\t\ttest_cmp expect wt/file.txt &&\n+\t\tgit -C wt status --porcelain >status &&\n+\t\ttest_must_be_empty status\n+\t)\n+'\n+\n+test_expect_success '--reflink rejects incompatible options' '\n+\ttest_must_fail git worktree add --reflink --no-checkout wt-bad HEAD 2>err &&\n+\ttest_grep \"cannot be used together\" err &&\n+\ttest_must_fail git worktree add --reflink --orphan wt-bad2 2>err &&\n+\ttest_grep \"cannot be used together\" err\n+'\n+\n+test_expect_success 'worktree.reflink config drives a correct checkout' '\n+\ttest_when_finished \"rm -rf reflinkcfg\" &&\n+\tgit init reflinkcfg &&\n+\t(\n+\t\tcd reflinkcfg &&\n+\t\ttest_commit cfg file.txt value &&\n+\t\tgit -c worktree.reflink=true worktree add wt HEAD &&\n+\t\techo value >expect &&\n+\t\ttest_cmp expect wt/file.txt\n+\t)\n+'\n+\n+test_expect_success 'worktree.reflink=auto does not break --orphan' '\n+\ttest_when_finished \"rm -rf reflinkorphan\" &&\n+\tgit init reflinkorphan &&\n+\t(\n+\t\tcd reflinkorphan &&\n+\t\ttest_commit base file.txt value &&\n+\t\tgit -c worktree.reflink=auto worktree add --orphan wt &&\n+\t\tgit -C wt symbolic-ref --short HEAD >actual &&\n+\t\techo wt >expect &&\n+\t\ttest_cmp expect actual\n+\t)\n+'\n+\n+test_expect_success '--no-reflink overrides worktree.reflink' '\n+\ttest_when_finished \"rm -rf reflinkoff\" &&\n+\tgit init reflinkoff &&\n+\t(\n+\t\tcd reflinkoff &&\n+\t\ttest_commit base file.txt value &&\n+\t\tgit -c worktree.reflink=true worktree add --no-reflink wt HEAD &&\n+\t\techo value >expect &&\n+\t\ttest_cmp expect wt/file.txt\n+\t)\n+'\n+\n+# Reflinks are only available on copy-on-write filesystems (btrfs, XFS,\n+# bcachefs, APFS, ...). Where they are unavailable, --reflink transparently\n+# falls back to a regular checkout, which the test above already covers.\n+#\n+# GNU cp probes with --reflink=always. macOS cp has no such option; -c\n+# is clonefile(2), which is what the APFS CI jobs exercise.\n+test_lazy_prereq REFLINK '\n+\techo probe >reflink-src &&\n+\tif test_have_prereq MACOS\n+\tthen\n+\t\tcp -c reflink-src reflink-dst 2>/dev/null\n+\telse\n+\t\tcp --reflink=always reflink-src reflink-dst 2>/dev/null\n+\tfi\n+'\n+\n+test_expect_success REFLINK '--reflink carries untracked files and reconciles changes' '\n+\ttest_when_finished \"rm -rf cowrepo\" &&\n+\tgit init cowrepo &&\n+\t(\n+\t\tcd cowrepo &&\n+\t\ttest_commit same same.txt content &&\n+\t\ttest_commit old change.txt old-value &&\n+\t\ttest_commit new change.txt new-value &&\n+\t\techo artifact >untracked.bin &&\n+\t\tgit worktree add --reflink wt -b cowbr old &&\n+\t\techo content >expect &&\n+\t\ttest_cmp expect wt/same.txt &&\n+\t\techo old-value >expect &&\n+\t\ttest_cmp expect wt/change.txt &&\n+\t\techo artifact >expect &&\n+\t\ttest_cmp expect wt/untracked.bin &&\n+\t\tgit -C wt status --porcelain >status &&\n+\t\ttest_grep \"?? untracked.bin\" status\n+\t)\n+'\n+\n test_done\n-- \ngitgitgadget\n\n\n"},{"id":"555686","messageId":"042485f0e9cd8cf1765b811ea7334247aec44971.1792567061.git.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.v3.git.git.1792567061.gitgitgadget@gmail.com","subject":"[PATCH v3 2/4] worktree: reap ephemeral branches created by \"worktree add\"","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-21T07:17:39Z","receivedAt":"2026-10-21T07:17:39Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"From: Jason Newton <nevion@gmail.com>\n\nWhen \"git worktree add <path>\" is given no branch to check out, it\nauto-creates one named after the path. Such a branch exists only to back\nthe new worktree, yet it outlives it: removing the worktree leaves the\nbranch behind, so a fleet of throwaway worktrees fills refs/heads/ with\ndead branches that have to be cleaned up by hand.\n\nTreat an auto-created branch as owned by the worktree. Record it in the\nworktree's administrative directory (worktrees/<id>/owned-branch) at\ncreation time -- the one moment we can know for certain the branch is\nworktree-private, since we are the one that created it. \"git worktree\nremove\" then deletes the owned branch once the worktree is gone and it\nis no longer checked out.\n\nOwnership is recorded only when \"worktree add\" itself creates the branch\nvia DWIM auto-naming; a branch named explicitly with -b/-B, or one that\nalready existed, is never owned and never reaped. Deletion is\nunconditional (even for unmerged commits) because an ephemeral branch is\ndisposable by contract: to keep the work, pass --keep-branch, or anchor\nthe commits with an ordinary branch beforehand -- a normal branch can\npoint at the same commits, after which reaping the ephemeral ref loses\nnothing. \"git branch -m\" updates the marker so ownership follows a\nrename, and the branch stays ephemeral.\n\nThe marker is just another per-worktree administrative file, so older\nversions of Git simply ignore it (they keep the branch on removal, as\ntoday).\n\nSigned-off-by: Jason Newton <nevion@gmail.com>\n---\n Documentation/git-worktree.adoc | 22 ++++++++--\n builtin/branch.c                | 28 +++++++++++++\n builtin/worktree.c              | 74 ++++++++++++++++++++++++++++++++-\n t/t2400-worktree-add.sh         | 55 ++++++++++++++++++++++++\n t/t3200-branch.sh               |  2 +-\n t/t3400-rebase.sh               |  2 +-\n t/t5516-fetch-push.sh           |  2 +-\n 7 files changed, 178 insertions(+), 7 deletions(-)\n\ndiff --git a/Documentation/git-worktree.adoc b/Documentation/git-worktree.adoc\nindex 4264ee753a..99e6e55be4 100644\n--- a/Documentation/git-worktree.adoc\n+++ b/Documentation/git-worktree.adoc\n@@ -15,7 +15,7 @@ git worktree list [-v | --porcelain [-z]]\n git worktree lock [--reason <string>] <worktree>\n git worktree move <worktree> <new-path>\n git worktree prune [-n] [-v] [--expire <expire>]\n-git worktree remove [-f] <worktree>\n+git worktree remove [-f] [--keep-branch] <worktree>\n git worktree repair [<path>...]\n git worktree unlock <worktree>\n \n@@ -40,8 +40,11 @@ In its simplest form, `git worktree add <path>` automatically creates a\n new branch whose name is the final component of _<path>_, which is\n convenient if you plan to work on a new topic. For instance, `git\n worktree add ../hotfix` creates new branch `hotfix` and checks it out at\n-path `../hotfix`. To instead work on an existing branch in a new worktree,\n-use `git worktree add <path> <branch>`. On the other hand, if you just\n+path `../hotfix`. Such an automatically-created branch is _ephemeral_: it\n+is owned by the worktree and is deleted again when the worktree is removed\n+with `git worktree remove` (see that command and `--keep-branch`). To\n+instead work on an existing branch in a new worktree, use\n+`git worktree add <path> <branch>`. On the other hand, if you just\n plan to make some experimental changes or do testing without disturbing\n existing development, it is often convenient to create a 'throwaway'\n worktree not associated with any branch. For instance,\n@@ -145,6 +148,14 @@ Remove a worktree. Only clean worktrees (no untracked files and no\n modification in tracked files) can be removed. Unclean worktrees or ones\n with submodules can be removed with `--force`. The main worktree cannot be\n removed.\n++\n+If the worktree owns an _ephemeral_ branch -- one that `git worktree add`\n+created itself because no branch was named (the auto-naming case above) --\n+that branch is deleted along with the worktree, even if it has unmerged\n+commits, since it was created solely to back this worktree. To keep it, use\n+`--keep-branch`, or anchor the commits with an ordinary branch\n+(`git branch <name>`) beforehand. A branch you named explicitly (`-b`/`-B`)\n+or one that existed before the worktree is never deleted.\n \n `repair [<path>...]`::\n \n@@ -192,6 +203,11 @@ allows the move to proceed; use `--force` twice if the destination is locked.\n `remove` refuses to remove an unclean worktree unless `--force` is used.\n To remove a locked worktree, specify `--force` twice.\n \n+`--keep-branch`::\n+\tWith `remove`, do not delete the worktree's ephemeral (owned) branch;\n+\tkeep it as an ordinary branch. Has no effect on worktrees that do not\n+\town a branch.\n+\n `-b <new-branch>`::\n `-B <new-branch>`::\n \tWith `add`, create a new branch named _<new-branch>_ starting at\ndiff --git a/builtin/branch.c b/builtin/branch.c\nindex a613148fc7..ca2e25df03 100644\n--- a/builtin/branch.c\n+++ b/builtin/branch.c\n@@ -607,6 +607,32 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,\n #define IS_HEAD 1\n #define IS_ORPHAN 2\n \n+/*\n+ * When a branch that a worktree owns (its ephemeral branch, recorded in\n+ * worktrees/<id>/owned-branch) is renamed, update the marker so ownership\n+ * follows the new name -- it stays ephemeral.\n+ */\n+static void rename_owned_branch_markers(struct worktree **worktrees,\n+\t\t\t\t\tconst char *oldref, const char *newref)\n+{\n+\tfor (int i = 0; worktrees[i]; i++) {\n+\t\tstruct strbuf path = STRBUF_INIT, buf = STRBUF_INIT;\n+\n+\t\tif (!worktrees[i]->id)\n+\t\t\tcontinue;\t/* the main worktree keeps no marker */\n+\t\trepo_common_path_append(the_repository, &path,\n+\t\t\t\t\t\"worktrees/%s/owned-branch\",\n+\t\t\t\t\tworktrees[i]->id);\n+\t\tif (strbuf_read_file(&buf, path.buf, 64) > 0) {\n+\t\t\tstrbuf_trim(&buf);\n+\t\t\tif (!strcmp(buf.buf, oldref))\n+\t\t\t\twrite_file(path.buf, \"%s\", newref);\n+\t\t}\n+\t\tstrbuf_release(&path);\n+\t\tstrbuf_release(&buf);\n+\t}\n+}\n+\n static void copy_or_rename_branch(const char *oldname, const char *newname, int copy, int force)\n {\n \tstruct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;\n@@ -675,6 +701,8 @@ static void copy_or_rename_branch(const char *oldname, const char *newname, int\n \tif (!copy && !(oldref_usage & IS_ORPHAN) &&\n \t    refs_rename_ref(get_main_ref_store(the_repository), oldref.buf, newref.buf, logmsg.buf))\n \t\tdie(_(\"branch rename failed\"));\n+\tif (!copy && !(oldref_usage & IS_ORPHAN))\n+\t\trename_owned_branch_markers(worktrees, oldref.buf, newref.buf);\n \tif (copy && refs_copy_existing_ref(get_main_ref_store(the_repository), oldref.buf, newref.buf, logmsg.buf))\n \t\tdie(_(\"branch copy failed\"));\n \ndiff --git a/builtin/worktree.c b/builtin/worktree.c\nindex 9d4b51305e..1059429cbb 100644\n--- a/builtin/worktree.c\n+++ b/builtin/worktree.c\n@@ -41,7 +41,7 @@\n #define BUILTIN_WORKTREE_PRUNE_USAGE \\\n \tN_(\"git worktree prune [-n] [-v] [--expire <expire>]\")\n #define BUILTIN_WORKTREE_REMOVE_USAGE \\\n-\tN_(\"git worktree remove [-f] <worktree>\")\n+\tN_(\"git worktree remove [-f] [--keep-branch] <worktree>\")\n #define BUILTIN_WORKTREE_REPAIR_USAGE \\\n \tN_(\"git worktree repair [<path>...]\")\n #define BUILTIN_WORKTREE_UNLOCK_USAGE \\\n@@ -130,8 +130,34 @@ struct add_opts {\n \tint relative_paths;\n \tint reflink;\n \tconst char *keep_locked;\n+\tconst char *owned_branch;\n };\n \n+/*\n+ * An \"owned\" (ephemeral) branch is one that \"git worktree add\" created itself\n+ * because the user did not name a branch (the DWIM auto-name case). Its\n+ * lifetime is bound to the worktree: it is recorded in the worktree's\n+ * administrative directory at creation and reaped when the worktree is\n+ * removed. A pre-existing branch, or one named explicitly with -b/-B, is never\n+ * owned.\n+ */\n+static char *read_owned_branch(const char *id)\n+{\n+\tstruct strbuf path = STRBUF_INIT, buf = STRBUF_INIT;\n+\tchar *ret = NULL;\n+\n+\trepo_common_path_append(the_repository, &path,\n+\t\t\t\t\"worktrees/%s/owned-branch\", id);\n+\tif (strbuf_read_file(&buf, path.buf, 64) > 0) {\n+\t\tstrbuf_trim(&buf);\n+\t\tif (buf.len)\n+\t\t\tret = strbuf_detach(&buf, NULL);\n+\t}\n+\tstrbuf_release(&path);\n+\tstrbuf_release(&buf);\n+\treturn ret;\n+}\n+\n static int show_only;\n static int verbose;\n static int guess_remote;\n@@ -771,6 +797,16 @@ static int add_worktree(const char *path, const char *refname,\n \tif (the_repository->repository_format_worktree_config)\n \t\tcopy_filtered_worktree_config(sb_repo.buf);\n \n+\t/*\n+\t * Record an owned (ephemeral) branch so that \"git worktree remove\" can\n+\t * reap it. Only DWIM-created branches are owned (see read_owned_branch()).\n+\t */\n+\tif (opts->owned_branch) {\n+\t\tstrbuf_reset(&sb);\n+\t\tstrbuf_addf(&sb, \"%s/owned-branch\", sb_repo.buf);\n+\t\twrite_file(sb.buf, \"refs/heads/%s\", opts->owned_branch);\n+\t}\n+\n \tstrvec_pushf(&child_env, \"%s=%s\", GIT_DIR_ENVIRONMENT, sb_git.buf);\n \tstrvec_pushf(&child_env, \"%s=%s\", GIT_WORK_TREE_ENVIRONMENT, path);\n \n@@ -1148,6 +1184,13 @@ static int add(int ac, const char **av, const char *prefix,\n \t\t\tbranch = branch_to_free = s;\n \t\tnew_branch = new_branch_to_free;\n \n+\t\t/*\n+\t\t * A branch auto-created from the path (the user named no\n+\t\t * branch) is owned by this worktree and reaped on removal.\n+\t\t */\n+\t\tif (new_branch_to_free)\n+\t\t\topts.owned_branch = new_branch_to_free;\n+\n \t\t/* DWIM: Infer --orphan when repo has no refs. */\n \t\topts.orphan = (!s) && dwim_orphan(&opts, !!opt_track, 1);\n \t} else if (ac == 2 && new_branch) {\n@@ -1651,15 +1694,19 @@ static int remove_worktree(int ac, const char **av, const char *prefix,\n \t\t\t   struct repository *repo UNUSED)\n {\n \tint force = 0;\n+\tint keep_branch = 0;\n \tstruct option options[] = {\n \t\tOPT__FORCE(&force,\n \t\t\t N_(\"force removal even if worktree is dirty or locked\"),\n \t\t\t PARSE_OPT_NOCOMPLETE),\n+\t\tOPT_BOOL(0, \"keep-branch\", &keep_branch,\n+\t\t\t N_(\"keep the worktree's owned (ephemeral) branch\")),\n \t\tOPT_END()\n \t};\n \tstruct worktree **worktrees, *wt;\n \tstruct strbuf errmsg = STRBUF_INIT;\n \tconst char *reason = NULL;\n+\tchar *owned = NULL;\n \tint ret = 0;\n \n \tac = parse_options(ac, av, prefix, options, git_worktree_remove_usage, 0);\n@@ -1685,6 +1732,10 @@ static int remove_worktree(int ac, const char **av, const char *prefix,\n \t\t    errmsg.buf);\n \tstrbuf_release(&errmsg);\n \n+\t/* read the owned-branch marker before the admin dir is deleted */\n+\tif (!keep_branch)\n+\t\towned = read_owned_branch(wt->id);\n+\n \tif (file_exists(wt->path)) {\n \t\tif (!force)\n \t\t\tcheck_clean_worktree(wt, av[0]);\n@@ -1698,6 +1749,27 @@ static int remove_worktree(int ac, const char **av, const char *prefix,\n \tret |= delete_git_dir(wt->id);\n \tdelete_worktrees_dir_if_empty();\n \n+\t/*\n+\t * Reap the worktree's owned (ephemeral) branch now that the worktree\n+\t * is gone and the branch is no longer checked out. This is\n+\t * unconditional by design: the branch was created for this worktree\n+\t * and is disposable. To keep the work, anchor it with an ordinary\n+\t * branch (or pass --keep-branch) before removing the worktree.\n+\t */\n+\tif (owned) {\n+\t\tstruct ref_store *refs = get_main_ref_store(the_repository);\n+\t\tif (refs_ref_exists(refs, owned)) {\n+\t\t\tif (refs_delete_ref(refs, NULL, owned, NULL, 0))\n+\t\t\t\tret = error(_(\"failed to reap branch '%s'\"), owned);\n+\t\t\telse {\n+\t\t\t\tconst char *name = owned;\n+\t\t\t\tskip_prefix(owned, \"refs/heads/\", &name);\n+\t\t\t\tfprintf_ln(stderr, _(\"Removed branch '%s'\"), name);\n+\t\t\t}\n+\t\t}\n+\t\tfree(owned);\n+\t}\n+\n \tfree_worktrees(worktrees);\n \treturn ret;\n }\ndiff --git a/t/t2400-worktree-add.sh b/t/t2400-worktree-add.sh\nindex 4aa63c5d3f..14bf455736 100755\n--- a/t/t2400-worktree-add.sh\n+++ b/t/t2400-worktree-add.sh\n@@ -1384,4 +1384,59 @@ test_expect_success REFLINK '--reflink carries untracked files and reconciles ch\n \t)\n '\n \n+test_expect_success 'ephemeral: DWIM-created branch is owned and reaped on remove' '\n+\ttest_when_finished \"git worktree remove -f eph || :; git branch -D eph 2>/dev/null || :\" &&\n+\tgit worktree add eph &&\n+\techo refs/heads/eph >expect &&\n+\ttest_cmp expect .git/worktrees/eph/owned-branch &&\n+\tgit rev-parse --verify refs/heads/eph &&\n+\tgit worktree remove eph &&\n+\ttest_must_fail git rev-parse --verify --quiet refs/heads/eph\n+'\n+\n+test_expect_success 'ephemeral: -b branch is not owned and is kept on remove' '\n+\ttest_when_finished \"git worktree remove -f nb || :; git branch -D named 2>/dev/null || :\" &&\n+\tgit worktree add -b named nb &&\n+\ttest_path_is_missing .git/worktrees/nb/owned-branch &&\n+\tgit worktree remove nb &&\n+\tgit rev-parse --verify refs/heads/named\n+'\n+\n+test_expect_success 'ephemeral: pre-existing branch is not owned' '\n+\ttest_when_finished \"git worktree remove -f pe || :; git branch -D pre 2>/dev/null || :\" &&\n+\tgit branch pre &&\n+\tgit worktree add pe pre &&\n+\ttest_path_is_missing .git/worktrees/pe/owned-branch &&\n+\tgit worktree remove pe &&\n+\tgit rev-parse --verify refs/heads/pre\n+'\n+\n+test_expect_success 'ephemeral: --keep-branch keeps an owned branch' '\n+\ttest_when_finished \"git branch -D keepme 2>/dev/null || :\" &&\n+\tgit worktree add keepme &&\n+\tgit worktree remove --keep-branch keepme &&\n+\tgit rev-parse --verify refs/heads/keepme\n+'\n+\n+test_expect_success 'ephemeral: branch -m follows the marker and stays ephemeral' '\n+\ttest_when_finished \"git worktree remove -f mv || :; git branch -D mv2 2>/dev/null || :\" &&\n+\tgit worktree add mv &&\n+\tgit -C mv branch -m mv mv2 &&\n+\techo refs/heads/mv2 >expect &&\n+\ttest_cmp expect .git/worktrees/mv/owned-branch &&\n+\tgit worktree remove mv &&\n+\ttest_must_fail git rev-parse --verify --quiet refs/heads/mv2\n+'\n+\n+test_expect_success 'ephemeral: commits survive the reap when anchored by a normal branch' '\n+\ttest_when_finished \"git worktree remove -f anc || :; git branch -D anchored 2>/dev/null || :\" &&\n+\tgit worktree add anc &&\n+\ttest_commit -C anc agentwork &&\n+\ttip=$(git -C anc rev-parse HEAD) &&\n+\tgit branch anchored \"$tip\" &&\n+\tgit worktree remove anc &&\n+\ttest_must_fail git rev-parse --verify --quiet refs/heads/anc &&\n+\ttest \"$(git rev-parse anchored)\" = \"$tip\"\n+'\n+\n test_done\ndiff --git a/t/t3200-branch.sh b/t/t3200-branch.sh\nindex cdb6c6a634..67c7c67853 100755\n--- a/t/t3200-branch.sh\n+++ b/t/t3200-branch.sh\n@@ -190,7 +190,7 @@ test_expect_success 'git branch -M foo bar should fail when bar is checked out'\n \n test_expect_success 'git branch -M foo bar should fail when bar is checked out in worktree' '\n \tgit branch -f bar &&\n-\ttest_when_finished \"git worktree remove wt && git branch -D wt\" &&\n+\ttest_when_finished \"git worktree remove --keep-branch wt && git branch -D wt\" &&\n \tgit worktree add wt &&\n \ttest_must_fail git branch -M bar wt\n '\ndiff --git a/t/t3400-rebase.sh b/t/t3400-rebase.sh\nindex accaaba4d4..9c0c80f113 100755\n--- a/t/t3400-rebase.sh\n+++ b/t/t3400-rebase.sh\n@@ -471,7 +471,7 @@ test_expect_success 'git rebase --update-ref with core.commentChar and branch on\n \ttest_when_finished git branch -D base topic2 &&\n \ttest_when_finished git checkout main &&\n \ttest_when_finished git branch -D wt-topic &&\n-\ttest_when_finished git worktree remove wt-topic &&\n+\ttest_when_finished git worktree remove --keep-branch wt-topic &&\n \tgit checkout main &&\n \tgit checkout -b base &&\n \tgit checkout -b topic2 &&\ndiff --git a/t/t5516-fetch-push.sh b/t/t5516-fetch-push.sh\nindex b982b209bf..6ffeb064fa 100755\n--- a/t/t5516-fetch-push.sh\n+++ b/t/t5516-fetch-push.sh\n@@ -1873,7 +1873,7 @@ test_expect_success 'updateInstead with bare repository worktree and unborn bare\n '\n \n test_expect_success 'refuse fetch to current branch of worktree' '\n-\ttest_when_finished \"git worktree remove --force wt && git branch -D wt\" &&\n+\ttest_when_finished \"git worktree remove --force --keep-branch wt && git branch -D wt\" &&\n \tgit worktree add wt &&\n \ttest_commit apple &&\n \ttest_must_fail git fetch . HEAD:wt &&\n-- \ngitgitgadget\n\n\n"},{"id":"555687","messageId":"91806975a6909265b1325206ef2f33a169393920.1792567061.git.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.v3.git.git.1792567061.gitgitgadget@gmail.com","subject":"[PATCH v3 3/4] worktree: disable reflink on Windows","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-21T07:17:40Z","receivedAt":"2026-10-21T07:17:40Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"From: Jason Newton <nevion@gmail.com>\n\nFSCTL_DUPLICATE_EXTENTS_TO_FILE can publish zeros when the source\ndata is still cached. git-lfs issue 6312 reports that on Windows 11\nbuild 26200, and a later reproduction hit build 26200.9448. No fixed\nWindows build is identified, so reflink_file() refuses on every\nWindows version.\n\ngit worktree add --reflink and worktree.reflink=true warn with that\nbuild number and fall back to a regular checkout. worktree.reflink=auto\nstays silent, as it does when the filesystem cannot reflink.\n\nSigned-off-by: Jason Newton <nevion@gmail.com>\n---\n Documentation/config/worktree.adoc |   6 +-\n Documentation/git-worktree.adoc    |  12 ++-\n builtin/worktree.c                 |  13 +++\n copy.c                             | 133 +++--------------------------\n t/t2400-worktree-add.sh            |  15 ++++\n 5 files changed, 53 insertions(+), 126 deletions(-)\n\ndiff --git a/Documentation/config/worktree.adoc b/Documentation/config/worktree.adoc\nindex aa849c08d2..e221efc615 100644\n--- a/Documentation/config/worktree.adoc\n+++ b/Documentation/config/worktree.adoc\n@@ -25,6 +25,8 @@ thus making it incompatible with older versions of Git.\n \t(see linkgit:git-worktree[1]). May be set to \"`true`\", \"`false`\"\n \t(the default), or \"`auto`\". With \"`true`\", a filesystem that does\n \tnot support reflinks produces a warning before falling back to an\n-\tordinary checkout; with \"`auto`\", the fallback is silent. An\n-\texplicit `--reflink` or `--no-reflink` on the command line\n+\tordinary checkout; with \"`auto`\", the fallback is silent. On Windows\n+\tthe request always falls back. An explicit request warns that block\n+\tcloning can zero-fill files on Windows build 26200; \"`auto`\" stays\n+\tsilent. An explicit `--reflink` or `--no-reflink` on the command line\n \toverrides this setting.\ndiff --git a/Documentation/git-worktree.adoc b/Documentation/git-worktree.adoc\nindex 99e6e55be4..6cc7c1f27a 100644\n--- a/Documentation/git-worktree.adoc\n+++ b/Documentation/git-worktree.adoc\n@@ -244,10 +244,14 @@ To remove a locked worktree, specify `--force` twice.\n +\n Reflinks require a copy-on-write filesystem: for example btrfs, XFS,\n bcachefs or ZFS on Linux (and overlayfs on top of one of these, as used by\n-containers), APFS on macOS, or ReFS on Windows. On a filesystem that does\n-not support reflinks, `--reflink` transparently falls back to an ordinary\n-checkout. Because the source worktree's untracked and ignored files are\n-cloned as well, only use `--reflink` when that is acceptable.\n+containers), or APFS on macOS. Reflink is disabled on Windows. ReFS block\n+cloning can zero-fill files on Windows build 26200 (git-lfs issue 6312),\n+and no fixed build is known. On Windows, `--reflink` falls back to an\n+ordinary checkout and, unless `worktree.reflink` is `auto`, warns with\n+that build number. On a filesystem that does not support reflinks,\n+`--reflink` transparently falls back to an ordinary checkout. Because the\n+source worktree's untracked and ignored files are cloned as well, only use\n+`--reflink` when that is acceptable.\n +\n This option cannot be combined with `--no-checkout` or `--orphan`. It can\n be enabled by default with the `worktree.reflink` configuration; see\ndiff --git a/builtin/worktree.c b/builtin/worktree.c\nindex 1059429cbb..93fcaa5ecd 100644\n--- a/builtin/worktree.c\n+++ b/builtin/worktree.c\n@@ -563,6 +563,18 @@ static int reflink_worktree(const char *path, const char *wt_git_dir,\n \t\treturn error(_(\"--reflink needs a source working tree, but this \"\n \t\t\t       \"repository does not have one\"));\n \n+#ifdef GIT_WINDOWS_NATIVE\n+\t/*\n+\t * reflink_file() refuses on Windows. Build 26200 is the version\n+\t * named in git-lfs issue 6312; no later build is known to be fixed.\n+\t * Auto mode stays quiet, matching the non-Windows fallback.\n+\t */\n+\tif (!opts->quiet && opts->reflink != REFLINK_AUTO)\n+\t\twarning(_(\"reflink is disabled on Windows; block cloning \"\n+\t\t\t  \"can zero-fill files on Windows build 26200; \"\n+\t\t\t  \"falling back to a regular checkout\"));\n+\treturn 1;\n+#else\n \tif (!reflink_supported(path)) {\n \t\t/* In auto mode the fallback is expected, so stay quiet. */\n \t\tif (!opts->quiet && opts->reflink != REFLINK_AUTO)\n@@ -570,6 +582,7 @@ static int reflink_worktree(const char *path, const char *wt_git_dir,\n \t\t\t\t  \"falling back to a regular checkout\"), path);\n \t\treturn 1;\n \t}\n+#endif\n \n \tif (stat(path, &dst_st))\n \t\treturn error_errno(_(\"could not stat '%s'\"), path);\ndiff --git a/copy.c b/copy.c\nindex e6dfe33f6a..2eb4c7477e 100644\n--- a/copy.c\n+++ b/copy.c\n@@ -18,23 +18,6 @@\n #elif defined(__APPLE__)\n #include <sys/attr.h>\n #include <sys/clonefile.h>\n-#elif defined(GIT_WINDOWS_NATIVE)\n-#include <winioctl.h>\n-/*\n- * Block cloning on ReFS uses FSCTL_DUPLICATE_EXTENTS_TO_FILE. Older Windows\n- * SDK headers may lack the control code and its payload struct, so define\n- * them ourselves when missing (the values are part of the stable Win32 API).\n- */\n-#ifndef FSCTL_DUPLICATE_EXTENTS_TO_FILE\n-#define FSCTL_DUPLICATE_EXTENTS_TO_FILE \\\n-\tCTL_CODE(FILE_DEVICE_FILE_SYSTEM, 209, METHOD_BUFFERED, FILE_WRITE_DATA)\n-typedef struct _DUPLICATE_EXTENTS_DATA {\n-\tHANDLE FileHandle;\n-\tLARGE_INTEGER SourceFileOffset;\n-\tLARGE_INTEGER TargetFileOffset;\n-\tLARGE_INTEGER ByteCount;\n-} DUPLICATE_EXTENTS_DATA, *PDUPLICATE_EXTENTS_DATA;\n-#endif\n #endif\n \n int copy_fd(int ifd, int ofd)\n@@ -105,29 +88,6 @@ int copy_file_with_time(struct repository *repo,\n \treturn status;\n }\n \n-#ifdef GIT_WINDOWS_NATIVE\n-/*\n- * Clone [offset, offset+count) of \"src\" onto \"dst\" via ReFS block cloning.\n- * \"count\" is rounded up to a cluster boundary by the caller; a range that\n- * runs past the source's end of file is harmless and ignored by Windows.\n- */\n-static int clone_extent_windows(HANDLE dst, HANDLE src,\n-\t\t\t\tuint64_t offset, uint64_t count)\n-{\n-\tDUPLICATE_EXTENTS_DATA dup;\n-\tDWORD bytes;\n-\n-\tdup.FileHandle = src;\n-\tdup.SourceFileOffset.QuadPart = offset;\n-\tdup.TargetFileOffset.QuadPart = offset;\n-\tdup.ByteCount.QuadPart = count;\n-\tif (!DeviceIoControl(dst, FSCTL_DUPLICATE_EXTENTS_TO_FILE,\n-\t\t\t     &dup, sizeof(dup), NULL, 0, &bytes, NULL))\n-\t\treturn -1;\n-\treturn 0;\n-}\n-#endif\n-\n int reflink_file(struct repository *repo,\n \t\t const char *dst, const char *src, int mode)\n {\n@@ -171,87 +131,20 @@ int reflink_file(struct repository *repo,\n \treturn 0;\n #elif defined(GIT_WINDOWS_NATIVE)\n \t/*\n-\t * ReFS supports copy-on-write block cloning via\n-\t * FSCTL_DUPLICATE_EXTENTS_TO_FILE, the same mechanism Git LFS uses.\n-\t * Cloned ranges must start and end on a cluster boundary (ReFS uses\n-\t * 64K or 4K clusters) and span less than 4GiB, so clone in <=1GiB\n-\t * chunks and round the final chunk up to a cluster; the destination is\n-\t * sized to the source's exact length and an over-long final range past\n-\t * the source's EOF is ignored.\n+\t * ReFS block cloning (FSCTL_DUPLICATE_EXTENTS_TO_FILE) is disabled.\n+\t * On Windows 11 build 26200 the ioctl remaps on-disk clusters, so a\n+\t * clone of data still sitting in the cache captures unwritten zeros.\n+\t * The later flush of the source does not update the clone, and the\n+\t * zeros are permanent. That is git-lfs issue 6312, reproduced on\n+\t * build 26200.9448. No fixed Windows build is identified, so refuse\n+\t * on every Windows version and let the caller fall back to a copy.\n \t */\n-\tconst uint64_t GiB = (uint64_t)1 << 30;\n-\tconst uint64_t clusters[] = { 64 * 1024, 4 * 1024 };\n-\tint fdi, fdo, ret = -1;\n-\tHANDLE hi, ho;\n-\tLARGE_INTEGER size;\n-\tuint64_t off;\n-\tsize_t i;\n-\n-\tmode = (mode & 0111) ? 0777 : 0666;\n-\tif ((fdi = open(src, O_RDONLY | O_BINARY)) < 0)\n-\t\treturn -1;\n-\tif ((fdo = open(dst, O_RDWR | O_CREAT | O_EXCL | O_BINARY, mode)) < 0) {\n-\t\tint saved = errno;\n-\t\tclose(fdi);\n-\t\terrno = saved;\n-\t\treturn -1;\n-\t}\n-\thi = (HANDLE)_get_osfhandle(fdi);\n-\tho = (HANDLE)_get_osfhandle(fdo);\n-\tif (hi == INVALID_HANDLE_VALUE || ho == INVALID_HANDLE_VALUE ||\n-\t    !GetFileSizeEx(hi, &size)) {\n-\t\terrno = EINVAL;\n-\t\tgoto cleanup;\n-\t}\n-\n-\t/* the destination must be the source's exact size before cloning */\n-\tif (!SetFilePointerEx(ho, size, NULL, FILE_BEGIN) || !SetEndOfFile(ho)) {\n-\t\terrno = EIO;\n-\t\tgoto cleanup;\n-\t}\n-\n-\tret = 0;\n-\t/* clone whole 1GiB regions (already cluster aligned) */\n-\tfor (off = 0; (uint64_t)size.QuadPart > off &&\n-\t\t      (uint64_t)size.QuadPart - off > GiB; off += GiB) {\n-\t\tif (clone_extent_windows(ho, hi, off, GiB)) {\n-\t\t\terrno = ENOSYS;\n-\t\t\tret = -1;\n-\t\t\tgoto cleanup;\n-\t\t}\n-\t}\n-\t/* clone the tail, rounding its length up to a cluster (64K then 4K) */\n-\tif (!ret && (uint64_t)size.QuadPart > off) {\n-\t\tuint64_t rem = (uint64_t)size.QuadPart - off;\n-\n-\t\tret = -1;\n-\t\tfor (i = 0; i < ARRAY_SIZE(clusters); i++) {\n-\t\t\tuint64_t count = (rem + clusters[i] - 1) &\n-\t\t\t\t\t ~(clusters[i] - 1);\n-\t\t\tif (!clone_extent_windows(ho, hi, off, count)) {\n-\t\t\t\tret = 0;\n-\t\t\t\tbreak;\n-\t\t\t}\n-\t\t}\n-\t\tif (ret)\n-\t\t\terrno = ENOSYS;\t/* not a CoW volume */\n-\t}\n-\n-cleanup:\n-\tclose(fdi);\n-\tif (close(fdo) && !ret) {\n-\t\terrno = EIO;\n-\t\tret = -1;\n-\t}\n-\tif (ret) {\n-\t\tint saved = errno;\n-\t\tunlink(dst);\n-\t\terrno = saved;\n-\t\treturn -1;\n-\t}\n-\tif (adjust_shared_perm(repo, dst))\n-\t\treturn -1;\n-\treturn 0;\n+\t(void)repo;\n+\t(void)dst;\n+\t(void)src;\n+\t(void)mode;\n+\terrno = ENOSYS;\n+\treturn -1;\n #else\n \t/* No reflink primitive on this platform. */\n \t(void)repo;\ndiff --git a/t/t2400-worktree-add.sh b/t/t2400-worktree-add.sh\nindex 14bf455736..592f414955 100755\n--- a/t/t2400-worktree-add.sh\n+++ b/t/t2400-worktree-add.sh\n@@ -1288,6 +1288,21 @@ test_expect_success 'relative worktree sets extension config' '\n \ttest_cmp_config -C repo true extensions.relativeworktrees\n '\n \n+test_expect_success MINGW 'reflink is disabled on Windows build 26200' '\n+\ttest_when_finished \"rm -rf winreflink\" &&\n+\tgit init winreflink &&\n+\t(\n+\t\tcd winreflink &&\n+\t\ttest_commit base file.txt base &&\n+\t\tgit worktree add --reflink wt -b winbr base 2>err &&\n+\t\ttest_grep \"build 26200\" err &&\n+\t\techo base >expect &&\n+\t\ttest_cmp expect wt/file.txt &&\n+\t\tgit -C wt status --porcelain >status &&\n+\t\ttest_must_be_empty status\n+\t)\n+'\n+\n test_expect_success '--reflink produces a correct checkout on any filesystem' '\n \ttest_when_finished \"rm -rf reflinkrepo\" &&\n \tgit init reflinkrepo &&\n-- \ngitgitgadget\n\n\n"},{"id":"555688","messageId":"876fb541a8e1d43731bb72ddbbf1c49da8760775.1792567061.git.gitgitgadget@gmail.com","threadId":"65762","inReplyTo":"pull.2317.v3.git.git.1792567061.gitgitgadget@gmail.com","subject":"[PATCH v3 4/4] worktree: keep the reflink probe referenced on Windows","fromName":"Jason Newton via GitGitGadget","fromEmail":"gitgitgadget@gmail.com","sentAt":"2026-10-21T07:17:41Z","receivedAt":"2026-10-21T07:17:41Z","isPatch":true,"sender":{"key":"name:Jason Newton","avatar":null},"body":"From: Jason Newton <nevion@gmail.com>\n\nThe mingw build compiles with -Werror=unused-function. Putting the\nreflink_supported() call in the non-Windows branch left that function\nunused, so \"win build\" failed at builtin/worktree.c:445. Leave the\ncall in the common path. The Windows return still happens first.\n\nSigned-off-by: Jason Newton <nevion@gmail.com>\n---\n builtin/worktree.c | 5 +++--\n 1 file changed, 3 insertions(+), 2 deletions(-)\n\ndiff --git a/builtin/worktree.c b/builtin/worktree.c\nindex 93fcaa5ecd..07adf6bb7f 100644\n--- a/builtin/worktree.c\n+++ b/builtin/worktree.c\n@@ -568,13 +568,15 @@ static int reflink_worktree(const char *path, const char *wt_git_dir,\n \t * reflink_file() refuses on Windows. Build 26200 is the version\n \t * named in git-lfs issue 6312; no later build is known to be fixed.\n \t * Auto mode stays quiet, matching the non-Windows fallback.\n+\t * Return before the probe, but leave the call compiled: an #else\n+\t * around it makes reflink_supported() unused under -Werror.\n \t */\n \tif (!opts->quiet && opts->reflink != REFLINK_AUTO)\n \t\twarning(_(\"reflink is disabled on Windows; block cloning \"\n \t\t\t  \"can zero-fill files on Windows build 26200; \"\n \t\t\t  \"falling back to a regular checkout\"));\n \treturn 1;\n-#else\n+#endif\n \tif (!reflink_supported(path)) {\n \t\t/* In auto mode the fallback is expected, so stay quiet. */\n \t\tif (!opts->quiet && opts->reflink != REFLINK_AUTO)\n@@ -582,7 +584,6 @@ static int reflink_worktree(const char *path, const char *wt_git_dir,\n \t\t\t\t  \"falling back to a regular checkout\"), path);\n \t\treturn 1;\n \t}\n-#endif\n \n \tif (stat(path, &dst_st))\n \t\treturn error_errno(_(\"could not stat '%s'\"), path);\n-- \ngitgitgadget\n\n"},{"id":"555690","messageId":"CAGou9MgdF_xA+e8YYn8ud8TUSmY3j_q9jbUTy2wLibTz1ObJ7A@mail.gmail.com","threadId":"65762","inReplyTo":"CAPig+cRsSN9gY405MGsCQzLuxzBKcfHo2Oc8Z4WB-U3BGd6m_Q@mail.gmail.com","subject":"Re: [PATCH v2 2/2] worktree: reap ephemeral branches created by \"worktree add\"","fromName":"Jason Newton","fromEmail":"nevion@gmail.com","sentAt":"2026-10-21T07:40:08Z","receivedAt":"2026-10-21T07:40:08Z","isPatch":true,"sender":{"key":"nevion@gmail.com","avatar":null},"body":"--detach and an ephemeral branch differ while the worktree exists.\n\n--detach leaves HEAD with no branch, so status, push, rename,\nupstream, and symbolic-ref have nothing to name. An ephemeral\nbranch is a normal refs/heads/ ref for the life of the worktree.\nCommits go on it, and another ref can point at them before\n\"worktree remove\" deletes that branch.\n\nDeleting the branch that \"worktree add <path>\" creates today\nwould change the default, so this has to be opt-in. That opt-in\nis not --detach: the worktree stays on a branch until removal.\n\nThese worktrees might be minutes or they might go on for months;\neither way they should be easy to use and not require flags to assist\n in the majority of common case behaviors, moreover detached feels\nike a degraded halfway state, frequently allowing a gotcha to strike or\n a loss of a safety like a gc based reap.\n\n\"git worktree remove\" does not delete whatever branch a worktree\nhas checked out. It deletes a branch only when this \"git worktree\nadd\" created it by DWIM (the final component of <path>) and recorded\nthat in worktrees/<id>/owned-branch.\n\nA branch named with -b/-B, a branch that already existed, and a\ndetached HEAD are not owned and are not removed. A worktree created\nby an older Git has no marker, so removing it still leaves its\nbranch in place.\n\n\"Unconditional\" in the commit means that this one owned branch is\ndeleted even if it has unmerged commits. --keep-branch turns that\noff. \"git branch <name> <tip>\" before removal keeps the commits on\nan ordinary branch; only the owned ref is deleted.\n\nThe call that changes is \"git worktree add <path>\" with no branch,\nfollowed by \"git worktree remove\". A caller who wants that branch\nto outlive the worktree already has a spelling this series does not\ntouch: \"git worktree add -b <name> <path>\", or \"git worktree add\n<path> <existing>\". --detach still creates no branch, so it is not\nthe same state while the worktree exists.\n\nOwnership is written only when the worktree is created, so I'll confirm\nan older worktree still has no marker after an upgrade.  The branch stays.\nUpgrading does not mark a worktree you already have so no upgrade\nheadaches are expected.\n\n-Jason\n\n\nOn Tue, Oct 20, 2026 at 11:52 PM Eric Sunshine <sunshine@sunshineco.com> wrote:\n>\n> On Tue, Oct 20, 2026 at 12:09 PM Jason Newton via GitGitGadget\n> <gitgitgadget@gmail.com> wrote:\n> > When \"git worktree add <path>\" is given no branch to check out, it\n> > auto-creates one named after the path. Such a branch exists only to back\n> > the new worktree, yet it outlives it: removing the worktree leaves the\n> > branch behind, so a fleet of throwaway worktrees fills refs/heads/ with\n> > dead branches that have to be cleaned up by hand.\n> >\n> > Treat an auto-created branch as owned by the worktree. Record it in the\n> > worktree's administrative directory (worktrees/<id>/owned-branch) at\n> > creation time -- the one moment we can know for certain the branch is\n> > worktree-private, since we are the one that created it. \"git worktree\n> > remove\" then deletes the owned branch once the worktree is gone and it\n> > is no longer checked out.\n> >\n> > Ownership is recorded only when \"worktree add\" itself creates the branch\n> > via DWIM auto-naming; a branch named explicitly with -b/-B, or one that\n> > already existed, is never owned and never reaped. Deletion is\n> > unconditional (even for unmerged commits) because an ephemeral branch is\n> > disposable by contract: to keep the work, pass --keep-branch, or anchor\n> > the commits with an ordinary branch beforehand -- a normal branch can\n> > point at the same commits, after which reaping the ephemeral ref loses\n> > nothing. \"git branch -m\" updates the marker so ownership follows a\n> > rename, and the branch stays ephemeral.\n> >\n> > The marker is just another per-worktree administrative file, so older\n> > versions of Git simply ignore it (they keep the branch on removal, as\n> > today).\n> >\n> > Signed-off-by: Jason Newton <nevion@gmail.com>\n>\n> Sorry, I may be missing something obvious, but this message never\n> explains why we should add all this additional complexity for a\n> use-case already directly supported by `git worktree add -d <path>`.\n> Specifically, worktree's --detach option is exactly what you want when\n> creating throwaway worktrees, even \"fleets\" of them (using terminology\n> from this apparently fully or partially LLM-generated message). If\n> your tooling or agent is not using -d/--detach for throwaway\n> worktrees, then the problem is fixable by modifying the tooling or by\n> teaching the agent about --detach, without bulking up the git-worktree\n> implementation unnecessarily.\n>\n> Moreover, a change like this which makes the new behavior\n> unconditional is certainly going to break existing tooling and\n> workflows, thus it will not go over well, even with the --keep-branch\n> escape-hatch. At minimum, to be acceptable, assuming such new\n> functionality is even desirable, to avoid breaking existing setups, it\n> would have to be opt-in, not opt-out (via --keep-branch). But if it's\n> going to be opt-in, then you may as well just use --detach to achieve\n> the same effect.\n\n"},{"id":"555693","messageId":"CAPig+cRCaSmEULP1JpW3fjiJDR0Lee78puq+KRaXiD9ciX3fvg@mail.gmail.com","threadId":"65762","inReplyTo":"CAGou9MgdF_xA+e8YYn8ud8TUSmY3j_q9jbUTy2wLibTz1ObJ7A@mail.gmail.com","subject":"Re: [PATCH v2 2/2] worktree: reap ephemeral branches created by \"worktree add\"","fromName":"Eric Sunshine","fromEmail":"sunshine@sunshineco.com","sentAt":"2026-10-21T08:06:48Z","receivedAt":"2026-10-21T08:06:48Z","isPatch":true,"sender":{"key":"sunshine@sunshineco.com","avatar":"https://avatars.githubusercontent.com/u/163641?v=4"},"body":"On Wed, Oct 21, 2026 at 3:40 AM Jason Newton <nevion@gmail.com> wrote:>\n> --detach and an ephemeral branch differ while the worktree exists.\n>\n> --detach leaves HEAD with no branch, so status, push, rename,\n> upstream, and symbolic-ref have nothing to name. An ephemeral\n> branch is a normal refs/heads/ ref for the life of the worktree.\n> Commits go on it, and another ref can point at them before\n> \"worktree remove\" deletes that branch.\n>\n> Deleting the branch that \"worktree add <path>\" creates today\n> would change the default, so this has to be opt-in. That opt-in\n> is not --detach: the worktree stays on a branch until removal.\n>\n> These worktrees might be minutes or they might go on for months;\n> either way they should be easy to use and not require flags to assist\n>  in the majority of common case behaviors, moreover detached feels\n> ike a degraded halfway state, frequently allowing a gotcha to strike or\n>  a loss of a safety like a gc based reap.\n>\n> \"git worktree remove\" does not delete whatever branch a worktree\n> has checked out. It deletes a branch only when this \"git worktree\n> add\" created it by DWIM (the final component of <path>) and recorded\n> that in worktrees/<id>/owned-branch.\n>\n> A branch named with -b/-B, a branch that already existed, and a\n> detached HEAD are not owned and are not removed. A worktree created\n> by an older Git has no marker, so removing it still leaves its\n> branch in place.\n>\n> \"Unconditional\" in the commit means that this one owned branch is\n> deleted even if it has unmerged commits. --keep-branch turns that\n> off. \"git branch <name> <tip>\" before removal keeps the commits on\n> an ordinary branch; only the owned ref is deleted.\n>\n> The call that changes is \"git worktree add <path>\" with no branch,\n> followed by \"git worktree remove\". A caller who wants that branch\n> to outlive the worktree already has a spelling this series does not\n> touch: \"git worktree add -b <name> <path>\", or \"git worktree add\n> <path> <existing>\". --detach still creates no branch, so it is not\n> the same state while the worktree exists.\n>\n> Ownership is written only when the worktree is created, so I'll confirm\n> an older worktree still has no marker after an upgrade.  The branch stays.\n> Upgrading does not mark a worktree you already have so no upgrade\n> headaches are expected.\n\nFeeding a reviewer's comments into an agent and pasting its\nLLM-generated response into an email is not a good way to convince\nproject stakeholders that the submission has value. If you can't\nexplain its value in concrete terms in your own words, then you're\ngoing to have a hard time eliciting any responses or additional\nreviewer feedback.\n\n"},{"id":"555697","messageId":"CAGou9MirKucUdx8eM-BfqO9sZrDrckwpp9sYDnDVfiqkdZ8wdw@mail.gmail.com","threadId":"65762","inReplyTo":"CAPig+cRCaSmEULP1JpW3fjiJDR0Lee78puq+KRaXiD9ciX3fvg@mail.gmail.com","subject":"Re: [PATCH v2 2/2] worktree: reap ephemeral branches created by \"worktree add\"","fromName":"Jason Newton","fromEmail":"nevion@gmail.com","sentAt":"2026-10-21T08:28:09Z","receivedAt":"2026-10-21T08:28:09Z","isPatch":true,"sender":{"key":"nevion@gmail.com","avatar":null},"body":"Please focus on reviewing, I use mixed but you shouldn't assume which\nparts are and are not llms.\n\nWhat you don't realize by working in a silo for a long time is your\ncommunication skills to external parties gets reduced with jargon and\nnitpicking ; I have the llms both assume you're wrong and right while\nseeing the undesirable behaviors your stances have to the one that I\nknow is correct.  You seem overly sensitive to the usage so far. I\nhave no tollerance left to give - so stay on point. You should\nconsider several harnesses chose not to even go through PRs and work\naround the functionality like grok build did, patching it in\nexternally which is kind of nuts - and replicated.  I think it's\nsomething you should think about the nature of quite a bit.\n\nAs I mentioned, detached IOWs sucks and you shouldn't have bothered\nmentioning it because it fails hard, though it was noted and evaluated\nin earnest for a bad idea - want to go back to the long but more\nneutral form?\n\n-Jason\n\n\nOn Wed, Oct 21, 2026 at 1:07 AM Eric Sunshine <sunshine@sunshineco.com> wrote:\n>\n> On Wed, Oct 21, 2026 at 3:40 AM Jason Newton <nevion@gmail.com> wrote:>\n> > --detach and an ephemeral branch differ while the worktree exists.\n> >\n> > --detach leaves HEAD with no branch, so status, push, rename,\n> > upstream, and symbolic-ref have nothing to name. An ephemeral\n> > branch is a normal refs/heads/ ref for the life of the worktree.\n> > Commits go on it, and another ref can point at them before\n> > \"worktree remove\" deletes that branch.\n> >\n> > Deleting the branch that \"worktree add <path>\" creates today\n> > would change the default, so this has to be opt-in. That opt-in\n> > is not --detach: the worktree stays on a branch until removal.\n> >\n> > These worktrees might be minutes or they might go on for months;\n> > either way they should be easy to use and not require flags to assist\n> >  in the majority of common case behaviors, moreover detached feels\n> > ike a degraded halfway state, frequently allowing a gotcha to strike or\n> >  a loss of a safety like a gc based reap.\n> >\n> > \"git worktree remove\" does not delete whatever branch a worktree\n> > has checked out. It deletes a branch only when this \"git worktree\n> > add\" created it by DWIM (the final component of <path>) and recorded\n> > that in worktrees/<id>/owned-branch.\n> >\n> > A branch named with -b/-B, a branch that already existed, and a\n> > detached HEAD are not owned and are not removed. A worktree created\n> > by an older Git has no marker, so removing it still leaves its\n> > branch in place.\n> >\n> > \"Unconditional\" in the commit means that this one owned branch is\n> > deleted even if it has unmerged commits. --keep-branch turns that\n> > off. \"git branch <name> <tip>\" before removal keeps the commits on\n> > an ordinary branch; only the owned ref is deleted.\n> >\n> > The call that changes is \"git worktree add <path>\" with no branch,\n> > followed by \"git worktree remove\". A caller who wants that branch\n> > to outlive the worktree already has a spelling this series does not\n> > touch: \"git worktree add -b <name> <path>\", or \"git worktree add\n> > <path> <existing>\". --detach still creates no branch, so it is not\n> > the same state while the worktree exists.\n> >\n> > Ownership is written only when the worktree is created, so I'll confirm\n> > an older worktree still has no marker after an upgrade.  The branch stays.\n> > Upgrading does not mark a worktree you already have so no upgrade\n> > headaches are expected.\n>\n> Feeding a reviewer's comments into an agent and pasting its\n> LLM-generated response into an email is not a good way to convince\n> project stakeholders that the submission has value. If you can't\n> explain its value in concrete terms in your own words, then you're\n> going to have a hard time eliciting any responses or additional\n> reviewer feedback.\n\n"},{"id":"555739","messageId":"43b81ed2-6cc2-409b-be39-fa5b0911f532@gmail.com","threadId":"65762","inReplyTo":"CAGou9MirKucUdx8eM-BfqO9sZrDrckwpp9sYDnDVfiqkdZ8wdw@mail.gmail.com","subject":"Re: [PATCH v2 2/2] worktree: reap ephemeral branches created by \"worktree add\"","fromName":"Phillip Wood","fromEmail":"phillip.wood123@gmail.com","sentAt":"2026-10-21T14:03:52Z","receivedAt":"2026-10-21T14:03:52Z","isPatch":true,"sender":{"key":"phillip.wood@dunelm.org.uk","avatar":null},"body":"On 21/10/2026 09:28, Jason Newton wrote:\n> Please focus on reviewing, I use mixed but you shouldn't assume which\n> parts are and are not llms.\n> > What you don't realize by working in a silo for a long time is your\n> communication skills to external parties gets reduced with jargon and\n> nitpicking ; I have the llms both assume you're wrong and right while\n> seeing the undesirable behaviors your stances have to the one that I\n> know is correct.  You seem overly sensitive to the usage so far. I\n> have no tollerance left to give - so stay on point. You should\n> consider several harnesses chose not to even go through PRs and work\n> around the functionality like grok build did, patching it in\n> externally which is kind of nuts - and replicated.  I think it's\n> something you should think about the nature of quite a bit.\n> > As I mentioned, detached IOWs sucks and you shouldn't have bothered\n> mentioning it because it fails hard, though it was noted and evaluated\n> in earnest for a bad idea - want to go back to the long but more\n> neutral form?\n\nI'm afraid this messages falls far short of the standard of constructive discussion that is expected on this list. It is perfectly possible to disagree with someone without attacking them or telling them what they should or should not be doing.\n\nIt is clear that you do not like the current behavior of \"git worktree add\", but replying with a generic list of the differences between a branch checkout and a detached HEAD and then attacking the reviewer does not explain what problem you are trying to solve and is not going to convince anyone that this patch is a good idea.\n\nThanks\n\nPhillip\n> -Jason\n> > > On Wed, Oct 21, 2026 at 1:07 AM Eric Sunshine <sunshine@sunshineco.com> wrote:\n>>\n>> On Wed, Oct 21, 2026 at 3:40 AM Jason Newton <nevion@gmail.com> wrote:>\n>>> --detach and an ephemeral branch differ while the worktree exists.\n>>>\n>>> --detach leaves HEAD with no branch, so status, push, rename,\n>>> upstream, and symbolic-ref have nothing to name. An ephemeral\n>>> branch is a normal refs/heads/ ref for the life of the worktree.\n>>> Commits go on it, and another ref can point at them before\n>>> \"worktree remove\" deletes that branch.\n>>>\n>>> Deleting the branch that \"worktree add <path>\" creates today\n>>> would change the default, so this has to be opt-in. That opt-in\n>>> is not --detach: the worktree stays on a branch until removal.\n>>>\n>>> These worktrees might be minutes or they might go on for months;\n>>> either way they should be easy to use and not require flags to assist\n>>>   in the majority of common case behaviors, moreover detached feels\n>>> ike a degraded halfway state, frequently allowing a gotcha to strike or\n>>>   a loss of a safety like a gc based reap.\n>>>\n>>> \"git worktree remove\" does not delete whatever branch a worktree\n>>> has checked out. It deletes a branch only when this \"git worktree\n>>> add\" created it by DWIM (the final component of <path>) and recorded\n>>> that in worktrees/<id>/owned-branch.\n>>>\n>>> A branch named with -b/-B, a branch that already existed, and a\n>>> detached HEAD are not owned and are not removed. A worktree created\n>>> by an older Git has no marker, so removing it still leaves its\n>>> branch in place.\n>>>\n>>> \"Unconditional\" in the commit means that this one owned branch is\n>>> deleted even if it has unmerged commits. --keep-branch turns that\n>>> off. \"git branch <name> <tip>\" before removal keeps the commits on\n>>> an ordinary branch; only the owned ref is deleted.\n>>>\n>>> The call that changes is \"git worktree add <path>\" with no branch,\n>>> followed by \"git worktree remove\". A caller who wants that branch\n>>> to outlive the worktree already has a spelling this series does not\n>>> touch: \"git worktree add -b <name> <path>\", or \"git worktree add\n>>> <path> <existing>\". --detach still creates no branch, so it is not\n>>> the same state while the worktree exists.\n>>>\n>>> Ownership is written only when the worktree is created, so I'll confirm\n>>> an older worktree still has no marker after an upgrade.  The branch stays.\n>>> Upgrading does not mark a worktree you already have so no upgrade\n>>> headaches are expected.\n>>\n>> Feeding a reviewer's comments into an agent and pasting its\n>> LLM-generated response into an email is not a good way to convince\n>> project stakeholders that the submission has value. If you can't\n>> explain its value in concrete terms in your own words, then you're\n>> going to have a hard time eliciting any responses or additional\n>> reviewer feedback.\n> "},{"id":"555807","messageId":"CAGou9MjGsTNnxYh8+zJXE1V8xCfkdknHqO0kaF=FBGztJfCdVw@mail.gmail.com","threadId":"65762","inReplyTo":"43b81ed2-6cc2-409b-be39-fa5b0911f532@gmail.com","subject":"Re: [PATCH v2 2/2] worktree: reap ephemeral branches created by \"worktree add\"","fromName":"Jason Newton","fromEmail":"nevion@gmail.com","sentAt":"2026-10-21T22:44:15Z","receivedAt":"2026-10-21T22:44:15Z","isPatch":true,"sender":{"key":"nevion@gmail.com","avatar":null},"body":"Just matching energy levels of Eric's messaging, I did not make the\nfirst move but I will defend my position using the same energy he\nbrought to the table.\n\nThe detached-based workflow does not satisfy user expectations - my\nframing there is no user would like that that didn't explicitly want\ndetached, which I'm not sure has a use case.  At face value it does\nnot seem a worth while suggestion, sometimes it's worth doing a\ncleaner thing even if you have 60% of a technical solution that can be\nleveraged to overlapping ends.\n\nI do understand the usecase of short and long term worktrees which\nbehave like branches though, and that's the common user expectation.\nThe current behavior of can't checkout the same branch more than once\nis also not user expected behavior.\n\n-Jason\n\nOn Wed, Oct 21, 2026 at 7:03 AM Phillip Wood <phillip.wood123@gmail.com> wrote:\n>\n> On 21/10/2026 09:28, Jason Newton wrote:\n> > Please focus on reviewing, I use mixed but you shouldn't assume which\n> > parts are and are not llms.\n> >\n> > What you don't realize by working in a silo for a long time is your\n> > communication skills to external parties gets reduced with jargon and\n> > nitpicking ; I have the llms both assume you're wrong and right while\n> > seeing the undesirable behaviors your stances have to the one that I\n> > know is correct.  You seem overly sensitive to the usage so far. I\n> > have no tollerance left to give - so stay on point. You should\n> > consider several harnesses chose not to even go through PRs and work\n> > around the functionality like grok build did, patching it in\n> > externally which is kind of nuts - and replicated.  I think it's\n> > something you should think about the nature of quite a bit.\n> >\n> > As I mentioned, detached IOWs sucks and you shouldn't have bothered\n> > mentioning it because it fails hard, though it was noted and evaluated\n> > in earnest for a bad idea - want to go back to the long but more\n> > neutral form?\n>\n> I'm afraid this messages falls far short of the standard of constructive\n> discussion that is expected on this list. It is perfectly possible to\n> disagree with someone without attacking them or telling them what they\n> should or should not be doing.\n>\n> It is clear that you do not like the current behavior of \"git worktree\n> add\", but replying with a generic list of the differences between a\n> branch checkout and a detached HEAD and then attacking the reviewer does\n> not explain what problem you are trying to solve and is not going to\n> convince anyone that this patch is a good idea.\n>\n> Thanks\n>\n> Phillip\n> > -Jason\n> >\n> >\n> > On Wed, Oct 21, 2026 at 1:07 AM Eric Sunshine <sunshine@sunshineco.com> wrote:\n> >>\n> >> On Wed, Oct 21, 2026 at 3:40 AM Jason Newton <nevion@gmail.com> wrote:>\n> >>> --detach and an ephemeral branch differ while the worktree exists.\n> >>>\n> >>> --detach leaves HEAD with no branch, so status, push, rename,\n> >>> upstream, and symbolic-ref have nothing to name. An ephemeral\n> >>> branch is a normal refs/heads/ ref for the life of the worktree.\n> >>> Commits go on it, and another ref can point at them before\n> >>> \"worktree remove\" deletes that branch.\n> >>>\n> >>> Deleting the branch that \"worktree add <path>\" creates today\n> >>> would change the default, so this has to be opt-in. That opt-in\n> >>> is not --detach: the worktree stays on a branch until removal.\n> >>>\n> >>> These worktrees might be minutes or they might go on for months;\n> >>> either way they should be easy to use and not require flags to assist\n> >>>   in the majority of common case behaviors, moreover detached feels\n> >>> ike a degraded halfway state, frequently allowing a gotcha to strike or\n> >>>   a loss of a safety like a gc based reap.\n> >>>\n> >>> \"git worktree remove\" does not delete whatever branch a worktree\n> >>> has checked out. It deletes a branch only when this \"git worktree\n> >>> add\" created it by DWIM (the final component of <path>) and recorded\n> >>> that in worktrees/<id>/owned-branch.\n> >>>\n> >>> A branch named with -b/-B, a branch that already existed, and a\n> >>> detached HEAD are not owned and are not removed. A worktree created\n> >>> by an older Git has no marker, so removing it still leaves its\n> >>> branch in place.\n> >>>\n> >>> \"Unconditional\" in the commit means that this one owned branch is\n> >>> deleted even if it has unmerged commits. --keep-branch turns that\n> >>> off. \"git branch <name> <tip>\" before removal keeps the commits on\n> >>> an ordinary branch; only the owned ref is deleted.\n> >>>\n> >>> The call that changes is \"git worktree add <path>\" with no branch,\n> >>> followed by \"git worktree remove\". A caller who wants that branch\n> >>> to outlive the worktree already has a spelling this series does not\n> >>> touch: \"git worktree add -b <name> <path>\", or \"git worktree add\n> >>> <path> <existing>\". --detach still creates no branch, so it is not\n> >>> the same state while the worktree exists.\n> >>>\n> >>> Ownership is written only when the worktree is created, so I'll confirm\n> >>> an older worktree still has no marker after an upgrade.  The branch stays.\n> >>> Upgrading does not mark a worktree you already have so no upgrade\n> >>> headaches are expected.\n> >>\n> >> Feeding a reviewer's comments into an agent and pasting its\n> >> LLM-generated response into an email is not a good way to convince\n> >> project stakeholders that the submission has value. If you can't\n> >> explain its value in concrete terms in your own words, then you're\n> >> going to have a hard time eliciting any responses or additional\n> >> reviewer feedback.\n> >\n>\n\n"},{"id":"555929","messageId":"atqOqRE866bgyxfL@fruit.crustytoothpaste.net","threadId":"65762","inReplyTo":"CAGou9MhkmSZs3ViSj6qqkZY6LLLQQ+5RzjLG5EhM-AXx+d7h=A@mail.gmail.com","subject":"Re: [PATCH v2 1/2] worktree: add --reflink for copy-on-write worktree creation","fromName":"brian m. carlson","fromEmail":"sandals@crustytoothpaste.net","sentAt":"2026-10-22T22:31:06Z","receivedAt":"2026-10-22T22:31:06Z","isPatch":true,"sender":{"key":"sandals@crustytoothpaste.net","avatar":"https://avatars.githubusercontent.com/u/497054?v=4"},"body":"On 2026-10-21 at 07:15:50, Jason Newton wrote:\n> Brian,\n\nHay,\n\n> macOS cp has no --reflink=always. The clone option is -c, which is\n> clonefile(2). t/t2400-worktree-add.sh already probes that way. The\n> REFLINK prerequisite runs \"cp -c\" when the MACOS prerequisite is set,\n> and \"cp --reflink=always\" otherwise. The test that depends on REFLINK\n> is \"--reflink carries untracked files and reconciles changes\".\n> \n> That is in 042485f0e9cd8cf1765b811ea7334247aec44971. The pull request\n> CI for that commit is the APFS run:\n> \n> https://github.com/git/git/pull/2317\n> https://github.com/git/git/actions/runs/39502233266\n> \n> All four macos-14 jobs succeeded. The runners were macOS 14.8.9\n> (23J631), image macos-14-arm64 20260831.0302.1. \"print test failures\"\n> was skipped on each job, which is the step that runs only when a test\n> script fails.\n\nYou have a test_lazy_prereq for REFLINK in your test file and it uses\n`cp --reflink=always`.  If that doesn't work on macOS, then the\nprerequisite fails, so the test with the REFLINK prerequisite is\nskipped.  That means it doesn't fail, but it also doesn't run, so it\nisn't testing anything at all.\n\nWhat I'm saying is that it should actually pass the REFLINK prerequisite\nand run the test on macOS.  It looks like you did do that in v3, which\nis good.\n\nIt also looks like at the very least substantial portions of this email\nare the output of an LLM.  You should read and understand our AI\npolicy[0].  In any event, I'm not going to review or respond further to\nAI slop, especially since I work on Git entirely in my personal time and\nmy time is currently quite limited.\n\nWe consider it important to explain our patches and our thought process\nwell on this list and we have high standards for inclusion—as we\nshould—since many developers around the world depend on us.  You're\nwelcome to participate, but you should respond to other humans with your\nown words and thoughts, since we're giving you the same time and\ncourtesy.  If I wanted to know what an LLM thinks about what I have to\nsay, I know where to find one—I wouldn't have asked.[1]\n\n[0] https://git-scm.com/docs/SubmittingPatches#ai\n[1] For the avoidance of doubt, these em dashes are my own creation and\ncome from my love of language and the fact that I have an English\ndegree.\n-- \nbrian m. carlson (they/them)\nToronto, Ontario, CA\n"}]}