* Re: [PATCH v3 15/17] odb/source-packed: stub out remaining functions
From: Patrick Steinhardt @ 2026-06-19 5:18 UTC (permalink / raw)
To: Junio C Hamano; +Cc: git, Karthik Nayak, Justin Tobler
In-Reply-To: <xmqqik7frapn.fsf@gitster.g>
On Thu, Jun 18, 2026 at 10:59:32AM -0700, Junio C Hamano wrote:
> Patrick Steinhardt <ps@pks.im> writes:
>
> Just FYI (i.e. nothing wrong in this patch)
>
> > +static int odb_source_packed_write_object(struct odb_source *source UNUSED,
> > + const void *buf UNUSED,
> > + unsigned long len UNUSED,
>
> The type of this parameter will become size_t via another topic in
> flight; I prepared an evil merge to address it (otherwise winbuild
> would barf, as expected).
>
> -- >8 --
> Author: Junio C Hamano <gitster@pobox.com>
> Date: Thu Jun 18 10:49:10 2026 -0700
>
> merge-fix po/hash-object-size-t vs ps/odb-source-packed
>
> diff --git a/odb/source-packed.c b/odb/source-packed.c
> index 42c28fba0e..decc81aa52 100644
> --- a/odb/source-packed.c
> +++ b/odb/source-packed.c
> @@ -503,7 +503,7 @@ static int odb_source_packed_freshen_object(struct odb_source *source,
>
> static int odb_source_packed_write_object(struct odb_source *source UNUSED,
> const void *buf UNUSED,
> - unsigned long len UNUSED,
> + size_t len UNUSED,
> enum object_type type UNUSED,
> struct object_id *oid UNUSED,
> struct object_id *compat_oid UNUSED,
Thanks for the heads up, the change looks obviously correct to me. I'm
also happy to send a rebased version -- just give me a nudge and I'll do
that.
Patrick
^ permalink raw reply
* Re: [PATCH] rebase: mention --abort alongside --continue
From: Junio C Hamano @ 2026-06-19 1:36 UTC (permalink / raw)
To: Harald Nordgren; +Cc: Phillip Wood, Harald Nordgren via GitGitGadget, git
In-Reply-To: <CAHwyqnV8je6gCTExr=CFCdYskN1dVaEDVSKDLUo5A4Ukv=qhiA@mail.gmail.com>
Harald Nordgren <haraldnordgren@gmail.com> writes:
> Just an example when working on a different topic:
>
> I rebased with -x to run all the tests, but ran a test that didn't
> exist yet on the first commit and ended up in a bad state. Here it
> should clearly show the 'git rebase --abort', so I can start over,
> it's not something to fix:
>
> ```
> $ git rebase --keep-base -x 'make -s' -x 'cd t && prove -j8
> t3454-history-squash.sh t3453-history-fixup.sh t3452-history-split.sh
> t3451-history-reword.sh t3450-history.sh'
> Executing: make -s
> GIT_VERSION=2.55.0.rc1.20.g1e31474ef6
> Executing: cd t && prove -j8 t3454-history-squash.sh
> t3453-history-fixup.sh t3452-history-split.sh t3451-history-reword.sh
> t3450-history.sh
> Cannot detect source of 't3454-history-squash.sh'! at
> /System/Library/Perl/5.34/TAP/Parser/IteratorFactory.pm line 256.
> ...
> warning: execution failed: cd t && prove -j8 t3454-history-squash.sh
> t3453-history-fixup.sh t3452-history-split.sh t3451-history-reword.sh
> t3450-history.sh
> You can fix the problem, and then run
>
> git rebase --continue
Hmph, you do not have to "fix" as you know some of the test scripts
did not exist at this stage. So the solution to the issue seems to
be just to say "git rebase --continue", instead of starting over by
aborting. It is especially true if the test scripts are introduced
in the middle of this rebase session somewhere later in the series,
no?
Of course if you gave a totally broken script to "-x" option, you'd
need to be able to abort it, but is that the use case we should be
giving one extra line of output for users in all other situations?
I dunno.
^ permalink raw reply
* Re: git-2.55.0-rc1 t4216 broken TAP failures on non-x86 arch
From: Junio C Hamano @ 2026-06-19 0:36 UTC (permalink / raw)
To: Jeff King; +Cc: Patrick Steinhardt, Todd Zullinger, git, Taylor Blau
In-Reply-To: <20260618233536.GA1431359@coredump.intra.peff.net>
Jeff King <peff@peff.net> writes:
> ... But since 389c83025d (t:
> let prove fail when parsing invalid TAP output, 2026-06-04) it will
> cause a test failure.
Thanks. That was the piece I was missing.
^ permalink raw reply
* [RFH] Why do osx CI jobs so unreliable?
From: Junio C Hamano @ 2026-06-19 0:35 UTC (permalink / raw)
To: git
I've been observing that in recent push-out to 'master' and 'next',
osx-* jobs in GitHub Actions CI keep running for 6 hours and get
killed.
What is troubling is that this seems to be very flaky. For example,
https://github.com/git/git/actions/runs/27778820659 is testing
95e20213 (Hopefully final batch before -rc2, 2026-06-17) which got
killed after wasting 6 hours in osx-clang and osx-gcc jobs.
https://github.com/git/git/actions/runs/27790036076 is testing
the same 'master', with a patch to .github/workflows/main.yml to
remove everything except for config and osx-* jobs, which succeeded
within 30 minutes.
Stumped...
^ permalink raw reply
* Re: [PATCH v3 0/4] history: add squash subcommand to fold a range
From: Junio C Hamano @ 2026-06-19 0:34 UTC (permalink / raw)
To: Patrick Steinhardt; +Cc: Harald Nordgren via GitGitGadget, git, Harald Nordgren
In-Reply-To: <pull.2337.v3.git.git.1781810226.gitgitgadget@gmail.com>
"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
> Adds git history squash <revision-range> to fold a range of commits into its
> oldest one, reusing that commit's message and replaying any descendants on
> top.
One thing that just occurred to me.
When you have a linear history
o---A---B---C
you run "git history squash A..C" and come to
o---X
where the tree of X is the same as C, with the log message of A
reused for it. That is simple, clean, and easy to explain.
But what should happen to refs (i.e., branch head) that point at A
or B?
I am adressing this message to Patrick as this question relates to
the grand vision for the "git history" command. I think "git
replay" wants to rewrite all the refs that are involved in the
rewrite operation, while "git rebase" (without "--update-refs")
wants to leave all others refs intact and update only the branch it
was told to rewrite. Is it the same design as "rebase" and
"--update-refs" controls if we update _other_ refs that happened to
be in the range that are rewritten?
Now, assuming that there do exist a mode where the command can
update these refs that point into the history that got rewritten,
there probably are at least two possibilities.
On one hand, I think it is reasonable to _remove_ these refs that
used to point at a section of history that disappeared (like the one
that were pointing at A or B). Perhaps A and B were pointed at by
two branches or tags that were used to mark "up to this point things
are broken" and "from here on things are fixed" (i.e., imagine a
manual bisection). After squashing all of the commits in this
section of history, the result no longer has such transition points.
It also is plausible that users may want these refs that used to
point at A or B to point at X, just like the ref that used to point
at C would now point at X, even though I cannot offhand think of a
good story (like "there used to be transtion points, now there
isn't" I said above to explain why these refs should disappear) to
support such a behaviour.
Thoughts?
^ permalink raw reply
* Re: git-2.55.0-rc1 t4216 broken TAP failures on non-x86 arch
From: Jeff King @ 2026-06-18 23:35 UTC (permalink / raw)
To: Junio C Hamano; +Cc: Patrick Steinhardt, Todd Zullinger, git, Taylor Blau
In-Reply-To: <xmqq4iizpkig.fsf@gitster.g>
On Thu, Jun 18, 2026 at 03:10:47PM -0700, Junio C Hamano wrote:
> Patrick Steinhardt <ps@pks.im> writes:
>
> >> Building git-2.55.0-rc1 today, all non-x86 architectures
> >> failed with:
> >> ...
> >> This looks like it comes from the following chunk of code in
> >> the test:
> >>
> >> # expect will not match actual if char is unsigned by default. Write the test
> >> # in this way, so that a user running this test script can still see if the two
> >> # files match. (It will appear as an ordinary success if they match, and a skip
> >> # if not.)
> >> if test_cmp highbit1/expect highbit1/actual
> >> then
> >> test_set_prereq SIGNED_CHAR_BY_DEFAULT
> >> fi
> >> test_expect_success SIGNED_CHAR_BY_DEFAULT 'check value of version 1 changed-path' '
> >> # Only the prereq matters for this test.
> >> true
> >> '
>
> The "problematic" part is from mid 2024, so it is not anything new
> in 2.55-rc1, is it? Nobody built and ran tests for the past two
> years on non-x86 boxes?
Presumably they did not notice the extra cruft to stdout, either because
it was being eaten by the TAP harness or for a raw "make test" it was
mixed in with a million other lines of output. But since 389c83025d (t:
let prove fail when parsing invalid TAP output, 2026-06-04) it will
cause a test failure.
-Peff
^ permalink raw reply
* Re: git-2.55.0-rc1 t4216 broken TAP failures on non-x86 arch
From: Junio C Hamano @ 2026-06-18 22:10 UTC (permalink / raw)
To: Patrick Steinhardt; +Cc: Todd Zullinger, git, Taylor Blau
In-Reply-To: <ajOP1IOjA3EYvRfm@pks.im>
Patrick Steinhardt <ps@pks.im> writes:
>> Building git-2.55.0-rc1 today, all non-x86 architectures
>> failed with:
>> ...
>> This looks like it comes from the following chunk of code in
>> the test:
>>
>> # expect will not match actual if char is unsigned by default. Write the test
>> # in this way, so that a user running this test script can still see if the two
>> # files match. (It will appear as an ordinary success if they match, and a skip
>> # if not.)
>> if test_cmp highbit1/expect highbit1/actual
>> then
>> test_set_prereq SIGNED_CHAR_BY_DEFAULT
>> fi
>> test_expect_success SIGNED_CHAR_BY_DEFAULT 'check value of version 1 changed-path' '
>> # Only the prereq matters for this test.
>> true
>> '
The "problematic" part is from mid 2024, so it is not anything new
in 2.55-rc1, is it? Nobody built and ran tests for the past two
years on non-x86 boxes?
> Hm, this thing is indeed somewhat puzzling to me. I assume the intent is
> to give the developer some information that their platform is using
> signed characters by default? Other than that it's not really doing
> anything, as the prereq is only used by the one test shown above. I hope
> that Taylor has some more insight here.
>
> There's two potential fixes:
>
> - We can just drop this completely, as it ultimately doesn't even end
> up doing anything.
>
> - We can convert the call to `test_cmp` into a `test_lazy_prereq`,
> like done in the below patch, which retains the current behaviour.
Yeah, unless Taylor can tell us something we are not seeing, I am
inclined to say that we can just get rid of the whole thing.
SIGNED_CHAR_BY_DEFAULT is not used anywhere else, and the only place
it is used isd to run "true".
^ permalink raw reply
* Re: [PATCH 5/7] line-log: support diff stat formats with -L
From: Junio C Hamano @ 2026-06-18 22:00 UTC (permalink / raw)
To: Michael Montalbo via GitGitGadget; +Cc: git, D. Ben Knoble, Michael Montalbo
In-Reply-To: <a70d861d27a13459bab34f6681b3ccfe2f20d0d8.1781806593.git.gitgitgadget@gmail.com>
"Michael Montalbo via GitGitGadget" <gitgitgadget@gmail.com> writes:
> diff --git a/Documentation/line-range-options.adoc b/Documentation/line-range-options.adoc
> index 72f639b5e7..1a25f55bb1 100644
> --- a/Documentation/line-range-options.adoc
> +++ b/Documentation/line-range-options.adoc
> @@ -9,10 +9,14 @@
> _<start>_ and _<end>_ (or _<funcname>_) must exist in the starting revision.
> You can specify this option more than once. Implies `--patch`.
> Patch output can be suppressed using `--no-patch`.
> - Non-patch diff formats `--raw`, `--name-only`, `--name-status`,
> - and `--summary` are supported. Diff stat formats
> - (`--stat`, `--numstat`, `--shortstat`, `--dirstat`) are not
> - currently implemented.
> + The following non-patch diff formats are supported: `--raw`,
> + `--name-only`, `--name-status`, `--summary`,
> + `--stat`, `--numstat`, and `--shortstat`.
> + The stat formats show range-scoped counts: only lines within
> + the tracked range are counted. `--dirstat` is not supported
If "range-scoped" is a widely known term (as opposed to a new word
invented only during the introduction of this topic), the above
reads well with a nice rhythm, but otherwise it may be easier to
read, i.e., something like
The stat formats counts only lines within the tracked range.
without having readers learn yet another new term that is only used
here.
> diff --git a/diff.c b/diff.c
> index 6233a96bf0..026fafeb90 100644
> --- a/diff.c
> +++ b/diff.c
> @@ -4289,7 +4289,18 @@ static void builtin_diffstat(const char *name_a, const char *name_b,
> xecfg.ctxlen = o->context;
> xecfg.interhunkctxlen = o->interhunkcontext;
> xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
> - if (xdi_diff_outf(&mf1, &mf2, NULL,
> +
> + if (p->line_ranges) {
> + struct line_range_filter lr_filter;
> +
> + line_range_filter_init(&lr_filter, p->line_ranges,
> + diffstat_consume, diffstat);
> +
> + if (line_range_filter_diff(&lr_filter, &mf1, &mf2,
> + &xpp, &xecfg))
> + die("unable to generate diffstat for %s",
> + one->path);
> + } else if (xdi_diff_outf(&mf1, &mf2, NULL,
> diffstat_consume, diffstat, &xpp, &xecfg))
> die("unable to generate diffstat for %s", one->path);
It is pleasing to see that this can be done with such a surprisingly
small change.
^ permalink raw reply
* Re: [PATCH v3 3/4] history: add squash subcommand to fold a range
From: D. Ben Knoble @ 2026-06-18 21:29 UTC (permalink / raw)
To: Junio C Hamano; +Cc: Harald Nordgren via GitGitGadget, git, Harald Nordgren
In-Reply-To: <xmqqzf0rpmn0.fsf@gitster.g>
On Thu, Jun 18, 2026 at 5:25 PM Junio C Hamano <gitster@pobox.com> wrote:
>
> Junio C Hamano <gitster@pobox.com> writes:
>
> > As t3454 is taken by another topic already in flight, I've queued a
> > trivial "rename it to t3455" patch on top before queuing the topic.
>
> Another tweak I had to make was to replace "grep" with "test_grep"
> to avoid triggering test lint added by another topic in flight.
>
> For the one in the second hunk, it may be much better to rewrite it
> to process "out" directly with the awk script without preprocessing
> it with "grep", as awk is a programming language capable enough to
> recognize a line that matches a pattern and process only those
> matching lines by itself.
>
> --- >8 ---
> Author: Junio C Hamano <gitster@pobox.com>
> Date: Thu Jun 18 13:44:36 2026 -0700
>
> SQUASH??? avoid test_grep lint triggering on uses of raw grep
>
> diff --git a/t/t3455-history-squash.sh b/t/t3455-history-squash.sh
> index 1edd148295..20370c0136 100755
> --- a/t/t3455-history-squash.sh
> +++ b/t/t3455-history-squash.sh
[snip]
> @@ -177,7 +177,7 @@ test_expect_success '--dry-run predicts the rewrite without performing it' '
> head_before=$(git rev-parse HEAD) &&
>
> git history squash --dry-run start.. >out &&
> - grep "^update refs/heads/" out >update &&
> + test_grep "^update refs/heads/" out >update &&
> predicted=$(awk "{print \$3}" update) &&
> test_cmp_rev "$head_before" HEAD &&
Odd: I thought the other topic acknowledged that bare grep as a filter
(here, with stdout redirected) was fine. My memory must not be right
:)
--
D. Ben Knoble
^ permalink raw reply
* Re: [PATCH v3 3/4] history: add squash subcommand to fold a range
From: Junio C Hamano @ 2026-06-18 21:24 UTC (permalink / raw)
To: Harald Nordgren via GitGitGadget; +Cc: git, Harald Nordgren
In-Reply-To: <xmqq7bnvr3qb.fsf@gitster.g>
Junio C Hamano <gitster@pobox.com> writes:
> As t3454 is taken by another topic already in flight, I've queued a
> trivial "rename it to t3455" patch on top before queuing the topic.
Another tweak I had to make was to replace "grep" with "test_grep"
to avoid triggering test lint added by another topic in flight.
For the one in the second hunk, it may be much better to rewrite it
to process "out" directly with the awk script without preprocessing
it with "grep", as awk is a programming language capable enough to
recognize a line that matches a pattern and process only those
matching lines by itself.
--- >8 ---
Author: Junio C Hamano <gitster@pobox.com>
Date: Thu Jun 18 13:44:36 2026 -0700
SQUASH??? avoid test_grep lint triggering on uses of raw grep
diff --git a/t/t3455-history-squash.sh b/t/t3455-history-squash.sh
index 1edd148295..20370c0136 100755
--- a/t/t3455-history-squash.sh
+++ b/t/t3455-history-squash.sh
@@ -150,10 +150,10 @@ test_expect_success '--reedit-message offers every folded-in message' '
test_set_editor "$(pwd)/editor" &&
git history squash --reedit-message start.. &&
- grep "re-one subject" buffer &&
- grep "re-one body line" buffer &&
- grep re-two buffer &&
- grep re-three buffer &&
+ test_grep "re-one subject" buffer &&
+ test_grep "re-one body line" buffer &&
+ test_grep re-two buffer &&
+ test_grep re-three buffer &&
git log --format="%s" -1 >actual &&
echo combined >expect &&
test_cmp expect actual
@@ -177,7 +177,7 @@ test_expect_success '--dry-run predicts the rewrite without performing it' '
head_before=$(git rev-parse HEAD) &&
git history squash --dry-run start.. >out &&
- grep "^update refs/heads/" out >update &&
+ test_grep "^update refs/heads/" out >update &&
predicted=$(awk "{print \$3}" update) &&
test_cmp_rev "$head_before" HEAD &&
^ permalink raw reply related
* Re: [PATCH v3 0/4] history: add squash subcommand to fold a range
From: D. Ben Knoble @ 2026-06-18 21:23 UTC (permalink / raw)
To: Harald Nordgren via GitGitGadget; +Cc: git, Harald Nordgren
In-Reply-To: <pull.2337.v3.git.git.1781810226.gitgitgadget@gmail.com>
On Thu, Jun 18, 2026 at 3:17 PM Harald Nordgren via GitGitGadget
<gitgitgadget@gmail.com> wrote:
>
> Adds git history squash <revision-range> to fold a range of commits into its
> oldest one, reusing that commit's message and replaying any descendants on
> top.
>
> Changes in v3:
>
> * Moved the feature out of git rebase and into a new git history squash
> <revision-range> subcommand, per the list discussion. git rebase --squash
> is dropped.
> * Takes an arbitrary range (git history squash @~3.., git history squash
> @~5..@~2), folding it into the oldest commit and replaying any
> descendants on top.
> * Implemented as a single tree operation rather than picking each commit,
> so there are no repeated conflict stops (addresses Phillip's efficiency
> point).
I think I mentioned this, too, albeit indirectly. I'm not concerned
about credit, though. Just excited to have this.
Thanks!
> * A merge inside the range is folded fine, only a range with more than one
> base is rejected.
> * --reedit-message seeds the editor with every folded-in message, not just
> the oldest.
>
> Harald Nordgren (4):
> history: extract helper for a commit's parent tree
> history: give commit_tree_ext a message template
> history: add squash subcommand to fold a range
> history: re-edit a squash with every message
^ permalink raw reply
* Re: [PATCH v3 3/4] history: add squash subcommand to fold a range
From: Junio C Hamano @ 2026-06-18 20:30 UTC (permalink / raw)
To: Harald Nordgren via GitGitGadget; +Cc: git, Harald Nordgren
In-Reply-To: <66b2f49fb427c7328136b2d440dc7461b97fb4e0.1781810227.git.gitgitgadget@gmail.com>
"Harald Nordgren via GitGitGadget" <gitgitgadget@gmail.com> writes:
> +static int cmd_history_squash(int argc,
> + const char **argv,
> + const char *prefix,
> + struct repository *repo)
> +{
> + base_tree_oid = &repo_get_commit_tree(repo, base)->object.oid;
> + tip_tree_oid = &repo_get_commit_tree(repo, tip)->object.oid;
> + commit_list_append(base, &parents);
> +
> + ret = commit_tree_ext(repo, "squash", oldest, NULL, parents,
> + base_tree_oid, tip_tree_oid, &rewritten, flags);
We use the tree object taken from the commit at the top end of the
range, and create a new commit directly on top of the boundary
commit beyond the bottom of the range, using the message from the
commit at the bottom of the range. No need to go through the
rigmarole of replaying commits in the range stepwise like sequencer
does, since we are not transplanting the history on top of a
different tree at all. Very nice.
When I do drunken-walk development to build many commits, making
detour to arrive at an ideal state, the key message is often not in
the bottommost commit but somewhere in the middle where I discovered
why my initial attempt were wrong and discovered a much better
solution, so using only the message from the oldest limits the
usefulness of this feature, but I guess for certain people the
bottommost commit would be a good default.
I see you have already an option to grab messages from all the
commits in the range (many of which may have useless "oops, that was
wrong" single-liner) in a way similar to how "git rebase --squash"
or "squash" insn in the "git rebase -i" todo list lets you use them
in the next step, which is workable. It is plausible that we would
later want to offer an option to name the single commit that may not
be the bottommost one and use the message only from that commit.
But we'd need to start from somewhere, and "use the bottommost
commit and nothing else" and "we will give you messages from all the
commits, just rearrange them in your editor" may be a good place to
start.
As t3454 is taken by another topic already in flight, I've queued a
trivial "rename it to t3455" patch on top before queuing the topic.
Thanks.
^ permalink raw reply
* [PATCH v16 7/7] branch: add --dry-run for --delete-merged
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:25 UTC (permalink / raw)
To: git
Cc: Kristoffer Haugsbakk, Johannes Sixt, Phillip Wood,
Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2285.v16.git.git.1781810729.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
With --dry-run, --delete-merged prints the local branches it would
delete, one "Would delete branch <name>" line each, and exits
without touching any ref. The same filtering applies, so the output
is exactly the set that the real run would delete.
--dry-run is only meaningful together with --delete-merged and is
rejected otherwise.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
Documentation/git-branch.adoc | 8 +++++++-
builtin/branch.c | 9 ++++++++-
t/t3200-branch.sh | 11 ++++++++++-
3 files changed, 25 insertions(+), 3 deletions(-)
diff --git a/Documentation/git-branch.adoc b/Documentation/git-branch.adoc
index 91700f2e8a..09063d74f2 100644
--- a/Documentation/git-branch.adoc
+++ b/Documentation/git-branch.adoc
@@ -25,7 +25,7 @@ git branch (-m|-M) [<old-branch>] <new-branch>
git branch (-c|-C) [<old-branch>] <new-branch>
git branch (-d|-D) [-r] <branch-name>...
git branch --edit-description [<branch-name>]
-git branch --delete-merged <branch>...
+git branch [--dry-run] --delete-merged <branch>...
DESCRIPTION
-----------
@@ -226,6 +226,12 @@ A branch whose work has not yet been merged into its upstream is
silently skipped. Delete it with `git branch -D` if you want to
remove it anyway.
+`--dry-run`::
+ With `--delete-merged`, print which branches would be
+ deleted and exit without touching any ref. Useful for
+ sanity-checking a wide pattern like `'origin/*'` before
+ committing to the deletion.
+
`-v`::
`-vv`::
`--verbose`::
diff --git a/builtin/branch.c b/builtin/branch.c
index 942e2297c8..f67d0949fe 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -826,6 +826,7 @@ int cmd_branch(int argc,
int delete = 0, rename = 0, copy = 0, list = 0,
unset_upstream = 0, show_current = 0, edit_description = 0;
int delete_merged = 0;
+ int dry_run = 0;
const char *new_upstream = NULL;
int noncreate_actions = 0;
/* possible options */
@@ -881,6 +882,8 @@ int cmd_branch(int argc,
N_("edit the description for the branch")),
OPT_BOOL(0, "delete-merged", &delete_merged,
N_("delete local branches whose upstream matches <branch> and are merged")),
+ OPT_BOOL(0, "dry-run", &dry_run,
+ N_("with --delete-merged, only print which branches would be deleted")),
OPT__FORCE(&force, N_("force creation, move/rename, deletion"), PARSE_OPT_NOCOMPLETE),
OPT_MERGED(&filter, N_("print only branches that are merged")),
OPT_NO_MERGED(&filter, N_("print only branches that are not merged")),
@@ -943,6 +946,9 @@ int cmd_branch(int argc,
if (noncreate_actions > 1)
usage_with_options(builtin_branch_usage, options);
+ if (dry_run && !delete_merged)
+ die(_("--dry-run requires --delete-merged"));
+
if (recurse_submodules_explicit) {
if (!submodule_propagate_branches)
die(_("branch with --recurse-submodules can only be used if submodule.propagateBranches is enabled"));
@@ -983,7 +989,8 @@ int cmd_branch(int argc,
goto out;
} else if (delete_merged) {
ret = delete_merged_branches(argc, argv,
- quiet ? DELETE_BRANCH_QUIET : 0);
+ (quiet ? DELETE_BRANCH_QUIET : 0) |
+ (dry_run ? DELETE_BRANCH_DRY_RUN : 0));
goto out;
} else if (show_current) {
print_current_branch_name();
diff --git a/t/t3200-branch.sh b/t/t3200-branch.sh
index 09cecfaff5..4a71845c76 100755
--- a/t/t3200-branch.sh
+++ b/t/t3200-branch.sh
@@ -1892,8 +1892,12 @@ test_expect_success '--delete-merged deletes merged branches and spares the rest
) &&
sha=$(git -C repo rev-parse --short merged) &&
- git -C repo branch --delete-merged origin/next >actual 2>&1 &&
+ git -C repo branch --dry-run --delete-merged origin/next >actual 2>&1 &&
+ echo "Would delete branch merged (was $sha)." >expect &&
+ test_cmp expect actual &&
+ git -C repo rev-parse --verify refs/heads/merged &&
+ git -C repo branch --delete-merged origin/next >actual 2>&1 &&
echo "Deleted branch merged (was $sha)." >expect &&
test_cmp expect actual &&
git -C repo for-each-ref --format="%(refname:short)" refs/heads/ >actual &&
@@ -1970,4 +1974,9 @@ test_expect_success "branch -d still deletes a deleteMerged=false branch" '
test_must_fail git -C repo rev-parse --verify refs/heads/kept
'
+test_expect_success '--dry-run without --delete-merged is rejected' '
+ test_must_fail git -C forked branch --dry-run 2>err &&
+ test_grep "requires --delete-merged" err
+'
+
test_done
--
gitgitgadget
^ permalink raw reply related
* [PATCH v16 6/7] branch: add branch.<name>.deleteMerged opt-out
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:25 UTC (permalink / raw)
To: git
Cc: Kristoffer Haugsbakk, Johannes Sixt, Phillip Wood,
Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2285.v16.git.git.1781810729.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
Setting branch.<name>.deleteMerged=false exempts that branch from
"git branch --delete-merged", which is useful for a topic you want
to keep developing after an early round of it has been merged
upstream. Unless --quiet is given, each skip is reported so the
user knows why their topic was kept.
Explicit deletion with "git branch -d" still uses the normal merge
check and ignores this setting.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
Documentation/config/branch.adoc | 7 +++++++
Documentation/git-branch.adoc | 5 +++--
builtin/branch.c | 15 +++++++++++++++
t/t3200-branch.sh | 26 ++++++++++++++++++++++++++
4 files changed, 51 insertions(+), 2 deletions(-)
diff --git a/Documentation/config/branch.adoc b/Documentation/config/branch.adoc
index a4db9fa5c8..d8483acb4f 100644
--- a/Documentation/config/branch.adoc
+++ b/Documentation/config/branch.adoc
@@ -102,3 +102,10 @@ for details).
`git branch --edit-description`. Branch description is
automatically added to the `format-patch` cover letter or
`request-pull` summary.
+
+`branch.<name>.deleteMerged`::
+ If set to `false`, branch _<name>_ is exempt from
+ `git branch --delete-merged`. Useful for a topic branch you
+ intend to develop further after an initial round has been
+ merged upstream. Defaults to true. Explicit deletion via
+ `git branch -d` is unaffected.
diff --git a/Documentation/git-branch.adoc b/Documentation/git-branch.adoc
index f82cfa36d0..91700f2e8a 100644
--- a/Documentation/git-branch.adoc
+++ b/Documentation/git-branch.adoc
@@ -215,10 +215,11 @@ A branch is not deleted when:
+
--
* its upstream remote-tracking branch no longer exists,
-* it is checked out in any worktree, or
+* it is checked out in any worktree,
* its push destination (`<branch>@{push}`) equals its upstream
(`<branch>@{upstream}`), so it cannot be distinguished from a
- branch that just looks "fully merged" right after a pull.
+ branch that just looks "fully merged" right after a pull, or
+* `branch.<name>.deleteMerged` is set to `false`.
--
+
A branch whose work has not yet been merged into its upstream is
diff --git a/builtin/branch.c b/builtin/branch.c
index e7e4f1d27f..942e2297c8 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -722,6 +722,8 @@ static int delete_merged_branches(int argc, const char **argv,
struct ref_filter filter = REF_FILTER_INIT;
struct ref_array candidates = { 0 };
struct strvec deletable = STRVEC_INIT;
+ struct strbuf key = STRBUF_INIT;
+ bool quiet = flags & DELETE_BRANCH_QUIET;
int i, ret = 0;
if (!argc)
@@ -739,6 +741,7 @@ static int delete_merged_branches(int argc, const char **argv,
const char *short_name;
struct branch *branch;
const char *upstream, *push;
+ int opt_out;
if (!skip_prefix(full_name, "refs/heads/", &short_name))
BUG("filter returned non-branch ref '%s'", full_name);
@@ -753,6 +756,17 @@ static int delete_merged_branches(int argc, const char **argv,
if (!push || !strcmp(push, upstream))
continue;
+ strbuf_reset(&key);
+ strbuf_addf(&key, "branch.%s.deletemerged", short_name);
+ if (!repo_config_get_bool(the_repository, key.buf, &opt_out) &&
+ !opt_out) {
+ if (!quiet)
+ fprintf(stderr,
+ _("Skipping '%s' (branch.%s.deleteMerged is false)\n"),
+ short_name, short_name);
+ continue;
+ }
+
strvec_push(&deletable, short_name);
}
@@ -763,6 +777,7 @@ static int delete_merged_branches(int argc, const char **argv,
DELETE_BRANCH_NO_HEAD_FALLBACK |
flags);
+ strbuf_release(&key);
strvec_clear(&deletable);
ref_array_clear(&candidates);
ref_filter_clear(&filter);
diff --git a/t/t3200-branch.sh b/t/t3200-branch.sh
index 609a67bb5a..09cecfaff5 100755
--- a/t/t3200-branch.sh
+++ b/t/t3200-branch.sh
@@ -1944,4 +1944,30 @@ test_expect_success '--delete-merged requires at least one <branch>' '
test_grep "requires at least one <branch>" err
'
+test_expect_success '--delete-merged honours branch.<name>.deleteMerged=false' '
+ test_when_finished "rm -rf repo" &&
+ setup_repo_for_delete_merged &&
+ merged_branch deleted origin/next &&
+ merged_branch kept origin/next &&
+ git -C repo config branch.kept.deleteMerged false &&
+ git -C repo checkout --detach &&
+
+ git -C repo branch --delete-merged origin/next 2>err &&
+
+ test_grep "Skipping .kept." err &&
+ test_must_fail git -C repo rev-parse --verify refs/heads/deleted &&
+ git -C repo rev-parse --verify refs/heads/kept
+'
+
+test_expect_success "branch -d still deletes a deleteMerged=false branch" '
+ test_when_finished "rm -rf repo" &&
+ setup_repo_for_delete_merged &&
+ merged_branch kept origin/next &&
+ git -C repo config branch.kept.deleteMerged false &&
+ git -C repo checkout --detach &&
+
+ git -C repo branch -d kept &&
+ test_must_fail git -C repo rev-parse --verify refs/heads/kept
+'
+
test_done
--
gitgitgadget
^ permalink raw reply related
* [PATCH v16 5/7] branch: add --delete-merged <branch>
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:25 UTC (permalink / raw)
To: git
Cc: Kristoffer Haugsbakk, Johannes Sixt, Phillip Wood,
Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2285.v16.git.git.1781810729.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
git branch --delete-merged <branch>...
deletes the local branches that "--forked <branch>" would list,
keeping only those whose tip is reachable from their configured
upstream. The work has already landed on the upstream they track,
so the local copy is no longer needed.
Three kinds of branches are not deleted:
* any branch checked out in any worktree
* any branch whose upstream remote-tracking branch no longer
exists, since a missing upstream is not by itself a sign of
integration
* any branch whose push destination equals its upstream
(<branch>@{push} is the same as <branch>@{upstream}), such as
a local "main" that tracks and pushes to "origin/main". Right
after a pull it just looks "fully merged", so it is kept. Only
branches that push somewhere other than their upstream,
typically topics in a fork workflow, are candidates.
A branch whose work is not yet merged into its upstream is silently
skipped, so one unmerged topic does not abort the whole sweep.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
Documentation/git-branch.adoc | 24 ++++++++
builtin/branch.c | 67 +++++++++++++++++++++-
t/t3200-branch.sh | 105 ++++++++++++++++++++++++++++++++++
3 files changed, 194 insertions(+), 2 deletions(-)
diff --git a/Documentation/git-branch.adoc b/Documentation/git-branch.adoc
index b0d66a6deb..f82cfa36d0 100644
--- a/Documentation/git-branch.adoc
+++ b/Documentation/git-branch.adoc
@@ -25,6 +25,7 @@ git branch (-m|-M) [<old-branch>] <new-branch>
git branch (-c|-C) [<old-branch>] <new-branch>
git branch (-d|-D) [-r] <branch-name>...
git branch --edit-description [<branch-name>]
+git branch --delete-merged <branch>...
DESCRIPTION
-----------
@@ -201,6 +202,29 @@ This option is only applicable in non-verbose mode.
Print the name of the current branch. In detached `HEAD` state,
nothing is printed.
+`--delete-merged <branch>...`::
+ Delete the local branches that `--forked` would list for the
+ given _<branch>_ arguments, but only those whose tip is
+ reachable from their configured upstream. In other words, the
+ work on the branch has already landed on the upstream it
+ tracks, so the local copy is no longer needed. Several
+ _<branch>_ patterns may be given, e.g. `git branch
+ --delete-merged origin/main 'feature*'`.
++
+A branch is not deleted when:
++
+--
+* its upstream remote-tracking branch no longer exists,
+* it is checked out in any worktree, or
+* its push destination (`<branch>@{push}`) equals its upstream
+ (`<branch>@{upstream}`), so it cannot be distinguished from a
+ branch that just looks "fully merged" right after a pull.
+--
++
+A branch whose work has not yet been merged into its upstream is
+silently skipped. Delete it with `git branch -D` if you want to
+remove it anyway.
+
`-v`::
`-vv`::
`--verbose`::
diff --git a/builtin/branch.c b/builtin/branch.c
index 1d3f28e4cb..e7e4f1d27f 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -38,6 +38,7 @@ static const char * const builtin_branch_usage[] = {
N_("git branch [<options>] (-c | -C) [<old-branch>] <new-branch>"),
N_("git branch [<options>] [-r | -a] [--points-at]"),
N_("git branch [<options>] [-r | -a] [--format]"),
+ N_("git branch [<options>] --delete-merged <branch>..."),
NULL
};
@@ -714,6 +715,60 @@ static int parse_opt_forked(const struct option *opt, const char *arg, int unset
return 0;
}
+static int delete_merged_branches(int argc, const char **argv,
+ unsigned int flags)
+{
+ struct ref_store *refs = get_main_ref_store(the_repository);
+ struct ref_filter filter = REF_FILTER_INIT;
+ struct ref_array candidates = { 0 };
+ struct strvec deletable = STRVEC_INIT;
+ int i, ret = 0;
+
+ if (!argc)
+ die(_("--delete-merged requires at least one <branch>"));
+
+ for (i = 0; i < argc; i++)
+ if (ref_filter_forked_add(&filter, argv[i]) < 0)
+ die(_("'%s' is not a valid branch or pattern"), argv[i]);
+
+ filter.kind = FILTER_REFS_BRANCHES;
+ filter_refs(&candidates, &filter, filter.kind);
+
+ for (i = 0; i < candidates.nr; i++) {
+ const char *full_name = candidates.items[i]->refname;
+ const char *short_name;
+ struct branch *branch;
+ const char *upstream, *push;
+
+ if (!skip_prefix(full_name, "refs/heads/", &short_name))
+ BUG("filter returned non-branch ref '%s'", full_name);
+ if (branch_checked_out(full_name))
+ continue;
+
+ branch = branch_get(short_name);
+ upstream = branch_get_upstream(branch, NULL);
+ if (!upstream || !refs_ref_exists(refs, upstream))
+ continue;
+ push = branch_get_push(branch, NULL);
+ if (!push || !strcmp(push, upstream))
+ continue;
+
+ strvec_push(&deletable, short_name);
+ }
+
+ if (deletable.nr)
+ ret = delete_branches(deletable.nr, deletable.v,
+ FILTER_REFS_BRANCHES,
+ DELETE_BRANCH_SKIP_UNMERGED |
+ DELETE_BRANCH_NO_HEAD_FALLBACK |
+ flags);
+
+ strvec_clear(&deletable);
+ ref_array_clear(&candidates);
+ ref_filter_clear(&filter);
+ return ret;
+}
+
static GIT_PATH_FUNC(edit_description, "EDIT_DESCRIPTION")
static int edit_branch_description(const char *branch_name)
@@ -755,6 +810,7 @@ int cmd_branch(int argc,
/* possible actions */
int delete = 0, rename = 0, copy = 0, list = 0,
unset_upstream = 0, show_current = 0, edit_description = 0;
+ int delete_merged = 0;
const char *new_upstream = NULL;
int noncreate_actions = 0;
/* possible options */
@@ -808,6 +864,8 @@ int cmd_branch(int argc,
OPT_BOOL(0, "create-reflog", &reflog, N_("create the branch's reflog")),
OPT_BOOL(0, "edit-description", &edit_description,
N_("edit the description for the branch")),
+ OPT_BOOL(0, "delete-merged", &delete_merged,
+ N_("delete local branches whose upstream matches <branch> and are merged")),
OPT__FORCE(&force, N_("force creation, move/rename, deletion"), PARSE_OPT_NOCOMPLETE),
OPT_MERGED(&filter, N_("print only branches that are merged")),
OPT_NO_MERGED(&filter, N_("print only branches that are not merged")),
@@ -855,7 +913,8 @@ int cmd_branch(int argc,
0);
if (!delete && !rename && !copy && !edit_description && !new_upstream &&
- !show_current && !unset_upstream && argc == 0)
+ !show_current && !unset_upstream && !delete_merged &&
+ argc == 0)
list = 1;
if (filter.with_commit || filter.no_commit ||
@@ -865,7 +924,7 @@ int cmd_branch(int argc,
noncreate_actions = !!delete + !!rename + !!copy + !!new_upstream +
!!show_current + !!list + !!edit_description +
- !!unset_upstream;
+ !!unset_upstream + !!delete_merged;
if (noncreate_actions > 1)
usage_with_options(builtin_branch_usage, options);
@@ -907,6 +966,10 @@ int cmd_branch(int argc,
(delete > 1 ? DELETE_BRANCH_FORCE : 0) |
(quiet ? DELETE_BRANCH_QUIET : 0));
goto out;
+ } else if (delete_merged) {
+ ret = delete_merged_branches(argc, argv,
+ quiet ? DELETE_BRANCH_QUIET : 0);
+ goto out;
} else if (show_current) {
print_current_branch_name();
ret = 0;
diff --git a/t/t3200-branch.sh b/t/t3200-branch.sh
index 3104c555f6..609a67bb5a 100755
--- a/t/t3200-branch.sh
+++ b/t/t3200-branch.sh
@@ -1839,4 +1839,109 @@ test_expect_success '--forked narrows a <pattern> argument' '
test_cmp expect actual
'
+test_expect_success '--delete-merged: setup' '
+ git init -b main upstream &&
+ (
+ cd upstream &&
+ test_commit base &&
+ git checkout -b next &&
+ test_commit next-work &&
+ git checkout main
+ ) &&
+ git init -b main other &&
+ test_commit -C other other-base &&
+ git init -b main fork
+'
+
+setup_repo_for_delete_merged () {
+ rm -rf repo &&
+ git clone upstream repo &&
+ (
+ cd repo &&
+ git remote add fork ../fork &&
+ git remote add other ../other &&
+ git config remote.pushDefault fork &&
+ git config push.default current &&
+ git fetch other
+ )
+}
+
+merged_branch () {
+ (
+ cd repo &&
+ git checkout -b "$1" "$2" &&
+ git commit --allow-empty -m "$1 work" &&
+ git push origin "$1:next" &&
+ git fetch origin &&
+ git branch --set-upstream-to="$2" "$1"
+ )
+}
+
+test_expect_success '--delete-merged deletes merged branches and spares the rest' '
+ test_when_finished "rm -rf repo" &&
+ setup_repo_for_delete_merged &&
+ merged_branch merged origin/next &&
+ (
+ cd repo &&
+ git checkout -b unmerged origin/next &&
+ git commit --allow-empty -m "unmerged work" &&
+ git branch --set-upstream-to=origin/next unmerged &&
+ git checkout -b tracks-other other/main &&
+ git branch --set-upstream-to=other/main tracks-other &&
+ git checkout --detach
+ ) &&
+ sha=$(git -C repo rev-parse --short merged) &&
+
+ git -C repo branch --delete-merged origin/next >actual 2>&1 &&
+
+ echo "Deleted branch merged (was $sha)." >expect &&
+ test_cmp expect actual &&
+ git -C repo for-each-ref --format="%(refname:short)" refs/heads/ >actual &&
+ cat >expect <<-\EOF &&
+ main
+ tracks-other
+ unmerged
+ EOF
+ test_cmp expect actual
+'
+
+test_expect_success '--delete-merged deletes merged branches and spares protected ones' '
+ test_when_finished "rm -rf repo" &&
+ setup_repo_for_delete_merged &&
+ merged_branch on-next origin/next &&
+ merged_branch checked-out origin/next &&
+ merged_branch upstream-gone origin/next &&
+ (
+ cd repo &&
+ git checkout -b mainline main &&
+ git checkout -b on-local mainline &&
+ git branch --set-upstream-to=mainline on-local &&
+ git update-ref refs/remotes/origin/topic refs/remotes/origin/next &&
+ git branch --set-upstream-to=origin/topic upstream-gone &&
+ git update-ref -d refs/remotes/origin/topic &&
+ git branch --set-upstream-to=origin/main main &&
+ git config branch.main.pushRemote origin &&
+ git checkout -b tracks-other other/main &&
+ git branch --set-upstream-to=other/main tracks-other &&
+ git checkout checked-out
+ ) &&
+
+ git -C repo branch --delete-merged origin/next mainline &&
+
+ git -C repo for-each-ref --format="%(refname:short)" refs/heads/ >actual &&
+ cat >expect <<-\EOF &&
+ checked-out
+ main
+ mainline
+ tracks-other
+ upstream-gone
+ EOF
+ test_cmp expect actual
+'
+
+test_expect_success '--delete-merged requires at least one <branch>' '
+ test_must_fail git -C forked branch --delete-merged 2>err &&
+ test_grep "requires at least one <branch>" err
+'
+
test_done
--
gitgitgadget
^ permalink raw reply related
* [PATCH v16 4/7] branch: prepare delete_branches for a bulk caller
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:25 UTC (permalink / raw)
To: git
Cc: Kristoffer Haugsbakk, Johannes Sixt, Phillip Wood,
Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2285.v16.git.git.1781810729.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
Teach delete_branches() two new modes for the upcoming
--delete-merged: one that asks only whether a branch is merged into
its upstream, without falling back to HEAD when there is no
upstream, and one that rehearses the deletions without removing any
ref. Existing callers keep their current behavior.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
builtin/branch.c | 26 ++++++++++++++++++++------
1 file changed, 20 insertions(+), 6 deletions(-)
diff --git a/builtin/branch.c b/builtin/branch.c
index 4c569d056a..1d3f28e4cb 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -168,10 +168,13 @@ static int branch_merged(int kind, const char *name,
* upstream, if any, otherwise with HEAD", we should just
* return the result of the repo_in_merge_bases() above without
* any of the following code, but during the transition period,
- * a gentle reminder is in order.
+ * a gentle reminder is in order. Callers that opt out of the
+ * HEAD fallback by passing head_rev=NULL are not interested in
+ * the reminder either: they have already established that the
+ * branch has an upstream, so HEAD is irrelevant to the decision.
*/
- if (head_rev != reference_rev) {
- int expect = head_rev ? repo_in_merge_bases(the_repository, rev, head_rev) : 0;
+ if (head_rev && head_rev != reference_rev) {
+ int expect = repo_in_merge_bases(the_repository, rev, head_rev);
if (expect < 0)
exit(128);
if (expect == merged)
@@ -193,6 +196,8 @@ enum delete_branch_flags {
DELETE_BRANCH_FORCE = (1 << 0),
DELETE_BRANCH_QUIET = (1 << 1),
DELETE_BRANCH_SKIP_UNMERGED = (1 << 2),
+ DELETE_BRANCH_NO_HEAD_FALLBACK = (1 << 3),
+ DELETE_BRANCH_DRY_RUN = (1 << 4),
};
static int check_branch_commit(const char *branchname, const char *refname,
@@ -241,6 +246,8 @@ static int delete_branches(int argc, const char **argv, int kinds,
bool force;
bool quiet = flags & DELETE_BRANCH_QUIET;
bool skip_unmerged = flags & DELETE_BRANCH_SKIP_UNMERGED;
+ bool dry_run = flags & DELETE_BRANCH_DRY_RUN;
+ bool no_head_fallback = flags & DELETE_BRANCH_NO_HEAD_FALLBACK;
struct strbuf bname = STRBUF_INIT;
enum interpret_branch_kind allowed_interpret;
struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
@@ -268,7 +275,7 @@ static int delete_branches(int argc, const char **argv, int kinds,
force = flags & DELETE_BRANCH_FORCE;
- if (!force)
+ if (!force && !no_head_fallback)
head_rev = lookup_commit_reference(the_repository, &head_oid);
for (i = 0; i < argc; i++, strbuf_reset(&bname)) {
@@ -339,13 +346,20 @@ static int delete_branches(int argc, const char **argv, int kinds,
free(target);
}
- if (refs_delete_refs(get_main_ref_store(the_repository), NULL, &refs_to_delete, REF_NO_DEREF))
+ if (!dry_run &&
+ refs_delete_refs(get_main_ref_store(the_repository), NULL, &refs_to_delete, REF_NO_DEREF))
ret = 1;
for_each_string_list_item(item, &refs_to_delete) {
char *describe_ref = item->util;
char *name = item->string;
- if (!refs_ref_exists(get_main_ref_store(the_repository), name)) {
+ if (dry_run) {
+ if (!quiet)
+ printf(remote_branch
+ ? _("Would delete remote-tracking branch %s (was %s).\n")
+ : _("Would delete branch %s (was %s).\n"),
+ name + branch_name_pos, describe_ref);
+ } else if (!refs_ref_exists(get_main_ref_store(the_repository), name)) {
char *refname = name + branch_name_pos;
if (!quiet)
printf(remote_branch
--
gitgitgadget
^ permalink raw reply related
* [PATCH v16 3/7] branch: let delete_branches skip unmerged branches on bulk refusal
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:25 UTC (permalink / raw)
To: git
Cc: Kristoffer Haugsbakk, Johannes Sixt, Phillip Wood,
Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2285.v16.git.git.1781810729.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
Add a skip-unmerged mode to delete_branches() and check_branch_commit()
so a bulk caller can silently skip branches that are not fully merged
and carry on, rather than erroring with the "use 'git branch -D'"
advice that the plain "git branch -d" path emits. Existing callers are
unaffected.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
builtin/branch.c | 17 ++++++++++++-----
1 file changed, 12 insertions(+), 5 deletions(-)
diff --git a/builtin/branch.c b/builtin/branch.c
index a9be980aef..4c569d056a 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -192,6 +192,7 @@ static int branch_merged(int kind, const char *name,
enum delete_branch_flags {
DELETE_BRANCH_FORCE = (1 << 0),
DELETE_BRANCH_QUIET = (1 << 1),
+ DELETE_BRANCH_SKIP_UNMERGED = (1 << 2),
};
static int check_branch_commit(const char *branchname, const char *refname,
@@ -199,16 +200,20 @@ static int check_branch_commit(const char *branchname, const char *refname,
int kinds, unsigned int flags)
{
bool force = flags & DELETE_BRANCH_FORCE;
+ bool skip_unmerged = flags & DELETE_BRANCH_SKIP_UNMERGED;
struct commit *rev = lookup_commit_reference(the_repository, oid);
if (!force && !rev) {
error(_("couldn't look up commit object for '%s'"), refname);
return -1;
}
if (!force && !branch_merged(kinds, branchname, rev, head_rev)) {
- error(_("the branch '%s' is not fully merged"), branchname);
- advise_if_enabled(ADVICE_FORCE_DELETE_BRANCH,
- _("If you are sure you want to delete it, "
- "run 'git branch -D %s'"), branchname);
+ if (!skip_unmerged) {
+ error(_("the branch '%s' is not fully merged"),
+ branchname);
+ advise_if_enabled(ADVICE_FORCE_DELETE_BRANCH,
+ _("If you are sure you want to delete it, "
+ "run 'git branch -D %s'"), branchname);
+ }
return -1;
}
return 0;
@@ -235,6 +240,7 @@ static int delete_branches(int argc, const char **argv, int kinds,
int remote_branch = 0;
bool force;
bool quiet = flags & DELETE_BRANCH_QUIET;
+ bool skip_unmerged = flags & DELETE_BRANCH_SKIP_UNMERGED;
struct strbuf bname = STRBUF_INIT;
enum interpret_branch_kind allowed_interpret;
struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
@@ -319,7 +325,8 @@ static int delete_branches(int argc, const char **argv, int kinds,
if (!(ref_flags & (REF_ISSYMREF|REF_ISBROKEN)) &&
check_branch_commit(bname.buf, name, &oid, head_rev, kinds,
flags)) {
- ret = 1;
+ if (!skip_unmerged)
+ ret = 1;
goto next;
}
--
gitgitgadget
^ permalink raw reply related
* [PATCH v16 2/7] branch: convert delete_branches() to a flags argument
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:25 UTC (permalink / raw)
To: git
Cc: Kristoffer Haugsbakk, Johannes Sixt, Phillip Wood,
Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2285.v16.git.git.1781810729.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
delete_branches() and check_branch_commit() take a pair of int
booleans (force and quiet) that the next commits would grow further.
Replace them with a single "unsigned int flags" argument and an
enum, splitting the bits back into named bool locals so the body
keeps reading the same named values.
No change in behavior.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
builtin/branch.c | 36 ++++++++++++++++++++++++------------
1 file changed, 24 insertions(+), 12 deletions(-)
diff --git a/builtin/branch.c b/builtin/branch.c
index c159f45b4c..a9be980aef 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -189,10 +189,16 @@ static int branch_merged(int kind, const char *name,
return merged;
}
+enum delete_branch_flags {
+ DELETE_BRANCH_FORCE = (1 << 0),
+ DELETE_BRANCH_QUIET = (1 << 1),
+};
+
static int check_branch_commit(const char *branchname, const char *refname,
const struct object_id *oid, struct commit *head_rev,
- int kinds, int force)
+ int kinds, unsigned int flags)
{
+ bool force = flags & DELETE_BRANCH_FORCE;
struct commit *rev = lookup_commit_reference(the_repository, oid);
if (!force && !rev) {
error(_("couldn't look up commit object for '%s'"), refname);
@@ -217,8 +223,8 @@ static void delete_branch_config(const char *branchname)
strbuf_release(&buf);
}
-static int delete_branches(int argc, const char **argv, int force, int kinds,
- int quiet)
+static int delete_branches(int argc, const char **argv, int kinds,
+ unsigned int flags)
{
struct commit *head_rev = NULL;
struct object_id oid;
@@ -227,6 +233,8 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
int i;
int ret = 0;
int remote_branch = 0;
+ bool force;
+ bool quiet = flags & DELETE_BRANCH_QUIET;
struct strbuf bname = STRBUF_INIT;
enum interpret_branch_kind allowed_interpret;
struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
@@ -241,7 +249,7 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
remote_branch = 1;
allowed_interpret = INTERPRET_BRANCH_REMOTE;
- force = 1;
+ flags |= DELETE_BRANCH_FORCE;
break;
case FILTER_REFS_BRANCHES:
fmt = "refs/heads/%s";
@@ -252,12 +260,14 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
}
branch_name_pos = strcspn(fmt, "%");
+ force = flags & DELETE_BRANCH_FORCE;
+
if (!force)
head_rev = lookup_commit_reference(the_repository, &head_oid);
for (i = 0; i < argc; i++, strbuf_reset(&bname)) {
char *target = NULL;
- int flags = 0;
+ int ref_flags = 0;
copy_branchname(&bname, argv[i], allowed_interpret);
free(name);
@@ -279,7 +289,7 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
RESOLVE_REF_READING
| RESOLVE_REF_NO_RECURSE
| RESOLVE_REF_ALLOW_BAD_NAME,
- &oid, &flags);
+ &oid, &ref_flags);
if (!target) {
if (remote_branch) {
error(_("remote-tracking branch '%s' not found"), bname.buf);
@@ -291,7 +301,7 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
| RESOLVE_REF_NO_RECURSE
| RESOLVE_REF_ALLOW_BAD_NAME,
&oid,
- &flags);
+ &ref_flags);
FREE_AND_NULL(virtual_name);
if (virtual_target)
@@ -306,16 +316,16 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
continue;
}
- if (!(flags & (REF_ISSYMREF|REF_ISBROKEN)) &&
+ if (!(ref_flags & (REF_ISSYMREF|REF_ISBROKEN)) &&
check_branch_commit(bname.buf, name, &oid, head_rev, kinds,
- force)) {
+ flags)) {
ret = 1;
goto next;
}
item = string_list_append(&refs_to_delete, name);
- item->util = xstrdup((flags & REF_ISBROKEN) ? "broken"
- : (flags & REF_ISSYMREF) ? target
+ item->util = xstrdup((ref_flags & REF_ISBROKEN) ? "broken"
+ : (ref_flags & REF_ISSYMREF) ? target
: repo_find_unique_abbrev(the_repository, &oid, DEFAULT_ABBREV));
next:
@@ -872,7 +882,9 @@ int cmd_branch(int argc,
if (delete) {
if (!argc)
die(_("branch name required"));
- ret = delete_branches(argc, argv, delete > 1, filter.kind, quiet);
+ ret = delete_branches(argc, argv, filter.kind,
+ (delete > 1 ? DELETE_BRANCH_FORCE : 0) |
+ (quiet ? DELETE_BRANCH_QUIET : 0));
goto out;
} else if (show_current) {
print_current_branch_name();
--
gitgitgadget
^ permalink raw reply related
* [PATCH v16 1/7] branch: add --forked filter for --list mode
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:25 UTC (permalink / raw)
To: git
Cc: Kristoffer Haugsbakk, Johannes Sixt, Phillip Wood,
Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2285.v16.git.git.1781810729.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
Add a --forked option to "git branch" list mode that lists only
branches whose configured upstream matches <branch>. The argument
can be a ref (e.g. "origin/main", "master"), a remote name like
"origin" for the branch its origin/HEAD points at, or a shell glob
(e.g. "origin/*"), and may be repeated to widen the filter.
It is an ordinary list filter, so it combines with the others:
git branch --merged origin/main --forked 'origin/*'
lists branches forked from origin that are already merged into
origin/main, and --no-merged inverts the question.
This is the building block for --delete-merged, which deletes the
listed branches once they have landed on their upstream.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
Documentation/git-branch.adoc | 12 +++-
builtin/branch.c | 18 ++++-
ref-filter.c | 70 +++++++++++++++++++
ref-filter.h | 10 +++
t/t3200-branch.sh | 122 ++++++++++++++++++++++++++++++++++
5 files changed, 229 insertions(+), 3 deletions(-)
diff --git a/Documentation/git-branch.adoc b/Documentation/git-branch.adoc
index c0afddc424..b0d66a6deb 100644
--- a/Documentation/git-branch.adoc
+++ b/Documentation/git-branch.adoc
@@ -13,6 +13,7 @@ git branch [--color[=<when>] | --no-color] [--show-current]
[--column[=<options>] | --no-column] [--sort=<key>]
[--merged [<commit>]] [--no-merged [<commit>]]
[--contains [<commit>]] [--no-contains [<commit>]]
+ [(--forked <branch>)...]
[--points-at <object>] [--format=<format>]
[(-r|--remotes) | (-a|--all)]
[--list] [<pattern>...]
@@ -51,7 +52,8 @@ merged into the named commit (i.e. the branches whose tip commits are
reachable from the named commit) will be listed. With `--no-merged` only
branches not merged into the named commit will be listed. If the _<commit>_
argument is missing it defaults to `HEAD` (i.e. the tip of the current
-branch).
+branch). With `--forked`, only branches whose configured upstream matches
+the given branch or pattern will be listed.
The command's second form creates a new branch head named _<branch-name>_
which points to the current `HEAD`, or _<start-point>_ if given. As a
@@ -311,6 +313,14 @@ superproject's "origin/main", but tracks the submodule's "origin/main".
Only list branches whose tips are not reachable from
_<commit>_ (`HEAD` if not specified). Implies `--list`.
+`--forked <branch>`::
+ Only list branches whose configured upstream matches
+ _<branch>_. The argument can be a ref (e.g. `origin/main`,
+ `master`), a remote name like `origin` for the branch its
+ `origin/HEAD` points at, or a shell-style glob (e.g.
+ `'origin/*'`). The option can be repeated to widen the
+ filter. Implies `--list`.
+
`--points-at <object>`::
Only list branches of _<object>_.
diff --git a/builtin/branch.c b/builtin/branch.c
index 1572a4f9ef..c159f45b4c 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -30,7 +30,7 @@
#include "commit-reach.h"
static const char * const builtin_branch_usage[] = {
- N_("git branch [<options>] [-r | -a] [--merged] [--no-merged]"),
+ N_("git branch [<options>] [-r | -a] [--merged] [--no-merged] [(--forked <branch>)...]"),
N_("git branch [<options>] [-f] [--recurse-submodules] <branch-name> [<start-point>]"),
N_("git branch [<options>] [-l] [<pattern>...]"),
N_("git branch [<options>] [-r] (-d | -D) <branch-name>..."),
@@ -673,6 +673,16 @@ static void copy_or_rename_branch(const char *oldname, const char *newname, int
free_worktrees(worktrees);
}
+static int parse_opt_forked(const struct option *opt, const char *arg, int unset)
+{
+ struct ref_filter *filter = opt->value;
+
+ BUG_ON_OPT_NEG(unset);
+ if (ref_filter_forked_add(filter, arg) < 0)
+ die(_("'%s' is not a valid branch or pattern"), arg);
+ return 0;
+}
+
static GIT_PATH_FUNC(edit_description, "EDIT_DESCRIPTION")
static int edit_branch_description(const char *branch_name)
@@ -770,6 +780,9 @@ int cmd_branch(int argc,
OPT__FORCE(&force, N_("force creation, move/rename, deletion"), PARSE_OPT_NOCOMPLETE),
OPT_MERGED(&filter, N_("print only branches that are merged")),
OPT_NO_MERGED(&filter, N_("print only branches that are not merged")),
+ OPT_CALLBACK_F(0, "forked", &filter, N_("branch"),
+ N_("print only branches whose upstream matches <branch> (repeatable)"),
+ PARSE_OPT_NONEG, parse_opt_forked),
OPT_COLUMN(0, "column", &colopts, N_("list branches in columns")),
OPT_REF_SORT(&sorting_options),
OPT_CALLBACK(0, "points-at", &filter.points_at, N_("object"),
@@ -815,7 +828,8 @@ int cmd_branch(int argc,
list = 1;
if (filter.with_commit || filter.no_commit ||
- filter.reachable_from || filter.unreachable_from || filter.points_at.nr)
+ filter.reachable_from || filter.unreachable_from ||
+ filter.points_at.nr || filter.forked.nr)
list = 1;
noncreate_actions = !!delete + !!rename + !!copy + !!new_upstream +
diff --git a/ref-filter.c b/ref-filter.c
index 1da4c0e60d..1ddd5a3f6d 100644
--- a/ref-filter.c
+++ b/ref-filter.c
@@ -2744,6 +2744,72 @@ static int filter_exclude_match(struct ref_filter *filter, const char *refname)
return match_pattern(filter->exclude.v, refname, filter->ignore_case);
}
+static const char *short_upstream_name(const char *full_ref)
+{
+ const char *short_name = full_ref;
+ (void)(skip_prefix(short_name, "refs/heads/", &short_name) ||
+ skip_prefix(short_name, "refs/remotes/", &short_name));
+ return short_name;
+}
+
+/*
+ * Match the configured upstream of a branch against the registered
+ * --forked patterns. Exact patterns are compared against the full
+ * upstream refname so they are unambiguous; glob patterns are matched
+ * against the abbreviated upstream so that a glob such as origin/...
+ * works as typed.
+ */
+static int filter_forked_match(struct ref_filter *filter, const char *refname)
+{
+ const char *short_name;
+ struct branch *branch;
+ const char *upstream;
+ int i;
+
+ if (!skip_prefix(refname, "refs/heads/", &short_name))
+ return 0;
+ branch = branch_get(short_name);
+ if (!branch)
+ return 0;
+ upstream = branch_get_upstream(branch, NULL);
+ if (!upstream)
+ return 0;
+
+ for (i = 0; i < filter->forked.nr; i++) {
+ const char *pattern = filter->forked.v[i];
+ if (has_glob_specials(pattern)) {
+ if (!wildmatch(pattern, short_upstream_name(upstream),
+ WM_PATHNAME))
+ return 1;
+ } else if (!strcmp(pattern, upstream)) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int ref_filter_forked_add(struct ref_filter *filter, const char *arg)
+{
+ struct object_id oid;
+ char *full_ref = NULL;
+
+ if (has_glob_specials(arg)) {
+ strvec_push(&filter->forked, arg);
+ return 0;
+ }
+
+ if (repo_dwim_ref(the_repository, arg, strlen(arg), &oid,
+ &full_ref, 0) == 1 &&
+ (starts_with(full_ref, "refs/heads/") ||
+ starts_with(full_ref, "refs/remotes/"))) {
+ strvec_push(&filter->forked, full_ref);
+ free(full_ref);
+ return 0;
+ }
+ free(full_ref);
+ return -1;
+}
+
/*
* We need to seek to the reference right after a given marker but excluding any
* matching references. So we seek to the lexicographically next reference.
@@ -2979,6 +3045,9 @@ static struct ref_array_item *apply_ref_filter(const struct reference *ref,
if (filter->points_at.nr && !match_points_at(&filter->points_at, ref->oid, ref->name))
return NULL;
+ if (filter->forked.nr && !filter_forked_match(filter, ref->name))
+ return NULL;
+
/*
* A merge filter is applied on refs pointing to commits. Hence
* obtain the commit using the 'oid' available and discard all
@@ -3765,6 +3834,7 @@ void ref_filter_init(struct ref_filter *filter)
void ref_filter_clear(struct ref_filter *filter)
{
strvec_clear(&filter->exclude);
+ strvec_clear(&filter->forked);
oid_array_clear(&filter->points_at);
commit_list_free(filter->with_commit);
commit_list_free(filter->no_commit);
diff --git a/ref-filter.h b/ref-filter.h
index 120221b47f..9361296e2a 100644
--- a/ref-filter.h
+++ b/ref-filter.h
@@ -67,6 +67,7 @@ struct ref_filter {
const char **name_patterns;
const char *start_after;
struct strvec exclude;
+ struct strvec forked;
struct oid_array points_at;
struct commit_list *with_commit;
struct commit_list *no_commit;
@@ -110,6 +111,7 @@ struct ref_format {
#define REF_FILTER_INIT { \
.points_at = OID_ARRAY_INIT, \
.exclude = STRVEC_INIT, \
+ .forked = STRVEC_INIT, \
}
#define REF_FORMAT_INIT { \
.use_color = GIT_COLOR_UNKNOWN, \
@@ -172,6 +174,14 @@ void ref_sorting_release(struct ref_sorting *);
struct ref_sorting *ref_sorting_options(struct string_list *);
/* Function to parse --merged and --no-merged options */
int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset);
+/*
+ * Register a --forked <branch> pattern on the filter. The argument is
+ * either a ref, which is resolved to its full refname, or a shell-style
+ * glob. Branches are kept only when their configured upstream matches
+ * one of the registered patterns. Returns -1 if the argument is not a
+ * valid ref or pattern.
+ */
+int ref_filter_forked_add(struct ref_filter *filter, const char *arg);
/* Get the current HEAD's description */
char *get_head_description(void);
/* Set up translated strings in the output. */
diff --git a/t/t3200-branch.sh b/t/t3200-branch.sh
index e7829c2c4b..3104c555f6 100755
--- a/t/t3200-branch.sh
+++ b/t/t3200-branch.sh
@@ -1717,4 +1717,126 @@ test_expect_success 'errors if given a bad branch name' '
test_cmp expect actual
'
+test_expect_success '--forked: setup' '
+ test_create_repo forked-upstream &&
+ (
+ cd forked-upstream &&
+ test_commit base &&
+ git branch one base &&
+ git branch two base
+ ) &&
+
+ test_create_repo forked-other &&
+ (
+ cd forked-other &&
+ test_commit other-base &&
+ git branch foreign other-base
+ ) &&
+
+ git clone forked-upstream forked &&
+ (
+ cd forked &&
+ git remote add -f other ../forked-other &&
+ git remote set-head origin one &&
+ git branch local-base &&
+ git branch --track local-one origin/one &&
+ git branch --track local-two origin/two &&
+ git branch --track local-foreign other/foreign &&
+ git branch --track local-onbase local-base &&
+
+ git checkout local-one &&
+ test_commit --no-tag local-one-work local-one.t &&
+ git checkout local-foreign &&
+ test_commit --no-tag local-foreign-work local-foreign.t &&
+ git checkout --detach
+ )
+'
+
+test_expect_success '--forked <upstream-tracking-branch> filters by upstream' '
+ git -C forked branch --forked origin/one --format="%(refname:short)" >actual &&
+ echo local-one >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success '--forked <glob> filters by wildmatch' '
+ git -C forked branch --forked "origin/*" --format="%(refname:short)" >actual &&
+ cat >expect <<-\EOF &&
+ local-one
+ local-two
+ main
+ EOF
+ test_cmp expect actual
+'
+
+test_expect_success '--forked <local-branch> matches branches with local upstream' '
+ git -C forked branch --forked local-base --format="%(refname:short)" >actual &&
+ echo local-onbase >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success '--forked can be repeated to widen the filter' '
+ git -C forked branch --forked origin/one --forked other/foreign --format="%(refname:short)" >actual &&
+ cat >expect <<-\EOF &&
+ local-foreign
+ local-one
+ EOF
+ test_cmp expect actual
+'
+
+test_expect_success '--forked combines literal and glob arguments' '
+ git -C forked branch --forked local-base --forked "other/*" --format="%(refname:short)" >actual &&
+ cat >expect <<-\EOF &&
+ local-foreign
+ local-onbase
+ EOF
+ test_cmp expect actual
+'
+
+test_expect_success '--forked "*/*" covers every remote-tracking upstream' '
+ git -C forked branch --forked "*/*" --format="%(refname:short)" >actual &&
+ cat >expect <<-\EOF &&
+ local-foreign
+ local-one
+ local-two
+ main
+ EOF
+ test_cmp expect actual
+'
+
+test_expect_success '--forked composes with --no-merged' '
+ test_when_finished "git -C forked checkout --detach" &&
+ git -C forked checkout local-one &&
+ test_commit -C forked local-only &&
+ git -C forked branch --forked "origin/*" --no-merged origin/one \
+ --format="%(refname:short)" >actual &&
+ echo local-one >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success '--forked rejects unknown branch/pattern' '
+ test_must_fail git -C forked branch --forked nope 2>err &&
+ test_grep "not a valid branch or pattern" err
+'
+
+test_expect_success '--forked requires a value' '
+ test_must_fail git -C forked branch --forked 2>err &&
+ test_grep "requires a value" err
+'
+
+test_expect_success '--forked <remote> uses the branch <remote>/HEAD points at' '
+ git -C forked branch --forked origin --format="%(refname:short)" >actual &&
+ echo local-one >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success '--forked narrows a <pattern> argument' '
+ git -C forked branch --forked "origin/*" "local-*" \
+ --format="%(refname:short)" >actual &&
+ cat >expect <<-\EOF &&
+ local-one
+ local-two
+ EOF
+ test_cmp expect actual
+'
+
test_done
--
gitgitgadget
^ permalink raw reply related
* [PATCH v16 0/7] branch: delete-merged
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:25 UTC (permalink / raw)
To: git; +Cc: Kristoffer Haugsbakk, Johannes Sixt, Phillip Wood,
Harald Nordgren
In-Reply-To: <pull.2285.v15.git.git.1781542042.gitgitgadget@gmail.com>
Delete branches that have already been merged on upstream.
Changes in v16:
* Convert delete_merged_branches() to take an unsigned int flags argument
instead of separate quiet/dry_run booleans, matching delete_branches()
* Reuse the strbuf across the skip-config loop (strbuf_reset per iteration,
single strbuf_release after) instead of allocating and freeing it each
time
* Rewrite the --delete-merged tests as integration tests: branches that
land commits upstream, with deletion and the checked-out, upstream-gone,
and push-equals-upstream safety cases exercised together in one run and
output asserted via test_cmp
* Collapse the many per-aspect test repos into a single reused repo set up
by a setup_repo_for_delete_merged helper, and rename helpers off the old
pm_/prune naming
* Nest single-repo setup sequences in ( cd ... ) subshells instead of
prefixing every command with -C
Changes in v15:
* Renamed --prune-merged to --delete-merged throughout. Not necessarily
final, but something to advance the discussion.
* --delete-merged now silently skips not-yet-merged branches instead of
warning.
* Initialized the delete_branches() flag locals where declared. Only force
stays deferred.
* delete_branches()/check_branch_commit() doc and code cleanups: redundant
branch NULL checks dropped, ref_array candidates = { 0 }, a BUG() for the
unreachable non-branch ref, and reworked --delete-merged doc wording.
* Broadened the --forked tests (local commits for realism, remote add -f,
--forked coverage), renamed the misleading trunk fixture, and replaced
the misnamed detached branch with git checkout --detach.
Changes in v14:
* Fixed a git branch -d -r regression (broke t5404/t5505/t5514): the
remotes path set a local force but not the DELETE_BRANCH_FORCE bit that
check_branch_commit() reads, so it wrongly ran the merge check.
* Made flags the single source of truth in delete_branches() so the bit and
the derived locals can't disagree.
* Works locally, but GitHub CI has problems that are there for other
branches too, hopefully not related
(https://github.com/git/git/pull/2285).
Changes in v13:
* Reworked --forked into a real ref-filter applied in apply_ref_filter()
instead of a post-pass, so non-matching branches are never allocated.
* Match exact --forked patterns on full refnames (only globs use the
abbreviated upstream), and dropped the old helper machinery, forward
declaration, and string_list in favor of a strvec.
* Replaced the boolean parameters of
delete_branches()/check_branch_commit() with a single unsigned int flags.
* --prune-merged now collects candidates via filter_refs() rather than its
own branch walk.
* --prune-merged now takes its patterns as positional arguments (e.g. git
branch --prune-merged origin/main 'feature*') instead of repeating the
option.
Changes in v12:
* Reworked --forked from a standalone action into a --list-mode filter.
* Switched --forked and --prune-merged to repeatable OPT_STRING_LIST
options.
* Dropped the bare-remote-name resolution for --forked, the argument is now
a ref or a glob.
Changes in v11:
* The flags now take a branch, not a remote. --forked and --prune-merged
accept a literal upstream short name like origin/main or a wildmatch
pattern like origin/. The old --all-remotes flag is gone, since origin/
covers that case.
* The prune guard now compares @{push} against @{upstream}. A branch is
spared when these are equal. That is the trunk like case, such as local
main tracking and pushing to origin/main, where "fully merged to
upstream" cannot be told apart from "just pulled". Only branches that
push somewhere other than their upstream, typically fork based topics,
are candidates. The earlier /HEAD by name guard that the reviewer
rejected is gone.
* New --dry-run for --prune-merged.
Changes in v10:
* --forked / --prune-merged now take a branch glob instead of a remote name
— origin, origin/*, origin/release-- all work. This replaces the
remote-only form and subsumes the old --all-remotes flag, which has been
dropped.
* New --dry-run for --prune-merged.
Changes in v9:
* --force no longer has special meaning with --prune-merged; reachability
is always enforced. Use git branch -D to delete an unmerged branch.
Matches how git branch's other read/safe actions treat --force.
* Synopsis drops [-f]; "not fully merged" hint points at git branch -D.
* Dropped the --prune-merged --force tests.
Changes in v8:
* Delete only when the branch's work is actually reachable from its
upstream
* Skip branches whose upstream is gone (even with --force)
* Simplified the internal safety flag to live in one place
Changes in v7:
* --prune-merged now checks if a branch is merged into its own upstream
first. If the upstream is gone, it checks against the remote's default
branch instead. If neither exists, the branch is refused (use --force to
delete anyway).
Changes in v6:
* --prune-merged now measures merged-ness against the remote's default
branch instead of the candidate's upstream — so the decision no longer
depends on which branch happens to be checked out locally.
* delete_branches() / check_branch_commit() gained a per-candidate override
that lets a caller substitute a different "what counts as merged"
reference (or skip the check). branch -d callers pass NULL and keep their
existing semantics.
* prune_merged_branches() resolves each candidate's push-remote HEAD and
threads it through, so --prune-merged --all-remotes measures each
candidate against its own remote rather than a single global reference.
Changes in v5:
* Drop commit 'fetch: add --prune-merged'
Changes in v4:
* Resolve each remote's HEAD and collect the targets into a
protected_default_refs set in collect_forked_set.
* In prune_merged_branches, skip a candidate when its upstream is a
protected default ref and the local branch name matches the default
branch's leaf name (so a local main tracking origin/main is spared, but a
renamed trunk tracking origin/main is not).
* Also skip when the candidate's push ref points at a protected default
ref, so a topic branch configured to push to origin/main is never pruned.
* Tests: spare the local default branch; only protect by matching leaf name
(not by upstream alone); spare a branch whose push ref is the remote
default.
Changes in v3:
* s/remote-tracking refs/remote-tracking branches/g
Changes in v2:
* The whole feature moved out of git fetch and into git branch. git fetch
--prune-merged now just calls git branch --prune-merged after fetching.
* The fetch.pruneLocalBranches and remote..pruneLocalBranches config
options are gone, replaced by per-branch opt-out via branch..pruneMerged.
* New git branch --forked lists local branches whose upstream lives on the
given remote (read-only building block).
* New git branch --prune-merged deletes those branches, but only if their
tip is reachable from the upstream tracking ref; --force skips that
safety check.
* New git branch --all-remotes lets --forked/--prune-merged operate across
every configured remote at once.
* The currently checked-out branch in any worktree is always preserved.
* branch..pruneMerged=false lets you exempt a branch (e.g. a long-running
topic branch) even with --force; doesn't affect explicit git branch -d.
* delete_branches() got a warn_only mode so bulk deletion prints a one-line
warning per skipped branch instead of the noisy four-line hint that git
branch -d shows.
* New section in git-branch docs; git-fetch docs trimmed to just mention
--prune-merged.
* New tests in t3200-branch.sh for the new branch flags; t5510-fetch.sh
shrunk since most logic moved.
Harald Nordgren (7):
branch: add --forked filter for --list mode
branch: convert delete_branches() to a flags argument
branch: let delete_branches skip unmerged branches on bulk refusal
branch: prepare delete_branches for a bulk caller
branch: add --delete-merged <branch>
branch: add branch.<name>.deleteMerged opt-out
branch: add --dry-run for --delete-merged
Documentation/config/branch.adoc | 7 +
Documentation/git-branch.adoc | 43 ++++-
builtin/branch.c | 186 ++++++++++++++++++----
ref-filter.c | 70 +++++++++
ref-filter.h | 10 ++
t/t3200-branch.sh | 262 +++++++++++++++++++++++++++++++
6 files changed, 550 insertions(+), 28 deletions(-)
base-commit: 4621f8ce5e9b97aa2e8d0d9ffe9d25df2471074d
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2285%2FHaraldNordgren%2Ffetch-prune-local-branches-v16
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2285/HaraldNordgren/fetch-prune-local-branches-v16
Pull-Request: https://github.com/git/git/pull/2285
Range-diff vs v15:
1: da741b5ea7 ! 1: 1f6a758265 branch: add --forked filter for --list mode
@@ t/t3200-branch.sh: test_expect_success 'errors if given a bad branch name' '
+test_expect_success '--forked: setup' '
+ test_create_repo forked-upstream &&
-+ test_commit -C forked-upstream base &&
-+ git -C forked-upstream branch one base &&
-+ git -C forked-upstream branch two base &&
++ (
++ cd forked-upstream &&
++ test_commit base &&
++ git branch one base &&
++ git branch two base
++ ) &&
+
+ test_create_repo forked-other &&
-+ test_commit -C forked-other other-base &&
-+ git -C forked-other branch foreign other-base &&
++ (
++ cd forked-other &&
++ test_commit other-base &&
++ git branch foreign other-base
++ ) &&
+
+ git clone forked-upstream forked &&
-+ git -C forked remote add -f other ../forked-other &&
-+ git -C forked remote set-head origin one &&
-+ git -C forked branch local-base &&
-+ git -C forked branch --track local-one origin/one &&
-+ git -C forked branch --track local-two origin/two &&
-+ git -C forked branch --track local-foreign other/foreign &&
-+ git -C forked branch --track local-onbase local-base &&
++ (
++ cd forked &&
++ git remote add -f other ../forked-other &&
++ git remote set-head origin one &&
++ git branch local-base &&
++ git branch --track local-one origin/one &&
++ git branch --track local-two origin/two &&
++ git branch --track local-foreign other/foreign &&
++ git branch --track local-onbase local-base &&
+
-+ git -C forked checkout local-one &&
-+ test_commit -C forked --no-tag local-one-work local-one.t &&
-+ git -C forked checkout local-foreign &&
-+ test_commit -C forked --no-tag local-foreign-work local-foreign.t &&
-+ git -C forked checkout --detach
++ git checkout local-one &&
++ test_commit --no-tag local-one-work local-one.t &&
++ git checkout local-foreign &&
++ test_commit --no-tag local-foreign-work local-foreign.t &&
++ git checkout --detach
++ )
+'
+
+test_expect_success '--forked <upstream-tracking-branch> filters by upstream' '
2: 91c35f10cc = 2: 4f8af602ba branch: convert delete_branches() to a flags argument
3: e101dd2886 = 3: efc891c255 branch: let delete_branches skip unmerged branches on bulk refusal
4: 6c3534901a = 4: b1ecd38fe3 branch: prepare delete_branches for a bulk caller
5: 5899013b8f ! 5: 998fb6a68c branch: add --delete-merged <branch>
@@ builtin/branch.c: static int parse_opt_forked(const struct option *opt, const ch
}
+static int delete_merged_branches(int argc, const char **argv,
-+ int quiet)
++ unsigned int flags)
+{
+ struct ref_store *refs = get_main_ref_store(the_repository);
+ struct ref_filter filter = REF_FILTER_INIT;
@@ builtin/branch.c: static int parse_opt_forked(const struct option *opt, const ch
+ FILTER_REFS_BRANCHES,
+ DELETE_BRANCH_SKIP_UNMERGED |
+ DELETE_BRANCH_NO_HEAD_FALLBACK |
-+ (quiet ? DELETE_BRANCH_QUIET : 0));
++ flags);
+
+ strvec_clear(&deletable);
+ ref_array_clear(&candidates);
@@ builtin/branch.c: int cmd_branch(int argc,
(quiet ? DELETE_BRANCH_QUIET : 0));
goto out;
+ } else if (delete_merged) {
-+ ret = delete_merged_branches(argc, argv, quiet);
++ ret = delete_merged_branches(argc, argv,
++ quiet ? DELETE_BRANCH_QUIET : 0);
+ goto out;
} else if (show_current) {
print_current_branch_name();
@@ t/t3200-branch.sh: test_expect_success '--forked narrows a <pattern> argument' '
'
+test_expect_success '--delete-merged: setup' '
-+ test_create_repo pm-upstream &&
-+ test_commit -C pm-upstream base &&
-+ git -C pm-upstream checkout -b next &&
-+ test_commit -C pm-upstream one-commit &&
-+ test_commit -C pm-upstream two-commit &&
-+ git -C pm-upstream branch one HEAD~ &&
-+ git -C pm-upstream branch two HEAD &&
-+ git -C pm-upstream branch wip main &&
-+ git -C pm-upstream checkout main &&
-+ test_create_repo pm-fork
++ git init -b main upstream &&
++ (
++ cd upstream &&
++ test_commit base &&
++ git checkout -b next &&
++ test_commit next-work &&
++ git checkout main
++ ) &&
++ git init -b main other &&
++ test_commit -C other other-base &&
++ git init -b main fork
+'
+
-+test_expect_success '--delete-merged deletes branches integrated into upstream' '
-+ test_when_finished "rm -rf pm-merged" &&
-+ git clone pm-upstream pm-merged &&
-+ git -C pm-merged remote add fork ../pm-fork &&
-+ test_config -C pm-merged remote.pushDefault fork &&
-+ test_config -C pm-merged push.default current &&
-+ git -C pm-merged branch one one-commit &&
-+ git -C pm-merged branch --set-upstream-to=origin/next one &&
-+ git -C pm-merged branch two two-commit &&
-+ git -C pm-merged branch --set-upstream-to=origin/next two &&
-+
-+ git -C pm-merged branch --delete-merged "origin/*" &&
-+
-+ test_must_fail git -C pm-merged rev-parse --verify refs/heads/one &&
-+ test_must_fail git -C pm-merged rev-parse --verify refs/heads/two
-+'
-+
-+test_expect_success '--delete-merged accepts a literal upstream' '
-+ test_when_finished "rm -rf pm-literal" &&
-+ git clone pm-upstream pm-literal &&
-+ git -C pm-literal remote add fork ../pm-fork &&
-+ test_config -C pm-literal remote.pushDefault fork &&
-+ test_config -C pm-literal push.default current &&
-+ git -C pm-literal branch one one-commit &&
-+ git -C pm-literal branch --set-upstream-to=origin/next one &&
-+
-+ git -C pm-literal branch --delete-merged origin/next &&
-+
-+ test_must_fail git -C pm-literal rev-parse --verify refs/heads/one
-+'
-+
-+test_expect_success '--delete-merged unions multiple <branch> arguments' '
-+ test_when_finished "rm -rf pm-union" &&
-+ git clone pm-upstream pm-union &&
-+ git -C pm-union remote add fork ../pm-fork &&
-+ test_config -C pm-union remote.pushDefault fork &&
-+ test_config -C pm-union push.default current &&
-+ git -C pm-union branch one one-commit &&
-+ git -C pm-union branch --set-upstream-to=origin/next one &&
-+ git -C pm-union branch two base &&
-+ git -C pm-union branch --set-upstream-to=origin/main two &&
-+ git -C pm-union checkout --detach &&
-+
-+ git -C pm-union branch --delete-merged origin/next origin/main &&
-+
-+ test_must_fail git -C pm-union rev-parse --verify refs/heads/one &&
-+ test_must_fail git -C pm-union rev-parse --verify refs/heads/two
-+'
-+
-+test_expect_success '--delete-merged accepts a local upstream' '
-+ test_when_finished "rm -rf pm-local" &&
-+ git clone pm-upstream pm-local &&
-+ git -C pm-local remote add fork ../pm-fork &&
-+ test_config -C pm-local remote.pushDefault fork &&
-+ test_config -C pm-local push.default current &&
-+ git -C pm-local checkout -b mainline &&
-+ git -C pm-local branch one one-commit &&
-+ git -C pm-local branch --set-upstream-to=mainline one &&
-+ git -C pm-local merge --ff-only one-commit &&
-+
-+ git -C pm-local branch --delete-merged mainline &&
-+
-+ test_must_fail git -C pm-local rev-parse --verify refs/heads/one
-+'
-+
-+test_expect_success '--delete-merged silently skips un-integrated commits' '
-+ test_when_finished "rm -rf pm-unmerged" &&
-+ git clone pm-upstream pm-unmerged &&
-+ git -C pm-unmerged remote add fork ../pm-fork &&
-+ test_config -C pm-unmerged remote.pushDefault fork &&
-+ test_config -C pm-unmerged push.default current &&
-+ git -C pm-unmerged checkout -b wip origin/wip &&
-+ git -C pm-unmerged branch --set-upstream-to=origin/next wip &&
-+ test_commit -C pm-unmerged local-only &&
-+ git -C pm-unmerged checkout - &&
-+
-+ git -C pm-unmerged branch --delete-merged "origin/*" 2>err &&
-+ test_grep ! "not fully merged" err &&
-+ git -C pm-unmerged rev-parse --verify refs/heads/wip
-+'
-+
-+test_expect_success '--delete-merged is silent about not-merged-to-HEAD' '
-+ test_when_finished "rm -rf pm-nohead" &&
-+ git clone pm-upstream pm-nohead &&
-+ git -C pm-nohead remote add fork ../pm-fork &&
-+ test_config -C pm-nohead remote.pushDefault fork &&
-+ test_config -C pm-nohead push.default current &&
-+ git -C pm-nohead branch topic one-commit &&
-+ git -C pm-nohead branch --set-upstream-to=origin/next topic &&
-+
-+ git -C pm-nohead branch --delete-merged "origin/*" 2>err &&
-+
-+ test_grep ! "not yet merged to HEAD" err &&
-+ test_must_fail git -C pm-nohead rev-parse --verify refs/heads/topic
-+'
-+
-+test_expect_success '--delete-merged skips branches whose upstream is gone' '
-+ test_when_finished "rm -rf pm-upstream-gone" &&
-+ git clone pm-upstream pm-upstream-gone &&
-+ git -C pm-upstream-gone remote add fork ../pm-fork &&
-+ test_config -C pm-upstream-gone remote.pushDefault fork &&
-+ test_config -C pm-upstream-gone push.default current &&
-+ git -C pm-upstream-gone branch one one-commit &&
-+ git -C pm-upstream-gone branch --set-upstream-to=origin/next one &&
-+
-+ git -C pm-upstream-gone update-ref -d refs/remotes/origin/next &&
-+ git -C pm-upstream-gone branch --delete-merged "origin/*" &&
-+
-+ git -C pm-upstream-gone rev-parse --verify refs/heads/one
-+'
-+
-+test_expect_success '--delete-merged never deletes the checked-out branch' '
-+ test_when_finished "rm -rf pm-head" &&
-+ git clone pm-upstream pm-head &&
-+ git -C pm-head remote add fork ../pm-fork &&
-+ test_config -C pm-head remote.pushDefault fork &&
-+ test_config -C pm-head push.default current &&
-+ git -C pm-head checkout -b one one-commit &&
-+ git -C pm-head branch --set-upstream-to=origin/next one &&
-+
-+ git -C pm-head branch --delete-merged "origin/*" &&
-+
-+ git -C pm-head rev-parse --verify refs/heads/one
-+'
-+
-+test_expect_success '--delete-merged spares branches that push back to their upstream' '
-+ test_when_finished "rm -rf pm-push-eq" &&
-+ git clone pm-upstream pm-push-eq &&
-+ git -C pm-push-eq checkout --detach &&
-+
-+ git -C pm-push-eq branch --delete-merged "origin/*" &&
-+
-+ git -C pm-push-eq rev-parse --verify refs/heads/main
-+'
-+
-+test_expect_success '--delete-merged spares a per-branch pushRemote==upstream remote' '
-+ test_when_finished "rm -rf pm-push-branch" &&
-+ git clone pm-upstream pm-push-branch &&
-+ git -C pm-push-branch remote add fork ../pm-fork &&
-+ test_config -C pm-push-branch remote.pushDefault fork &&
-+ test_config -C pm-push-branch push.default current &&
-+ test_config -C pm-push-branch branch.main.pushRemote origin &&
-+ git -C pm-push-branch checkout --detach &&
++setup_repo_for_delete_merged () {
++ rm -rf repo &&
++ git clone upstream repo &&
++ (
++ cd repo &&
++ git remote add fork ../fork &&
++ git remote add other ../other &&
++ git config remote.pushDefault fork &&
++ git config push.default current &&
++ git fetch other
++ )
++}
+
-+ git -C pm-push-branch branch --delete-merged "origin/*" &&
++merged_branch () {
++ (
++ cd repo &&
++ git checkout -b "$1" "$2" &&
++ git commit --allow-empty -m "$1 work" &&
++ git push origin "$1:next" &&
++ git fetch origin &&
++ git branch --set-upstream-to="$2" "$1"
++ )
++}
+
-+ git -C pm-push-branch rev-parse --verify refs/heads/main
++test_expect_success '--delete-merged deletes merged branches and spares the rest' '
++ test_when_finished "rm -rf repo" &&
++ setup_repo_for_delete_merged &&
++ merged_branch merged origin/next &&
++ (
++ cd repo &&
++ git checkout -b unmerged origin/next &&
++ git commit --allow-empty -m "unmerged work" &&
++ git branch --set-upstream-to=origin/next unmerged &&
++ git checkout -b tracks-other other/main &&
++ git branch --set-upstream-to=other/main tracks-other &&
++ git checkout --detach
++ ) &&
++ sha=$(git -C repo rev-parse --short merged) &&
++
++ git -C repo branch --delete-merged origin/next >actual 2>&1 &&
++
++ echo "Deleted branch merged (was $sha)." >expect &&
++ test_cmp expect actual &&
++ git -C repo for-each-ref --format="%(refname:short)" refs/heads/ >actual &&
++ cat >expect <<-\EOF &&
++ main
++ tracks-other
++ unmerged
++ EOF
++ test_cmp expect actual
+'
+
-+test_expect_success '--delete-merged prunes when @{push} differs from @{upstream}' '
-+ test_when_finished "rm -rf pm-push-diff" &&
-+ git clone pm-upstream pm-push-diff &&
-+ git -C pm-push-diff remote add fork ../pm-fork &&
-+ test_config -C pm-push-diff remote.pushDefault fork &&
-+ test_config -C pm-push-diff push.default current &&
-+ git -C pm-push-diff branch topic one-commit &&
-+ git -C pm-push-diff branch --set-upstream-to=origin/next topic &&
-+ git -C pm-push-diff checkout --detach &&
-+
-+ git -C pm-push-diff branch --delete-merged "origin/*" &&
-+
-+ test_must_fail git -C pm-push-diff rev-parse --verify refs/heads/topic
++test_expect_success '--delete-merged deletes merged branches and spares protected ones' '
++ test_when_finished "rm -rf repo" &&
++ setup_repo_for_delete_merged &&
++ merged_branch on-next origin/next &&
++ merged_branch checked-out origin/next &&
++ merged_branch upstream-gone origin/next &&
++ (
++ cd repo &&
++ git checkout -b mainline main &&
++ git checkout -b on-local mainline &&
++ git branch --set-upstream-to=mainline on-local &&
++ git update-ref refs/remotes/origin/topic refs/remotes/origin/next &&
++ git branch --set-upstream-to=origin/topic upstream-gone &&
++ git update-ref -d refs/remotes/origin/topic &&
++ git branch --set-upstream-to=origin/main main &&
++ git config branch.main.pushRemote origin &&
++ git checkout -b tracks-other other/main &&
++ git branch --set-upstream-to=other/main tracks-other &&
++ git checkout checked-out
++ ) &&
++
++ git -C repo branch --delete-merged origin/next mainline &&
++
++ git -C repo for-each-ref --format="%(refname:short)" refs/heads/ >actual &&
++ cat >expect <<-\EOF &&
++ checked-out
++ main
++ mainline
++ tracks-other
++ upstream-gone
++ EOF
++ test_cmp expect actual
+'
+
+test_expect_success '--delete-merged requires at least one <branch>' '
+ test_must_fail git -C forked branch --delete-merged 2>err &&
+ test_grep "requires at least one <branch>" err
+'
-+
-+test_expect_success '--delete-merged takes positional <branch> arguments' '
-+ test_when_finished "rm -rf pm-positional" &&
-+ git clone pm-upstream pm-positional &&
-+ git -C pm-positional remote add fork ../pm-fork &&
-+ test_config -C pm-positional remote.pushDefault fork &&
-+ test_config -C pm-positional push.default current &&
-+ git -C pm-positional branch one one-commit &&
-+ git -C pm-positional branch --set-upstream-to=origin/next one &&
-+ git -C pm-positional branch two base &&
-+ git -C pm-positional branch --set-upstream-to=origin/main two &&
-+ git -C pm-positional checkout --detach &&
-+
-+ git -C pm-positional branch --delete-merged origin/next origin/main &&
-+
-+ test_must_fail git -C pm-positional rev-parse --verify refs/heads/one &&
-+ test_must_fail git -C pm-positional rev-parse --verify refs/heads/two
-+'
+
test_done
6: 72aaca0666 ! 6: a27d2724a2 branch: add branch.<name>.deleteMerged opt-out
@@ Documentation/git-branch.adoc: A branch is not deleted when:
A branch whose work has not yet been merged into its upstream is
## builtin/branch.c ##
+@@ builtin/branch.c: static int delete_merged_branches(int argc, const char **argv,
+ struct ref_filter filter = REF_FILTER_INIT;
+ struct ref_array candidates = { 0 };
+ struct strvec deletable = STRVEC_INIT;
++ struct strbuf key = STRBUF_INIT;
++ bool quiet = flags & DELETE_BRANCH_QUIET;
+ int i, ret = 0;
+
+ if (!argc)
@@ builtin/branch.c: static int delete_merged_branches(int argc, const char **argv,
const char *short_name;
struct branch *branch;
const char *upstream, *push;
-+ struct strbuf key = STRBUF_INIT;
+ int opt_out;
if (!skip_prefix(full_name, "refs/heads/", &short_name))
@@ builtin/branch.c: static int delete_merged_branches(int argc, const char **argv,
if (!push || !strcmp(push, upstream))
continue;
++ strbuf_reset(&key);
+ strbuf_addf(&key, "branch.%s.deletemerged", short_name);
+ if (!repo_config_get_bool(the_repository, key.buf, &opt_out) &&
+ !opt_out) {
@@ builtin/branch.c: static int delete_merged_branches(int argc, const char **argv,
+ fprintf(stderr,
+ _("Skipping '%s' (branch.%s.deleteMerged is false)\n"),
+ short_name, short_name);
-+ strbuf_release(&key);
+ continue;
+ }
-+ strbuf_release(&key);
+
strvec_push(&deletable, short_name);
}
+@@ builtin/branch.c: static int delete_merged_branches(int argc, const char **argv,
+ DELETE_BRANCH_NO_HEAD_FALLBACK |
+ flags);
+
++ strbuf_release(&key);
+ strvec_clear(&deletable);
+ ref_array_clear(&candidates);
+ ref_filter_clear(&filter);
## t/t3200-branch.sh ##
-@@ t/t3200-branch.sh: test_expect_success '--delete-merged takes positional <branch> arguments' '
- test_must_fail git -C pm-positional rev-parse --verify refs/heads/two
+@@ t/t3200-branch.sh: test_expect_success '--delete-merged requires at least one <branch>' '
+ test_grep "requires at least one <branch>" err
'
+test_expect_success '--delete-merged honours branch.<name>.deleteMerged=false' '
-+ test_when_finished "rm -rf pm-optout" &&
-+ git clone pm-upstream pm-optout &&
-+ git -C pm-optout remote add fork ../pm-fork &&
-+ test_config -C pm-optout remote.pushDefault fork &&
-+ test_config -C pm-optout push.default current &&
-+ git -C pm-optout branch one one-commit &&
-+ git -C pm-optout branch --set-upstream-to=origin/next one &&
-+ git -C pm-optout branch two two-commit &&
-+ git -C pm-optout branch --set-upstream-to=origin/next two &&
-+ test_config -C pm-optout branch.one.deleteMerged false &&
++ test_when_finished "rm -rf repo" &&
++ setup_repo_for_delete_merged &&
++ merged_branch deleted origin/next &&
++ merged_branch kept origin/next &&
++ git -C repo config branch.kept.deleteMerged false &&
++ git -C repo checkout --detach &&
+
-+ git -C pm-optout branch --delete-merged "origin/*" 2>err &&
++ git -C repo branch --delete-merged origin/next 2>err &&
+
-+ git -C pm-optout rev-parse --verify refs/heads/one &&
-+ test_must_fail git -C pm-optout rev-parse --verify refs/heads/two &&
-+ test_grep "Skipping .one." err
++ test_grep "Skipping .kept." err &&
++ test_must_fail git -C repo rev-parse --verify refs/heads/deleted &&
++ git -C repo rev-parse --verify refs/heads/kept
+'
+
-+test_expect_success 'branch -d still deletes a deleteMerged=false branch' '
-+ test_when_finished "rm -rf pm-optout-d" &&
-+ git clone pm-upstream pm-optout-d &&
-+ git -C pm-optout-d branch one one-commit &&
-+ git -C pm-optout-d branch --set-upstream-to=origin/next one &&
-+ test_config -C pm-optout-d branch.one.deleteMerged false &&
++test_expect_success "branch -d still deletes a deleteMerged=false branch" '
++ test_when_finished "rm -rf repo" &&
++ setup_repo_for_delete_merged &&
++ merged_branch kept origin/next &&
++ git -C repo config branch.kept.deleteMerged false &&
++ git -C repo checkout --detach &&
+
-+ git -C pm-optout-d branch -d one &&
-+ test_must_fail git -C pm-optout-d rev-parse --verify refs/heads/one
++ git -C repo branch -d kept &&
++ test_must_fail git -C repo rev-parse --verify refs/heads/kept
+'
+
test_done
7: 7b2b01b988 ! 7: 6d5c52353e branch: add --dry-run for --delete-merged
@@ Documentation/git-branch.adoc: A branch whose work has not yet been merged into
`--verbose`::
## builtin/branch.c ##
-@@ builtin/branch.c: static int parse_opt_forked(const struct option *opt, const char *arg, int unset
- }
-
- static int delete_merged_branches(int argc, const char **argv,
-- int quiet)
-+ int quiet, int dry_run)
- {
- struct ref_store *refs = get_main_ref_store(the_repository);
- struct ref_filter filter = REF_FILTER_INIT;
-@@ builtin/branch.c: static int delete_merged_branches(int argc, const char **argv,
- FILTER_REFS_BRANCHES,
- DELETE_BRANCH_SKIP_UNMERGED |
- DELETE_BRANCH_NO_HEAD_FALLBACK |
-- (quiet ? DELETE_BRANCH_QUIET : 0));
-+ (quiet ? DELETE_BRANCH_QUIET : 0) |
-+ (dry_run ? DELETE_BRANCH_DRY_RUN : 0));
-
- strvec_clear(&deletable);
- ref_array_clear(&candidates);
@@ builtin/branch.c: int cmd_branch(int argc,
int delete = 0, rename = 0, copy = 0, list = 0,
unset_upstream = 0, show_current = 0, edit_description = 0;
@@ builtin/branch.c: int cmd_branch(int argc,
if (!submodule_propagate_branches)
die(_("branch with --recurse-submodules can only be used if submodule.propagateBranches is enabled"));
@@ builtin/branch.c: int cmd_branch(int argc,
- (quiet ? DELETE_BRANCH_QUIET : 0));
goto out;
} else if (delete_merged) {
-- ret = delete_merged_branches(argc, argv, quiet);
-+ ret = delete_merged_branches(argc, argv, quiet, dry_run);
+ ret = delete_merged_branches(argc, argv,
+- quiet ? DELETE_BRANCH_QUIET : 0);
++ (quiet ? DELETE_BRANCH_QUIET : 0) |
++ (dry_run ? DELETE_BRANCH_DRY_RUN : 0));
goto out;
} else if (show_current) {
print_current_branch_name();
## t/t3200-branch.sh ##
-@@ t/t3200-branch.sh: test_expect_success 'branch -d still deletes a deleteMerged=false branch' '
- test_must_fail git -C pm-optout-d rev-parse --verify refs/heads/one
+@@ t/t3200-branch.sh: test_expect_success '--delete-merged deletes merged branches and spares the rest
+ ) &&
+ sha=$(git -C repo rev-parse --short merged) &&
+
+- git -C repo branch --delete-merged origin/next >actual 2>&1 &&
++ git -C repo branch --dry-run --delete-merged origin/next >actual 2>&1 &&
++ echo "Would delete branch merged (was $sha)." >expect &&
++ test_cmp expect actual &&
++ git -C repo rev-parse --verify refs/heads/merged &&
+
++ git -C repo branch --delete-merged origin/next >actual 2>&1 &&
+ echo "Deleted branch merged (was $sha)." >expect &&
+ test_cmp expect actual &&
+ git -C repo for-each-ref --format="%(refname:short)" refs/heads/ >actual &&
+@@ t/t3200-branch.sh: test_expect_success "branch -d still deletes a deleteMerged=false branch" '
+ test_must_fail git -C repo rev-parse --verify refs/heads/kept
'
-+test_expect_success '--delete-merged --dry-run lists but does not delete' '
-+ test_when_finished "rm -rf pm-dry" &&
-+ git clone pm-upstream pm-dry &&
-+ git -C pm-dry remote add fork ../pm-fork &&
-+ test_config -C pm-dry remote.pushDefault fork &&
-+ test_config -C pm-dry push.default current &&
-+ git -C pm-dry branch one one-commit &&
-+ git -C pm-dry branch --set-upstream-to=origin/next one &&
-+ git -C pm-dry branch two two-commit &&
-+ git -C pm-dry branch --set-upstream-to=origin/next two &&
-+
-+ git -C pm-dry branch --dry-run --delete-merged "origin/*" >actual &&
-+ test_grep "Would delete branch one " actual &&
-+ test_grep "Would delete branch two " actual &&
-+
-+ git -C pm-dry rev-parse --verify refs/heads/one &&
-+ git -C pm-dry rev-parse --verify refs/heads/two
-+'
-+
-+test_expect_success '--delete-merged --dry-run only lists branches the live run would delete' '
-+ test_when_finished "rm -rf pm-dry-mixed" &&
-+ git clone pm-upstream pm-dry-mixed &&
-+ git -C pm-dry-mixed remote add fork ../pm-fork &&
-+ test_config -C pm-dry-mixed remote.pushDefault fork &&
-+ test_config -C pm-dry-mixed push.default current &&
-+ git -C pm-dry-mixed checkout -b wip origin/next &&
-+ git -C pm-dry-mixed branch --set-upstream-to=origin/next wip &&
-+ test_commit -C pm-dry-mixed local-only &&
-+ git -C pm-dry-mixed checkout - &&
-+ git -C pm-dry-mixed branch merged one-commit &&
-+ git -C pm-dry-mixed branch --set-upstream-to=origin/next merged &&
-+
-+ git -C pm-dry-mixed branch --dry-run --delete-merged "origin/*" >out &&
-+ test_grep "Would delete branch merged" out &&
-+ test_grep ! "Would delete branch wip" out &&
-+ git -C pm-dry-mixed rev-parse --verify refs/heads/wip &&
-+ git -C pm-dry-mixed rev-parse --verify refs/heads/merged
-+'
-+
+test_expect_success '--dry-run without --delete-merged is rejected' '
+ test_must_fail git -C forked branch --dry-run 2>err &&
+ test_grep "requires --delete-merged" err
--
gitgitgadget
^ permalink raw reply
* [PATCH v3 4/4] history: re-edit a squash with every message
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:17 UTC (permalink / raw)
To: git; +Cc: Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2337.v3.git.git.1781810226.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
By default "git history squash" reuses the oldest commit's message.
When --reedit-message is given it only reopened that one message, so the
messages of the folded-in commits were lost.
Gather the messages of every commit in the range, oldest first, and use
them as the editor template when re-editing, mirroring how "git rebase
-i" presents a squash. The combined message is built before the
descendant walk so it is not disturbed by the flags that walk leaves on
the commits.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
Documentation/git-history.adoc | 5 +--
builtin/history.c | 61 +++++++++++++++++++++++++++++++++-
t/t3454-history-squash.sh | 37 +++++++++++++++++++++
3 files changed, 100 insertions(+), 3 deletions(-)
diff --git a/Documentation/git-history.adoc b/Documentation/git-history.adoc
index d3a5ad28a3..dd3544832d 100644
--- a/Documentation/git-history.adoc
+++ b/Documentation/git-history.adoc
@@ -111,8 +111,9 @@ history squash @~3..` folds the three most recent commits into one, and
`git history squash @~5..@~2` squashes an interior range while leaving
the two newest commits in place.
+
-The oldest commit's message and authorship are preserved by default,
-unless you specify `--reedit-message`. A merge commit inside the range is
+The oldest commit's message and authorship are preserved by default. With
+`--reedit-message`, an editor opens pre-filled with the messages of all the
+folded commits so you can combine them. A merge commit inside the range is
folded like any other, but the range must have a single base, so a range
that reaches more than one entry point (for example a side branch that
forked before the range and was later merged into it) is rejected.
diff --git a/builtin/history.c b/builtin/history.c
index 9d9416870f..eb12a5d7e8 100644
--- a/builtin/history.c
+++ b/builtin/history.c
@@ -1047,6 +1047,56 @@ out:
return ret;
}
+static int build_squash_message(struct repository *repo,
+ struct commit *base,
+ struct commit *tip,
+ struct strbuf *out)
+{
+ struct rev_info revs;
+ struct commit *commit;
+ struct strvec args = STRVEC_INIT;
+ int n = 0, ret;
+
+ repo_init_revisions(repo, &revs, NULL);
+ strvec_push(&args, "ignored");
+ strvec_push(&args, "--reverse");
+ strvec_push(&args, "--topo-order");
+ strvec_pushf(&args, "%s..%s", oid_to_hex(&base->object.oid),
+ oid_to_hex(&tip->object.oid));
+ setup_revisions_from_strvec(&args, &revs, NULL);
+
+ if (prepare_revision_walk(&revs) < 0) {
+ ret = error(_("error preparing revisions"));
+ goto out;
+ }
+
+ while ((commit = get_revision(&revs))) {
+ const char *message, *body;
+ struct strbuf one = STRBUF_INIT;
+
+ message = repo_logmsg_reencode(repo, commit, NULL, NULL);
+ find_commit_subject(message, &body);
+ strbuf_addstr(&one, body);
+ strbuf_trim_trailing_newline(&one);
+
+ if (n++)
+ strbuf_addch(out, '\n');
+ strbuf_addbuf(out, &one);
+ strbuf_addch(out, '\n');
+
+ strbuf_release(&one);
+ repo_unuse_commit_buffer(repo, commit, message);
+ }
+
+ ret = 0;
+
+out:
+ reset_revision_walk();
+ release_revisions(&revs);
+ strvec_clear(&args);
+ return ret;
+}
+
static int cmd_history_squash(int argc,
const char **argv,
const char *prefix,
@@ -1071,6 +1121,7 @@ static int cmd_history_squash(int argc,
OPT_END(),
};
struct strbuf reflog_msg = STRBUF_INIT;
+ struct strbuf message = STRBUF_INIT;
struct commit *base, *oldest, *tip, *rewritten;
const struct object_id *base_tree_oid, *tip_tree_oid;
struct commit_list *parents = NULL;
@@ -1091,6 +1142,12 @@ static int cmd_history_squash(int argc,
if (ret < 0)
goto out;
+ if (flags & COMMIT_TREE_EDIT_MESSAGE) {
+ ret = build_squash_message(repo, base, tip, &message);
+ if (ret < 0)
+ goto out;
+ }
+
ret = setup_revwalk(repo, action, tip, &revs);
if (ret < 0)
goto out;
@@ -1099,7 +1156,8 @@ static int cmd_history_squash(int argc,
tip_tree_oid = &repo_get_commit_tree(repo, tip)->object.oid;
commit_list_append(base, &parents);
- ret = commit_tree_ext(repo, "squash", oldest, NULL, parents,
+ ret = commit_tree_ext(repo, "squash", oldest,
+ message.len ? message.buf : NULL, parents,
base_tree_oid, tip_tree_oid, &rewritten, flags);
if (ret < 0) {
ret = error(_("failed writing squashed commit"));
@@ -1120,6 +1178,7 @@ static int cmd_history_squash(int argc,
out:
strbuf_release(&reflog_msg);
+ strbuf_release(&message);
commit_list_free(parents);
release_revisions(&revs);
return ret;
diff --git a/t/t3454-history-squash.sh b/t/t3454-history-squash.sh
index 6c6a75bf00..1edd148295 100755
--- a/t/t3454-history-squash.sh
+++ b/t/t3454-history-squash.sh
@@ -135,6 +135,43 @@ test_expect_success 'preserves authorship of the oldest commit' '
test_cmp expect actual
'
+test_expect_success '--reedit-message offers every folded-in message' '
+ git reset --hard start &&
+ echo b >file &&
+ git add file &&
+ git commit -m "re-one subject" -m "re-one body line" &&
+ test_commit re-two file c &&
+ test_commit re-three file d &&
+
+ write_script editor <<-\EOF &&
+ cp "$1" buffer &&
+ echo combined >"$1"
+ EOF
+ test_set_editor "$(pwd)/editor" &&
+ git history squash --reedit-message start.. &&
+
+ grep "re-one subject" buffer &&
+ grep "re-one body line" buffer &&
+ grep re-two buffer &&
+ grep re-three buffer &&
+ git log --format="%s" -1 >actual &&
+ echo combined >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success '--reedit-message aborts on an empty message' '
+ git reset --hard three &&
+ head_before=$(git rev-parse HEAD) &&
+
+ write_script editor <<-\EOF &&
+ >"$1"
+ EOF
+ test_set_editor "$(pwd)/editor" &&
+ test_must_fail git history squash --reedit-message start.. &&
+
+ test_cmp_rev "$head_before" HEAD
+'
+
test_expect_success '--dry-run predicts the rewrite without performing it' '
git reset --hard three &&
head_before=$(git rev-parse HEAD) &&
--
gitgitgadget
^ permalink raw reply related
* [PATCH v3 3/4] history: add squash subcommand to fold a range
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:17 UTC (permalink / raw)
To: git; +Cc: Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2337.v3.git.git.1781810226.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
Folding a series of commits into one required either an interactive
rebase where each commit after the first was hand-edited to "fixup", or
a "git reset --soft" to the merge base followed by "git commit --amend".
Add "git history squash <revision-range>" to do this directly. It folds
every commit in the range into the oldest one, keeping that commit's
message and authorship and taking the tree of the newest commit, so the
range collapses into a single commit. Commits above the range are
replayed on top of the result.
The range is given as <base>..<tip>, so "git history squash @~3.."
folds the three most recent commits and "git history squash @~5..@~2"
squashes an interior range. A merge inside the range is folded like any
other commit, but the range must have a single base, so a range with
more than one entry point is rejected.
Inspired-by: Sergey Chernov <serega.morph@gmail.com>
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
Documentation/git-history.adoc | 20 ++++
builtin/history.c | 154 ++++++++++++++++++++++++
t/meson.build | 1 +
t/t3454-history-squash.sh | 213 +++++++++++++++++++++++++++++++++
4 files changed, 388 insertions(+)
create mode 100755 t/t3454-history-squash.sh
diff --git a/Documentation/git-history.adoc b/Documentation/git-history.adoc
index 2ba8121795..d3a5ad28a3 100644
--- a/Documentation/git-history.adoc
+++ b/Documentation/git-history.adoc
@@ -11,6 +11,7 @@ SYNOPSIS
git history fixup <commit> [--dry-run] [--update-refs=(branches|head)] [--reedit-message] [--empty=(drop|keep|abort)]
git history reword <commit> [--dry-run] [--update-refs=(branches|head)]
git history split <commit> [--dry-run] [--update-refs=(branches|head)] [--] [<pathspec>...]
+git history squash <revision-range> [--dry-run] [--update-refs=(branches|head)] [--reedit-message]
DESCRIPTION
-----------
@@ -97,6 +98,25 @@ linkgit:gitglossary[7].
It is invalid to select either all or no hunks, as that would lead to
one of the commits becoming empty.
+`squash <revision-range>`::
+ Fold all commits in _<revision-range>_ into the oldest commit of that
+ range. The resulting commit keeps the oldest commit's message and
+ authorship and takes the tree of the range's newest commit, so the
+ whole range collapses into a single commit. Commits above the range
+ are replayed on top of the result.
++
+The range is given in the usual `<base>..<tip>` form, where _<base>_ is
+the commit just below the oldest commit to squash. For example, `git
+history squash @~3..` folds the three most recent commits into one, and
+`git history squash @~5..@~2` squashes an interior range while leaving
+the two newest commits in place.
++
+The oldest commit's message and authorship are preserved by default,
+unless you specify `--reedit-message`. A merge commit inside the range is
+folded like any other, but the range must have a single base, so a range
+that reaches more than one entry point (for example a side branch that
+forked before the range and was later merged into it) is rejected.
+
OPTIONS
-------
diff --git a/builtin/history.c b/builtin/history.c
index 305bde3102..9d9416870f 100644
--- a/builtin/history.c
+++ b/builtin/history.c
@@ -30,6 +30,8 @@
N_("git history reword <commit> [--dry-run] [--update-refs=(branches|head)]")
#define GIT_HISTORY_SPLIT_USAGE \
N_("git history split <commit> [--dry-run] [--update-refs=(branches|head)] [--] [<pathspec>...]")
+#define GIT_HISTORY_SQUASH_USAGE \
+ N_("git history squash <revision-range> [--dry-run] [--update-refs=(branches|head)] [--reedit-message]")
static void change_data_free(void *util, const char *str UNUSED)
{
@@ -973,6 +975,156 @@ out:
return ret;
}
+/*
+ * Resolve a "<base>..<tip>" revision range into the base commit just outside
+ * the range (which becomes the parent of the squashed commit), the oldest
+ * commit contained in the range (whose message the squash reuses), and the
+ * range tip (whose tree becomes the result). A merge inside the range is fine,
+ * but the range must have a single base and must not reach a root commit.
+ */
+static int resolve_squash_range(struct repository *repo,
+ const char *range,
+ struct commit **base_out,
+ struct commit **oldest_out,
+ struct commit **tip_out)
+{
+ struct rev_info revs;
+ struct commit *commit, *base = NULL, *oldest = NULL, *tip = NULL;
+ struct strvec args = STRVEC_INIT;
+ int ret;
+
+ repo_init_revisions(repo, &revs, NULL);
+ strvec_push(&args, "ignored");
+ strvec_push(&args, "--reverse");
+ strvec_push(&args, "--topo-order");
+ strvec_push(&args, "--boundary");
+ strvec_push(&args, range);
+ setup_revisions_from_strvec(&args, &revs, NULL);
+ if (args.nr != 1) {
+ ret = error(_("'%s' does not name a revision range"), range);
+ goto out;
+ }
+
+ if (prepare_revision_walk(&revs) < 0) {
+ ret = error(_("error preparing revisions"));
+ goto out;
+ }
+
+ while ((commit = get_revision(&revs))) {
+ if (commit->object.flags & BOUNDARY) {
+ if (base) {
+ ret = error(_("range '%s' has more than one base; "
+ "cannot squash"), range);
+ goto out;
+ }
+ base = commit;
+ continue;
+ }
+ if (!oldest)
+ oldest = commit;
+ tip = commit;
+ }
+
+ if (!oldest) {
+ ret = error(_("the range '%s' is empty"), range);
+ goto out;
+ }
+
+ if (!base) {
+ ret = error(_("cannot squash the root commit"));
+ goto out;
+ }
+
+ *base_out = base;
+ *oldest_out = oldest;
+ *tip_out = tip;
+ ret = 0;
+
+out:
+ reset_revision_walk();
+ release_revisions(&revs);
+ strvec_clear(&args);
+ return ret;
+}
+
+static int cmd_history_squash(int argc,
+ const char **argv,
+ const char *prefix,
+ struct repository *repo)
+{
+ const char * const usage[] = {
+ GIT_HISTORY_SQUASH_USAGE,
+ NULL,
+ };
+ enum ref_action action = REF_ACTION_DEFAULT;
+ enum commit_tree_flags flags = 0;
+ int dry_run = 0;
+ struct option options[] = {
+ OPT_CALLBACK_F(0, "update-refs", &action, "(branches|head)",
+ N_("control which refs should be updated"),
+ PARSE_OPT_NONEG, parse_ref_action),
+ OPT_BOOL('n', "dry-run", &dry_run,
+ N_("perform a dry-run without updating any refs")),
+ OPT_BIT(0, "reedit-message", &flags,
+ N_("open an editor to modify the commit message"),
+ COMMIT_TREE_EDIT_MESSAGE),
+ OPT_END(),
+ };
+ struct strbuf reflog_msg = STRBUF_INIT;
+ struct commit *base, *oldest, *tip, *rewritten;
+ const struct object_id *base_tree_oid, *tip_tree_oid;
+ struct commit_list *parents = NULL;
+ struct rev_info revs = { 0 };
+ int ret;
+
+ argc = parse_options(argc, argv, prefix, options, usage, 0);
+ if (argc != 1) {
+ ret = error(_("command expects a single revision range"));
+ goto out;
+ }
+ repo_config(repo, git_default_config, NULL);
+
+ if (action == REF_ACTION_DEFAULT)
+ action = REF_ACTION_BRANCHES;
+
+ ret = resolve_squash_range(repo, argv[0], &base, &oldest, &tip);
+ if (ret < 0)
+ goto out;
+
+ ret = setup_revwalk(repo, action, tip, &revs);
+ if (ret < 0)
+ goto out;
+
+ base_tree_oid = &repo_get_commit_tree(repo, base)->object.oid;
+ tip_tree_oid = &repo_get_commit_tree(repo, tip)->object.oid;
+ commit_list_append(base, &parents);
+
+ ret = commit_tree_ext(repo, "squash", oldest, NULL, parents,
+ base_tree_oid, tip_tree_oid, &rewritten, flags);
+ if (ret < 0) {
+ ret = error(_("failed writing squashed commit"));
+ goto out;
+ }
+
+ strbuf_addf(&reflog_msg, "squash: updating %s", argv[0]);
+
+ ret = handle_reference_updates(&revs, action, tip, rewritten,
+ reflog_msg.buf, dry_run,
+ REPLAY_EMPTY_COMMIT_ABORT);
+ if (ret < 0) {
+ ret = error(_("failed replaying descendants"));
+ goto out;
+ }
+
+ ret = 0;
+
+out:
+ strbuf_release(&reflog_msg);
+ commit_list_free(parents);
+ release_revisions(&revs);
+ return ret;
+}
+
int cmd_history(int argc,
const char **argv,
const char *prefix,
@@ -982,6 +1134,7 @@ int cmd_history(int argc,
GIT_HISTORY_FIXUP_USAGE,
GIT_HISTORY_REWORD_USAGE,
GIT_HISTORY_SPLIT_USAGE,
+ GIT_HISTORY_SQUASH_USAGE,
NULL,
};
parse_opt_subcommand_fn *fn = NULL;
@@ -989,6 +1142,7 @@ int cmd_history(int argc,
OPT_SUBCOMMAND("fixup", &fn, cmd_history_fixup),
OPT_SUBCOMMAND("reword", &fn, cmd_history_reword),
OPT_SUBCOMMAND("split", &fn, cmd_history_split),
+ OPT_SUBCOMMAND("squash", &fn, cmd_history_squash),
OPT_END(),
};
diff --git a/t/meson.build b/t/meson.build
index 3219264fe7..d7ae5a46ef 100644
--- a/t/meson.build
+++ b/t/meson.build
@@ -399,6 +399,7 @@ integration_tests = [
't3451-history-reword.sh',
't3452-history-split.sh',
't3453-history-fixup.sh',
+ 't3454-history-squash.sh',
't3500-cherry.sh',
't3501-revert-cherry-pick.sh',
't3502-cherry-pick-merge.sh',
diff --git a/t/t3454-history-squash.sh b/t/t3454-history-squash.sh
new file mode 100755
index 0000000000..6c6a75bf00
--- /dev/null
+++ b/t/t3454-history-squash.sh
@@ -0,0 +1,213 @@
+#!/bin/sh
+
+test_description='tests for git-history squash subcommand'
+
+. ./test-lib.sh
+
+test_expect_success 'setup linear history touching two files' '
+ test_commit base file a &&
+ git tag start &&
+ test_commit one other x &&
+ test_commit two file c &&
+ test_commit three file d
+'
+
+test_expect_success 'errors on missing range argument' '
+ test_must_fail git history squash 2>err &&
+ test_grep "command expects a single revision range" err
+'
+
+test_expect_success 'errors on too many arguments' '
+ test_must_fail git history squash start.. HEAD 2>err &&
+ test_grep "command expects a single revision range" err
+'
+
+test_expect_success 'errors on an empty range' '
+ test_must_fail git history squash HEAD..HEAD 2>err &&
+ test_grep "the range .* is empty" err
+'
+
+test_expect_success 'errors when the range includes the root commit' '
+ test_must_fail git history squash HEAD 2>err &&
+ test_grep "cannot squash the root commit" err
+'
+
+test_expect_success 'squashes a range into a single commit without changing the tree' '
+ git reset --hard three &&
+ tip_tree=$(git rev-parse HEAD^{tree}) &&
+
+ git history squash start.. &&
+
+ git rev-list --count start..HEAD >count &&
+ echo 1 >expect &&
+ test_cmp expect count &&
+ test_cmp_rev start HEAD^ &&
+ test "$tip_tree" = "$(git rev-parse HEAD^{tree})" &&
+ git log --format="%s" -1 >subject &&
+ echo one >expect &&
+ test_cmp expect subject &&
+ git reflog >reflog &&
+ test_grep "squash: updating" reflog
+'
+
+test_expect_success 'squashes an interior range and replays descendants verbatim' '
+ git reset --hard three &&
+ final_tree=$(git rev-parse HEAD^{tree}) &&
+
+ git history squash start..@~1 &&
+
+ git log --format="%s" start..HEAD >actual &&
+ cat >expect <<-\EOF &&
+ three
+ one
+ EOF
+ test_cmp expect actual &&
+
+ test_cmp_rev start HEAD~2 &&
+ test "$final_tree" = "$(git rev-parse HEAD^{tree})"
+'
+
+test_expect_success 'squashes when the base is the root commit' '
+ git reset --hard three &&
+ root=$(git rev-list --max-parents=0 HEAD) &&
+ tip_tree=$(git rev-parse HEAD^{tree}) &&
+
+ git history squash "$root.." &&
+
+ git rev-list --count "$root..HEAD" >count &&
+ echo 1 >expect &&
+ test_cmp expect count &&
+ test_cmp_rev "$root" HEAD^ &&
+ test "$tip_tree" = "$(git rev-parse HEAD^{tree})"
+'
+
+test_expect_success 'squashing a single-commit range replays the rest' '
+ git reset --hard three &&
+ tip_tree=$(git rev-parse HEAD^{tree}) &&
+
+ git history squash start..@~2 &&
+
+ git log --format="%s" start..HEAD >actual &&
+ cat >expect <<-\EOF &&
+ three
+ two
+ one
+ EOF
+ test_cmp expect actual &&
+ test "$tip_tree" = "$(git rev-parse HEAD^{tree})"
+'
+
+test_expect_success 'reuses the message of a fixup! commit in the range' '
+ git reset --hard start &&
+ test_commit reg1 file b &&
+ git commit --allow-empty -m "fixup! reg1" &&
+ test_commit reg2 file c &&
+
+ git history squash start.. &&
+
+ git log --format="%s" -1 >actual &&
+ echo reg1 >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success 'keeps the oldest message even if it is a fixup!' '
+ git reset --hard start &&
+ test_commit --no-tag "fixup! something" file b &&
+ test_commit tail file c &&
+
+ git history squash start.. &&
+
+ git log --format="%s" -1 >actual &&
+ echo "fixup! something" >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success 'preserves authorship of the oldest commit' '
+ git reset --hard start &&
+ GIT_AUTHOR_NAME=Squasher GIT_AUTHOR_EMAIL=squash@example.com \
+ test_commit oldest file b &&
+ test_commit newest file c &&
+
+ git history squash start.. &&
+
+ git log -1 --format="%an <%ae>" >actual &&
+ echo "Squasher <squash@example.com>" >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success '--dry-run predicts the rewrite without performing it' '
+ git reset --hard three &&
+ head_before=$(git rev-parse HEAD) &&
+
+ git history squash --dry-run start.. >out &&
+ grep "^update refs/heads/" out >update &&
+ predicted=$(awk "{print \$3}" update) &&
+ test_cmp_rev "$head_before" HEAD &&
+
+ git history squash start.. &&
+ test "$predicted" = "$(git rev-parse HEAD)"
+'
+
+test_expect_success '--update-refs=head only moves HEAD' '
+ git reset --hard three &&
+ git branch -f other HEAD &&
+ other_before=$(git rev-parse other) &&
+
+ git history squash --update-refs=head start.. &&
+
+ git rev-list --count start..HEAD >count &&
+ echo 1 >expect &&
+ test_cmp expect count &&
+ test_cmp_rev "$other_before" other
+'
+
+test_expect_success '--update-refs=branches moves a branch pointing into the range' '
+ git reset --hard three &&
+ git branch -f mid HEAD~2 &&
+ mid_before=$(git rev-parse mid) &&
+
+ git history squash start..@~1 &&
+
+ test_cmp_rev "$mid_before" mid &&
+ test_commit_message mid -m one
+'
+
+test_expect_success 'squashes a range whose internal merge has a single base' '
+ git reset --hard start &&
+ test_commit before-side file b &&
+ git checkout -b inner-side &&
+ test_commit on-inner-side inner x &&
+ git checkout - &&
+ test_commit after-side file c &&
+ git merge --no-ff -m merge inner-side &&
+ test_commit after-merge file d &&
+ tip_tree=$(git rev-parse HEAD^{tree}) &&
+
+ git history squash start.. &&
+
+ git rev-list --count start..HEAD >count &&
+ echo 1 >expect &&
+ test_cmp expect count &&
+ git log --format="%s" -1 >subject &&
+ echo before-side >expect &&
+ test_cmp expect subject &&
+ test "$tip_tree" = "$(git rev-parse HEAD^{tree})" &&
+ test_path_is_file inner
+'
+
+test_expect_success 'refuses to squash a range with more than one base' '
+ git reset --hard start &&
+ head_before=$(git rev-parse HEAD) &&
+ git checkout -b forked-before &&
+ test_commit forked-side fside x &&
+ git checkout - &&
+ test_commit forked-main file b &&
+ git merge --no-ff -m merge forked-before &&
+ merged=$(git rev-parse HEAD) &&
+
+ test_must_fail git history squash forked-main.. 2>err &&
+ test_grep "more than one base" err &&
+ test_cmp_rev "$merged" HEAD
+'
+
+test_done
--
gitgitgadget
^ permalink raw reply related
* [PATCH v3 2/4] history: give commit_tree_ext a message template
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:17 UTC (permalink / raw)
To: git; +Cc: Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2337.v3.git.git.1781810226.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
commit_tree_ext() reuses the message of the commit it is handed. A
caller that folds several commits together wants to seed the message
from more than that single commit, so add an optional message_template
parameter. When NULL, the behavior is unchanged.
Pass NULL from the existing fixup and split callers.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
builtin/history.c | 16 ++++++++++------
1 file changed, 10 insertions(+), 6 deletions(-)
diff --git a/builtin/history.c b/builtin/history.c
index f95f26e684..305bde3102 100644
--- a/builtin/history.c
+++ b/builtin/history.c
@@ -101,6 +101,7 @@ enum commit_tree_flags {
static int commit_tree_ext(struct repository *repo,
const char *action,
struct commit *commit_with_message,
+ const char *message_template,
const struct commit_list *parents,
const struct object_id *old_tree,
const struct object_id *new_tree,
@@ -130,13 +131,16 @@ static int commit_tree_ext(struct repository *repo,
original_author = xmemdupz(ptr, len);
find_commit_subject(original_message, &original_body);
+ if (!message_template)
+ message_template = original_body;
+
if (flags & COMMIT_TREE_EDIT_MESSAGE) {
ret = fill_commit_message(repo, old_tree, new_tree,
- original_body, action, &commit_message);
+ message_template, action, &commit_message);
if (ret < 0)
goto out;
} else {
- strbuf_addstr(&commit_message, original_body);
+ strbuf_addstr(&commit_message, message_template);
}
original_extra_headers = read_commit_extra_headers(commit_with_message,
@@ -189,7 +193,7 @@ static int commit_tree_with_edited_message(struct repository *repo,
if (first_parent_tree_oid(repo, original, &parent_tree_oid) < 0)
return -1;
- return commit_tree_ext(repo, action, original, original->parents,
+ return commit_tree_ext(repo, action, original, NULL, original->parents,
&parent_tree_oid, tree_oid, out, COMMIT_TREE_EDIT_MESSAGE);
}
@@ -644,7 +648,7 @@ static int cmd_history_fixup(int argc,
goto out;
if (!skip_commit) {
- ret = commit_tree_ext(repo, "fixup", original, original->parents,
+ ret = commit_tree_ext(repo, "fixup", original, NULL, original->parents,
&original_tree->object.oid, &merge_result.tree->object.oid,
&rewritten, flags);
if (ret < 0) {
@@ -855,7 +859,7 @@ static int split_commit(struct repository *repo,
* The first commit is constructed from the split-out tree. The base
* that shall be diffed against is the parent of the original commit.
*/
- ret = commit_tree_ext(repo, "split-out", original, original->parents, &parent_tree_oid,
+ ret = commit_tree_ext(repo, "split-out", original, NULL, original->parents, &parent_tree_oid,
&split_tree->object.oid, &first_commit, COMMIT_TREE_EDIT_MESSAGE);
if (ret < 0) {
ret = error(_("failed writing first commit"));
@@ -872,7 +876,7 @@ static int split_commit(struct repository *repo,
old_tree_oid = &repo_get_commit_tree(repo, first_commit)->object.oid;
new_tree_oid = &repo_get_commit_tree(repo, original)->object.oid;
- ret = commit_tree_ext(repo, "split-out", original, parents, old_tree_oid,
+ ret = commit_tree_ext(repo, "split-out", original, NULL, parents, old_tree_oid,
new_tree_oid, &second_commit, COMMIT_TREE_EDIT_MESSAGE);
if (ret < 0) {
ret = error(_("failed writing second commit"));
--
gitgitgadget
^ permalink raw reply related
* [PATCH v3 1/4] history: extract helper for a commit's parent tree
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:17 UTC (permalink / raw)
To: git; +Cc: Harald Nordgren, Harald Nordgren
In-Reply-To: <pull.2337.v3.git.git.1781810226.gitgitgadget@gmail.com>
From: Harald Nordgren <haraldnordgren@gmail.com>
Three places resolve the tree of a commit's first parent, falling back
to the empty tree for a root commit, each repeating the same parse and
oidcpy dance. Extract a first_parent_tree_oid() helper and route the
existing callers through it.
No change in behavior.
Signed-off-by: Harald Nordgren <haraldnordgren@gmail.com>
---
builtin/history.c | 58 +++++++++++++++++++++--------------------------
1 file changed, 26 insertions(+), 32 deletions(-)
diff --git a/builtin/history.c b/builtin/history.c
index 091465a59e..f95f26e684 100644
--- a/builtin/history.c
+++ b/builtin/history.c
@@ -157,6 +157,25 @@ out:
return ret;
}
+static int first_parent_tree_oid(struct repository *repo,
+ struct commit *commit,
+ struct object_id *out)
+{
+ struct commit *parent = commit->parents ? commit->parents->item : NULL;
+
+ if (!parent) {
+ oidcpy(out, repo->hash_algo->empty_tree);
+ return 0;
+ }
+
+ if (repo_parse_commit(repo, parent))
+ return error(_("unable to parse parent commit %s"),
+ oid_to_hex(&parent->object.oid));
+
+ oidcpy(out, &repo_get_commit_tree(repo, parent)->object.oid);
+ return 0;
+}
+
static int commit_tree_with_edited_message(struct repository *repo,
const char *action,
struct commit *original,
@@ -164,21 +183,11 @@ static int commit_tree_with_edited_message(struct repository *repo,
{
struct object_id parent_tree_oid;
const struct object_id *tree_oid;
- struct commit *parent;
tree_oid = &repo_get_commit_tree(repo, original)->object.oid;
- parent = original->parents ? original->parents->item : NULL;
- if (parent) {
- if (repo_parse_commit(repo, parent)) {
- return error(_("unable to parse parent commit %s"),
- oid_to_hex(&parent->object.oid));
- }
-
- parent_tree_oid = repo_get_commit_tree(repo, parent)->object.oid;
- } else {
- oidcpy(&parent_tree_oid, repo->hash_algo->empty_tree);
- }
+ if (first_parent_tree_oid(repo, original, &parent_tree_oid) < 0)
+ return -1;
return commit_tree_ext(repo, action, original, original->parents,
&parent_tree_oid, tree_oid, out, COMMIT_TREE_EDIT_MESSAGE);
@@ -444,18 +453,10 @@ static int commit_became_empty(struct repository *repo,
struct commit *original,
struct tree *result)
{
- struct commit *parent = original->parents ? original->parents->item : NULL;
struct object_id parent_tree_oid;
- if (parent) {
- if (repo_parse_commit(repo, parent))
- return error(_("unable to parse parent of %s"),
- oid_to_hex(&original->object.oid));
-
- parent_tree_oid = repo_get_commit_tree(repo, parent)->object.oid;
- } else {
- oidcpy(&parent_tree_oid, repo->hash_algo->empty_tree);
- }
+ if (first_parent_tree_oid(repo, original, &parent_tree_oid) < 0)
+ return -1;
return oideq(&result->object.oid, &parent_tree_oid);
}
@@ -799,16 +800,9 @@ static int split_commit(struct repository *repo,
struct tree *split_tree;
int ret;
- if (original->parents) {
- if (repo_parse_commit(repo, original->parents->item)) {
- ret = error(_("unable to parse parent commit %s"),
- oid_to_hex(&original->parents->item->object.oid));
- goto out;
- }
-
- parent_tree_oid = *get_commit_tree_oid(original->parents->item);
- } else {
- oidcpy(&parent_tree_oid, repo->hash_algo->empty_tree);
+ if (first_parent_tree_oid(repo, original, &parent_tree_oid) < 0) {
+ ret = -1;
+ goto out;
}
original_commit_tree_oid = get_commit_tree_oid(original);
--
gitgitgadget
^ permalink raw reply related
* [PATCH v3 0/4] history: add squash subcommand to fold a range
From: Harald Nordgren via GitGitGadget @ 2026-06-18 19:17 UTC (permalink / raw)
To: git; +Cc: Harald Nordgren
In-Reply-To: <pull.2337.v2.git.git.1781512625.gitgitgadget@gmail.com>
Adds git history squash <revision-range> to fold a range of commits into its
oldest one, reusing that commit's message and replaying any descendants on
top.
Changes in v3:
* Moved the feature out of git rebase and into a new git history squash
<revision-range> subcommand, per the list discussion. git rebase --squash
is dropped.
* Takes an arbitrary range (git history squash @~3.., git history squash
@~5..@~2), folding it into the oldest commit and replaying any
descendants on top.
* Implemented as a single tree operation rather than picking each commit,
so there are no repeated conflict stops (addresses Phillip's efficiency
point).
* A merge inside the range is folded fine, only a range with more than one
base is rejected.
* --reedit-message seeds the editor with every folded-in message, not just
the oldest.
Harald Nordgren (4):
history: extract helper for a commit's parent tree
history: give commit_tree_ext a message template
history: add squash subcommand to fold a range
history: re-edit a squash with every message
Documentation/git-history.adoc | 21 +++
builtin/history.c | 287 ++++++++++++++++++++++++++++-----
t/meson.build | 1 +
t/t3454-history-squash.sh | 250 ++++++++++++++++++++++++++++
4 files changed, 521 insertions(+), 38 deletions(-)
create mode 100755 t/t3454-history-squash.sh
base-commit: 95e20213faefeb95df29277c58ac1980ab68f701
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-git-2337%2FHaraldNordgren%2Frebase-fixup-fold-v3
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-git-2337/HaraldNordgren/rebase-fixup-fold-v3
Pull-Request: https://github.com/git/git/pull/2337
Range-diff vs v2:
1: c55b9cd6f7 < -: ---------- t3415: remove prepare-commit-msg hook after use
2: 22d4276ff5 < -: ---------- rebase: add --squash to fold a range
-: ---------- > 1: 1e31474ef6 history: extract helper for a commit's parent tree
-: ---------- > 2: 498da64046 history: give commit_tree_ext a message template
-: ---------- > 3: 66b2f49fb4 history: add squash subcommand to fold a range
-: ---------- > 4: 43e4270614 history: re-edit a squash with every message
--
gitgitgadget
^ permalink raw reply
page: next (older) | prev (newer) | latest
- recent:[subjects (threaded)|topics (new)|topics (active)]
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox