3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
6 # Copyright (C)2017,2018 Ian Jackson
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::GDR;
23 use Debian::Dgit::ExitStatus;
27 use Debian::Dgit qw(:DEFAULT :playground);
34 use Getopt::Long qw(:config posix_default gnu_compat bundling);
36 use File::FnMatch qw(:fnmatch);
39 our ($usage_message) = <<'END';
41 git-debrebase [<options>] [--|-i <git rebase options...>]
42 git-debrebase [<options>] status
43 git-debrebase [<options>] prepush [--prose=...]
44 git-debrebase [<options>] quick|conclude
45 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
46 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
48 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
51 our ($opt_force, $opt_noop_ok, @opt_anchors);
52 our ($opt_defaultcmd_interactive);
54 our $us = qw(git-debrebase);
60 print STDERR "$us: bad usage: $m\n";
66 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
67 GetOptions @_ or badusage $m;
71 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
75 my ($k, $optional) = @_;
77 my @cmd = qw(git config -z);
78 push @cmd, qw(--get-all) if wantarray;
80 my $out = cmdoutput_errok @cmd;
82 fail "missing required git config $k" unless $optional;
85 my @l = split /\0/, $out;
86 return wantarray ? @l : $l[0];
93 my $dd = new Data::Dumper [ $v ];
94 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
100 my $data = (git_cat_file $objid, 'commit');
101 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
105 sub D_UPS () { 0x02; } # upstream files
106 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
107 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
108 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
109 sub D_DEB_OTH () { 0x20; } # debian/changelog
110 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
112 our $playprefix = 'debrebase';
117 our @dgit = qw(dgit);
119 sub in_workarea ($) {
122 my $r = eval { $sub->(); };
123 { local $@; changedir $maindir; }
127 sub fresh_workarea () {
128 $workarea = fresh_playground "$playprefix/work";
129 in_workarea sub { playtree_setup };
132 our $snags_forced = 0;
133 our $snags_tripped = 0;
134 our $snags_summarised = 0;
135 our @deferred_updates;
136 our @deferred_update_messages;
138 sub all_snags_summarised () {
139 $snags_forced + $snags_tripped == $snags_summarised;
141 sub run_deferred_updates ($) {
144 confess 'dangerous internal error' unless all_snags_summarised();
146 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
147 debugcmd '>|', @upd_cmd;
148 open U, "|-", @upd_cmd or die $!;
149 foreach (@deferred_updates) {
150 printdebug ">= ", $_, "\n";
151 print U $_, "\n" or die $!;
154 close U or failedcmd @upd_cmd;
156 print $_, "\n" foreach @deferred_update_messages;
158 @deferred_updates = ();
159 @deferred_update_messages = ();
162 sub get_differs ($$) {
164 # This resembles quiltify_trees_differ, in dgit, a bit.
165 # But we don't care about modes, or dpkg-source-unrepresentable
166 # changes, and we don't need the plethora of different modes.
167 # Conversely we need to distinguish different kinds of changes to
168 # debian/ and debian/patches/.
173 my ($opts, $limits, $fn) = @_;
174 my @cmd = (@git, qw(diff-tree -z --no-renames));
176 push @cmd, "$_:" foreach $x, $y;
177 push @cmd, '--', @$limits;
178 my $diffs = cmdoutput @cmd;
179 foreach (split /\0/, $diffs) { $fn->(); }
182 $rundiff->([qw(--name-only)], [], sub {
183 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
186 if ($differs & DS_DEB) {
188 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
190 m{^debian/patches/} ? D_PAT_OTH :
191 $_ eq 'debian/changelog' ? D_DEB_CLOG :
194 die "mysterious debian changes $x..$y"
195 unless $differs & (D_PAT_OTH|DS_DEB);
198 if ($differs & D_PAT_OTH) {
200 $differs &= ~D_PAT_OTH;
202 $differs |= D_PAT_OTH;
203 no warnings qw(exiting); last;
205 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
206 no warnings qw(exiting);
207 if (!defined $mode) {
210 die unless s{^debian/patches/}{};
212 if ($mode eq 'A' && !m/\.series$/s) {
214 } elsif ($mode eq 'M' && $_ eq 'series') {
215 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
216 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
217 chomp $x_s; $x_s .= "\n";
218 $ok = $x_s eq substr($y_s, 0, length $x_s);
223 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
225 die "mysterious debian/patches changes $x..$y"
226 unless $differs & (D_PAT_ADD|D_PAT_OTH);
229 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
234 sub commit_pr_info ($) {
236 return Data::Dumper->dump([$r], [qw(commit)]);
239 sub calculate_committer_authline () {
240 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
241 'DUMMY COMMIT (git-debrebase)', "HEAD:";
242 my ($h,$m) = get_commit $c;
243 $h =~ m/^committer .*$/m or confess "($h) ?";
247 sub rm_subdir_cached ($) {
249 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
252 sub read_tree_subdir ($$) {
253 my ($subdir, $new_tree_object) = @_;
254 rm_subdir_cached $subdir;
255 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
258 sub read_tree_debian ($) {
260 read_tree_subdir 'debian', "$treeish:debian";
261 rm_subdir_cached 'debian/patches';
264 sub read_tree_upstream ($;$) {
265 my ($treeish, $keep_patches) = @_;
266 my $save = cmdoutput @git, qw(write-tree --prefix=debian/);
267 runcmd @git, qw(read-tree), $treeish;
268 read_tree_subdir 'debian', $save;
269 rm_subdir_cached 'debian/patches' unless $keep_patches;
272 sub make_commit ($$) {
273 my ($parents, $message_paras) = @_;
274 my $tree = cmdoutput @git, qw(write-tree);
275 my @cmd = (@git, qw(commit-tree), $tree);
276 push @cmd, qw(-p), $_ foreach @$parents;
277 push @cmd, qw(-m), $_ foreach @$message_paras;
278 return cmdoutput @cmd;
281 our @snag_force_opts;
283 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
284 if (grep { $_ eq $tag } @snag_force_opts) {
286 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
289 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
293 # Important: all mainline code must call snags_maybe_bail after
294 # any point where snag might be called, but before making changes
295 # (eg before any call to run_deferred_updates). snags_maybe_bail
296 # may be called more than once if necessary (but this is not ideal
297 # because then the messages about number of snags may be confusing).
298 sub snags_maybe_bail () {
299 return if all_snags_summarised();
302 "%s: snags: %d overriden by individual -f options\n",
305 if ($snags_tripped) {
308 "%s: snags: %d overriden by global --force\n",
312 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
316 $snags_summarised = $snags_forced + $snags_tripped;
318 sub snags_maybe_bail_early () {
319 # useful to bail out early without doing a lot of work;
320 # not a substitute for snags_maybe_bail.
321 snags_maybe_bail() if $snags_tripped && !$opt_force;
324 return $snags_forced || $snags_tripped;
327 sub gbp_pq_export ($$$) {
328 my ($bname, $base, $tip) = @_;
329 # must be run in a workarea. $bname and patch-queue/$bname
330 # ought not to exist. Leaves you on patch-queue/$bname with
331 # the patches staged but not committed.
332 runcmd @git, qw(checkout -q -b), $bname, $base;
333 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
334 my @gbp_cmd = (qw(gbp pq export));
335 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
337 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
340 runcmd @git, qw(add -f debian/patches);
344 # xxx allow merge separately from laundering
346 # xxx docs highlight forbidden things
347 # xxx docs list allowable things ?
348 # xxx docs explicitly forbid some rebase
350 # xxx provide a way for the user to help
351 # xxx (eg, provide wreckage provide way to continue)
354 # use git-format-patch?
355 # our own patch identification algorithm?
356 # this is an alternative strategy
358 sub merge_series ($$;@) {
359 my ($newbase, $base_q, @input_qs) = @_;
360 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
361 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
362 # ^ specifies several patch series (currently we only support exactly 2)
363 # return value is a commit which is the result of
364 # merging the two versions of the same topic branch
365 # $input_q[0] and $input_q[1]
366 # with respect to the old version
370 # Creates, in *_q, a key MR for its private use
372 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
373 $base_q->{MR}{S} = 'base';
376 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
377 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
378 # $prereq{<patch filename>} exists or not (even later)
382 local $workarea = fresh_playground "$playprefix/merge";
383 my $seriesfile = "debian/patches/series";
386 foreach my $q ($base_q, reverse @input_qs) {
388 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
389 if (open S, $seriesfile) {
391 while (my $patch = <S>) {
392 chomp $patch or die $!;
393 foreach my $earlier (@earlier) {
394 $prereq{$patch}{$earlier}{$s}++ and die;
396 push @earlier, $patch;
397 stat "debian/patches/$patch" or die "$patch ?";
399 S->error and die "$seriesfile $!";
402 die "$seriesfile $!" unless $!==ENOENT;
404 read_tree_upstream $newbase, 1;
405 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
406 "Convert $s to patch queue for merging",
407 "[git-debrebase merge-innards patch-queue import:".
410 runcmd @git, qw(rm -q --cached), $seriesfile;
411 $pec = make_commit [ $pec ], [
412 "Drop series file from $s to avoid merge trouble",
413 "[git-debrebase merge-innards patch-queue prep:".
416 runcmd @git, qw(reset -q --hard), $pec;
417 $q->{MR}{PEC} = $pec;
419 # now, because of reverse, we are on $input_q->{MR}{OQC}
420 runcmd @git, qw(checkout -q -b merge);
421 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
422 debugcmd '+', @mergecmd;
424 if (system @mergecmd) {
428 # We need to construct a new series file
429 # Firstly, resolve prereq
430 foreach my $f (keys %prereq) {
431 if (!stat_exists "debian/patches/$f") {
432 # git merge deleted it; that's how we tell it's not wanted
436 foreach my $g (keys %{ $prereq{$f} }) {
437 my $gfp = $prereq{$f}{$g};
440 !!$gfp->{0} == !!$gfp->{1}
444 delete $prereq{$f}{$g};
450 return scalar keys %{ $prereq{$f} };
453 my $nodate = time + 1;
455 # $authordate{<patch filename>};
456 my $authordate = sub {
458 $authordate{$f} //= do {
459 open PF, "<", "debian/patches/$f" or die "$f $!";
461 return $nodate if m/^$/;
462 last if s{^Date: }{};
465 return cmdoutput qw(date +%s -d), $_;
469 open NS, '>', $seriesfile or die $!;
471 while (keys %prereq) {
473 foreach my $try (sort keys %prereq) {
476 $unsat->($try) <=> $unsat->($best) or
477 $authordate->($try) <=> $authordate->($best) or
483 print NS "$best\n" or die $!;
484 delete $prereq{$best};
485 foreach my $gp (values %prereq) {
490 runcmd @git, qw(add), $seriesfile;
491 runcmd @git, qw(commit --quiet -m), 'Merged series';
493 runcmd qw(gbp pq import);
495 # OK now we are on patch-queue/merge, and we need to rebase
496 # onto the intended parent and drop the patches from each one
498 my $build = $newbase;
499 my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
500 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
501 my $commit = git_cat_file $c, 'commit';
502 read_tree_upstream $c;
503 my $tree = cmdoutput @git, qw(write-tree);
504 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
505 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
506 open C, ">", "../mcommit" or die $!;
507 print C $commit or die $!;
509 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
512 runcmd @git, qw(update-ref refs/heads/result), $result;
514 printdebug "merge_series returns $result\n";
518 # classify returns an info hash like this
520 # Hdr => # commit headers, including 1 final newline
521 # Msg => # commit message (so one newline is dropped)
523 # Type => (see below)
525 # Ix => $index # ie 0, 1, 2, ...
527 # Differs => return value from get_differs
529 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
531 # NewMsg => # commit message, but with any [dgit import ...] edited
532 # # to say "[was: ...]"
542 # has additional entres in classification result
543 # Overwritten = [ subset of Parents ]
544 # Contributor = $the_remaining_Parent
546 # DgitImportUnpatched
547 # has additional entry in classification result
548 # OrigParents = [ subset of Parents ]
551 # has additional entry in classification result
552 # OrigParents = [ subset of Parents ] # singleton list
559 # has additional entry in classification result
562 sub parsecommit ($;$) {
563 my ($objid, $p_ref) = @_;
564 # => hash with CommitId Hdr Msg Tree Parents
565 # Parents entries have only Ix CommitId
566 # $p_ref, if provided, must be [] and is used as a base for Parents
571 my ($h,$m) = get_commit $objid;
573 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
574 my (@ph) = $h =~ m/^parent (\w+)$/mg;
584 foreach my $ph (@ph) {
586 Ix => scalar @$p_ref,
598 my $r = parsecommit($objid, \@p);
602 $p->{Differs} = (get_differs $p->{CommitId}, $t),
605 printdebug "classify $objid \$t=$t \@p",
606 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
610 my ($type, @rest) = @_;
611 $r = { %$r, Type => $type, @rest };
613 printdebug " = $type ".(dd $r)."\n";
619 $r = { %$r, Type => qw(Unknown), Why => $why };
620 printdebug " ** Unknown\n";
624 if (grep { $_ eq $objid } @opt_anchors) {
625 return $classify->('TreatAsAnchor');
628 my @identical = grep { !$_->{Differs} } @p;
629 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
630 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
632 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
633 # multi-orig upstreams are represented with an anchor merge
634 # from a single upstream commit which combines the orig tarballs
636 # Every anchor tagged this way must be a merge.
637 # We are relying on the
638 # [git-debrebase anchor: ...]
639 # commit message annotation in "declare" anchor merges (which
640 # do not have any upstream changes), to distinguish those
641 # anchor merges from ordinary pseudomerges (which we might
642 # just try to strip).
644 # However, the user is going to be doing git-rebase a lot. We
645 # really don't want them to rewrite an anchor commit.
646 # git-rebase trips up on merges, so that is a useful safety
649 # BreakwaterStart commits are also anchors in the terminology
650 # of git-debrebase(5), but they are untagged (and always
651 # manually generated).
653 # We cannot not tolerate any tagged linear commit (ie,
654 # BreakwaterStart commits tagged `[anchor:') because such a
655 # thing could result from an erroneous linearising raw git
656 # rebase of a merge anchor. That would represent a corruption
657 # of the branch. and we want to detect and reject the results
658 # of such corruption before it makes it out anywhere. If we
659 # reject it here then we avoid making the pseudomerge which
660 # would be needed to push it.
662 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
663 @p == 2 or return $badanchor->("has other than two parents");
664 $haspatches and return $badanchor->("contains debian/patches");
666 # How to decide about l/r ordering of anchors ? git
667 # --topo-order prefers to expand 2nd parent first. There's
668 # already an easy rune to look for debian/ history anyway (git log
669 # debian/) so debian breakwater branch should be 1st parent; that
670 # way also there's also an easy rune to look for the upstream
671 # patches (--topo-order).
673 # Also this makes --first-parent be slightly more likely to
674 # be useful - it makes it provide a linearised breakwater history.
676 # Of course one can say somthing like
677 # gitk -- ':/' ':!/debian'
678 # to get _just_ the commits touching upstream files, and by
679 # the TREESAME logic in git-rev-list this will leave the
680 # breakwater into upstream at the first anchor. But that
681 # doesn't report debian/ changes at all.
683 # Other observations about gitk: by default, gitk seems to
684 # produce output in a different order to git-rev-list. I
685 # can't seem to find this documented anywhere. gitk
686 # --date-order DTRT. But, gitk always seems to put the
687 # parents from left to right, in order, so it's easy to see
688 # which way round a pseudomerge is.
690 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
691 $p[1]{Differs} & ~DS_DEB and
692 $badanchor->("upstream files differ from left parent");
693 $p[0]{Differs} & ~D_UPS and
694 $badanchor->("debian/ differs from right parent");
696 return $classify->(qw(Anchor),
697 OrigParents => [ $p[1] ]);
701 my $d = $r->{Parents}[0]{Differs};
702 if ($d == D_PAT_ADD) {
703 return $classify->(qw(AddPatches));
704 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
705 return $unknown->("edits debian/patches");
706 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
707 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
709 if ($d == D_DEB_CLOG) {
710 return $classify->(qw(Changelog));
712 return $classify->(qw(Packaging));
714 } elsif ($ty eq 'missing') {
715 return $classify->(qw(BreakwaterStart));
717 return $unknown->("parent's debian is not a directory");
719 } elsif ($d == D_UPS) {
720 return $classify->(qw(Upstream));
721 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
722 return $classify->(qw(Mixed));
724 return $unknown->("no changes");
726 confess "internal error $objid ?";
730 return $unknown->("origin commit");
733 if (@p == 2 && @identical == 1) {
734 my @overwritten = grep { $_->{Differs} } @p;
735 confess "internal error $objid ?" unless @overwritten==1;
736 return $classify->(qw(Pseudomerge),
737 Overwritten => [ $overwritten[0] ],
738 Contributor => $identical[0]);
740 if (@p == 2 && @identical == 2) {
742 my ($ph,$pm) = get_commit $_[0]{CommitId};
743 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
747 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
748 if ($order > 0) { # newer first
749 } elsif ($order < 0) {
750 @bytime = reverse @bytime;
752 # same age, default to order made by -s ours
753 # that is, commit was made by someone who preferred L
755 return $classify->(qw(Pseudomerge),
756 SubType => qw(Ambiguous),
757 Contributor => $bytime[0],
758 Overwritten => [ $bytime[1] ]);
761 my ($p_h, $p_m) = get_commit $p->{CommitId};
762 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
763 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
765 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
767 if (!(grep { !$_->{IsOrigin} } @p) and
768 (@orig_ps >= @p - 1) and
769 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
771 return $classify->(qw(DgitImportUnpatched),
772 OrigParents => \@orig_ps);
776 return $unknown->("octopus merge");
779 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
780 return $classify->("MergedBreakwaters");
782 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
783 return $unknown->("unknown kind of merge from $1");
786 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
787 return $unknown->("general two-parent merge");
790 return $classify->("VanillaMerge");
793 sub keycommits ($;$$$$) {
794 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
795 # => ($anchor, $breakwater)
797 # $unclean->("unclean-$tagsfx", $msg, $cl)
798 # $furniture->("unclean-$tagsfx", $msg, $cl)
799 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
800 # is callled for each situation or commit that
801 # wouldn't be found in a laundered branch
802 # $furniture is for furniture commits such as might be found on an
803 # interchange branch (pseudomerge, d/patches, changelog)
804 # $trouble is for things whnich prevent the return of
805 # anchor and breakwater information; if that is ignored,
806 # then keycommits returns (undef, undef) instead.
807 # $fatal is for unprocessable commits, and should normally cause
808 # a failure. If ignored, agaion, (undef, undef) is returned.
810 # If a callback is undef, fail is called instead.
811 # If a callback is defined but false, the situation is ignored.
813 # no warnings qw(exiting); last;
814 # if the answer is no longer wanted.
816 my ($anchor, $breakwater);
820 $fatal //= sub { fail $_[1]; };
822 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
823 my $why = $mainwhy.$xwhy;
824 my $m = "branch needs laundering (run git-debrebase): $why";
825 fail $m unless defined $cb;
827 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
830 $cl = classify $head;
831 my $ty = $cl->{Type};
832 if ($ty eq 'Packaging') {
833 $breakwater //= $clogonly;
834 $breakwater //= $head;
835 } elsif ($ty eq 'Changelog') {
836 # this is going to count as the tip of the breakwater
837 # only if it has no upstream stuff before it
839 } elsif ($ty eq 'Anchor' or
840 $ty eq 'TreatAsAnchor' or
841 $ty eq 'BreakwaterStart') {
843 $breakwater //= $clogonly;
844 $breakwater //= $head;
846 } elsif ($ty eq 'Upstream') {
847 $x->($unclean, 'ordering',
848 "packaging change ($breakwater) follows upstream change"," (eg $head)")
849 if defined $breakwater;
852 } elsif ($ty eq 'Mixed') {
853 $x->($unclean, 'mixed',
854 "found mixed upstream/packaging commit"," ($head)");
857 } elsif ($ty eq 'Pseudomerge' or
858 $ty eq 'AddPatches') {
860 $x->($furniture, (lc $ty),
861 "found interchange bureaucracy commit ($ty)"," ($head)");
862 } elsif ($ty eq 'DgitImportUnpatched') {
864 $x->($trouble, 'dgitimport',
865 "found dgit dsc import"," ($head)");
866 return (undef,undef);
868 $x->($fatal, 'unprocessable',
869 "found bare dgit dsc import with no prior history",
871 return (undef,undef);
873 } elsif ($ty eq 'VanillaMerge') {
874 $x->($trouble, 'vanillamerge',
875 "found vanilla merge"," ($head)");
876 return (undef,undef);
878 $x->($fatal, 'unprocessable',
879 "found unprocessable commit, cannot cope: $cl->{Why}",
881 return (undef,undef);
883 $head = $cl->{Parents}[0]{CommitId};
885 return ($anchor, $breakwater);
891 $nogenerate,$report, $report_lprefix) = @_;
892 # => ($tip, $breakwater_tip, $last_anchor)
893 # (or nothing, if $nogenerate)
895 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
896 $report_lprefix //= '';
898 # go through commits backwards
899 # we generate two lists of commits to apply:
900 # breakwater branch and upstream patches
901 my (@brw_cl, @upp_cl, @processed);
908 my ($prose, $info) = @_;
912 $ms .= "\n\n[git-debrebase$info: $prose]\n";
915 my $rewrite_from_here = sub {
917 my $sp_cl = { SpecialMethod => 'StartRewrite' };
919 push @processed, $sp_cl;
924 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
927 return unless $report;
928 print $report $prdelim, $report_lprefix, @_;
932 my $bomb = sub { # usage: return $bomb->();
933 print $report " Unprocessable" if $report;
934 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
937 return (undef,undef);
939 fail "found unprocessable commit, cannot cope".
940 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
941 " (commit $cur) (d.".
942 (join ' ', map { sprintf "%#x", $_->{Differs} }
943 @{ $cl->{Parents} }).
950 my $build_start = sub {
951 my ($msg, $parent) = @_;
954 no warnings qw(exiting); last;
958 fail "something useful about failed merge attempt @_ xxx".Dumper($cl);
965 my $ty = $cl->{Type};
966 my $st = $cl->{SubType};
967 $prline->("$cl->{CommitId} $cl->{Type}");
968 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
969 push @processed, $cl;
970 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
971 if ($ty eq 'AddPatches') {
973 $rewrite_from_here->(\@upp_cl);
975 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
979 } elsif ($ty eq 'BreakwaterStart') {
981 $build_start->('FirstPackaging', $cur);
982 } elsif ($ty eq 'Upstream') {
986 } elsif ($ty eq 'Mixed') {
989 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
992 $queue->(\@brw_cl, "debian");
993 $queue->(\@upp_cl, "upstream");
994 $rewrite_from_here->(\@brw_cl);
997 } elsif ($ty eq 'Pseudomerge') {
998 my $contrib = $cl->{Contributor}{CommitId};
999 print $report " Contributor=$contrib" if $report;
1000 push @pseudomerges, $cl;
1001 $rewrite_from_here->(\@upp_cl);
1004 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1005 $last_anchor = $cur;
1006 $build_start->("Anchor", $cur);
1007 } elsif ($ty eq 'DgitImportUnpatched') {
1008 my $pm = $pseudomerges[-1];
1010 # To an extent, this is heuristic. Imports don't have
1011 # a useful history of the debian/ branch. We assume
1012 # that the first pseudomerge after an import has a
1013 # useful history of debian/, and ignore the histories
1014 # from later pseudomerges. Often the first pseudomerge
1015 # will be the dgit import of the upload to the actual
1016 # suite intended by the non-dgit NMUer, and later
1017 # pseudomerges may represent in-archive copies.
1018 my $ovwrs = $pm->{Overwritten};
1019 printf $report " PM=%s \@Overwr:%d",
1020 $pm->{CommitId}, (scalar @$ovwrs)
1023 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1026 my $ovwr = $ovwrs->[0]{CommitId};
1027 printf $report " Overwr=%s", $ovwr if $report;
1028 # This import has a tree which is just like a
1029 # breakwater tree, but it has the wrong history. It
1030 # ought to have the previous breakwater (which the
1031 # pseudomerge overwrote) as an ancestor. That will
1032 # make the history of the debian/ files correct. As
1033 # for the upstream version: either it's the same as
1034 # was ovewritten (ie, same as the previous
1035 # breakwater), in which case that history is precisely
1036 # right; or, otherwise, it was a non-gitish upload of a
1037 # new upstream version. We can tell these apart by
1038 # looking at the tree of the supposed upstream.
1041 SpecialMethod => 'DgitImportDebianUpdate',
1042 $xmsg->("convert dgit import: debian changes")
1045 SpecialMethod => 'DgitImportUpstreamUpdate',
1046 $xmsg->("convert dgit import: upstream update",
1049 $prline->(" Import");
1050 $rewrite_from_here->(\@brw_cl);
1051 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1055 # Everything is from this import. This kind of import
1056 # is already nearly in valid breakwater format, with the
1057 # patches as commits. Unfortunately it contains
1059 printdebug "*** WALK BOMB bare dgit import\n";
1060 $cl->{Why} = "bare dgit dsc import";
1064 } elsif ($ty eq 'VanillaMerge' or $ty eq 'MergedBreakwaters') {
1065 # xxx need to handle ffq if one side was unstitched
1066 # wait both of them may be!
1069 # We expect to find a dominating anchor amongst the
1070 # inputs' anchors. That will be the new anchor.
1072 # More complicated is finding a merge base for the
1073 # breakwaters. We need a merge base that is a breakwater
1074 # commit. The ancestors of breakwater commits are more
1075 # breakwater commits and possibly upstream commits and the
1076 # ancestors of those upstream. Upstreams might have
1077 # arbitrary ancestors. But any upstream commit U is
1078 # either included in both anchors, in which case the
1079 # earlier anchor is a better merge base than any of U's
1080 # ancestors; or U is not included in the older anchor, in
1081 # which case U is not an ancestor of the vanilla merge at
1082 # all. So no upstream commit, nor any ancestor thereof,
1083 # is a best merge base. As for non-breakwater Debian
1084 # commits: these are never ancestors of any breakwater.
1086 # So any best merge base as found by git-merge-base
1087 # is a suitable breakwater anchor. Usually there will
1090 printdebug "*** MERGE\n";
1092 # xxx avoid calling walk without nogenerate when
1093 # we have a MergedBreakwater; instead call keycommits ?
1095 my @bwbcmd = (@git, qw(merge-base));
1096 my @ibcmd = (@git, qw(merge-base --all));
1097 my $might_be_in_bw = 1;
1099 my $ps = $cl->{Parents};
1101 foreach my $p (@$ps) {
1102 $prline->(" VanillaMerge ".$p->{Ix});
1104 my ($ptip, $pbw, $panchor) =
1105 walk $p->{CommitId}, 0, $report,
1106 $report_lprefix.' ';
1107 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1108 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1109 $p->{Anchor} = $panchor;
1111 $best_anchor = $panchor if
1112 !defined $best_anchor or
1113 is_fast_fwd $best_anchor, $panchor;
1115 printdebug " MERGE BA best=".($best_anchor//'-').
1119 foreach my $p (@$ps) {
1120 $prline->(" VanillaMerge ".$p->{Ix});
1121 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1122 $nomerge->('DivergentAnchor');
1123 } elsif ($p->{Anchor} eq $best_anchor) {
1124 print $report " SameAnchor" if $report;
1126 print $report " SupersededAnchor" if $report;
1128 if ($p->{Breakwater} eq $p->{CommitId}) {
1129 # this parent commit was its own breakwater,
1130 # ie it is part of the breakwater
1131 print $report " Breakwater" if $report;
1133 $might_be_in_bw = 0;
1135 push @bwbcmd, $p->{Breakwater};
1136 push @ibcmd, $p->{CommitId};
1139 if ($ok && $might_be_in_bw) {
1140 $prline->(" VanillaMerge MergedBreakwaters");
1141 $last_anchor = $best_anchor;
1142 $build_start->('MergedBreakwaters', $cur);
1145 $nomerge->("alleged merged-breakwater is not a breakwater")
1146 unless $ty eq 'VanillaMerge';
1148 my $bwb = cmdoutput @bwbcmd;
1150 # OK, now we have a breakwater base, but we need the merge
1151 # base for the interchange branch because we need the delta
1154 # This a the best merge base of our inputs which has the
1155 # breakwater merge base as an ancestor.
1158 grep { is_fast_fwd $bwb, $_ }
1163 or $nomerge->("no suitable interchange merge base");
1165 $prline->(" VanillaMerge Base");
1167 my ($btip, $bbw, $banchor) =
1168 walk $ib, 0, $report, $report_lprefix.' ';
1170 my $ibinfo = { SeriesTip => $btip,
1172 Anchor => $banchor };
1174 or $nomerge->("interchange merge-base ($ib)'s".
1175 " breakwater ($bbw)".
1176 " != breakwaters' merge-base ($bwb)");
1177 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1178 or $nomerge->("interchange merge-base ($ib)'s".
1179 " anchor ($ibinfo->{SeriesBase})".
1180 " != any merge input's anchor (".
1181 (join ' ', map { $_->{Anchor} } @$ps).
1185 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1186 $cl->{MergeBestAnchor} = $best_anchor;
1189 SpecialMethod => 'MergeCreateMergedBreakwaters',
1190 $xmsg->('construct merged breakwater from vanilla merge'),
1194 SpecialMethod => 'MergeMergeSeries',
1196 $build_start->('MergeBreakwaters', $cur);
1198 printdebug "*** WALK BOMB unrecognised\n";
1204 printdebug "*** WALK prep done cur=$cur".
1205 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1207 return if $nogenerate;
1209 # Now we build it back up again
1215 $#upp_cl = $upp_limit if defined $upp_limit;
1217 my $committer_authline = calculate_committer_authline();
1219 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1221 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1224 mkdir $rd or $!==EEXIST or die $!;
1226 runcmd @git, qw(read-tree), $build;
1227 foreach my $cl (qw(Debian), (reverse @brw_cl),
1228 { SpecialMethod => 'RecordBreakwaterTip' },
1229 qw(Upstream), (reverse @upp_cl)) {
1231 $current_method = $cl;
1234 my $method = $cl->{SpecialMethod} // $current_method;
1235 my @parents = ($build);
1236 my $cltree = $cl->{CommitId};
1237 printdebug "WALK BUILD ".($cltree//'undef').
1238 " $method (rewriting=$rewriting)\n";
1239 if ($method eq 'Debian') {
1240 read_tree_debian($cltree);
1241 } elsif ($method eq 'Upstream') {
1242 read_tree_upstream($cltree);
1243 } elsif ($method eq 'StartRewrite') {
1246 } elsif ($method eq 'RecordBreakwaterTip') {
1247 $breakwater = $build;
1249 } elsif ($method eq 'DgitImportDebianUpdate') {
1250 read_tree_debian($cltree);
1251 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1252 confess unless $rewriting;
1253 my $differs = (get_differs $build, $cltree);
1254 next unless $differs & D_UPS;
1255 read_tree_upstream($cltree);
1256 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1257 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1258 print "Found a general merge, will try to tidy it up.\n";
1260 read_tree_upstream($cl->{MergeBestAnchor});
1261 read_tree_upstream($cl->{MergeBestAnchor});
1262 read_tree_debian($cltree);
1263 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1264 } elsif ($method eq 'MergeMergeSeries') {
1265 print "Running merge resolution for $cl->{CommitId}...\n";
1266 $build = merge_series
1268 $cl->{MergeInterchangeBaseInfo},
1269 @{ $cl->{Parents} };
1270 $last_anchor = $cl->{MergeBestAnchor};
1271 # xxx need to check the tree somehow
1272 print "Merge resolution successful.\n";
1275 confess "$method ?";
1278 my $procd = (pop @processed) // 'UNDEF';
1279 if ($cl ne $procd) {
1281 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1284 my $newtree = cmdoutput @git, qw(write-tree);
1285 my $ch = $cl->{Hdr};
1286 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1287 $ch =~ s{^parent .*\n}{}mg;
1288 $ch =~ s{(?=^author)}{
1289 join '', map { "parent $_\n" } @parents
1290 }me or confess "$ch ?";
1292 $ch =~ s{^committer .*$}{$committer_authline}m
1295 my $cf = "$rd/m$rewriting";
1296 open CD, ">", $cf or die $!;
1297 print CD $ch, "\n", $cl->{Msg} or die $!;
1299 my @cmd = (@git, qw(hash-object));
1300 push @cmd, qw(-w) if $rewriting;
1301 push @cmd, qw(-t commit), $cf;
1302 my $newcommit = cmdoutput @cmd;
1303 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1304 $build = $newcommit;
1305 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1306 $last_anchor = $cur;
1311 my $final_check = get_differs $build, $input;
1312 die sprintf "internal error %#x %s %s", $final_check, $build, $input
1313 if $final_check & ~D_PAT_ADD;
1315 my @r = ($build, $breakwater, $last_anchor);
1316 printdebug "*** WALK RETURN @r\n";
1321 git_check_unmodified();
1322 return git_rev_parse qw(HEAD);
1325 sub update_head ($$$) {
1326 my ($old, $new, $mrest) = @_;
1327 push @deferred_updates, "update HEAD $new $old";
1328 run_deferred_updates $mrest;
1331 sub update_head_checkout ($$$) {
1332 my ($old, $new, $mrest) = @_;
1333 update_head $old, $new, $mrest;
1334 runcmd @git, qw(reset --hard);
1337 sub update_head_postlaunder ($$$) {
1338 my ($old, $tip, $reflogmsg) = @_;
1339 return if $tip eq $old;
1340 print "git-debrebase: laundered (head was $old)\n";
1341 update_head $old, $tip, $reflogmsg;
1342 # no tree changes except debian/patches
1343 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1346 sub currently_rebasing() {
1347 foreach (qw(rebase-merge rebase-apply)) {
1348 return 1 if stat_exists "$maindir_gitdir/$_";
1353 sub bail_if_rebasing() {
1354 fail "you are in the middle of a git-rebase already"
1355 if currently_rebasing();
1358 sub do_launder_head ($) {
1359 my ($reflogmsg) = @_;
1360 my $old = get_head();
1362 my ($tip,$breakwater) = walk $old;
1364 update_head_postlaunder $old, $tip, $reflogmsg;
1365 return ($tip,$breakwater);
1368 sub cmd_launder_v0 () {
1369 badusage "no arguments to launder-v0 allowed" if @ARGV;
1370 my $old = get_head();
1371 my ($tip,$breakwater,$last_anchor) = walk $old;
1372 update_head_postlaunder $old, $tip, 'launder';
1373 printf "# breakwater tip\n%s\n", $breakwater;
1374 printf "# working tip\n%s\n", $tip;
1375 printf "# last anchor\n%s\n", $last_anchor;
1378 sub defaultcmd_rebase () {
1379 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1380 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1381 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1384 sub cmd_analyse () {
1385 badusage "analyse does not support any options"
1386 if @ARGV and $ARGV[0] =~ m/^-/;
1387 badusage "too many arguments to analyse" if @ARGV>1;
1390 $old = git_rev_parse $old;
1392 $old = git_rev_parse 'HEAD';
1394 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1395 STDOUT->error and die $!;
1398 sub ffq_prev_branchinfo () {
1399 my $current = git_get_symref();
1400 return gdr_ffq_prev_branchinfo($current);
1403 sub ffq_check ($;$$) {
1404 # calls $ff and/or $notff zero or more times
1405 # then returns either (status,message) where status is
1410 # or (undef,undef, $ffq_prev,$gdrlast)
1411 # $ff and $notff are called like this:
1412 # $ff->("message for stdout\n");
1413 # $notff->('snag-name', $message);
1414 # normally $currentval should be HEAD
1415 my ($currentval, $ff, $notff) =@_;
1417 $ff //= sub { print $_[0] or die $!; };
1420 my ($status, $message, $current, $ffq_prev, $gdrlast)
1421 = ffq_prev_branchinfo();
1422 return ($status, $message) unless $status eq 'branch';
1424 my $exists = git_get_ref $ffq_prev;
1425 return ('exists',"$ffq_prev already exists") if $exists;
1427 return ('not-branch', 'HEAD symref is not to refs/heads/')
1428 unless $current =~ m{^refs/heads/};
1431 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1434 printdebug "ffq check_specs @check_specs\n";
1437 my ($lrref, $desc) = @_;
1438 printdebug "ffq might check $lrref ($desc)\n";
1440 for my $chk (@check_specs) {
1442 $invert = $glob =~ s{^[!^]}{};
1443 last if fnmatch $glob, $lrref;
1446 my $lrval = git_get_ref $lrref;
1447 return unless length $lrval;
1449 if (is_fast_fwd $lrval, $currentval) {
1450 $ff->("OK, you are ahead of $lrref\n");
1451 $checked{$lrref} = 1;
1452 } elsif (is_fast_fwd $currentval, $lrval) {
1453 $checked{$lrref} = -1;
1454 $notff->('behind', "you are behind $lrref, divergence risk");
1456 $checked{$lrref} = -1;
1457 $notff->('diverged', "you have diverged from $lrref");
1461 my $merge = cfg "branch.$branch.merge",1;
1462 if (defined $merge and $merge =~ m{^refs/heads/}) {
1464 printdebug "ffq merge $rhs\n";
1465 my $check_remote = sub {
1466 my ($remote, $desc) = @_;
1467 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1468 return unless defined $remote;
1469 $check->("refs/remotes/$remote/$rhs", $desc);
1471 $check_remote->((scalar cfg "branch.$branch.remote",1),
1472 'remote fetch/merge branch');
1473 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1474 (scalar cfg "branch.$branch.pushDefault",1),
1475 'remote push branch');
1477 if ($branch =~ m{^dgit/}) {
1478 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1479 } elsif ($branch =~ m{^master$}) {
1480 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1482 return (undef, undef, $ffq_prev, $gdrlast);
1485 sub record_ffq_prev_deferred () {
1486 # => ('status', "message")
1488 # deferred message is undef
1493 # if not ff from some branch we should be ff from, is an snag
1494 # if "deferred", will have added something about that to
1495 # @deferred_update_messages, and also maybe printed (already)
1496 # some messages about ff checks
1498 my $currentval = get_head();
1500 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1501 return ($status,$message) if defined $status;
1505 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1506 push @deferred_updates, "delete $gdrlast";
1507 push @deferred_update_messages, "Recorded previous head for preservation";
1508 return ('deferred', undef);
1511 sub record_ffq_auto () {
1512 my ($status, $message) = record_ffq_prev_deferred();
1513 if ($status eq 'deferred' || $status eq 'exists') {
1515 snag $status, "could not record ffq-prev: $message";
1520 sub ffq_prev_info () {
1522 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1523 my ($status, $message, $current, $ffq_prev, $gdrlast)
1524 = ffq_prev_branchinfo();
1525 if ($status ne 'branch') {
1526 snag $status, "could not check ffq-prev: $message";
1529 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1530 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1533 sub stitch ($$$$$) {
1534 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1536 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1538 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1539 my $differs = get_differs $old_head, $ffq_prev_commitish;
1540 unless ($differs & ~D_PAT_ADD) {
1541 # ffq-prev is ahead of us, and the only tree changes it has
1542 # are possibly addition of things in debian/patches/.
1543 # Just wind forwards rather than making a pointless pseudomerge.
1544 push @deferred_updates,
1545 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1546 update_head_checkout $old_head, $ffq_prev_commitish,
1547 "stitch (fast forward)";
1552 # We make pseudomerges with L as the contributing parent.
1553 # This makes git rev-list --first-parent work properly.
1554 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1555 'Declare fast forward / record previous work',
1556 "[git-debrebase pseudomerge: $prose]",
1558 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1559 update_head $old_head, $new_head, "stitch: $prose";
1562 sub do_stitch ($;$) {
1563 my ($prose, $unclean) = @_;
1565 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1566 if (!$ffq_prev_commitish) {
1567 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1570 my $dangling_head = get_head();
1572 keycommits $dangling_head, $unclean,$unclean,$unclean;
1575 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1578 sub upstream_commitish_search ($$) {
1579 my ($upstream_version, $tried) = @_;
1580 # todo: at some point maybe use git-deborig to do this
1581 foreach my $tagpfx ('', 'v', 'upstream/') {
1582 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1583 my $new_upstream = git_get_ref "refs/tags/$tag";
1585 return $new_upstream if length $new_upstream;
1589 sub resolve_upstream_version ($$) {
1590 my ($new_upstream, $upstream_version) = @_;
1592 if (!defined $new_upstream) {
1594 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1595 if (!length $new_upstream) {
1596 fail "Could not determine appropriate upstream commitish.\n".
1597 " (Tried these tags: @tried)\n".
1598 " Check version, and specify upstream commitish explicitly.";
1601 $new_upstream = git_rev_parse $new_upstream;
1603 return $new_upstream;
1606 sub cmd_new_upstream () {
1607 # automatically and unconditionally launders before rebasing
1608 # if rebase --abort is used, laundering has still been done
1612 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1614 # parse args - low commitment
1615 my $spec_version = shift @ARGV;
1616 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1617 fail "bad version number \`$spec_version'" unless defined $new_version;
1618 if ($new_version->is_native()) {
1619 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1622 my $new_upstream = shift @ARGV;
1623 my $new_upstream_version = upstreamversion $new_version;
1625 resolve_upstream_version $new_upstream, $new_upstream_version;
1630 my ($n, @x) = @_; # may be ''
1631 my $pc = $pieces{$n} //= {
1633 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1635 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1640 my $newpiece = sub {
1641 my ($n, @x) = @_; # may be ''
1642 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1643 push @newpieces, $pc;
1648 New => $new_upstream,
1650 while (@ARGV && $ARGV[0] !~ m{^-}) {
1651 my $n = shift @ARGV;
1653 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1654 unless @ARGV && $ARGV[0] !~ m{^-};
1656 my $c = git_rev_parse shift @ARGV;
1657 die unless $n =~ m/^$extra_orig_namepart_re$/;
1658 $newpiece->($n, New => $c);
1661 # now we need to investigate the branch this generates the
1662 # laundered version but we don't switch to it yet
1663 my $old_head = get_head();
1664 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1666 my $old_bw_cl = classify $old_bw;
1667 my $old_anchor_cl = classify $old_anchor;
1669 if (!$old_anchor_cl->{OrigParents}) {
1670 snag 'anchor-treated',
1671 'old anchor is recognised due to --anchor, cannot check upstream';
1673 $old_upstream = parsecommit
1674 $old_anchor_cl->{OrigParents}[0]{CommitId};
1675 $piece->('', Old => $old_upstream->{CommitId});
1678 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1679 if ($old_upstream->{Msg} =~
1680 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1682 my @oldpieces = (split / /, $1);
1683 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1684 if ($old_n_parents != @oldpieces &&
1685 $old_n_parents != @oldpieces + 1) {
1686 snag 'upstream-confusing', sprintf
1687 "previous upstream combine %s".
1688 " mentions %d pieces (each implying one parent)".
1689 " but has %d parents".
1690 " (one per piece plus maybe a previous combine)",
1691 $old_upstream->{CommitId},
1692 (scalar @oldpieces),
1694 } elsif ($oldpieces[0] ne '.') {
1695 snag 'upstream-confusing', sprintf
1696 "previous upstream combine %s".
1697 " first piece is not \`.'",
1701 foreach my $i (0..$#oldpieces) {
1702 my $n = $oldpieces[$i];
1703 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1704 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1708 snag 'upstream-confusing',
1709 "previous upstream $old_upstream->{CommitId} is from".
1710 " git-debrebase but not an \`upstream-combine' commit";
1714 foreach my $pc (values %pieces) {
1715 if (!$old_upstream) {
1716 # we have complained already
1717 } elsif (!$pc->{Old}) {
1718 snag 'upstream-new-piece',
1719 "introducing upstream piece \`$pc->{Name}'";
1720 } elsif (!$pc->{New}) {
1721 snag 'upstream-rm-piece',
1722 "dropping upstream piece \`$pc->{Name}'";
1723 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1724 snag 'upstream-not-ff',
1725 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1729 printdebug "%pieces = ", (dd \%pieces), "\n";
1730 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1738 my @upstream_merge_parents;
1741 push @upstream_merge_parents, $old_upstream->{CommitId};
1744 foreach my $pc (@newpieces) { # always has '' first
1746 read_tree_subdir $pc->{Name}, $pc->{New};
1748 runcmd @git, qw(read-tree), $pc->{New};
1750 push @upstream_merge_parents, $pc->{New};
1753 # index now contains the new upstream
1755 if (@newpieces > 1) {
1756 # need to make the upstream subtree merge commit
1757 $new_upstream = make_commit \@upstream_merge_parents,
1758 [ "Combine upstreams for $new_upstream_version",
1759 ("[git-debrebase upstream-combine . ".
1760 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1765 # $new_upstream is either the single upstream commit, or the
1766 # combined commit we just made. Either way it will be the
1767 # "upstream" parent of the anchor merge.
1769 read_tree_subdir 'debian', "$old_bw:debian";
1771 # index now contains the anchor merge contents
1772 $new_bw = make_commit [ $old_bw, $new_upstream ],
1773 [ "Update to upstream $new_upstream_version",
1774 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1777 my $clogsignoff = cmdoutput qw(git show),
1778 '--pretty=format:%an <%ae> %aD',
1781 # Now we have to add a changelog stanza so the Debian version
1783 die if unlink "debian";
1784 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1785 unlink "debian/changelog" or $!==ENOENT or die $!;
1786 mkdir "debian" or die $!;
1787 open CN, ">", "debian/changelog" or die $!;
1788 my $oldclog = git_cat_file ":debian/changelog";
1789 $oldclog =~ m/^($package_re) \(\S+\) / or
1790 fail "cannot parse old changelog to get package name";
1792 print CN <<END, $oldclog or die $!;
1793 $p ($new_version) UNRELEASED; urgency=medium
1795 * Update to new upstream version $new_upstream_version.
1801 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1803 # Now we have the final new breakwater branch in the index
1804 $new_bw = make_commit [ $new_bw ],
1805 [ "Update changelog for new upstream $new_upstream_version",
1806 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1810 # we have constructed the new breakwater. we now need to commit to
1811 # the laundering output, because git-rebase can't easily be made
1812 # to make a replay list which is based on some other branch
1814 update_head_postlaunder $old_head, $old_laundered_tip,
1815 'launder for new upstream';
1817 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1818 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1819 "debrebase new-upstream $new_version: rebase";
1821 # now it's for the user to sort out
1824 sub cmd_record_ffq_prev () {
1825 badusage "no arguments allowed" if @ARGV;
1826 my ($status, $msg) = record_ffq_prev_deferred();
1827 if ($status eq 'exists' && $opt_noop_ok) {
1828 print "Previous head already recorded\n" or die $!;
1829 } elsif ($status eq 'deferred') {
1830 run_deferred_updates 'record-ffq-prev';
1832 fail "Could not preserve: $msg";
1837 badusage "no arguments allowed" if @ARGV;
1838 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1839 print "$bw\n" or die $!;
1842 sub cmd_breakwater () {
1843 badusage "no arguments allowed" if @ARGV;
1844 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1845 print "$bw\n" or die $!;
1849 badusage "no arguments allowed" if @ARGV;
1851 # todo: gdr status should print divergence info
1852 # todo: gdr status should print upstream component(s) info
1853 # todo: gdr should leave/maintain some refs with this kind of info ?
1855 my $oldest = { Badness => 0 };
1858 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1859 if ($oldest->{Badness} < $badness) {
1860 $oldest = $newest = undef;
1863 Badness => $badness,
1864 CommitId => $cl->{CommitId},
1868 $newest //= $oldest;
1870 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1871 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1872 sub { $note->(2, 'branch is unlaundered', @_); },
1873 sub { $note->(3, 'branch needs laundering', @_); },
1874 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1876 my $prcommitinfo = sub {
1878 flush STDOUT or die $!;
1879 runcmd @git, qw(--no-pager log -n1),
1880 '--pretty=format: %h %s%n',
1884 print "current branch contents, in git-debrebase terms:\n";
1885 if (!$oldest->{Badness}) {
1886 print " branch is laundered\n";
1888 print " $oldest->{OurMsg}\n";
1890 foreach my $info ($oldest, $newest) {
1891 my $cid = $info->{CommitId};
1892 next if $cid eq $printed;
1894 print " $info->{KcMsg}\n";
1895 $prcommitinfo->($cid);
1900 my ($cid, $what) = @_;
1901 if (!defined $cid) {
1902 print " $what is not well-defined\n";
1905 $prcommitinfo->($cid);
1908 print "key git-debrebase commits:\n";
1909 $prab->($anchor, 'anchor');
1910 $prab->($bw, 'breakwater');
1912 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1913 ffq_prev_branchinfo();
1915 print "branch and ref status, in git-debrebase terms:\n";
1917 print " $ffq_msg\n";
1919 $ffq_prev = git_get_ref $ffq_prev;
1920 $gdrlast = git_get_ref $gdrlast;
1922 print " unstitched; previous tip was:\n";
1923 $prcommitinfo->($ffq_prev);
1924 } elsif (!$gdrlast) {
1925 print " stitched? (no record of git-debrebase work)\n";
1926 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1927 print " stitched\n";
1929 print " not git-debrebase (diverged since last stitch)\n"
1932 print "you are currently rebasing\n" if currently_rebasing();
1936 my $prose = 'stitch';
1937 getoptions("stitch",
1938 'prose=s', \$prose);
1939 badusage "no arguments allowed" if @ARGV;
1940 do_stitch $prose, 0;
1942 sub cmd_prepush () { cmd_stitch(); }
1945 badusage "no arguments allowed" if @ARGV;
1946 do_launder_head 'launder for git-debrebase quick';
1950 sub cmd_conclude () {
1951 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1952 if (!$ffq_prev_commitish) {
1953 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1956 my $dangling_head = get_head();
1958 badusage "no arguments allowed" if @ARGV;
1959 do_launder_head 'launder for git-debrebase quick';
1964 if (currently_rebasing()) {
1965 runcmd @git, qw(rebase --abort);
1967 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1968 if (!$ffq_prev_commitish) {
1969 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1972 my $scrapping_head = get_head();
1973 badusage "no arguments allowed" if @ARGV;
1974 push @deferred_updates,
1975 "update $gdrlast $ffq_prev_commitish $git_null_obj",
1976 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
1978 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
1981 sub make_patches_staged ($) {
1983 # Produces the patches that would result from $head if it were
1985 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1988 gbp_pq_export 'bw', $secret_bw, $secret_head;
1992 sub make_patches ($) {
1994 keycommits $head, 0, \&snag;
1995 make_patches_staged $head;
1998 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1999 runcmd @git, qw(read-tree), $head;
2000 read_tree_subdir 'debian/patches', $ptree;
2001 $out = make_commit [$head], [
2002 'Commit patch queue (exported by git-debrebase)',
2003 '[git-debrebase: export and commit patches]',
2009 sub cmd_make_patches () {
2010 my $opt_quiet_would_amend;
2011 getoptions("make-patches",
2012 'quiet-would-amend!', \$opt_quiet_would_amend);
2013 badusage "no arguments allowed" if @ARGV;
2015 my $old_head = get_head();
2016 my $new = make_patches $old_head;
2017 my $d = get_differs $old_head, $new;
2019 fail "No (more) patches to export." unless $opt_noop_ok;
2021 } elsif ($d == D_PAT_ADD) {
2023 update_head_checkout $old_head, $new, 'make-patches';
2025 print STDERR failmsg
2026 "Patch export produced patch amendments".
2027 " (abandoned output commit $new).".
2028 " Try laundering first."
2029 unless $opt_quiet_would_amend;
2034 sub cmd_convert_from_gbp () {
2035 badusage "want only 1 optional argument, the upstream git commitish"
2038 my $clogp = parsechangelog();
2039 my $version = $clogp->{'Version'}
2040 // die "missing Version from changelog";
2042 my ($upstream_spec) = @ARGV;
2044 my $upstream_version = upstreamversion $version;
2046 resolve_upstream_version($upstream_spec, $upstream_version);
2048 my $old_head = get_head();
2050 my $upsdiff = get_differs $upstream, $old_head;
2051 if ($upsdiff & D_UPS) {
2052 runcmd @git, qw(--no-pager diff --stat),
2053 $upstream, $old_head,
2054 qw( -- :!/debian :/);
2056 upstream ($upstream_spec) and HEAD are not
2057 identical in upstream files. See diffstat above, or run
2058 git diff $upstream_spec HEAD -- :!/debian :/
2062 if (!is_fast_fwd $upstream, $old_head) {
2063 snag 'upstream-not-ancestor',
2064 "upstream ($upstream) is not an ancestor of HEAD";
2066 my $wrong = cmdoutput
2067 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2068 qw(-- :/ :!/debian));
2069 if (length $wrong) {
2070 snag 'unexpected-upstream-changes',
2071 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2072 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2076 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2077 snag 'upstream-has-debian',
2078 "upstream ($upstream) contains debian/ directory";
2081 my $previous_dgit_view = eval {
2082 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2084 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2085 my ($stz, $desc) = @_;
2086 no warnings qw(exiting);
2087 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2088 next unless $stz->{Date};
2089 next unless $stz->{Distribution} ne 'UNRELEASED';
2090 $lvsn = $stz->{Version};
2091 $suite = $stz->{Distribution};
2094 die "neither of the first two changelog entries are released\n"
2095 unless defined $lvsn;
2096 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2097 my $mtag_pat = debiantag_maintview $lvsn, '*';
2098 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2100 die "could not find suitable maintainer view tag $mtag_pat\n"
2101 unless $mtag_pat =~ m{/};
2102 is_fast_fwd $mtag, 'HEAD' or
2103 die "HEAD is not FF from maintainer tag $mtag!";
2104 my $dtag = "archive/$mtag";
2105 is_fast_fwd $mtag, $dtag or
2106 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2107 print "will stitch in dgit view, $dtag\n";
2108 git_rev_parse $dtag;
2110 if (!$previous_dgit_view) {
2113 print STDERR "cannot stitch in dgit view: $@\n";
2116 snags_maybe_bail_early();
2122 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2123 # make a branch out of the patch queue - we'll want this in a mo
2124 runcmd qw(gbp pq import);
2125 # strip the patches out
2126 runcmd @git, qw(checkout -q gdr-internal~0);
2127 rm_subdir_cached 'debian/patches';
2128 $work = make_commit ['HEAD'], [
2129 'git-debrebase convert-from-gbp: drop patches from tree',
2130 'Delete debian/patches, as part of converting to git-debrebase format.',
2131 '[git-debrebase convert-from-gbp: drop patches from tree]'
2133 # make the anchor merge
2134 # the tree is already exactly right
2135 $work = make_commit [$work, $upstream], [
2136 'git-debrebase import: declare upstream',
2137 'First breakwater merge.',
2138 '[git-debrebase anchor: declare upstream]'
2141 # rebase the patch queue onto the new breakwater
2142 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2143 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2144 $work = git_rev_parse 'HEAD';
2146 if ($previous_dgit_view) {
2147 $work = make_commit [$work, $previous_dgit_view], [
2148 'git-debrebase import: declare ff from dgit archive view',
2149 '[git-debrebase pseudomerge: import-from-gbp]',
2156 update_head_checkout $old_head, $work, 'convert-from-gbp';
2159 sub cmd_convert_to_gbp () {
2160 badusage "no arguments allowed" if @ARGV;
2161 my $head = get_head();
2162 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2163 keycommits $head, 0;
2165 make_patches_staged $head;
2167 $out = make_commit ['HEAD'], [
2168 'Commit patch queue (converted from git-debrebase format)',
2169 '[git-debrebase convert-to-gbp: commit patches]',
2173 push @deferred_updates, "delete $ffq";
2174 push @deferred_updates, "delete $gdrlast";
2177 update_head_checkout $head, $out, "convert to gbp (v0)";
2178 print <<END or die $!;
2179 git-debrebase: converted to git-buildpackage branch format
2180 git-debrebase: WARNING: do not now run "git-debrebase" any more
2181 git-debrebase: WARNING: doing so would drop all upstream patches!
2185 sub cmd_convert_from_dgit_view () {
2186 my $clogp = parsechangelog();
2188 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2194 getoptions("convert-from-dgit-view",
2195 'diagnose!', \$diagnose,
2196 'build-products-dir:s', \$bpd,
2197 'origs!', \$do_origs,
2199 'always-convert-anyway!', \$always);
2200 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2205 my $spec = shift @ARGV;
2206 my $commit = git_rev_parse "$spec^{commit}";
2207 push @upstreams, { Commit => $commit,
2208 Source => "$ARGV[0], from command line",
2213 my $head = get_head();
2217 my $trouble = sub { $troubles++; };
2218 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2219 printdebug "troubles=$troubles\n";
2222 $us: Branch already seems to be in git-debrebase format!
2223 $us: --always-convert-anyway would do the conversion operation anyway
2224 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2226 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2231 snags_maybe_bail_early();
2233 my $version = upstreamversion $clogp->{Version};
2234 print STDERR "Considering possible commits corresponding to upstream:\n";
2239 my $ups_tag = upstream_commitish_search $version, \@tried;
2241 my $this = "git tag $tried[-1]";
2242 push @upstreams, { Commit => $ups_tag,
2247 " git tag: no suitable tag found (tried %s)\n",
2252 my $p = $clogp->{'Source'};
2253 # we do a quick check to see if there are plausible origs
2255 if (!opendir BPD, $bpd) {
2256 die "$bpd: opendir: $!" unless $!==ENOENT;
2258 while ($!=0, my $f = readdir BPD) {
2259 next unless is_orig_file_of_p_v $f, $p, $version;
2261 " orig: found what looks like a .orig, %s\n",
2266 die "read $bpd: $!" if $!;
2270 my $tree = cmdoutput
2271 @dgit, qw(--build-products-dir), $bpd,
2272 qw(print-unapplied-treeish);
2275 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2276 rm_subdir_cached 'debian';
2277 $tree = cmdoutput @git, qw(write-tree);
2278 my $ups_synth = make_commit [], [ <<END, <<END,
2279 Import effective orig tree for upstream version $version
2281 This includes the contents of the .orig(s), minus any debian/ directory.
2283 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2286 push @upstreams, { Commit => $ups_synth,
2287 Source => "orig(s) imported via dgit",
2292 " orig: no suitable origs found (looked for %s in %s)\n",
2293 "${p}_".(stripeoch $version)."...", $bpd;
2298 my $some_patches = stat_exists 'debian/patches/series';
2300 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2303 foreach my $u (@upstreams) {
2307 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2308 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2309 runcmd @git, qw(clean -xdff);
2310 runcmd @git, qw(checkout), $head, qw(-- debian);
2311 if ($some_patches) {
2312 rm_subdir_cached 'debian/patches';
2313 $work = make_commit [ $work ], [
2314 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2315 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2316 "to git-debrebase format. Upstream changes will appear as commits.",
2317 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2320 $work = make_commit [ $work, $u->{Commit} ], [
2321 'git-debrebase convert-from-dgit-view: declare upstream',
2322 '(Re)constructed breakwater merge.',
2323 '[git-debrebase anchor: declare upstream]'
2325 runcmd @git, qw(checkout --quiet -b mk), $work;
2326 if ($some_patches) {
2327 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2328 runcmd @git, qw(reset --quiet);
2329 my @gbp_cmd = (qw(gbp pq import));
2331 my $gbp_err = "../gbp-pq-err";
2332 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2334 my $r = system @gbp_cmd;
2337 " %s: couldn't apply patches: gbp pq %s",
2338 $u->{Source}, waitstatusmsg();
2342 my $work = git_rev_parse qw(HEAD);
2343 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2344 if (length $diffout) {
2346 " $u->{Source}: applying patches gives different tree\n";
2347 print STDERR $diffout if $diagnose;
2351 $u->{Result} = $work;
2359 Could not find or construct a suitable upstream commit.
2360 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2361 upstream commmit explicitly or provide suitable origs.
2365 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2367 ffq_check $result->{Result};
2369 update_head_checkout $head, $result->{Result},
2370 'convert-from-dgit-view';
2373 sub cmd_downstream_rebase_launder_v0 () {
2374 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2376 $base = git_rev_parse $base;
2377 my $old_head = get_head();
2378 my $current = $old_head;
2381 if ($current eq $base) {
2382 $topmost_keep //= $current;
2383 print " $current BASE stop\n";
2386 my $cl = classify $current;
2387 print " $current $cl->{Type}";
2389 my $p0 = $cl->{Parents}[0]{CommitId};
2391 if ($cl->{Type} eq 'Pseudomerge') {
2392 print " ^".($cl->{Contributor}{Ix}+1);
2393 $next = $cl->{Contributor}{CommitId};
2394 } elsif ($cl->{Type} eq 'AddPatches' or
2395 $cl->{Type} eq 'Changelog') {
2405 $topmost_keep //= $current;
2407 die "to-be stripped changes not on top of the branch\n"
2412 if ($topmost_keep eq $old_head) {
2413 print "unchanged\n";
2415 print "updating to $topmost_keep\n";
2416 update_head_checkout
2417 $old_head, $topmost_keep,
2418 'downstream-rebase-launder-v0';
2424 "D+" => \$debuglevel,
2425 'noop-ok', => \$opt_noop_ok,
2426 'f=s' => \@snag_force_opts,
2427 'anchor=s' => \@opt_anchors,
2428 '--dgit=s' => \($dgit[0]),
2431 my ($opt,$val) = @_;
2432 badusage "git-debrebase: no cuddling to -i for git-rebase"
2434 die if $opt_defaultcmd_interactive; # should not happen
2435 $opt_defaultcmd_interactive = [ qw(-i) ];
2436 # This access to @ARGV is excessive familiarity with
2437 # Getopt::Long, but there isn't another sensible
2438 # approach. '-i=s{0,}' does not work with bundling.
2439 push @$opt_defaultcmd_interactive, @ARGV;
2442 'help' => sub { print $usage_message or die $!; finish 0; },
2445 initdebug('git-debrebase ');
2446 enabledebug if $debuglevel;
2448 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2449 chdir $toplevel or die "chdir $toplevel: $!";
2451 $rd = fresh_playground "$playprefix/misc";
2453 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2455 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2456 defaultcmd_rebase();
2458 my $cmd = shift @ARGV;
2461 $cmdfn = ${*::}{"cmd_$cmdfn"};
2463 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";