3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
6 # Copyright (C)2017-2019 Ian Jackson
7 # Copyright (C)2019 Niko Tyni
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
23 use Debian::Dgit::GDR;
24 use Debian::Dgit::ExitStatus;
25 use Debian::Dgit::I18n;
29 use Debian::Dgit qw(:DEFAULT :playground);
37 use Getopt::Long qw(:config posix_default gnu_compat bundling);
39 use File::FnMatch qw(:fnmatch);
42 $debugcmd_when_debuglevel = 2;
44 our ($usage_message) = i_ <<'END';
46 git-debrebase [<options>] [--|-i <git rebase options...>]
47 git-debrebase [<options>] status
48 git-debrebase [<options>] prepush [--prose=...]
49 git-debrebase [<options>] quick|conclude
50 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
51 git-debrebase [<options>] convert-from-* ...
53 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
56 our ($opt_force, $opt_noop_ok, $opt_merges, @opt_anchors);
57 our ($opt_defaultcmd_interactive);
59 our $us = qw(git-debrebase);
61 our $wrecknoteprefix = 'refs/debrebase/wreckage';
62 our $merge_cache_ref = 'refs/debrebase/merge-resolutions';
68 print STDERR f_ "%s: bad usage: %s\n", $us, $m;
74 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
75 GetOptions @_ or badusage $m;
79 getoptions_main +(f_ "bad options follow \`git-debrebase %s'", $sc), @_;
83 my ($k, $optional) = @_;
85 my @cmd = qw(git config -z);
86 push @cmd, qw(--get-all) if wantarray;
88 my $out = cmdoutput_errok @cmd;
90 fail f_ "missing required git config %s", $k unless $optional;
93 my @l = split /\0/, $out;
94 return wantarray ? @l : $l[0];
101 my $dd = new Data::Dumper [ $v ];
102 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
108 my $data = (git_cat_file $objid, 'commit');
109 $data =~ m/(?<=\n)\n/ or confess "$objid ($data) ?";
113 sub D_UPS () { 0x02; } # upstream files
114 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
115 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
116 sub D_DEB_CLOG () { 0x10; } # debian/changelog
117 sub D_DEB_OTH () { 0x20; } # debian/ (not patches/ or changelog)
118 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
120 our $playprefix = 'debrebase';
124 our @dgit = qw(dgit);
126 sub in_workarea ($) {
129 my $r = eval { $sub->(); };
130 { local $@; changedir $maindir; }
134 sub fresh_workarea (;$) {
137 $workarea = fresh_playground "$playprefix/$subdir";
138 in_workarea sub { playtree_setup };
141 sub run_ref_updates_now ($$) {
142 my ($mrest, $updates) = @_;
143 # @$updates is a list of lines for git-update-ref, without \ns
145 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
146 debugcmd '>|', @upd_cmd;
147 open U, "|-", @upd_cmd or confess "$!";
148 foreach (@$updates) {
149 printdebug ">= ", $_, "\n";
150 print U $_, "\n" or confess "$!";
153 close U or failedcmd @upd_cmd;
156 our $snags_forced = 0;
157 our $snags_tripped = 0;
158 our $snags_summarised = 0;
159 our @deferred_updates;
160 our @deferred_update_messages;
162 sub merge_wreckage_cleaning ($) {
164 git_for_each_ref("$wrecknoteprefix/*", sub {
165 my ($objid,$objtype,$fullrefname,$reftail) = @_;
166 push @$updates, "delete $fullrefname";
170 sub all_snags_summarised () {
171 $snags_forced + $snags_tripped == $snags_summarised;
173 sub run_deferred_updates ($) {
176 my $m = 'dangerous internal error';
177 confess $m.' - '.__ $m unless all_snags_summarised();
179 merge_wreckage_cleaning \@deferred_updates;
180 run_ref_updates_now $mrest, \@deferred_updates;
181 print $_, "\n" foreach @deferred_update_messages;
183 @deferred_updates = ();
184 @deferred_update_messages = ();
187 sub get_tree ($;$$) {
188 # tree object name => ([ $name, $info ], ...)
189 # where $name is the sort key, ie has / at end for subtrees
190 # $info is the LHS from git-ls-tree (<mode> <type> <hash>)
191 # without $precheck, will crash if $x does not exist, so don't do that;
192 # instead pass '' to get ().
193 my ($x, $precheck, $recurse) = @_;
195 return () if !length $x;
198 my ($type, $dummy) = git_cat_file $x, [qw(tree missing)];
199 return () if $type eq 'missing';
202 $recurse = !!$recurse;
204 confess "get_tree needs object not $x ?" unless $x =~ m{^[0-9a-f]+\:};
206 our (@get_tree_memo, %get_tree_memo);
207 my $memo = $get_tree_memo{$recurse,$x};
208 return @$memo if $memo;
210 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
212 my @cmd = (qw(git ls-tree -z --full-tree));
213 push @cmd, qw(-r) if $recurse;
214 push @cmd, qw(--), $x;
215 my $o = cmdoutput @cmd;
218 foreach my $l (split /\0/, $o) {
219 my ($i, $n) = split /\t/, $l, 2;
220 $n .= '/' if $i =~ m/^\d+ tree /;
222 confess "$x need $last < $n ?" unless $last lt $n;
224 $get_tree_memo{$recurse,$x} = \@l;
225 push @get_tree_memo, $x;
226 if (@get_tree_memo > 10) {
227 delete $get_tree_memo{ shift @get_tree_memo };
232 sub trees_diff_walk ($$$;$) {
233 # trees_diff_walk [{..opts...},] $x, $y, sub {... }
234 # calls sub->($name, $ix, $iy) for each difference
235 # $x and $y are as for get_tree
236 # where $name, $ix, $iy are $name and $info from get_tree
237 # opts are all call even for names same in both
238 # recurse call even for names same in both
239 my $opts = shift @_ if @_>=4;
240 my ($x,$y,$call) = @_;
241 my $all = $opts->{all};
242 return if !$all and $x eq $y;
243 my @x = get_tree $x, 0, $opts->{recurse};
244 my @y = get_tree $y, 0, $opts->{recurse};
245 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
248 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
249 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
250 my ($n, $ix, $iy); # all same? $cmp=0, use both
252 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
254 ($n, $ix) = @{ shift @x } if $cmp <= 0;
255 ($n, $iy) = @{ shift @y } if $cmp >= 0;
256 next if !$all and $ix eq $iy;
258 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
259 !!$all,$x,$y, $n,$ix,$iy
261 $call->($n, $ix, $iy);
265 sub get_differs ($$) {
267 # This does a similar job to quiltify_trees_differ, in dgit, a bit.
268 # But we don't care about modes, or dpkg-source-unrepresentable
269 # changes, and we don't need the plethora of different modes.
270 # Conversely we need to distinguish different kinds of changes to
271 # debian/ and debian/patches/.
272 # Also, here we have, and want to use, trees_diff_walk, because
273 # we may be calling this an awful lot and we want it to be fast.
278 no warnings qw(exiting);
280 my $plain = sub { $_[0] =~ m{^(100|0*)644 blob }s; };
282 trees_diff_walk "$x:", "$y:", sub {
283 my ($n,$ix,$iy) = @_;
285 # analyse difference at the toplevel
287 if ($n ne 'debian/') {
291 if ($n eq 'debian') {
292 # one side has a non-tree for ./debian !
293 $differs |= D_DEB_OTH;
297 my $xd = $ix && "$x:debian";
298 my $yd = $iy && "$y:debian";
299 trees_diff_walk $xd, $yd, sub {
300 my ($n,$ix,$iy) = @_;
302 # analyse difference in debian/
304 if ($n eq 'changelog' && (!$ix || $plain->($ix))
306 $differs |= D_DEB_CLOG;
309 if ($n ne 'patches/') {
310 $differs |= D_DEB_OTH;
314 my $xp = $ix && "$xd/patches";
315 my $yp = $iy && "$yd/patches";
316 trees_diff_walk { recurse=>1 }, $xp, $yp, sub {
317 my ($n,$ix,$iy) = @_;
319 # analyse difference in debian/patches
323 # we are recursing; directories may appear and disappear
325 } elsif ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
327 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
328 my $x_s = (git_cat_file "$xp/series", 'blob');
329 my $y_s = (git_cat_file "$yp/series", 'blob');
330 chomp $x_s; $x_s .= "\n";
331 $ok = $x_s eq substr($y_s, 0, length $x_s);
335 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
340 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
345 sub commit_pr_info ($) {
347 return Data::Dumper->dump([$r], [qw(commit)]);
350 sub calculate_committer_authline () {
351 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
352 'DUMMY COMMIT (git-debrebase)', "HEAD:";
353 my ($h,$m) = get_commit $c;
354 $h =~ m/^committer .*$/m or confess "($h) ?";
358 our @snag_force_opts;
360 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
361 if (grep { $_ eq $tag } @snag_force_opts) {
363 print STDERR f_ "%s: snag ignored (-f%s): %s\n", $us, $tag, $msg;
366 print STDERR f_ "%s: snag detected (-f%s): %s\n", $us, $tag, $msg;
370 # Important: all mainline code must call snags_maybe_bail after
371 # any point where snag might be called, but before making changes
372 # (eg before any call to run_deferred_updates). snags_maybe_bail
373 # may be called more than once if necessary (but this is not ideal
374 # because then the messages about number of snags may be confusing).
375 sub snags_maybe_bail () {
376 return if all_snags_summarised();
379 "%s: snags: %d overriden by individual -f options\n",
382 if ($snags_tripped) {
385 "%s: snags: %d overriden by global --force\n",
389 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
393 $snags_summarised = $snags_forced + $snags_tripped;
395 sub snags_maybe_bail_early () {
396 # useful to bail out early without doing a lot of work;
397 # not a substitute for snags_maybe_bail.
398 snags_maybe_bail() if $snags_tripped && !$opt_force;
401 return $snags_forced || $snags_tripped;
404 sub ffq_prev_branchinfo () {
405 my $current = git_get_symref();
406 return gdr_ffq_prev_branchinfo($current);
409 sub record_gdrlast ($$;$) {
410 my ($gdrlast, $newvalue, $oldvalue) = @_;
411 $oldvalue ||= $git_null_obj;
412 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
415 sub fail_unprocessable ($) {
418 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
420 my $mangled = __ <<END;
421 Branch/history seems mangled - no longer in gdr format.
422 See ILLEGAL OPERATIONS in git-debrebase(5).
427 fail f_ <<END, $msg, $ffqm;
429 Is this meant to be a gdr branch? %s
431 } elsif (git_get_ref $ffq_prev) {
432 fail f_ <<END, $msg, $mangled;
435 Consider git-debrebase scrap, to throw away your recent work.
437 } elsif (!git_get_ref $gdrlast) {
440 Branch does not seem to be meant to be a git-debrebase branch?
441 Wrong branch, or maybe you needed git-debrebase convert-from-*.
443 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
451 Branch/history mangled, and diverged since last git-debrebase.
452 Maybe you reset to, or rebased from, somewhere inappropriate.
457 sub gbp_pq_export ($$$) {
458 my ($bname, $base, $tip) = @_;
459 # must be run in a workarea. $bname and patch-queue/$bname
460 # ought not to exist. Leaves you on patch-queue/$bname with
461 # the patches staged but not committed.
462 # returns 1 if there were any patches
463 printdebug "gbp_pq_export $bname $base $tip\n";
464 runcmd @git, qw(checkout -q -b), $bname, $base;
465 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
466 my @gbp_cmd = (qw(gbp pq export));
467 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
469 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
472 return 0 unless stat_exists 'debian/patches';
473 runcmd @git, qw(add -f debian/patches);
478 # MERGE-TODO allow merge resolution separately from laundering, before git merge
481 # use git-format-patch?
482 # our own patch identification algorithm?
483 # this is an alternative strategy
485 sub merge_failed ($$;@) {
486 my ($wrecknotes, $emsg, @xmsgs) = @_;
488 push @m, "Merge resolution failed: $emsg";
494 merge_wreckage_cleaning \@updates;
495 run_ref_updates_now "merge failed", \@updates;
499 while (my ($k,$v) = each %$wrecknotes) {
500 push @updates, "create $wrecknoteprefix/$k $v";
502 run_ref_updates_now "merge failed", \@updates;
503 push @m, "Wreckage left in $wrecknoteprefix/*.";
505 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
507 # use finish rather than fail, in case we are within an eval
508 # (that can happen inside walk!)
510 print STDERR "$us: $_\n" foreach @m;
514 sub mwrecknote ($$$) {
515 my ($wrecknotes, $reftail, $commitish) = @_;
516 confess unless defined $commitish;
517 printdebug "mwrecknote $reftail $commitish\n";
518 $wrecknotes->{$reftail} = $commitish;
521 sub merge_attempt_cmd {
522 my $wrecknotes = shift @_;
526 merge_failed $wrecknotes,
527 failedcmd_waitstatus(),
528 "failed command: @_";
532 sub merge_series_patchqueue_convert ($$$);
534 sub merge_series ($$$;@) {
535 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
536 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
537 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
538 # ^ specifies several patch series (currently we only support exactly 2)
539 # return value is a commit which is the result of
540 # merging the two versions of the same topic branch
541 # $input_q[0] and $input_q[1]
542 # with respect to the old version
546 # Creates, in *_q, a key MR for its private use
548 printdebug "merge_series newbase=$newbase\n";
550 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
551 $base_q->{MR}{S} = 'base';
554 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
555 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
556 # $prereq{<patch filename>} exists or not (even later)
560 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
562 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
565 fresh_workarea "merge";
566 my $seriesfile = "debian/patches/series";
569 foreach my $q ($base_q, reverse @input_qs) {
571 my $any = gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
574 open S, $seriesfile or confess "$seriesfile $!";
575 while (my $patch = <S>) {
576 chomp $patch or confess "$!";
577 $prereq{$patch} //= {};
578 foreach my $earlier (@earlier) {
579 $prereq{$patch}{$earlier}{$s}++ and confess;
581 push @earlier, $patch;
582 stat "debian/patches/$patch" or confess "$patch ?";
584 S->error and confess "$seriesfile $!";
587 read_tree_upstream $newbase, 1;
588 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
589 "Convert $s to patch queue for merging",
590 "[git-debrebase merge-innards patch-queue import:".
593 printdebug "merge_series pec $pec ";
594 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
595 $pec = make_commit [ $pec ], [
596 "Drop series file from $s to avoid merge trouble",
597 "[git-debrebase merge-innards patch-queue prep:".
601 read_tree_debian $newbase;
603 read_tree_subdir 'debian/patches', "$pec:debian/patches";
605 rm_subdir_cached 'debian/patches';
607 $pec = make_commit [ $pec ], [
608 "Update debian/ (excluding patches) to final to avoid re-merging",
609 "debian/ was already merged and we need to just take that.",
610 "[git-debrebase merge-innards patch-queue packaging:".
614 printdebug "pec' $pec\n";
615 runcmd @git, qw(reset -q --hard), $pec;
616 $q->{MR}{PEC} = $pec;
617 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
619 # now, because of reverse, we are on $input_q->{MR}{OQC}
620 runcmd @git, qw(checkout -q -b merge);
621 printdebug "merge_series merging...\n";
622 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
624 $attempt_cmd->(@mergecmd);
626 printdebug "merge_series merge ok, series...\n";
627 # We need to construct a new series file
628 # Firstly, resolve prereq
629 foreach my $f (sort keys %prereq) {
630 printdebug "merge_series patch\t$f\t";
631 if (!stat_exists "debian/patches/$f") {
632 print DEBUG " drop\n" if $debuglevel;
633 # git merge deleted it; that's how we tell it's not wanted
637 print DEBUG " keep\n" if $debuglevel;
638 foreach my $g (sort keys %{ $prereq{$f} }) {
639 my $gfp = $prereq{$f}{$g};
640 printdebug "merge_series prereq\t$f\t-> $g\t";
641 if (!!$gfp->{0} == !!$gfp->{1}
644 print DEBUG "\tkeep\n" if $debuglevel;
646 print DEBUG "\tdrop\n" if $debuglevel;
647 delete $prereq{$f}{$g};
654 return scalar keys %{ $prereq{$f} };
657 my $nodate = time + 1;
659 # $authordate{<patch filename>};
660 my $authordate = sub {
662 $authordate{$f} //= do {
663 open PF, "<", "debian/patches/$f" or confess "$f $!";
665 return $nodate if m/^$/;
666 last if s{^Date: }{};
669 return cmdoutput qw(date +%s -d), $_;
673 open NS, '>', $seriesfile or confess "$!";
675 while (keys %prereq) {
677 foreach my $try (sort keys %prereq) {
680 $unsat->($try) <=> $unsat->($best) or
681 $authordate->($try) <=> $authordate->($best) or
687 printdebug "merge_series series next $best\n";
688 print NS "$best\n" or confess "$!";
689 delete $prereq{$best};
690 foreach my $gp (values %prereq) {
695 runcmd @git, qw(add), $seriesfile;
696 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
697 $merged_pq = git_rev_parse 'HEAD';
698 $mwrecknote->('merged-patchqueue', $merged_pq);
700 return merge_series_patchqueue_convert
701 $wrecknotes, $newbase, $merged_pq;
704 sub merge_series_patchqueue_convert ($$$) {
705 my ($wrecknotes, $newbase, $merged_pq) = @_;
710 printdebug "merge_series series gbp pq import\n";
711 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
713 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
714 # MERGE-TODO consider git-format-patch etc. instead,
715 # since gbp pq doesn't always round-trip :-/
717 # OK now we are on patch-queue/merge, and we need to rebase
718 # onto the intended parent and drop the patches from each one
720 printdebug "merge_series series ok, building...\n";
721 my $build = $newbase;
722 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
723 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
724 my $commit = git_cat_file $c, 'commit';
725 printdebug "merge_series series ok, building $c\n";
726 read_tree_upstream $c, 0, $newbase;
727 my $tree = cmdoutput @git, qw(write-tree);
728 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
729 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
730 open C, ">", "../mcommit" or confess "$!";
731 print C $commit or confess "$!";
732 close C or confess "$!";
733 $build = hash_commit '../mcommit';
736 mwrecknote($wrecknotes, 'merged-result', $result);
738 runcmd @git, qw(update-ref refs/heads/result), $result;
740 runcmd @git, qw(checkout -q -b debug);
741 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
742 runcmd @git, qw(add .);
743 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
744 my $mdebug = git_rev_parse 'HEAD';
745 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
746 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
748 printdebug "merge_series returns $result\n";
752 # classify returns an info hash like this
754 # Hdr => # commit headers, including 1 final newline
755 # Msg => # commit message (so one newline is dropped)
757 # Type => (see below)
759 # Ix => $index # ie 0, 1, 2, ...
761 # Differs => return value from get_differs
763 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
765 # NewMsg => # commit message, but with any [dgit import ...] edited
766 # # to say "[was: ...]"
776 # has additional entres in classification result
777 # Overwritten = [ subset of Parents ]
778 # Contributor = $the_remaining_Parent
780 # DgitImportUnpatched
781 # has additional entry in classification result
782 # OrigParents = [ subset of Parents ]
785 # has additional entry in classification result
786 # OrigParents = [ subset of Parents ] # singleton list
793 # has additional entry in classification result
796 sub parsecommit ($;$) {
797 my ($objid, $p_ref) = @_;
798 # => hash with CommitId Hdr Msg Tree Parents
799 # Parents entries have only Ix CommitId
800 # $p_ref, if provided, must be [] and is used as a base for Parents
805 my ($h,$m) = get_commit $objid;
807 my ($t) = $h =~ m/^tree (\w+)$/m or confess $objid;
808 my (@ph) = $h =~ m/^parent (\w+)$/mg;
818 foreach my $ph (@ph) {
820 Ix => scalar @$p_ref,
832 my $r = parsecommit($objid, \@p);
836 $p->{Differs} = (get_differs $p->{CommitId}, $t),
839 printdebug "classify $objid \$t=$t \@p",
840 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
844 my ($type, @rest) = @_;
845 $r = { %$r, Type => $type, @rest };
847 printdebug " = $type ".(dd $r)."\n";
853 $r = { %$r, Type => qw(Unknown), Why => $why };
854 printdebug " ** Unknown\n";
858 if (grep { $_ eq $objid } @opt_anchors) {
859 return $classify->('TreatAsAnchor');
862 my @identical = grep { !$_->{Differs} } @p;
863 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
864 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
866 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
867 # multi-orig upstreams are represented with an anchor merge
868 # from a single upstream commit which combines the orig tarballs
870 # Every anchor tagged this way must be a merge.
871 # We are relying on the
872 # [git-debrebase anchor: ...]
873 # commit message annotation in "declare" anchor merges (which
874 # do not have any upstream changes), to distinguish those
875 # anchor merges from ordinary pseudomerges (which we might
876 # just try to strip).
878 # However, the user is going to be doing git-rebase a lot. We
879 # really don't want them to rewrite an anchor commit.
880 # git-rebase trips up on merges, so that is a useful safety
883 # BreakwaterStart commits are also anchors in the terminology
884 # of git-debrebase(5), but they are untagged (and always
885 # manually generated).
887 # We cannot not tolerate any tagged linear commit (ie,
888 # BreakwaterStart commits tagged `[anchor:') because such a
889 # thing could result from an erroneous linearising raw git
890 # rebase of a merge anchor. That would represent a corruption
891 # of the branch. and we want to detect and reject the results
892 # of such corruption before it makes it out anywhere. If we
893 # reject it here then we avoid making the pseudomerge which
894 # would be needed to push it.
896 my $badanchor = sub {
897 $unknown->(f_ "git-debrebase \`anchor' but %s", "@_");
899 @p == 2 or return $badanchor->(__ "has other than two parents");
900 $haspatches and return $badanchor->(__ "contains debian/patches");
902 # How to decide about l/r ordering of anchors ? git
903 # --topo-order prefers to expand 2nd parent first. There's
904 # already an easy rune to look for debian/ history anyway (git log
905 # debian/) so debian breakwater branch should be 1st parent; that
906 # way also there's also an easy rune to look for the upstream
907 # patches (--topo-order).
909 # Also this makes --first-parent be slightly more likely to
910 # be useful - it makes it provide a linearised breakwater history.
912 # Of course one can say somthing like
913 # gitk -- ':/' ':!/debian'
914 # to get _just_ the commits touching upstream files, and by
915 # the TREESAME logic in git-rev-list this will leave the
916 # breakwater into upstream at the first anchor. But that
917 # doesn't report debian/ changes at all.
919 # Other observations about gitk: by default, gitk seems to
920 # produce output in a different order to git-rev-list. I
921 # can't seem to find this documented anywhere. gitk
922 # --date-order DTRT. But, gitk always seems to put the
923 # parents from left to right, in order, so it's easy to see
924 # which way round a pseudomerge is.
926 $p[0]{IsOrigin} and $badanchor->(__ "is an origin commit");
927 $p[1]{Differs} & ~DS_DEB and
928 $badanchor->(__ "upstream files differ from left parent");
929 $p[0]{Differs} & ~D_UPS and
930 $badanchor->(__ "debian/ differs from right parent");
932 return $classify->(qw(Anchor),
933 OrigParents => [ $p[1] ]);
937 my $d = $r->{Parents}[0]{Differs};
938 if ($d == D_PAT_ADD) {
939 return $classify->(qw(AddPatches));
940 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
941 return $unknown->(__ "edits debian/patches");
942 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
943 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
945 if ($d == D_DEB_CLOG) {
946 return $classify->(qw(Changelog));
948 return $classify->(qw(Packaging));
950 } elsif ($ty eq 'missing') {
951 return $classify->(qw(BreakwaterStart));
953 return $unknown->(__ "parent's debian is not a directory");
955 } elsif ($d == D_UPS) {
956 return $classify->(qw(Upstream));
957 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
958 return $classify->(qw(Mixed));
960 return $unknown->(__ "no changes");
962 confess "internal error $objid ?";
966 return $unknown->(__ "origin commit");
969 if (@p == 2 && @identical == 1) {
970 my @overwritten = grep { $_->{Differs} } @p;
971 confess "internal error $objid ?" unless @overwritten==1;
972 return $classify->(qw(Pseudomerge),
973 Overwritten => [ $overwritten[0] ],
974 Contributor => $identical[0]);
976 if (@p == 2 && @identical == 2) {
978 my ($ph,$pm) = get_commit $_[0]{CommitId};
979 $ph =~ m/^committer .* (\d+) [-+]\d+$/m
980 or confess "$_->{CommitId} ?";
984 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
985 if ($order > 0) { # newer first
986 } elsif ($order < 0) {
987 @bytime = reverse @bytime;
989 # same age, default to order made by -s ours
990 # that is, commit was made by someone who preferred L
992 return $classify->(qw(Pseudomerge),
993 SubType => qw(Ambiguous),
994 Contributor => $bytime[0],
995 Overwritten => [ $bytime[1] ]);
998 my ($p_h, $p_m) = get_commit $p->{CommitId};
999 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1000 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1002 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1004 if (!(grep { !$_->{IsOrigin} } @p) and
1005 (@orig_ps >= @p - 1) and
1006 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1008 return $classify->(qw(DgitImportUnpatched),
1009 OrigParents => \@orig_ps);
1013 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1014 return $classify->("MergedBreakwaters");
1016 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1017 return $unknown->(f_ "unknown kind of merge from %s", $1);
1020 return $unknown->(__ "octopus merge");
1024 return $unknown->(__ "general two-parent merge");
1027 return $classify->("VanillaMerge");
1030 sub keycommits ($;$$$$$);
1032 sub mergedbreakwaters_anchor ($) {
1035 foreach my $p (@{ $cl->{Parents} }) {
1036 my ($panchor, $pbw) = keycommits $p->{CommitId},
1037 undef,undef,undef,undef, 1;
1038 $best_anchor = $panchor
1039 if !defined $best_anchor
1040 or is_fast_fwd $best_anchor, $panchor;
1041 fail f_ "inconsistent anchors in merged-breakwaters %s",
1043 unless is_fast_fwd $panchor, $best_anchor;
1045 return $best_anchor;
1048 sub keycommits ($;$$$$$) {
1049 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1050 # => ($anchor, $breakwater)
1052 # $furniture->("unclean-$tagsfx", $msg, $cl)
1053 # $unclean->("unclean-$tagsfx", $msg, $cl)
1054 # is callled for each situation or commit that
1055 # wouldn't be found in a laundered branch
1056 # $furniture is for furniture commits such as might be found on an
1057 # interchange branch (pseudomerge, d/patches, changelog)
1058 # $trouble is for things whnich prevent the return of
1059 # anchor and breakwater information; if that is ignored,
1060 # then keycommits returns (undef, undef) instead.
1061 # $fatal is for unprocessable commits, and should normally cause
1062 # a failure. If ignored, agaion, (undef, undef) is returned.
1064 # If $claimed_bw, this is supposed to be a breakwater commit.
1066 # If a callback is undef, fail is called instead.
1067 # If a callback is defined but false, the situation is ignored.
1068 # Callbacks may say:
1069 # no warnings qw(exiting); last;
1070 # if the answer is no longer wanted.
1072 my ($anchor, $breakwater);
1073 $breakwater = $head if $claimed_bw;
1077 $fatal //= sub { fail_unprocessable $_[1]; };
1079 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1080 my $why = $mainwhy.$xwhy;
1081 my $m = f_ "branch needs laundering (run git-debrebase): %s", $why;
1082 fail $m unless defined $cb;
1084 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1086 my $found_anchor = sub {
1088 $breakwater //= $clogonly;
1089 $breakwater //= $head;
1090 no warnings qw(exiting);
1094 $cl = classify $head;
1095 my $ty = $cl->{Type};
1096 if ($ty eq 'Packaging') {
1097 $breakwater //= $clogonly;
1098 $breakwater //= $head;
1099 } elsif ($ty eq 'Changelog') {
1100 # this is going to count as the tip of the breakwater
1101 # only if it has no upstream stuff before it
1102 $clogonly //= $head;
1103 } elsif ($ty eq 'Anchor' or
1104 $ty eq 'TreatAsAnchor' or
1105 $ty eq 'BreakwaterStart') {
1106 $found_anchor->($head);
1107 } elsif ($ty eq 'Upstream') {
1108 $x->($unclean, 'ordering',
1109 (f_ "packaging change (%s) follows upstream change", $breakwater),
1110 (f_ " (eg %s)", $head))
1111 if defined $breakwater;
1113 $breakwater = undef;
1114 } elsif ($ty eq 'Mixed') {
1115 $x->($unclean, 'mixed',
1116 (__ "found mixed upstream/packaging commit"),
1117 (f_ " (%s)", $head));
1119 $breakwater = undef;
1120 } elsif ($ty eq 'Pseudomerge' or
1121 $ty eq 'AddPatches') {
1123 $x->($furniture, (lc $ty),
1124 (f_ "found interchange bureaucracy commit (%s)", $ty),
1125 (f_ " (%s)", $head));
1126 } elsif ($ty eq 'DgitImportUnpatched') {
1128 $x->($trouble, 'dgitimport',
1129 (__ "found dgit dsc import"),
1130 (f_ " (%s)", $head));
1131 return (undef,undef);
1133 $x->($fatal, 'unprocessable',
1134 (__ "found bare dgit dsc import with no prior history"),
1135 (f_ " (%s)", $head));
1136 return (undef,undef);
1138 } elsif ($ty eq 'VanillaMerge') {
1139 $x->($trouble, 'vanillamerge',
1140 (__ "found vanilla merge"),
1141 (f_ " (%s)", $head));
1142 return (undef,undef);
1143 } elsif ($ty eq 'MergedBreakwaters') {
1144 $found_anchor->(mergedbreakwaters_anchor $cl);
1146 $x->($fatal, 'unprocessable',
1147 (f_ "found unprocessable commit, cannot cope: %s",
1149 (f_ " (%s)", $head));
1150 return (undef,undef);
1152 $head = $cl->{Parents}[0]{CommitId};
1154 return ($anchor, $breakwater);
1160 $nogenerate,$report, $report_lprefix) = @_;
1161 # => ($tip, $breakwater_tip, $last_anchor)
1162 # (or nothing, if $nogenerate)
1164 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1165 $report_lprefix //= '';
1167 # go through commits backwards
1168 # we generate two lists of commits to apply:
1169 # breakwater branch and upstream patches
1170 my (@brw_cl, @upp_cl, @processed);
1177 my ($prose, $info) = @_;
1178 # We deliberately do not translate $prose, since this mostly
1179 # appears in commits in Debian and they should be in English.
1180 my $ms = $cl->{Msg};
1182 confess unless defined $info;
1183 $ms .= "\n\n[git-debrebase $info: $prose]\n";
1184 return (Msg => $ms);
1186 my $rewrite_from_here = sub {
1188 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1190 push @processed, $sp_cl;
1195 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1198 return unless $report;
1199 print $report $prdelim, $report_lprefix, @_;
1203 my $bomb = sub { # usage: return $bomb->();
1204 print $report " Unprocessable" if $report;
1205 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1208 return (undef,undef);
1212 map { sprintf "%#x", $_->{Differs} }
1213 @{ $cl->{Parents} };
1214 fail_unprocessable f_ +(defined $cl->{Why}
1215 ? i_ 'found unprocessable commit, cannot cope; %3$s: (commit %1$s) (d.%2$s)'
1216 : i_ 'found unprocessable commit, cannot cope: (commit %1$s) (d.%2$s)'),
1217 $cur, $d, $cl->{Why};
1223 my $build_start = sub {
1224 my ($msg, $parent) = @_;
1227 no warnings qw(exiting); last;
1232 merge_failed $cl->{MergeWreckNotes}, $emsg;
1235 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1240 $cl = classify $cur;
1241 $cl->{MergeWreckNotes} //= {};
1242 my $ty = $cl->{Type};
1243 my $st = $cl->{SubType};
1244 $prline->("$cl->{CommitId} $cl->{Type}");
1245 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1246 push @processed, $cl;
1247 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1248 if ($ty eq 'AddPatches') {
1250 $rewrite_from_here->(\@upp_cl);
1252 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1256 } elsif ($ty eq 'BreakwaterStart') {
1257 $last_anchor = $cur;
1258 $build_start->('FirstPackaging', $cur);
1259 } elsif ($ty eq 'Upstream') {
1263 } elsif ($ty eq 'Mixed') {
1266 my $cls = { %$cl, $xmsg->("mixed commit: $wh part",'split') };
1269 $queue->(\@brw_cl, "debian");
1270 $queue->(\@upp_cl, "upstream");
1271 $rewrite_from_here->(\@brw_cl);
1274 } elsif ($ty eq 'Pseudomerge') {
1275 my $contrib = $cl->{Contributor}{CommitId};
1276 print $report " Contributor=$contrib" if $report;
1277 push @pseudomerges, $cl;
1278 $rewrite_from_here->(\@upp_cl);
1281 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1282 $last_anchor = $cur;
1283 $build_start->("Anchor", $cur);
1284 } elsif ($ty eq 'DgitImportUnpatched') {
1285 my $pm = $pseudomerges[-1];
1287 # To an extent, this is heuristic. Imports don't have
1288 # a useful history of the debian/ branch. We assume
1289 # that the first pseudomerge after an import has a
1290 # useful history of debian/, and ignore the histories
1291 # from later pseudomerges. Often the first pseudomerge
1292 # will be the dgit import of the upload to the actual
1293 # suite intended by the non-dgit NMUer, and later
1294 # pseudomerges may represent in-archive copies.
1295 my $ovwrs = $pm->{Overwritten};
1296 printf $report " PM=%s \@Overwr:%d",
1297 $pm->{CommitId}, (scalar @$ovwrs)
1300 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1303 my $ovwr = $ovwrs->[0]{CommitId};
1304 printf $report " Overwr=%s", $ovwr if $report;
1305 # This import has a tree which is just like a
1306 # breakwater tree, but it has the wrong history. It
1307 # ought to have the previous breakwater (which the
1308 # pseudomerge overwrote) as an ancestor. That will
1309 # make the history of the debian/ files correct. As
1310 # for the upstream version: either it's the same as
1311 # was ovewritten (ie, same as the previous
1312 # breakwater), in which case that history is precisely
1313 # right; or, otherwise, it was a non-gitish upload of a
1314 # new upstream version. We can tell these apart by
1315 # looking at the tree of the supposed upstream.
1318 SpecialMethod => 'DgitImportDebianUpdate',
1319 $xmsg->("debian changes", 'convert dgit import')
1322 SpecialMethod => 'DgitImportUpstreamUpdate',
1323 $xmsg->("convert dgit import: upstream update",
1326 $prline->(" Import");
1327 $rewrite_from_here->(\@brw_cl);
1328 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1332 # Everything is from this import. This kind of import
1333 # is already nearly in valid breakwater format, with the
1334 # patches as commits. Unfortunately it contains
1336 printdebug "*** WALK BOMB bare dgit import\n";
1337 $cl->{Why} = __ "bare dgit dsc import";
1341 } elsif ($ty eq 'MergedBreakwaters') {
1342 $last_anchor = mergedbreakwaters_anchor $cl;
1343 $build_start->(' MergedBreakwaters', $cur);
1345 } elsif ($ty eq 'VanillaMerge') {
1346 # User may have merged unstitched branch(es). We will
1347 # have now lost what ffq-prev was then (since the later
1348 # pseudomerge may introduce further changes). The effect
1349 # of resolving such a merge is that we may have to go back
1350 # further in history to find a merge base, since the one
1351 # which was reachable via ffq-prev is no longer findable.
1352 # This is suboptimal, but if it all works we'll have done
1354 # MERGE-TODO we should warn the user in the docs about this
1358 # We expect to find a dominating anchor amongst the
1359 # inputs' anchors. That will be the new anchor.
1361 # More complicated is finding a merge base for the
1362 # breakwaters. We need a merge base that is a breakwater
1363 # commit. The ancestors of breakwater commits are more
1364 # breakwater commits and possibly upstream commits and the
1365 # ancestors of those upstream. Upstreams might have
1366 # arbitrary ancestors. But any upstream commit U is
1367 # either included in both anchors, in which case the
1368 # earlier anchor is a better merge base than any of U's
1369 # ancestors; or U is not included in the older anchor, in
1370 # which case U is not an ancestor of the vanilla merge at
1371 # all. So no upstream commit, nor any ancestor thereof,
1372 # is a best merge base. As for non-breakwater Debian
1373 # commits: these are never ancestors of any breakwater.
1375 # So any best merge base as found by git-merge-base
1376 # is a suitable breakwater anchor. Usually there will
1379 printdebug "*** MERGE\n";
1381 my @bwbcmd = (@git, qw(merge-base));
1382 my @ibcmd = (@git, qw(merge-base --all));
1383 my $might_be_in_bw = 1;
1385 my $ps = $cl->{Parents};
1387 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1389 foreach my $p (@$ps) {
1390 $prline->(" VanillaMerge ".$p->{Ix});
1392 my ($ptip, $pbw, $panchor) =
1393 walk $p->{CommitId}, 0, $report,
1394 $report_lprefix.' ';
1395 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1396 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1397 $p->{Anchor} = $panchor;
1399 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1400 $mwrecknote->("$lr-input", $p->{CommitId});
1402 my $mwrecknote_parent = sub {
1404 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1406 $mwrecknote_parent->('Laundered');
1407 $mwrecknote_parent->('Breakwater');
1408 $mwrecknote_parent->('Anchor');
1410 $best_anchor = $panchor if
1411 !defined $best_anchor or
1412 is_fast_fwd $best_anchor, $panchor;
1414 printdebug " MERGE BA best=".($best_anchor//'-').
1418 $mwrecknote->('result-anchor', $best_anchor);
1420 foreach my $p (@$ps) {
1421 $prline->(" VanillaMerge ".$p->{Ix});
1422 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1423 $nomerge->('divergent anchors');
1424 } elsif ($p->{Anchor} eq $best_anchor) {
1425 print $report " SameAnchor" if $report;
1427 print $report " SupersededAnchor" if $report;
1429 if ($p->{Breakwater} eq $p->{CommitId}) {
1430 # this parent commit was its own breakwater,
1431 # ie it is part of the breakwater
1432 print $report " Breakwater" if $report;
1434 $might_be_in_bw = 0;
1436 push @bwbcmd, $p->{Breakwater};
1437 push @ibcmd, $p->{CommitId};
1440 if ($ok && $might_be_in_bw) {
1441 # We could rewrite this to contaion the metadata
1442 # declaring it to be MergedBreakwaters, but
1443 # unnecessarily rewriting a merge seems unhelpful.
1444 $prline->(" VanillaMerge MergedBreakwaters");
1445 $last_anchor = $best_anchor;
1446 $build_start->('MergedBreakwaters', $cur);
1449 my $bwb = cmdoutput @bwbcmd;
1451 # OK, now we have a breakwater base, but we need the merge
1452 # base for the interchange branch because we need the delta
1455 # This a the best merge base of our inputs which has the
1456 # breakwater merge base as an ancestor.
1463 @ibs or confess 'internal error, expected anchor at least ?';
1467 foreach my $tibix (0..$#ibs) {
1468 my $tib = $ibs[$tibix];
1469 my $ff = is_fast_fwd $bwb, $tib;
1470 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1471 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1472 $mwrecknote->($tibleaf, $tib);
1479 $ib or $nomerge->("no suitable interchange merge base");
1481 $prline->(" VanillaMerge Base");
1483 my ($btip, $bbw, $banchor) = eval {
1484 walk $ib, 0, $report, $report_lprefix.' ';
1486 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1490 $mwrecknote->("mergebase-laundered", $btip);
1491 $mwrecknote->("mergebase-breakwater", $bbw);
1492 $mwrecknote->("mergebase-anchor", $banchor);
1494 my $ibinfo = { SeriesTip => $btip,
1497 LeftRight => 'mergebase' };
1500 or $nomerge->("interchange merge-base ($ib)'s".
1501 " breakwater ($bbw)".
1502 " != breakwaters' merge-base ($bwb)");
1504 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1505 or $nomerge->("interchange merge-base ($ib)'s".
1506 " anchor ($ibinfo->{SeriesBase})".
1507 " != any merge input's anchor (".
1508 (join ' ', map { $_->{Anchor} } @$ps).
1511 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1512 $cl->{MergeBestAnchor} = $best_anchor;
1515 SpecialMethod => 'MergeCreateMergedBreakwaters',
1516 $xmsg->('constructed from vanilla merge',
1517 'merged-breakwater'),
1521 SpecialMethod => 'MergeMergeSeries',
1523 $build_start->('MergeBreakwaters', $cur);
1525 printdebug "*** WALK BOMB unrecognised\n";
1531 printdebug "*** WALK prep done cur=$cur".
1532 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1534 return if $nogenerate;
1536 # Now we build it back up again
1542 $#upp_cl = $upp_limit if defined $upp_limit;
1544 my $committer_authline = calculate_committer_authline();
1546 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1548 confess __ "internal error" unless $build eq (pop @processed)->{CommitId};
1551 mkdir $rd or $!==EEXIST or confess "$!";
1553 my $want_debian = $build;
1554 my $want_upstream = $build;
1556 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1557 my $read_tree_debian = sub { ($want_debian) = @_; };
1559 foreach my $cl (qw(Debian), (reverse @brw_cl),
1560 { SpecialMethod => 'RecordBreakwaterTip' },
1561 qw(Upstream), (reverse @upp_cl)) {
1563 $current_method = $cl;
1566 my $method = $cl->{SpecialMethod} // $current_method;
1567 my @parents = ($build);
1568 my $cltree = $cl->{CommitId};
1569 printdebug "WALK BUILD ".($cltree//'undef').
1570 " $method (rewriting=$rewriting)\n";
1571 if ($method eq 'Debian') {
1572 $read_tree_debian->($cltree);
1573 } elsif ($method eq 'Upstream') {
1574 $read_tree_upstream->($cltree);
1575 } elsif ($method eq 'StartRewrite') {
1578 } elsif ($method eq 'RecordBreakwaterTip') {
1579 $breakwater = $build;
1581 } elsif ($method eq 'DgitImportDebianUpdate') {
1582 $read_tree_debian->($cltree);
1583 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1584 confess unless $rewriting;
1585 my $differs = (get_differs $build, $cltree);
1586 next unless $differs & D_UPS;
1587 $read_tree_upstream->($cltree);
1588 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1589 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1590 print "Found a general merge, will try to tidy it up.\n";
1592 $read_tree_upstream->($cl->{MergeBestAnchor});
1593 $read_tree_debian->($cltree);
1594 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1595 } elsif ($method eq 'MergeMergeSeries') {
1596 my $cachehit = reflog_cache_lookup
1597 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1599 print "Using supplied resolution for $cl->{CommitId}...\n";
1601 $mwrecknote->('cached-resolution', $build);
1603 print "Running merge resolution for $cl->{CommitId}...\n";
1604 $mwrecknote->('new-base', $build);
1605 $build = merge_series
1606 $build, $cl->{MergeWreckNotes},
1607 $cl->{MergeInterchangeBaseInfo},
1608 @{ $cl->{Parents} };
1610 $last_anchor = $cl->{MergeBestAnchor};
1612 # Check for mismerges:
1614 my ($against, $allow, $what) = @_;
1615 my $differs = get_differs $build, $against;
1617 "merge misresolved: %s are not the same (%s %s d.%#x)",
1618 $what, $against, $build, $differs)
1619 if $differs & ~($allow | D_PAT_ADD);
1622 # Breakwater changes which were in each side of the
1623 # merge will have been incorporated into the
1624 # MergeCreateMergedBreakwaters output. Because the
1625 # upstream series was rebased onto the new breakwater,
1626 # so should all of the packaging changes which were in
1628 $check->($input, D_UPS, 'debian files');
1630 # Upstream files are merge_series, which ought to
1631 # have been identical to the original merge.
1632 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1634 print "Merge resolution successful.\n";
1637 confess "$method ?";
1640 my $procd = (pop @processed) // 'UNDEF';
1641 if ($cl ne $procd) {
1643 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1647 read_tree_upstream $want_upstream, 0, $want_debian;
1649 my $newtree = cmdoutput @git, qw(write-tree);
1650 my $ch = $cl->{Hdr};
1651 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1652 $ch =~ s{^parent .*\n}{}mg;
1653 $ch =~ s{(?=^author)}{
1654 join '', map { "parent $_\n" } @parents
1655 }me or confess "$ch ?";
1657 $ch =~ s{^committer .*$}{$committer_authline}m
1660 my $cf = "$rd/m$rewriting";
1661 open CD, ">", $cf or confess "$!";
1662 print CD $ch, "\n", $cl->{Msg} or confess "$!";
1663 close CD or confess "$!";
1664 my @cmd = (@git, qw(hash-object));
1665 push @cmd, qw(-w) if $rewriting;
1666 push @cmd, qw(-t commit), $cf;
1667 my $newcommit = cmdoutput @cmd;
1668 confess "$ch ?" unless $rewriting
1669 or $newcommit eq $cl->{CommitId};
1670 $build = $newcommit;
1672 $build = $cl->{CommitId};
1673 trees_diff_walk "$want_upstream:", "$build:", sub {
1675 no warnings qw(exiting);
1676 next if $n eq 'debian/';
1677 confess f_ "mismatch %s ?", "@_";
1679 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1680 confess f_ "mismatch %s ?", "@_";
1682 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1683 confess f_ "mismatch %s != %s ?", "@parents", "@old_parents"
1684 unless "@parents" eq "@old_parents";
1686 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1687 $last_anchor = $cur;
1692 my $final_check = get_differs $build, $input;
1693 confess f_ "internal error %#x %s %s", $final_check, $input, $build
1694 if $final_check & ~D_PAT_ADD;
1696 my @r = ($build, $breakwater, $last_anchor);
1697 printdebug "*** WALK RETURN @r\n";
1702 git_check_unmodified();
1703 return git_rev_parse qw(HEAD);
1706 sub update_head ($$$) {
1707 my ($old, $new, $mrest) = @_;
1708 push @deferred_updates, "update HEAD $new $old";
1709 run_deferred_updates $mrest;
1712 sub update_head_checkout ($$$) {
1713 my ($old, $new, $mrest) = @_;
1714 update_head $old, $new, $mrest;
1715 runcmd @git, qw(reset --hard);
1718 sub update_head_postlaunder ($$$) {
1719 my ($old, $tip, $reflogmsg) = @_;
1720 return if $tip eq $old && !@deferred_updates;
1721 print f_ "%s: laundered (head was %s)\n", $us, $old;
1722 update_head $old, $tip, $reflogmsg;
1723 # no tree changes except debian/patches
1724 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1727 sub currently_rebasing() {
1728 foreach (qw(rebase-merge rebase-apply)) {
1729 return 1 if stat_exists "$maindir_gitdir/$_";
1734 sub bail_if_rebasing() {
1735 fail __ "you are in the middle of a git-rebase already"
1736 if currently_rebasing();
1739 sub do_launder_head ($) {
1740 my ($reflogmsg) = @_;
1741 my $old = get_head();
1743 my ($tip,$breakwater) = walk $old;
1745 update_head_postlaunder $old, $tip, $reflogmsg;
1746 return ($tip,$breakwater);
1749 sub cmd_launder_v0 () {
1750 badusage "no arguments to launder-v0 allowed" if @ARGV;
1751 my $old = get_head();
1752 my ($tip,$breakwater,$last_anchor) = walk $old;
1753 update_head_postlaunder $old, $tip, 'launder';
1754 printf "# breakwater tip\n%s\n", $breakwater;
1755 printf "# working tip\n%s\n", $tip;
1756 printf "# last anchor\n%s\n", $last_anchor;
1759 sub defaultcmd_rebase () {
1760 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1761 my ($tip,$breakwater) = do_launder_head __ 'launder for rebase';
1762 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1765 sub cmd_analyse () {
1766 badusage __ "analyse does not support any options"
1767 if @ARGV and $ARGV[0] =~ m/^-/;
1768 badusage __ "too many arguments to analyse" if @ARGV>1;
1771 $old = git_rev_parse $old;
1773 $old = git_rev_parse 'HEAD';
1775 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1776 STDOUT->error and confess "$!";
1779 sub ffq_check ($;$$) {
1780 # calls $ff and/or $notff zero or more times
1781 # then returns either (status,message) where status is
1786 # or (undef,undef, $ffq_prev,$gdrlast)
1787 # $ff and $notff are called like this:
1788 # $ff->("message for stdout\n");
1789 # $notff->('snag-name', $message);
1790 # normally $currentval should be HEAD
1791 my ($currentval, $ff, $notff) =@_;
1793 $ff //= sub { print $_[0] or confess "$!"; };
1796 my ($status, $message, $current, $ffq_prev, $gdrlast)
1797 = ffq_prev_branchinfo();
1798 return ($status, $message) unless $status eq 'branch';
1800 my $exists = git_get_ref $ffq_prev;
1801 return ('exists', f_ "%s already exists", $ffq_prev) if $exists;
1803 return ('not-branch', __ 'HEAD symref is not to refs/heads/')
1804 unless $current =~ m{^refs/heads/};
1807 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1810 printdebug "ffq check_specs @check_specs\n";
1813 my ($lrref, $desc) = @_;
1814 printdebug "ffq might check $lrref ($desc)\n";
1816 for my $chk (@check_specs) {
1818 $invert = $glob =~ s{^[!^]}{};
1819 last if fnmatch $glob, $lrref;
1822 my $lrval = git_get_ref $lrref;
1823 return unless length $lrval;
1825 if (is_fast_fwd $lrval, $currentval) {
1826 $ff->(f_ "OK, you are ahead of %s\n", $lrref);
1827 $checked{$lrref} = 1;
1828 } elsif (is_fast_fwd $currentval, $lrval) {
1829 $checked{$lrref} = -1;
1830 $notff->('behind', f_ "you are behind %s, divergence risk",
1833 $checked{$lrref} = -1;
1834 $notff->('diverged', f_ "you have diverged from %s", $lrref);
1838 my $merge = cfg "branch.$branch.merge",1;
1839 if (defined $merge and $merge =~ m{^refs/heads/}) {
1841 printdebug "ffq merge $rhs\n";
1842 my $check_remote = sub {
1843 my ($remote, $desc) = @_;
1844 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1845 return unless defined $remote;
1846 $check->("refs/remotes/$remote/$rhs", $desc);
1848 $check_remote->((scalar cfg "branch.$branch.remote",1),
1849 'remote fetch/merge branch');
1850 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1851 (scalar cfg "branch.$branch.pushDefault",1),
1852 'remote push branch');
1854 if ($branch =~ m{^dgit/}) {
1855 $check->("refs/remotes/dgit/$branch",
1856 __ 'remote dgit branch');
1857 } elsif ($branch =~ m{^master$}) {
1858 $check->("refs/remotes/dgit/dgit/sid",
1859 __ 'remote dgit branch for sid');
1861 return (undef, undef, $ffq_prev, $gdrlast);
1864 sub record_ffq_prev_deferred () {
1865 # => ('status', "message")
1867 # deferred message is undef
1872 # if not ff from some branch we should be ff from, is an snag
1873 # if "deferred", will have added something about that to
1874 # @deferred_update_messages, and also maybe printed (already)
1875 # some messages about ff checks
1877 my $currentval = get_head();
1879 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1880 return ($status,$message) if defined $status;
1884 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1885 push @deferred_updates, "delete $gdrlast";
1886 push @deferred_update_messages,
1887 __ "Recorded previous head for preservation";
1888 return ('deferred', undef);
1891 sub record_ffq_auto () {
1892 my ($status, $message) = record_ffq_prev_deferred();
1893 if ($status eq 'deferred' || $status eq 'exists') {
1895 snag $status, f_ "could not record ffq-prev: %s", $message;
1900 sub ffq_prev_info () {
1902 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1903 my ($status, $message, $current, $ffq_prev, $gdrlast)
1904 = ffq_prev_branchinfo();
1905 if ($status ne 'branch') {
1906 snag $status, f_ "could not check ffq-prev: %s", $message;
1909 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1910 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1913 sub stitch ($$$$$) {
1914 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1916 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1918 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1919 my $differs = get_differs $old_head, $ffq_prev_commitish;
1920 unless ($differs & ~D_PAT_ADD) {
1921 # ffq-prev is ahead of us, and the only tree changes it has
1922 # are possibly addition of things in debian/patches/.
1923 # Just wind forwards rather than making a pointless pseudomerge.
1924 record_gdrlast $gdrlast, $ffq_prev_commitish;
1925 update_head_checkout $old_head, $ffq_prev_commitish,
1926 sprintf "stitch (%s)", __ 'fast forward';
1931 # We make pseudomerges with L as the contributing parent.
1932 # This makes git rev-list --first-parent work properly.
1933 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1934 # we translate this against the time when this same code is
1935 # used outside Debian, for downstreams and users
1936 (__ 'Declare fast forward / record previous work'),
1937 "[git-debrebase pseudomerge: $prose]",
1939 record_gdrlast $gdrlast, $new_head;
1940 update_head $old_head, $new_head, "stitch: $prose";
1943 sub do_stitch ($;$) {
1944 my ($prose, $unclean) = @_;
1946 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1947 if (!$ffq_prev_commitish) {
1948 fail __ "No ffq-prev to stitch." unless $opt_noop_ok;
1951 my $dangling_head = get_head();
1953 keycommits $dangling_head, $unclean,$unclean,$unclean;
1956 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1959 sub cmd_new_upstream () {
1960 # automatically and unconditionally launders before rebasing
1961 # if rebase --abort is used, laundering has still been done
1965 badusage __ "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1967 # parse args - low commitment
1968 my $spec_version = shift @ARGV;
1969 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1970 fail f_ "bad version number \`%s'", $spec_version
1971 unless defined $new_version;
1972 if ($new_version->is_native()) {
1973 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1976 my $new_upstream = shift @ARGV;
1977 my $new_upstream_version = upstreamversion $new_version;
1978 my $new_upstream_used;
1979 ($new_upstream, $new_upstream_used) =
1980 resolve_upstream_version $new_upstream, $new_upstream_version;
1985 my ($n, @x) = @_; # may be ''
1986 my $pc = $pieces{$n} //= {
1988 Desc => ($n ? (f_ "upstream piece \`%s'", $n)
1989 : (__ "upstream (main piece")),
1991 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1996 my $newpiece = sub {
1997 my ($n, @x) = @_; # may be ''
1998 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1999 push @newpieces, $pc;
2004 New => $new_upstream,
2006 while (@ARGV && $ARGV[0] !~ m{^-}) {
2007 my $n = shift @ARGV;
2009 badusage __ "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2010 unless @ARGV && $ARGV[0] !~ m{^-};
2012 my $c = git_rev_parse shift @ARGV;
2013 confess unless $n =~ m/^$extra_orig_namepart_re$/;
2014 $newpiece->($n, New => $c);
2017 # now we need to investigate the branch this generates the
2018 # laundered version but we don't switch to it yet
2019 my $old_head = get_head();
2020 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2022 my $old_bw_cl = classify $old_bw;
2023 my $old_anchor_cl = classify $old_anchor;
2025 if (!$old_anchor_cl->{OrigParents}) {
2026 snag 'anchor-treated',
2027 __ 'old anchor is recognised due to --anchor, cannot check upstream';
2029 $old_upstream = parsecommit
2030 $old_anchor_cl->{OrigParents}[0]{CommitId};
2031 $piece->('', Old => $old_upstream->{CommitId});
2034 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2035 if ($old_upstream->{Msg} =~
2036 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2038 my @oldpieces = (split / /, $1);
2039 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2040 if ($old_n_parents != @oldpieces &&
2041 $old_n_parents != @oldpieces + 1) {
2042 snag 'upstream-confusing', f_
2043 "previous upstream combine %s".
2044 " mentions %d pieces (each implying one parent)".
2045 " but has %d parents".
2046 " (one per piece plus maybe a previous combine)",
2047 $old_upstream->{CommitId},
2048 (scalar @oldpieces),
2050 } elsif ($oldpieces[0] ne '.') {
2051 snag 'upstream-confusing', f_
2052 "previous upstream combine %s".
2053 " first piece is not \`.'",
2057 foreach my $i (0..$#oldpieces) {
2058 my $n = $oldpieces[$i];
2059 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2060 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2064 snag 'upstream-confusing', f_
2065 "previous upstream %s is from".
2066 " git-debrebase but not an \`upstream-combine' commit",
2067 $old_upstream->{CommitId};
2071 foreach my $pc (values %pieces) {
2072 if (!$old_upstream) {
2073 # we have complained already
2074 } elsif (!$pc->{Old}) {
2075 snag 'upstream-new-piece',
2076 f_ "introducing upstream piece \`%s'", $pc->{Name};
2077 } elsif (!$pc->{New}) {
2078 snag 'upstream-rm-piece',
2079 f_ "dropping upstream piece \`%s'", $pc->{Name};
2080 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2081 snag 'upstream-not-ff',
2082 f_ "not fast forward: %s %s",
2083 $pc->{Name}, "$pc->{Old}..$pc->{New}";
2087 printdebug "%pieces = ", (dd \%pieces), "\n";
2088 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2096 my @upstream_merge_parents;
2099 push @upstream_merge_parents, $old_upstream->{CommitId};
2102 foreach my $pc (@newpieces) { # always has '' first
2104 read_tree_subdir $pc->{Name}, $pc->{New};
2106 runcmd @git, qw(read-tree), $pc->{New};
2108 push @upstream_merge_parents, $pc->{New};
2111 # index now contains the new upstream
2113 if (@newpieces > 1) {
2114 # need to make the upstream subtree merge commit
2115 $new_upstream = make_commit \@upstream_merge_parents,
2116 [ "Combine upstreams for $new_upstream_version",
2117 ("[git-debrebase upstream-combine . ".
2118 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2123 # $new_upstream is either the single upstream commit, or the
2124 # combined commit we just made. Either way it will be the
2125 # "upstream" parent of the anchor merge.
2127 read_tree_subdir 'debian', "$old_bw:debian";
2129 # index now contains the anchor merge contents
2130 $new_bw = make_commit [ $old_bw, $new_upstream ],
2131 [ "Update to upstream $new_upstream_version",
2132 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2135 # Now we have to add a changelog stanza so the Debian version
2136 # is right. We use debchange to do this. Invoking debchange
2137 # here is a bit fiddly because it has a lot of optional
2138 # exciting behaviours, some of which will break stuff, and
2139 # some of which won't work in a playtree.
2141 # Make debchange use git's idea of the user's identity.
2142 # That way, if the user never uses debchange et al, configuring
2147 defined $v or return;
2150 $usetup->('DEBEMAIL', 'user.email');
2151 $usetup->('DEBFULLNAME', 'user.name');
2153 my @dch = (qw(debchange
2154 --allow-lower-version .*
2157 --vendor=Unknown-Vendor
2158 --changelog debian/changelog
2159 --check-dirname-level 0
2160 --release-heuristic=changelog
2162 "Update to new upstream version $new_upstream_version.");
2164 runcmd @git, qw(checkout -q debian/changelog);
2166 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2168 # Now we have the final new breakwater branch in the index
2169 $new_bw = make_commit [ $new_bw ],
2170 [ "Update changelog for new upstream $new_upstream_version",
2171 "[git-debrebase changelog: new upstream $new_upstream_version]",
2175 # we have constructed the new breakwater. we now need to commit to
2176 # the laundering output, because git-rebase can't easily be made
2177 # to make a replay list which is based on some other branch
2179 update_head_postlaunder $old_head, $old_laundered_tip,
2180 'launder for new upstream';
2182 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2183 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2184 "debrebase new-upstream $new_version: rebase";
2186 # now it's for the user to sort out
2189 sub cmd_record_ffq_prev () {
2190 badusage "no arguments allowed" if @ARGV;
2191 my ($status, $msg) = record_ffq_prev_deferred();
2192 if ($status eq 'exists' && $opt_noop_ok) {
2193 print __ "Previous head already recorded\n" or confess "$!";
2194 } elsif ($status eq 'deferred') {
2195 run_deferred_updates 'record-ffq-prev';
2197 fail f_ "Could not preserve: %s", $msg;
2202 badusage __ "no arguments allowed" if @ARGV;
2203 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2204 print "$anchor\n" or confess "$!";
2207 sub cmd_breakwater () {
2208 badusage __ "no arguments allowed" if @ARGV;
2209 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2210 print "$bw\n" or confess "$!";
2214 badusage __ "no arguments allowed" if @ARGV;
2216 # todo: gdr status should print divergence info
2217 # todo: gdr status should print upstream component(s) info
2218 # todo: gdr should leave/maintain some refs with this kind of info ?
2220 my $oldest = { Badness => 0 };
2223 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2224 if ($oldest->{Badness} < $badness) {
2225 $oldest = $newest = undef;
2228 Badness => $badness,
2229 CommitId => $cl->{CommitId},
2233 $newest //= $oldest;
2235 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2236 sub { $note->(1, __ 'branch contains furniture (not laundered)',@_); },
2237 sub { $note->(2, __ 'branch is unlaundered', @_); },
2238 sub { $note->(3, __ 'branch needs laundering', @_); },
2239 sub { $note->(4, __ 'branch not in git-debrebase form', @_); };
2241 my $prcommitinfo = sub {
2243 flush STDOUT or confess "$!";
2244 runcmd @git, qw(--no-pager log -n1),
2245 '--pretty=format: %h %s%n',
2249 print __ "current branch contents, in git-debrebase terms:\n";
2250 if (!$oldest->{Badness}) {
2251 print __ " branch is laundered\n";
2253 print " $oldest->{OurMsg}\n";
2255 foreach my $info ($oldest, $newest) {
2256 my $cid = $info->{CommitId};
2257 next if $cid eq $printed;
2259 print " $info->{KcMsg}\n";
2260 $prcommitinfo->($cid);
2265 my ($cid, $what) = @_;
2266 if (!defined $cid) {
2267 print f_ " %s is not well-defined\n", $what;
2270 $prcommitinfo->($cid);
2273 print __ "key git-debrebase commits:\n";
2274 $prab->($anchor, __ 'anchor');
2275 $prab->($bw, __ 'breakwater');
2277 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2278 ffq_prev_branchinfo();
2280 print __ "branch and ref status, in git-debrebase terms:\n";
2282 print " $ffq_msg\n";
2284 $ffq_prev = git_get_ref $ffq_prev;
2285 $gdrlast = git_get_ref $gdrlast;
2287 print __ " unstitched; previous tip was:\n";
2288 $prcommitinfo->($ffq_prev);
2289 } elsif (!$gdrlast) {
2290 print __ " stitched? (no record of git-debrebase work)\n";
2291 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2292 print __ " stitched\n";
2294 print __ " not git-debrebase (diverged since last stitch)\n"
2297 print __ "you are currently rebasing\n" if currently_rebasing();
2301 my $prose = 'stitch';
2302 getoptions("stitch",
2303 'prose=s', \$prose);
2304 badusage __ "no arguments allowed" if @ARGV;
2305 do_stitch $prose, 0;
2307 sub cmd_prepush () {
2313 badusage __ "no arguments allowed" if @ARGV;
2314 do_launder_head __ 'launder for git-debrebase quick';
2318 sub cmd_conclude () {
2319 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2320 if (!$ffq_prev_commitish) {
2321 fail __ "No ongoing git-debrebase session." unless $opt_noop_ok;
2324 my $dangling_head = get_head();
2326 badusage "no arguments allowed" if @ARGV;
2327 do_launder_head __ 'launder for git-debrebase quick';
2332 if (currently_rebasing()) {
2333 runcmd @git, qw(rebase --abort);
2334 push @deferred_updates, 'verify HEAD HEAD';
2335 # noop, but stops us complaining that scrap was a noop
2337 badusage __ "no arguments allowed" if @ARGV;
2338 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2340 if ($ffq_prev_commitish) {
2341 $scrapping_head = get_head();
2342 push @deferred_updates,
2343 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2344 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2346 if (git_get_ref $merge_cache_ref) {
2347 push @deferred_updates,
2348 "delete $merge_cache_ref";
2350 if (!@deferred_updates) {
2351 fail __ "No ongoing git-debrebase session." unless $opt_noop_ok;
2355 if ($scrapping_head) {
2356 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2358 run_deferred_updates "scrap";
2362 sub make_patches_staged ($) {
2364 # Produces the patches that would result from $head if it were
2366 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2370 $any = gbp_pq_export 'bw', $secret_bw, $secret_head;
2375 sub make_patches ($) {
2377 keycommits $head, 0, \&snag;
2378 my $any = make_patches_staged $head;
2381 my $ptree = !$any ? undef :
2382 cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2383 runcmd @git, qw(read-tree), $head;
2385 read_tree_subdir 'debian/patches', $ptree;
2387 rm_subdir_cached 'debian/patches';
2389 $out = make_commit [$head], [
2390 (__ 'Commit patch queue (exported by git-debrebase)'),
2391 '[git-debrebase make-patches: export and commit patches]',
2397 sub cmd_make_patches () {
2398 my $opt_quiet_would_amend;
2399 getoptions("make-patches",
2400 'quiet-would-amend!', \$opt_quiet_would_amend);
2401 badusage __ "no arguments allowed" if @ARGV;
2403 my $old_head = get_head();
2404 my $new = make_patches $old_head;
2405 my $d = get_differs $old_head, $new;
2407 fail __ "No (more) patches to export." unless $opt_noop_ok;
2409 } elsif ($d == D_PAT_ADD) {
2411 update_head_checkout $old_head, $new, 'make-patches';
2413 print STDERR failmsg f_
2414 "Patch export produced patch amendments".
2415 " (abandoned output commit %s).".
2416 " Try laundering first.",
2418 unless $opt_quiet_would_amend;
2423 sub check_series_has_all_patches ($) {
2425 my $seriesfn = 'debian/patches/series';
2426 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2430 our $comments_snagged;
2431 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2432 if ($f =~ m/^\s*\#/) {
2433 snag 'series-comments', f_
2434 "%s contains comments, which will be discarded",
2436 unless $comments_snagged++;
2439 fail f_ "patch %s repeated in %s !", $f, $seriesfn if $series{$f}++;
2441 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2442 my ($f,$i) = @$patchfile;
2443 next if $series{$f};
2444 next if $f eq 'series';
2445 snag 'unused-patches', f_
2446 "Unused patch file %s will be discarded", $f;
2450 sub begin_convert_from () {
2451 my $head = get_head();
2452 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2454 fail __ "ffq-prev exists, this is already managed by git-debrebase!"
2455 if $ffq_prev && git_get_ref $ffq_prev;
2457 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2458 snag 'already-converted', __
2459 "ahead of debrebase-last, this is already managed by git-debrebase!"
2460 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2461 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2464 sub complete_convert_from ($$$$) {
2465 my ($old_head, $new_head, $gi, $mrest) = @_;
2466 ffq_check $new_head;
2467 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2470 update_head_checkout $old_head, $new_head, $mrest;
2473 sub cmd_convert_from_unapplied () { cmd_convert_from_gbp(); }
2474 sub cmd_convert_from_gbp () {
2475 badusage __ "want only 1 optional argument, the upstream git commitish"
2478 my $clogp = parsechangelog();
2479 my $version = $clogp->{'Version'}
2480 // fail __ "missing Version from changelog\n";
2482 my ($upstream_spec) = @ARGV;
2484 my $upstream_version = upstreamversion $version;
2485 my ($upstream, $upstream_used) =
2486 resolve_upstream_version($upstream_spec, $upstream_version);
2488 my ($old_head, $gdrlastinfo) = begin_convert_from();
2490 my $upsdiff = get_differs $upstream, $old_head;
2491 if ($upsdiff & D_UPS) {
2492 runcmd @git, qw(--no-pager diff --stat),
2493 $upstream, $old_head,
2494 qw( -- :!/debian :/);
2495 fail f_ <<END, $upstream_used, $upstream;
2496 upstream (%s) and HEAD are not
2497 identical in upstream files. See diffstat above, or run
2498 git diff %s HEAD -- :!/debian :/
2502 if (!is_fast_fwd $upstream, $old_head) {
2503 snag 'upstream-not-ancestor',
2504 f_ "upstream (%s) is not an ancestor of HEAD", $upstream;
2506 my $wrong = cmdoutput
2507 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2508 qw(-- :/ :!/debian));
2509 if (length $wrong) {
2510 snag 'unexpected-upstream-changes', f_
2511 "history between upstream (%s) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?",
2513 print STDERR f_ "list expected changes with: %s\n",
2514 "git log --stat --ancestry-path $upstream..HEAD -- :/ ':!/debian'";
2518 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2519 snag 'upstream-has-debian',
2520 f_ "upstream (%s) contains debian/ directory", $upstream;
2523 check_series_has_all_patches $old_head;
2525 my $previous_dgit_view = eval {
2526 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2528 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2529 my ($stz, $desc) = @_;
2530 no warnings qw(exiting);
2531 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2532 next unless $stz->{Date};
2533 next unless $stz->{Distribution} ne 'UNRELEASED';
2534 $lvsn = $stz->{Version};
2535 $suite = $stz->{Distribution};
2538 die __ "neither of the first two changelog entries are released\n"
2539 unless defined $lvsn;
2540 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2541 my $mtag_pat = debiantag_maintview $lvsn, '*';
2542 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2544 die f_ "could not find suitable maintainer view tag %s\n", $mtag_pat
2545 unless $mtag =~ m{/};
2546 is_fast_fwd $mtag, 'HEAD' or
2547 die f_ "HEAD is not FF from maintainer tag %s!", $mtag;
2548 my $dtag = "archive/$mtag";
2549 git_get_ref "refs/tags/$dtag" or
2550 die f_ "dgit view tag %s not found\n", $dtag;
2551 is_fast_fwd $mtag, $dtag or
2552 die f_ "dgit view tag %s is not FF from maintainer tag %s\n",
2554 print f_ "will stitch in dgit view, %s\n", $dtag;
2555 git_rev_parse $dtag;
2557 if (!$previous_dgit_view) {
2560 print STDERR f_ <<END, "$@";
2561 Cannot confirm dgit view: %s
2562 Failed to stitch in dgit view (see messages above).
2563 dgit --overwrite will be needed on the first dgit push after conversion.
2567 snags_maybe_bail_early();
2573 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2574 # make a branch out of the patch queue - we'll want this in a mo
2575 runcmd qw(gbp pq import);
2576 # strip the patches out
2577 runcmd @git, qw(checkout -q gdr-internal~0);
2578 rm_subdir_cached 'debian/patches';
2579 $work = make_commit ['HEAD'], [
2580 'git-debrebase convert-from-gbp: drop patches from tree',
2581 'Delete debian/patches, as part of converting to git-debrebase format.',
2582 '[git-debrebase convert-from-gbp: drop patches from tree]'
2584 # make the anchor merge
2585 # the tree is already exactly right
2586 $work = make_commit [$work, $upstream], [
2587 'git-debrebase import: declare upstream',
2588 'First breakwater merge.',
2589 '[git-debrebase anchor: declare upstream]'
2592 # rebase the patch queue onto the new breakwater
2593 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2594 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2595 $work = git_rev_parse 'HEAD';
2597 if ($previous_dgit_view) {
2598 $work = make_commit [$work, $previous_dgit_view], [
2599 'git-debrebase import: declare ff from dgit archive view',
2600 '[git-debrebase pseudomerge: import-from-gbp]',
2605 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2606 print f_ <<END, $us or confess "$!";
2607 %s: converted from patched-unapplied (gbp) branch format, OK
2611 sub cmd_convert_to_gbp () {
2612 badusage "no arguments allowed" if @ARGV;
2613 my $head = get_head();
2614 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2615 my ($anchor, $breakwater) = keycommits $head, 0;
2616 my $out = $breakwater;
2617 my $any = make_patches_staged $head;
2620 $out = make_commit [$out], [
2621 'Commit patch queue (converted from git-debrebase format)',
2622 '[git-debrebase convert-to-gbp: commit patches]',
2626 # in this case, it can be fast forward
2630 push @deferred_updates, "delete $ffq";
2631 push @deferred_updates, "delete $gdrlast";
2634 update_head_checkout $head, $out, "convert to gbp (v0)";
2635 print f_ <<END, $us,$us,$us or confess "$!";
2636 %s: converted to git-buildpackage branch format
2637 %s: WARNING: do not now run "git-debrebase" any more
2638 %s: WARNING: doing so would drop all upstream patches!
2642 sub cmd_convert_from_dgit_view () {
2643 my $clogp = parsechangelog();
2645 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2651 getoptions("convert-from-dgit-view",
2652 'diagnose!', \$diagnose,
2653 'build-products-dir:s', \$bpd,
2654 'origs!', \$do_origs,
2656 'always-convert-anyway!', \$always);
2657 fail __ "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2662 my $spec = shift @ARGV;
2663 my $commit = git_rev_parse "$spec^{commit}";
2664 push @upstreams, { Commit => $commit,
2665 Source => (f_ "%s, from command line", $spec),
2670 my ($head, $gdrlastinfo) = begin_convert_from();
2674 my $trouble = sub { $troubles++; };
2675 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2676 printdebug "troubles=$troubles\n";
2678 print STDERR f_ <<END, $us,$us,$us;
2679 %s: Branch already seems to be in git-debrebase format!
2680 %s: --always-convert-anyway would do the conversion operation anyway
2681 %s: but is probably a bad idea. Probably, you wanted to do nothing.
2683 fail __ "Branch already in git-debrebase format."
2684 unless $opt_noop_ok;
2689 check_series_has_all_patches $head;
2691 snags_maybe_bail_early();
2693 my $version = upstreamversion $clogp->{Version};
2695 "Considering possible commits corresponding to upstream:\n";
2700 my ($ups_tag, $ups_rev) =
2701 upstream_commitish_search $version, \@tried;
2703 my $this = f_ "git tag %s", $ups_tag;
2704 push @upstreams, { Commit => $ups_rev,
2709 " git tag: no suitable tag found (tried %s)\n",
2714 my $p = $clogp->{'Source'};
2715 # we do a quick check to see if there are plausible origs
2717 if (!opendir BPD, $bpd) {
2718 die f_ "opendir build-products-dir %s: %s", $bpd, $!
2721 while ($!=0, my $f = readdir BPD) {
2722 next unless is_orig_file_of_p_v $f, $p, $version;
2724 " orig: found what looks like a .orig, %s\n",
2729 confess "read $bpd: $!" if $!;
2733 my $tree = cmdoutput
2734 @dgit, qw(--build-products-dir), $bpd,
2735 qw(print-unapplied-treeish);
2738 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2739 rm_subdir_cached 'debian';
2740 $tree = cmdoutput @git, qw(write-tree);
2741 my $ups_synth = make_commit [], [ <<END, <<END,
2742 Import effective orig tree for upstream version $version
2744 This includes the contents of the .orig(s), minus any debian/ directory.
2746 [git-debrebase convert-from-dgit-view upstream-import-convert: $version]
2749 push @upstreams, { Commit => $ups_synth,
2750 Source => "orig(s) imported via dgit",
2755 " orig: no suitable origs found (looked for %s in %s)\n",
2756 "${p}_".(stripeoch $version)."...", $bpd;
2761 my $some_patches = stat_exists 'debian/patches/series';
2764 "Evaluating possible commits corresponding to upstream:\n";
2767 foreach my $u (@upstreams) {
2771 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2772 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2773 runcmd @git, qw(clean -xdff);
2774 runcmd @git, qw(checkout), $head, qw(-- debian);
2775 if ($some_patches) {
2776 rm_subdir_cached 'debian/patches';
2777 $work = make_commit [ $work ], [
2778 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2779 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2780 "to git-debrebase format. Upstream changes will appear as commits.",
2781 '[git-debrebase convert-from-dgit-view drop-patches]'
2784 $work = make_commit [ $work, $u->{Commit} ], [
2785 'git-debrebase convert-from-dgit-view: declare upstream',
2786 '(Re)constructed breakwater merge.',
2787 '[git-debrebase anchor: declare upstream]'
2789 runcmd @git, qw(checkout --quiet -b mk), $work;
2790 if ($some_patches) {
2791 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2792 runcmd @git, qw(reset --quiet);
2793 my @gbp_cmd = (qw(gbp pq import));
2795 my $gbp_err = "../gbp-pq-err";
2796 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2798 my $r = system @gbp_cmd;
2801 " %s: couldn't apply patches: gbp pq %s",
2802 $u->{Source}, waitstatusmsg();
2806 my $work = git_rev_parse qw(HEAD);
2807 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2808 if (length $diffout) {
2810 " %s: applying patches gives different tree\n",
2812 print STDERR $diffout if $diagnose;
2816 $u->{Result} = $work;
2824 Could not find or construct a suitable upstream commit.
2825 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2826 upstream commmit explicitly or provide suitable origs.
2830 print STDERR f_ "Yes, will base new branch on %s\n", $result->{Source};
2832 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2833 'convert-from-dgit-view';
2836 sub cmd_forget_was_ever_debrebase () {
2837 badusage __ "forget-was-ever-debrebase takes no further arguments"
2839 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2840 ffq_prev_branchinfo();
2841 fail f_ "Not suitable for recording git-debrebaseness anyway: %s",
2843 if defined $ffq_msg;
2844 push @deferred_updates, "delete $ffq_prev";
2845 push @deferred_updates, "delete $gdrlast";
2847 run_deferred_updates "forget-was-ever-debrebase";
2850 sub cmd_record_resolved_merge () {
2851 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2852 # MERGE-TODO needs documentation
2853 my $new = get_head();
2856 print "Checking how you have resolved the merge problem\n";
2857 my $nope = sub { print "Not $method: @_"; 0; };
2859 my $maybe = sub { print "Seems to be $method.\n"; };
2861 my ($key, $ref) = @_;
2862 reflog_cache_insert $merge_cache_ref, $key, $ref;
2863 print "OK. You can switch branches and try git-debrebase again.\n";
2867 fresh_workarea 'merge';
2869 $method = 'vanilla-merge patchqueue';
2870 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2871 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2872 foreach my $lr (qw(left right)) {
2873 my $n = "$wrecknoteprefix/$lr-patchqueue";
2874 my $lrpq = git_get_ref $n;
2875 $lrpq or return $nope->("wreckage did not contain patchqueues");
2876 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2879 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2880 or die "wreckage element $wrecknoteprefix/new-base missing";
2881 my $result = merge_series_patchqueue_convert
2883 $yes->("vanilla-merge $vanilla", $result);
2886 fail "No resolved merge method seems applicable.\n";
2890 sub cmd_downstream_rebase_launder_v0 () {
2891 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2893 $base = git_rev_parse $base;
2894 my $old_head = get_head();
2895 my $current = $old_head;
2898 if ($current eq $base) {
2899 $topmost_keep //= $current;
2900 print " $current BASE stop\n";
2903 my $cl = classify $current;
2904 print " $current $cl->{Type}";
2906 my $p0 = $cl->{Parents}[0]{CommitId};
2908 if ($cl->{Type} eq 'Pseudomerge') {
2909 print " ^".($cl->{Contributor}{Ix}+1);
2910 $next = $cl->{Contributor}{CommitId};
2911 } elsif ($cl->{Type} eq 'AddPatches' or
2912 $cl->{Type} eq 'Changelog') {
2922 $topmost_keep //= $current;
2924 die "to-be stripped changes not on top of the branch\n"
2929 if ($topmost_keep eq $old_head) {
2930 print "unchanged\n";
2932 print "updating to $topmost_keep\n";
2933 update_head_checkout
2934 $old_head, $topmost_keep,
2935 'downstream-rebase-launder-v0';
2939 setlocale(LC_MESSAGES, "");
2940 textdomain("git-debrebase");
2943 (__ "bad options\n",
2944 "D+" => \$debuglevel,
2945 'noop-ok', => \$opt_noop_ok,
2946 'f=s' => \@snag_force_opts,
2947 'anchor=s' => \@opt_anchors,
2948 '--dgit=s' => \($dgit[0]),
2950 'experimental-merge-resolution!', \$opt_merges,
2952 my ($opt,$val) = @_;
2953 badusage f_ "%s: no cuddling to -i for git-rebase", $us
2955 confess if $opt_defaultcmd_interactive; # should not happen
2956 $opt_defaultcmd_interactive = [ qw(-i) ];
2957 # This access to @ARGV is excessive familiarity with
2958 # Getopt::Long, but there isn't another sensible
2959 # approach. '-i=s{0,}' does not work with bundling.
2960 push @$opt_defaultcmd_interactive, @ARGV;
2963 'help' => sub { print __ $usage_message or confess "$!"; finish 0; },
2966 initdebug('git-debrebase ');
2967 enabledebug if $debuglevel;
2969 changedir_git_toplevel();
2971 $rd = fresh_playground "$playprefix/misc";
2973 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2975 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2976 defaultcmd_rebase();
2978 my $cmd = shift @ARGV;
2981 $cmdfn = ${*::}{"cmd_$cmdfn"};
2983 $cmdfn or badusage f_ "unknown git-debrebase sub-operation %s", $cmd;