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 $debugcmd_when_debuglevel = 2;
41 our ($usage_message) = <<'END';
43 git-debrebase [<options>] [--|-i <git rebase options...>]
44 git-debrebase [<options>] status
45 git-debrebase [<options>] prepush [--prose=...]
46 git-debrebase [<options>] quick|conclude
47 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
48 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
50 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
53 our ($opt_force, $opt_noop_ok, $opt_merges, @opt_anchors);
54 our ($opt_defaultcmd_interactive);
56 our $us = qw(git-debrebase);
58 our $wrecknoteprefix = 'refs/debrebase/wreckage';
59 our $merge_cache_ref = 'refs/debrebase/merge-resolutions';
65 print STDERR "$us: bad usage: $m\n";
71 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
72 GetOptions @_ or badusage $m;
76 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
80 my ($k, $optional) = @_;
82 my @cmd = qw(git config -z);
83 push @cmd, qw(--get-all) if wantarray;
85 my $out = cmdoutput_errok @cmd;
87 fail "missing required git config $k" unless $optional;
90 my @l = split /\0/, $out;
91 return wantarray ? @l : $l[0];
98 my $dd = new Data::Dumper [ $v ];
99 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
105 my $data = (git_cat_file $objid, 'commit');
106 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
110 sub D_UPS () { 0x02; } # upstream files
111 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
112 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
113 sub D_DEB_CLOG () { 0x10; } # debian/changelog
114 sub D_DEB_OTH () { 0x20; } # debian/ (not patches/ or changelog)
115 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
117 our $playprefix = 'debrebase';
122 our @dgit = qw(dgit);
124 sub in_workarea ($) {
127 my $r = eval { $sub->(); };
128 { local $@; changedir $maindir; }
132 sub fresh_workarea (;$) {
135 $workarea = fresh_playground "$playprefix/$subdir";
136 in_workarea sub { playtree_setup };
139 sub run_ref_updates_now ($$) {
140 my ($mrest, $updates) = @_;
141 # @$updates is a list of lines for git-update-ref, without \ns
143 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
144 debugcmd '>|', @upd_cmd;
145 open U, "|-", @upd_cmd or die $!;
146 foreach (@$updates) {
147 printdebug ">= ", $_, "\n";
148 print U $_, "\n" or die $!;
151 close U or failedcmd @upd_cmd;
154 our $snags_forced = 0;
155 our $snags_tripped = 0;
156 our $snags_summarised = 0;
157 our @deferred_updates;
158 our @deferred_update_messages;
160 sub merge_wreckage_cleaning ($) {
162 git_for_each_ref("$wrecknoteprefix/*", sub {
163 my ($objid,$objtype,$fullrefname,$reftail) = @_;
164 push @$updates, "delete $fullrefname";
168 sub all_snags_summarised () {
169 $snags_forced + $snags_tripped == $snags_summarised;
171 sub run_deferred_updates ($) {
174 confess 'dangerous internal error' unless all_snags_summarised();
176 merge_wreckage_cleaning \@deferred_updates;
177 run_ref_updates_now $mrest, \@deferred_updates;
178 print $_, "\n" foreach @deferred_update_messages;
180 @deferred_updates = ();
181 @deferred_update_messages = ();
184 sub get_tree ($;$$) {
185 # tree object name => ([ $name, $info ], ...)
186 # where $name is the sort key, ie has / at end for subtrees
187 # $info is the LHS from git-ls-tree (<mode> <type> <hash>)
188 # without $precheck, will crash if $x does not exist, so don't do that;
189 # instead pass '' to get ().
190 my ($x, $precheck, $recurse) = @_;
192 return () if !length $x;
195 my ($type, $dummy) = git_cat_file $x, [qw(tree missing)];
196 return () if $type eq 'missing';
199 $recurse = !!$recurse;
201 confess "get_tree needs object not $x ?" unless $x =~ m{^[0-9a-f]+\:};
203 our (@get_tree_memo, %get_tree_memo);
204 my $memo = $get_tree_memo{$recurse,$x};
205 return @$memo if $memo;
207 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
209 my @cmd = (qw(git ls-tree -z --full-tree));
210 push @cmd, qw(-r) if $recurse;
211 push @cmd, qw(--), $x;
212 my $o = cmdoutput @cmd;
215 foreach my $l (split /\0/, $o) {
216 my ($i, $n) = split /\t/, $l, 2;
217 $n .= '/' if $i =~ m/^\d+ tree /;
219 confess "$x need $last < $n ?" unless $last lt $n;
221 $get_tree_memo{$recurse,$x} = \@l;
222 push @get_tree_memo, $x;
223 if (@get_tree_memo > 10) {
224 delete $get_tree_memo{ shift @get_tree_memo };
229 sub trees_diff_walk ($$$;$) {
230 # trees_diff_walk [{..opts...},] $x, $y, sub {... }
231 # calls sub->($name, $ix, $iy) for each difference
232 # $x and $y are as for get_tree
233 # where $name, $ix, $iy are $name and $info from get_tree
234 # opts are all call even for names same in both
235 # recurse call even for names same in both
236 my $opts = shift @_ if @_>=4;
237 my ($x,$y,$call) = @_;
238 my $all = $opts->{all};
239 return if !$all and $x eq $y;
240 my @x = get_tree $x, 0, $opts->{recurse};
241 my @y = get_tree $y, 0, $opts->{recurse};
242 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
245 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
246 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
247 my ($n, $ix, $iy); # all same? $cmp=0, use both
249 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
251 ($n, $ix) = @{ shift @x } if $cmp <= 0;
252 ($n, $iy) = @{ shift @y } if $cmp >= 0;
253 next if !$all and $ix eq $iy;
255 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
256 !!$all,$x,$y, $n,$ix,$iy
258 $call->($n, $ix, $iy);
262 sub get_differs ($$) {
264 # This does a similar job to quiltify_trees_differ, in dgit, a bit.
265 # But we don't care about modes, or dpkg-source-unrepresentable
266 # changes, and we don't need the plethora of different modes.
267 # Conversely we need to distinguish different kinds of changes to
268 # debian/ and debian/patches/.
269 # Also, here we have, and want to use, trees_diff_walk, because
270 # we may be calling this an awful lot and we want it to be fast.
275 no warnings qw(exiting);
277 my $plain = sub { $_[0] =~ m{^(100|0*)644 blob }s; };
279 trees_diff_walk "$x:", "$y:", sub {
280 my ($n,$ix,$iy) = @_;
282 # analyse difference at the toplevel
284 if ($n ne 'debian/') {
288 if ($n eq 'debian') {
289 # one side has a non-tree for ./debian !
290 $differs |= D_DEB_OTH;
294 my $xd = $ix && "$x:debian";
295 my $yd = $iy && "$y:debian";
296 trees_diff_walk $xd, $yd, sub {
297 my ($n,$ix,$iy) = @_;
299 # analyse difference in debian/
301 if ($n eq 'changelog' && (!$ix || $plain->($ix))
303 $differs |= D_DEB_CLOG;
306 if ($n ne 'patches/') {
307 $differs |= D_DEB_OTH;
311 my $xp = $ix && "$xd/patches";
312 my $yp = $iy && "$yd/patches";
313 trees_diff_walk { recurse=>1 }, $xp, $yp, sub {
314 my ($n,$ix,$iy) = @_;
316 # analyse difference in debian/patches
320 # we are recursing; directories may appear and disappear
322 } elsif ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
324 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
325 my $x_s = (git_cat_file "$xp/series", 'blob');
326 my $y_s = (git_cat_file "$yp/series", 'blob');
327 chomp $x_s; $x_s .= "\n";
328 $ok = $x_s eq substr($y_s, 0, length $x_s);
332 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
337 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
342 sub commit_pr_info ($) {
344 return Data::Dumper->dump([$r], [qw(commit)]);
347 sub calculate_committer_authline () {
348 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
349 'DUMMY COMMIT (git-debrebase)', "HEAD:";
350 my ($h,$m) = get_commit $c;
351 $h =~ m/^committer .*$/m or confess "($h) ?";
355 sub rm_subdir_cached ($) {
357 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
360 sub read_tree_subdir ($$) {
361 my ($subdir, $new_tree_object) = @_;
362 rm_subdir_cached $subdir;
363 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
366 sub read_tree_debian ($) {
368 read_tree_subdir 'debian', "$treeish:debian";
369 rm_subdir_cached 'debian/patches';
372 sub read_tree_upstream ($;$$) {
373 my ($treeish, $keep_patches, $tree_with_debian) = @_;
374 # if $tree_with_debian is supplied, will use that for debian/
375 # otherwise will save and restore it.
377 $tree_with_debian ? "$tree_with_debian:debian"
378 : cmdoutput @git, qw(write-tree --prefix=debian/);
379 runcmd @git, qw(read-tree), $treeish;
380 read_tree_subdir 'debian', $debian;
381 rm_subdir_cached 'debian/patches' unless $keep_patches;
384 sub make_commit ($$) {
385 my ($parents, $message_paras) = @_;
386 my $tree = cmdoutput @git, qw(write-tree);
387 my @cmd = (@git, qw(commit-tree), $tree);
388 push @cmd, qw(-p), $_ foreach @$parents;
389 push @cmd, qw(-m), $_ foreach @$message_paras;
390 return cmdoutput @cmd;
393 our @snag_force_opts;
395 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
396 if (grep { $_ eq $tag } @snag_force_opts) {
398 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
401 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
405 # Important: all mainline code must call snags_maybe_bail after
406 # any point where snag might be called, but before making changes
407 # (eg before any call to run_deferred_updates). snags_maybe_bail
408 # may be called more than once if necessary (but this is not ideal
409 # because then the messages about number of snags may be confusing).
410 sub snags_maybe_bail () {
411 return if all_snags_summarised();
414 "%s: snags: %d overriden by individual -f options\n",
417 if ($snags_tripped) {
420 "%s: snags: %d overriden by global --force\n",
424 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
428 $snags_summarised = $snags_forced + $snags_tripped;
430 sub snags_maybe_bail_early () {
431 # useful to bail out early without doing a lot of work;
432 # not a substitute for snags_maybe_bail.
433 snags_maybe_bail() if $snags_tripped && !$opt_force;
436 return $snags_forced || $snags_tripped;
439 sub ffq_prev_branchinfo () {
440 my $current = git_get_symref();
441 return gdr_ffq_prev_branchinfo($current);
444 sub record_gdrlast ($$;$) {
445 my ($gdrlast, $newvalue, $oldvalue) = @_;
446 $oldvalue ||= $git_null_obj;
447 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
450 sub fail_unprocessable ($) {
453 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
456 Branch/history seems mangled - no longer in gdr format.
457 See ILLEGAL OPERATIONS in git-debrebase(5).
464 Is this meant to be a gdr branch? $ffqm
466 } elsif (git_get_ref $ffq_prev) {
470 Consider git-debrebase scrap, to throw away your recent work.
472 } elsif (!git_get_ref $gdrlast) {
475 Branch does not seem to be meant to be a git-debrebase branch?
476 Wrong branch, or maybe you needed git-debrebase convert-from-*.
478 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
486 Branch/history mangled, and diverged since last git-debrebase.
487 Maybe you reset to, or rebased from, somewhere inappropriate.
492 sub gbp_pq_export ($$$) {
493 my ($bname, $base, $tip) = @_;
494 # must be run in a workarea. $bname and patch-queue/$bname
495 # ought not to exist. Leaves you on patch-queue/$bname with
496 # the patches staged but not committed.
497 # returns 1 if there were any patches
498 printdebug "gbp_pq_export $bname $base $tip\n";
499 runcmd @git, qw(checkout -q -b), $bname, $base;
500 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
501 my @gbp_cmd = (qw(gbp pq export));
502 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
504 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
507 return 0 unless stat_exists 'debian/patches';
508 runcmd @git, qw(add -f debian/patches);
513 # MERGE-TODO allow merge resolution separately from laundering, before git merge
516 # use git-format-patch?
517 # our own patch identification algorithm?
518 # this is an alternative strategy
520 sub merge_failed ($$;@) {
521 my ($wrecknotes, $emsg, @xmsgs) = @_;
523 push @m, "Merge resolution failed: $emsg";
529 merge_wreckage_cleaning \@updates;
530 run_ref_updates_now "merge failed", \@updates;
534 while (my ($k,$v) = each %$wrecknotes) {
535 push @updates, "create $wrecknoteprefix/$k $v";
537 run_ref_updates_now "merge failed", \@updates;
538 push @m, "Wreckage left in $wrecknoteprefix/*.";
540 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
542 # use finish rather than fail, in case we are within an eval
543 # (that can happen inside walk!)
545 print STDERR "$us: $_\n" foreach @m;
549 sub mwrecknote ($$$) {
550 my ($wrecknotes, $reftail, $commitish) = @_;
551 confess unless defined $commitish;
552 printdebug "mwrecknote $reftail $commitish\n";
553 $wrecknotes->{$reftail} = $commitish;
556 sub merge_attempt_cmd {
557 my $wrecknotes = shift @_;
561 merge_failed $wrecknotes,
562 failedcmd_waitstatus(),
563 "failed command: @_";
567 sub merge_series_patchqueue_convert ($$$);
569 sub merge_series ($$$;@) {
570 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
571 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
572 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
573 # ^ specifies several patch series (currently we only support exactly 2)
574 # return value is a commit which is the result of
575 # merging the two versions of the same topic branch
576 # $input_q[0] and $input_q[1]
577 # with respect to the old version
581 # Creates, in *_q, a key MR for its private use
583 printdebug "merge_series newbase=$newbase\n";
585 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
586 $base_q->{MR}{S} = 'base';
589 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
590 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
591 # $prereq{<patch filename>} exists or not (even later)
595 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
597 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
600 fresh_workarea "merge";
601 my $seriesfile = "debian/patches/series";
604 foreach my $q ($base_q, reverse @input_qs) {
606 my $any = gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
609 open S, $seriesfile or die "$seriesfile $!";
610 while (my $patch = <S>) {
611 chomp $patch or die $!;
612 $prereq{$patch} //= {};
613 foreach my $earlier (@earlier) {
614 $prereq{$patch}{$earlier}{$s}++ and die;
616 push @earlier, $patch;
617 stat "debian/patches/$patch" or die "$patch ?";
619 S->error and die "$seriesfile $!";
622 read_tree_upstream $newbase, 1;
623 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
624 "Convert $s to patch queue for merging",
625 "[git-debrebase merge-innards patch-queue import:".
628 printdebug "merge_series pec $pec ";
629 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
630 $pec = make_commit [ $pec ], [
631 "Drop series file from $s to avoid merge trouble",
632 "[git-debrebase merge-innards patch-queue prep:".
636 read_tree_debian $newbase;
638 read_tree_subdir 'debian/patches', "$pec:debian/patches";
640 rm_subdir_cached 'debian/patches';
642 $pec = make_commit [ $pec ], [
643 "Update debian/ (excluding patches) to final to avoid re-merging",
644 "debian/ was already merged and we need to just take that.",
645 "[git-debrebase merge-innards patch-queue packaging:".
649 printdebug "pec' $pec\n";
650 runcmd @git, qw(reset -q --hard), $pec;
651 $q->{MR}{PEC} = $pec;
652 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
654 # now, because of reverse, we are on $input_q->{MR}{OQC}
655 runcmd @git, qw(checkout -q -b merge);
656 printdebug "merge_series merging...\n";
657 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
659 $attempt_cmd->(@mergecmd);
661 printdebug "merge_series merge ok, series...\n";
662 # We need to construct a new series file
663 # Firstly, resolve prereq
664 foreach my $f (sort keys %prereq) {
665 printdebug "merge_series patch\t$f\t";
666 if (!stat_exists "debian/patches/$f") {
667 print DEBUG " drop\n" if $debuglevel;
668 # git merge deleted it; that's how we tell it's not wanted
672 print DEBUG " keep\n" if $debuglevel;
673 foreach my $g (sort keys %{ $prereq{$f} }) {
674 my $gfp = $prereq{$f}{$g};
675 printdebug "merge_series prereq\t$f\t-> $g\t";
676 if (!!$gfp->{0} == !!$gfp->{1}
679 print DEBUG "\tkeep\n" if $debuglevel;
681 print DEBUG "\tdrop\n" if $debuglevel;
682 delete $prereq{$f}{$g};
689 return scalar keys %{ $prereq{$f} };
692 my $nodate = time + 1;
694 # $authordate{<patch filename>};
695 my $authordate = sub {
697 $authordate{$f} //= do {
698 open PF, "<", "debian/patches/$f" or die "$f $!";
700 return $nodate if m/^$/;
701 last if s{^Date: }{};
704 return cmdoutput qw(date +%s -d), $_;
708 open NS, '>', $seriesfile or die $!;
710 while (keys %prereq) {
712 foreach my $try (sort keys %prereq) {
715 $unsat->($try) <=> $unsat->($best) or
716 $authordate->($try) <=> $authordate->($best) or
722 printdebug "merge_series series next $best\n";
723 print NS "$best\n" or die $!;
724 delete $prereq{$best};
725 foreach my $gp (values %prereq) {
730 runcmd @git, qw(add), $seriesfile;
731 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
732 $merged_pq = git_rev_parse 'HEAD';
733 $mwrecknote->('merged-patchqueue', $merged_pq);
735 return merge_series_patchqueue_convert
736 $wrecknotes, $newbase, $merged_pq;
739 sub merge_series_patchqueue_convert ($$$) {
740 my ($wrecknotes, $newbase, $merged_pq) = @_;
745 printdebug "merge_series series gbp pq import\n";
746 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
748 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
749 # MERGE-TODO consider git-format-patch etc. instead,
750 # since gbp pq doesn't always round-trip :-/
752 # OK now we are on patch-queue/merge, and we need to rebase
753 # onto the intended parent and drop the patches from each one
755 printdebug "merge_series series ok, building...\n";
756 my $build = $newbase;
757 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
758 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
759 my $commit = git_cat_file $c, 'commit';
760 printdebug "merge_series series ok, building $c\n";
761 read_tree_upstream $c, 0, $newbase;
762 my $tree = cmdoutput @git, qw(write-tree);
763 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
764 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
765 open C, ">", "../mcommit" or die $!;
766 print C $commit or die $!;
768 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
771 mwrecknote($wrecknotes, 'merged-result', $result);
773 runcmd @git, qw(update-ref refs/heads/result), $result;
775 runcmd @git, qw(checkout -q -b debug);
776 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
777 runcmd @git, qw(add .);
778 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
779 my $mdebug = git_rev_parse 'HEAD';
780 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
781 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
783 printdebug "merge_series returns $result\n";
787 # classify returns an info hash like this
789 # Hdr => # commit headers, including 1 final newline
790 # Msg => # commit message (so one newline is dropped)
792 # Type => (see below)
794 # Ix => $index # ie 0, 1, 2, ...
796 # Differs => return value from get_differs
798 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
800 # NewMsg => # commit message, but with any [dgit import ...] edited
801 # # to say "[was: ...]"
811 # has additional entres in classification result
812 # Overwritten = [ subset of Parents ]
813 # Contributor = $the_remaining_Parent
815 # DgitImportUnpatched
816 # has additional entry in classification result
817 # OrigParents = [ subset of Parents ]
820 # has additional entry in classification result
821 # OrigParents = [ subset of Parents ] # singleton list
828 # has additional entry in classification result
831 sub parsecommit ($;$) {
832 my ($objid, $p_ref) = @_;
833 # => hash with CommitId Hdr Msg Tree Parents
834 # Parents entries have only Ix CommitId
835 # $p_ref, if provided, must be [] and is used as a base for Parents
840 my ($h,$m) = get_commit $objid;
842 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
843 my (@ph) = $h =~ m/^parent (\w+)$/mg;
853 foreach my $ph (@ph) {
855 Ix => scalar @$p_ref,
867 my $r = parsecommit($objid, \@p);
871 $p->{Differs} = (get_differs $p->{CommitId}, $t),
874 printdebug "classify $objid \$t=$t \@p",
875 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
879 my ($type, @rest) = @_;
880 $r = { %$r, Type => $type, @rest };
882 printdebug " = $type ".(dd $r)."\n";
888 $r = { %$r, Type => qw(Unknown), Why => $why };
889 printdebug " ** Unknown\n";
893 if (grep { $_ eq $objid } @opt_anchors) {
894 return $classify->('TreatAsAnchor');
897 my @identical = grep { !$_->{Differs} } @p;
898 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
899 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
901 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
902 # multi-orig upstreams are represented with an anchor merge
903 # from a single upstream commit which combines the orig tarballs
905 # Every anchor tagged this way must be a merge.
906 # We are relying on the
907 # [git-debrebase anchor: ...]
908 # commit message annotation in "declare" anchor merges (which
909 # do not have any upstream changes), to distinguish those
910 # anchor merges from ordinary pseudomerges (which we might
911 # just try to strip).
913 # However, the user is going to be doing git-rebase a lot. We
914 # really don't want them to rewrite an anchor commit.
915 # git-rebase trips up on merges, so that is a useful safety
918 # BreakwaterStart commits are also anchors in the terminology
919 # of git-debrebase(5), but they are untagged (and always
920 # manually generated).
922 # We cannot not tolerate any tagged linear commit (ie,
923 # BreakwaterStart commits tagged `[anchor:') because such a
924 # thing could result from an erroneous linearising raw git
925 # rebase of a merge anchor. That would represent a corruption
926 # of the branch. and we want to detect and reject the results
927 # of such corruption before it makes it out anywhere. If we
928 # reject it here then we avoid making the pseudomerge which
929 # would be needed to push it.
931 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
932 @p == 2 or return $badanchor->("has other than two parents");
933 $haspatches and return $badanchor->("contains debian/patches");
935 # How to decide about l/r ordering of anchors ? git
936 # --topo-order prefers to expand 2nd parent first. There's
937 # already an easy rune to look for debian/ history anyway (git log
938 # debian/) so debian breakwater branch should be 1st parent; that
939 # way also there's also an easy rune to look for the upstream
940 # patches (--topo-order).
942 # Also this makes --first-parent be slightly more likely to
943 # be useful - it makes it provide a linearised breakwater history.
945 # Of course one can say somthing like
946 # gitk -- ':/' ':!/debian'
947 # to get _just_ the commits touching upstream files, and by
948 # the TREESAME logic in git-rev-list this will leave the
949 # breakwater into upstream at the first anchor. But that
950 # doesn't report debian/ changes at all.
952 # Other observations about gitk: by default, gitk seems to
953 # produce output in a different order to git-rev-list. I
954 # can't seem to find this documented anywhere. gitk
955 # --date-order DTRT. But, gitk always seems to put the
956 # parents from left to right, in order, so it's easy to see
957 # which way round a pseudomerge is.
959 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
960 $p[1]{Differs} & ~DS_DEB and
961 $badanchor->("upstream files differ from left parent");
962 $p[0]{Differs} & ~D_UPS and
963 $badanchor->("debian/ differs from right parent");
965 return $classify->(qw(Anchor),
966 OrigParents => [ $p[1] ]);
970 my $d = $r->{Parents}[0]{Differs};
971 if ($d == D_PAT_ADD) {
972 return $classify->(qw(AddPatches));
973 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
974 return $unknown->("edits debian/patches");
975 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
976 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
978 if ($d == D_DEB_CLOG) {
979 return $classify->(qw(Changelog));
981 return $classify->(qw(Packaging));
983 } elsif ($ty eq 'missing') {
984 return $classify->(qw(BreakwaterStart));
986 return $unknown->("parent's debian is not a directory");
988 } elsif ($d == D_UPS) {
989 return $classify->(qw(Upstream));
990 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
991 return $classify->(qw(Mixed));
993 return $unknown->("no changes");
995 confess "internal error $objid ?";
999 return $unknown->("origin commit");
1002 if (@p == 2 && @identical == 1) {
1003 my @overwritten = grep { $_->{Differs} } @p;
1004 confess "internal error $objid ?" unless @overwritten==1;
1005 return $classify->(qw(Pseudomerge),
1006 Overwritten => [ $overwritten[0] ],
1007 Contributor => $identical[0]);
1009 if (@p == 2 && @identical == 2) {
1011 my ($ph,$pm) = get_commit $_[0]{CommitId};
1012 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
1016 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
1017 if ($order > 0) { # newer first
1018 } elsif ($order < 0) {
1019 @bytime = reverse @bytime;
1021 # same age, default to order made by -s ours
1022 # that is, commit was made by someone who preferred L
1024 return $classify->(qw(Pseudomerge),
1025 SubType => qw(Ambiguous),
1026 Contributor => $bytime[0],
1027 Overwritten => [ $bytime[1] ]);
1029 foreach my $p (@p) {
1030 my ($p_h, $p_m) = get_commit $p->{CommitId};
1031 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1032 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1034 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1036 if (!(grep { !$_->{IsOrigin} } @p) and
1037 (@orig_ps >= @p - 1) and
1038 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1040 return $classify->(qw(DgitImportUnpatched),
1041 OrigParents => \@orig_ps);
1045 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1046 return $classify->("MergedBreakwaters");
1048 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1049 return $unknown->("unknown kind of merge from $1");
1052 return $unknown->("octopus merge");
1056 return $unknown->("general two-parent merge");
1059 return $classify->("VanillaMerge");
1062 sub keycommits ($;$$$$$);
1064 sub mergedbreakwaters_anchor ($) {
1067 foreach my $p (@{ $cl->{Parents} }) {
1068 my ($panchor, $pbw) = keycommits $p->{CommitId},
1069 undef,undef,undef,undef, 1;
1070 $best_anchor = $panchor
1071 if !defined $best_anchor
1072 or is_fast_fwd $best_anchor, $panchor;
1073 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
1074 unless is_fast_fwd $panchor, $best_anchor;
1076 return $best_anchor;
1079 sub keycommits ($;$$$$$) {
1080 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1081 # => ($anchor, $breakwater)
1083 # $furniture->("unclean-$tagsfx", $msg, $cl)
1084 # $unclean->("unclean-$tagsfx", $msg, $cl)
1085 # is callled for each situation or commit that
1086 # wouldn't be found in a laundered branch
1087 # $furniture is for furniture commits such as might be found on an
1088 # interchange branch (pseudomerge, d/patches, changelog)
1089 # $trouble is for things whnich prevent the return of
1090 # anchor and breakwater information; if that is ignored,
1091 # then keycommits returns (undef, undef) instead.
1092 # $fatal is for unprocessable commits, and should normally cause
1093 # a failure. If ignored, agaion, (undef, undef) is returned.
1095 # If $claimed_bw, this is supposed to be a breakwater commit.
1097 # If a callback is undef, fail is called instead.
1098 # If a callback is defined but false, the situation is ignored.
1099 # Callbacks may say:
1100 # no warnings qw(exiting); last;
1101 # if the answer is no longer wanted.
1103 my ($anchor, $breakwater);
1104 $breakwater = $head if $claimed_bw;
1108 $fatal //= sub { fail_unprocessable $_[1]; };
1110 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1111 my $why = $mainwhy.$xwhy;
1112 my $m = "branch needs laundering (run git-debrebase): $why";
1113 fail $m unless defined $cb;
1115 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1117 my $found_anchor = sub {
1119 $breakwater //= $clogonly;
1120 $breakwater //= $head;
1121 no warnings qw(exiting);
1125 $cl = classify $head;
1126 my $ty = $cl->{Type};
1127 if ($ty eq 'Packaging') {
1128 $breakwater //= $clogonly;
1129 $breakwater //= $head;
1130 } elsif ($ty eq 'Changelog') {
1131 # this is going to count as the tip of the breakwater
1132 # only if it has no upstream stuff before it
1133 $clogonly //= $head;
1134 } elsif ($ty eq 'Anchor' or
1135 $ty eq 'TreatAsAnchor' or
1136 $ty eq 'BreakwaterStart') {
1137 $found_anchor->($head);
1138 } elsif ($ty eq 'Upstream') {
1139 $x->($unclean, 'ordering',
1140 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1141 if defined $breakwater;
1143 $breakwater = undef;
1144 } elsif ($ty eq 'Mixed') {
1145 $x->($unclean, 'mixed',
1146 "found mixed upstream/packaging commit"," ($head)");
1148 $breakwater = undef;
1149 } elsif ($ty eq 'Pseudomerge' or
1150 $ty eq 'AddPatches') {
1152 $x->($furniture, (lc $ty),
1153 "found interchange bureaucracy commit ($ty)"," ($head)");
1154 } elsif ($ty eq 'DgitImportUnpatched') {
1156 $x->($trouble, 'dgitimport',
1157 "found dgit dsc import"," ($head)");
1158 return (undef,undef);
1160 $x->($fatal, 'unprocessable',
1161 "found bare dgit dsc import with no prior history",
1163 return (undef,undef);
1165 } elsif ($ty eq 'VanillaMerge') {
1166 $x->($trouble, 'vanillamerge',
1167 "found vanilla merge"," ($head)");
1168 return (undef,undef);
1169 } elsif ($ty eq 'MergedBreakwaters') {
1170 $found_anchor->(mergedbreakwaters_anchor $cl);
1172 $x->($fatal, 'unprocessable',
1173 "found unprocessable commit, cannot cope: $cl->{Why}",
1175 return (undef,undef);
1177 $head = $cl->{Parents}[0]{CommitId};
1179 return ($anchor, $breakwater);
1185 $nogenerate,$report, $report_lprefix) = @_;
1186 # => ($tip, $breakwater_tip, $last_anchor)
1187 # (or nothing, if $nogenerate)
1189 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1190 $report_lprefix //= '';
1192 # go through commits backwards
1193 # we generate two lists of commits to apply:
1194 # breakwater branch and upstream patches
1195 my (@brw_cl, @upp_cl, @processed);
1202 my ($prose, $info) = @_;
1203 my $ms = $cl->{Msg};
1205 confess unless defined $info;
1206 $ms .= "\n\n[git-debrebase $info: $prose]\n";
1207 return (Msg => $ms);
1209 my $rewrite_from_here = sub {
1211 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1213 push @processed, $sp_cl;
1218 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1221 return unless $report;
1222 print $report $prdelim, $report_lprefix, @_;
1226 my $bomb = sub { # usage: return $bomb->();
1227 print $report " Unprocessable" if $report;
1228 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1231 return (undef,undef);
1233 fail_unprocessable "found unprocessable commit, cannot cope".
1234 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1235 " (commit $cur) (d.".
1236 (join ' ', map { sprintf "%#x", $_->{Differs} }
1237 @{ $cl->{Parents} }).
1244 my $build_start = sub {
1245 my ($msg, $parent) = @_;
1248 no warnings qw(exiting); last;
1253 merge_failed $cl->{MergeWreckNotes}, $emsg;
1256 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1261 $cl = classify $cur;
1262 $cl->{MergeWreckNotes} //= {};
1263 my $ty = $cl->{Type};
1264 my $st = $cl->{SubType};
1265 $prline->("$cl->{CommitId} $cl->{Type}");
1266 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1267 push @processed, $cl;
1268 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1269 if ($ty eq 'AddPatches') {
1271 $rewrite_from_here->(\@upp_cl);
1273 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1277 } elsif ($ty eq 'BreakwaterStart') {
1278 $last_anchor = $cur;
1279 $build_start->('FirstPackaging', $cur);
1280 } elsif ($ty eq 'Upstream') {
1284 } elsif ($ty eq 'Mixed') {
1287 my $cls = { %$cl, $xmsg->("mixed commit: $wh part",'split') };
1290 $queue->(\@brw_cl, "debian");
1291 $queue->(\@upp_cl, "upstream");
1292 $rewrite_from_here->(\@brw_cl);
1295 } elsif ($ty eq 'Pseudomerge') {
1296 my $contrib = $cl->{Contributor}{CommitId};
1297 print $report " Contributor=$contrib" if $report;
1298 push @pseudomerges, $cl;
1299 $rewrite_from_here->(\@upp_cl);
1302 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1303 $last_anchor = $cur;
1304 $build_start->("Anchor", $cur);
1305 } elsif ($ty eq 'DgitImportUnpatched') {
1306 my $pm = $pseudomerges[-1];
1308 # To an extent, this is heuristic. Imports don't have
1309 # a useful history of the debian/ branch. We assume
1310 # that the first pseudomerge after an import has a
1311 # useful history of debian/, and ignore the histories
1312 # from later pseudomerges. Often the first pseudomerge
1313 # will be the dgit import of the upload to the actual
1314 # suite intended by the non-dgit NMUer, and later
1315 # pseudomerges may represent in-archive copies.
1316 my $ovwrs = $pm->{Overwritten};
1317 printf $report " PM=%s \@Overwr:%d",
1318 $pm->{CommitId}, (scalar @$ovwrs)
1321 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1324 my $ovwr = $ovwrs->[0]{CommitId};
1325 printf $report " Overwr=%s", $ovwr if $report;
1326 # This import has a tree which is just like a
1327 # breakwater tree, but it has the wrong history. It
1328 # ought to have the previous breakwater (which the
1329 # pseudomerge overwrote) as an ancestor. That will
1330 # make the history of the debian/ files correct. As
1331 # for the upstream version: either it's the same as
1332 # was ovewritten (ie, same as the previous
1333 # breakwater), in which case that history is precisely
1334 # right; or, otherwise, it was a non-gitish upload of a
1335 # new upstream version. We can tell these apart by
1336 # looking at the tree of the supposed upstream.
1339 SpecialMethod => 'DgitImportDebianUpdate',
1340 $xmsg->("debian changes", 'convert dgit import')
1343 SpecialMethod => 'DgitImportUpstreamUpdate',
1344 $xmsg->("convert dgit import: upstream update",
1347 $prline->(" Import");
1348 $rewrite_from_here->(\@brw_cl);
1349 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1353 # Everything is from this import. This kind of import
1354 # is already nearly in valid breakwater format, with the
1355 # patches as commits. Unfortunately it contains
1357 printdebug "*** WALK BOMB bare dgit import\n";
1358 $cl->{Why} = "bare dgit dsc import";
1362 } elsif ($ty eq 'MergedBreakwaters') {
1363 $last_anchor = mergedbreakwaters_anchor $cl;
1364 $build_start->(' MergedBreakwaters', $cur);
1366 } elsif ($ty eq 'VanillaMerge') {
1367 # User may have merged unstitched branch(es). We will
1368 # have now lost what ffq-prev was then (since the later
1369 # pseudomerge may introduce further changes). The effect
1370 # of resolving such a merge is that we may have to go back
1371 # further in history to find a merge base, since the one
1372 # which was reachable via ffq-prev is no longer findable.
1373 # This is suboptimal, but if it all works we'll have done
1375 # MERGE-TODO we should warn the user in the docs about this
1379 # We expect to find a dominating anchor amongst the
1380 # inputs' anchors. That will be the new anchor.
1382 # More complicated is finding a merge base for the
1383 # breakwaters. We need a merge base that is a breakwater
1384 # commit. The ancestors of breakwater commits are more
1385 # breakwater commits and possibly upstream commits and the
1386 # ancestors of those upstream. Upstreams might have
1387 # arbitrary ancestors. But any upstream commit U is
1388 # either included in both anchors, in which case the
1389 # earlier anchor is a better merge base than any of U's
1390 # ancestors; or U is not included in the older anchor, in
1391 # which case U is not an ancestor of the vanilla merge at
1392 # all. So no upstream commit, nor any ancestor thereof,
1393 # is a best merge base. As for non-breakwater Debian
1394 # commits: these are never ancestors of any breakwater.
1396 # So any best merge base as found by git-merge-base
1397 # is a suitable breakwater anchor. Usually there will
1400 printdebug "*** MERGE\n";
1402 my @bwbcmd = (@git, qw(merge-base));
1403 my @ibcmd = (@git, qw(merge-base --all));
1404 my $might_be_in_bw = 1;
1406 my $ps = $cl->{Parents};
1408 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1410 foreach my $p (@$ps) {
1411 $prline->(" VanillaMerge ".$p->{Ix});
1413 my ($ptip, $pbw, $panchor) =
1414 walk $p->{CommitId}, 0, $report,
1415 $report_lprefix.' ';
1416 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1417 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1418 $p->{Anchor} = $panchor;
1420 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1421 $mwrecknote->("$lr-input", $p->{CommitId});
1423 my $mwrecknote_parent = sub {
1425 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1427 $mwrecknote_parent->('Laundered');
1428 $mwrecknote_parent->('Breakwater');
1429 $mwrecknote_parent->('Anchor');
1431 $best_anchor = $panchor if
1432 !defined $best_anchor or
1433 is_fast_fwd $best_anchor, $panchor;
1435 printdebug " MERGE BA best=".($best_anchor//'-').
1439 $mwrecknote->('result-anchor', $best_anchor);
1441 foreach my $p (@$ps) {
1442 $prline->(" VanillaMerge ".$p->{Ix});
1443 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1444 $nomerge->('divergent anchors');
1445 } elsif ($p->{Anchor} eq $best_anchor) {
1446 print $report " SameAnchor" if $report;
1448 print $report " SupersededAnchor" if $report;
1450 if ($p->{Breakwater} eq $p->{CommitId}) {
1451 # this parent commit was its own breakwater,
1452 # ie it is part of the breakwater
1453 print $report " Breakwater" if $report;
1455 $might_be_in_bw = 0;
1457 push @bwbcmd, $p->{Breakwater};
1458 push @ibcmd, $p->{CommitId};
1461 if ($ok && $might_be_in_bw) {
1462 # We could rewrite this to contaion the metadata
1463 # declaring it to be MergedBreakwaters, but
1464 # unnecessarily rewriting a merge seems unhelpful.
1465 $prline->(" VanillaMerge MergedBreakwaters");
1466 $last_anchor = $best_anchor;
1467 $build_start->('MergedBreakwaters', $cur);
1470 my $bwb = cmdoutput @bwbcmd;
1472 # OK, now we have a breakwater base, but we need the merge
1473 # base for the interchange branch because we need the delta
1476 # This a the best merge base of our inputs which has the
1477 # breakwater merge base as an ancestor.
1484 @ibs or confess 'internal error, expected anchor at least ?';
1488 foreach my $tibix (0..$#ibs) {
1489 my $tib = $ibs[$tibix];
1490 my $ff = is_fast_fwd $bwb, $tib;
1491 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1492 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1493 $mwrecknote->($tibleaf, $tib);
1500 $ib or $nomerge->("no suitable interchange merge base");
1502 $prline->(" VanillaMerge Base");
1504 my ($btip, $bbw, $banchor) = eval {
1505 walk $ib, 0, $report, $report_lprefix.' ';
1507 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1511 $mwrecknote->("mergebase-laundered", $btip);
1512 $mwrecknote->("mergebase-breakwater", $bbw);
1513 $mwrecknote->("mergebase-anchor", $banchor);
1515 my $ibinfo = { SeriesTip => $btip,
1518 LeftRight => 'mergebase' };
1521 or $nomerge->("interchange merge-base ($ib)'s".
1522 " breakwater ($bbw)".
1523 " != breakwaters' merge-base ($bwb)");
1525 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1526 or $nomerge->("interchange merge-base ($ib)'s".
1527 " anchor ($ibinfo->{SeriesBase})".
1528 " != any merge input's anchor (".
1529 (join ' ', map { $_->{Anchor} } @$ps).
1532 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1533 $cl->{MergeBestAnchor} = $best_anchor;
1536 SpecialMethod => 'MergeCreateMergedBreakwaters',
1537 $xmsg->('constructed from vanilla merge',
1538 'merged-breakwater'),
1542 SpecialMethod => 'MergeMergeSeries',
1544 $build_start->('MergeBreakwaters', $cur);
1546 printdebug "*** WALK BOMB unrecognised\n";
1552 printdebug "*** WALK prep done cur=$cur".
1553 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1555 return if $nogenerate;
1557 # Now we build it back up again
1563 $#upp_cl = $upp_limit if defined $upp_limit;
1565 my $committer_authline = calculate_committer_authline();
1567 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1569 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1572 mkdir $rd or $!==EEXIST or die $!;
1574 my $want_debian = $build;
1575 my $want_upstream = $build;
1577 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1578 my $read_tree_debian = sub { ($want_debian) = @_; };
1580 foreach my $cl (qw(Debian), (reverse @brw_cl),
1581 { SpecialMethod => 'RecordBreakwaterTip' },
1582 qw(Upstream), (reverse @upp_cl)) {
1584 $current_method = $cl;
1587 my $method = $cl->{SpecialMethod} // $current_method;
1588 my @parents = ($build);
1589 my $cltree = $cl->{CommitId};
1590 printdebug "WALK BUILD ".($cltree//'undef').
1591 " $method (rewriting=$rewriting)\n";
1592 if ($method eq 'Debian') {
1593 $read_tree_debian->($cltree);
1594 } elsif ($method eq 'Upstream') {
1595 $read_tree_upstream->($cltree);
1596 } elsif ($method eq 'StartRewrite') {
1599 } elsif ($method eq 'RecordBreakwaterTip') {
1600 $breakwater = $build;
1602 } elsif ($method eq 'DgitImportDebianUpdate') {
1603 $read_tree_debian->($cltree);
1604 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1605 confess unless $rewriting;
1606 my $differs = (get_differs $build, $cltree);
1607 next unless $differs & D_UPS;
1608 $read_tree_upstream->($cltree);
1609 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1610 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1611 print "Found a general merge, will try to tidy it up.\n";
1613 $read_tree_upstream->($cl->{MergeBestAnchor});
1614 $read_tree_debian->($cltree);
1615 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1616 } elsif ($method eq 'MergeMergeSeries') {
1617 my $cachehit = reflog_cache_lookup
1618 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1620 print "Using supplied resolution for $cl->{CommitId}...\n";
1622 $mwrecknote->('cached-resolution', $build);
1624 print "Running merge resolution for $cl->{CommitId}...\n";
1625 $mwrecknote->('new-base', $build);
1626 $build = merge_series
1627 $build, $cl->{MergeWreckNotes},
1628 $cl->{MergeInterchangeBaseInfo},
1629 @{ $cl->{Parents} };
1631 $last_anchor = $cl->{MergeBestAnchor};
1633 # Check for mismerges:
1635 my ($against, $allow, $what) = @_;
1636 my $differs = get_differs $build, $against;
1638 "merge misresolved: %s are not the same (%s %s d.%#x)",
1639 $what, $against, $build, $differs)
1640 if $differs & ~($allow | D_PAT_ADD);
1643 # Breakwater changes which were in each side of the
1644 # merge will have been incorporated into the
1645 # MergeCreateMergedBreakwaters output. Because the
1646 # upstream series was rebased onto the new breakwater,
1647 # so should all of the packaging changes which were in
1649 $check->($input, D_UPS, 'debian files');
1651 # Upstream files are merge_series, which ought to
1652 # have been identical to the original merge.
1653 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1655 print "Merge resolution successful.\n";
1658 confess "$method ?";
1661 my $procd = (pop @processed) // 'UNDEF';
1662 if ($cl ne $procd) {
1664 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1668 read_tree_upstream $want_upstream, 0, $want_debian;
1670 my $newtree = cmdoutput @git, qw(write-tree);
1671 my $ch = $cl->{Hdr};
1672 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1673 $ch =~ s{^parent .*\n}{}mg;
1674 $ch =~ s{(?=^author)}{
1675 join '', map { "parent $_\n" } @parents
1676 }me or confess "$ch ?";
1678 $ch =~ s{^committer .*$}{$committer_authline}m
1681 my $cf = "$rd/m$rewriting";
1682 open CD, ">", $cf or die $!;
1683 print CD $ch, "\n", $cl->{Msg} or die $!;
1685 my @cmd = (@git, qw(hash-object));
1686 push @cmd, qw(-w) if $rewriting;
1687 push @cmd, qw(-t commit), $cf;
1688 my $newcommit = cmdoutput @cmd;
1689 confess "$ch ?" unless $rewriting
1690 or $newcommit eq $cl->{CommitId};
1691 $build = $newcommit;
1693 $build = $cl->{CommitId};
1694 trees_diff_walk "$want_upstream:", "$build:", sub {
1696 no warnings qw(exiting);
1697 next if $n eq 'debian/';
1698 confess "mismatch @_ ?";
1700 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1701 confess "mismatch @_ ?";
1703 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1704 confess "mismatch @parents != @old_parents ?"
1705 unless "@parents" eq "@old_parents";
1707 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1708 $last_anchor = $cur;
1713 my $final_check = get_differs $build, $input;
1714 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1715 if $final_check & ~D_PAT_ADD;
1717 my @r = ($build, $breakwater, $last_anchor);
1718 printdebug "*** WALK RETURN @r\n";
1723 git_check_unmodified();
1724 return git_rev_parse qw(HEAD);
1727 sub update_head ($$$) {
1728 my ($old, $new, $mrest) = @_;
1729 push @deferred_updates, "update HEAD $new $old";
1730 run_deferred_updates $mrest;
1733 sub update_head_checkout ($$$) {
1734 my ($old, $new, $mrest) = @_;
1735 update_head $old, $new, $mrest;
1736 runcmd @git, qw(reset --hard);
1739 sub update_head_postlaunder ($$$) {
1740 my ($old, $tip, $reflogmsg) = @_;
1741 return if $tip eq $old && !@deferred_updates;
1742 print "git-debrebase: laundered (head was $old)\n";
1743 update_head $old, $tip, $reflogmsg;
1744 # no tree changes except debian/patches
1745 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1748 sub currently_rebasing() {
1749 foreach (qw(rebase-merge rebase-apply)) {
1750 return 1 if stat_exists "$maindir_gitdir/$_";
1755 sub bail_if_rebasing() {
1756 fail "you are in the middle of a git-rebase already"
1757 if currently_rebasing();
1760 sub do_launder_head ($) {
1761 my ($reflogmsg) = @_;
1762 my $old = get_head();
1764 my ($tip,$breakwater) = walk $old;
1766 update_head_postlaunder $old, $tip, $reflogmsg;
1767 return ($tip,$breakwater);
1770 sub cmd_launder_v0 () {
1771 badusage "no arguments to launder-v0 allowed" if @ARGV;
1772 my $old = get_head();
1773 my ($tip,$breakwater,$last_anchor) = walk $old;
1774 update_head_postlaunder $old, $tip, 'launder';
1775 printf "# breakwater tip\n%s\n", $breakwater;
1776 printf "# working tip\n%s\n", $tip;
1777 printf "# last anchor\n%s\n", $last_anchor;
1780 sub defaultcmd_rebase () {
1781 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1782 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1783 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1786 sub cmd_analyse () {
1787 badusage "analyse does not support any options"
1788 if @ARGV and $ARGV[0] =~ m/^-/;
1789 badusage "too many arguments to analyse" if @ARGV>1;
1792 $old = git_rev_parse $old;
1794 $old = git_rev_parse 'HEAD';
1796 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1797 STDOUT->error and die $!;
1800 sub ffq_check ($;$$) {
1801 # calls $ff and/or $notff zero or more times
1802 # then returns either (status,message) where status is
1807 # or (undef,undef, $ffq_prev,$gdrlast)
1808 # $ff and $notff are called like this:
1809 # $ff->("message for stdout\n");
1810 # $notff->('snag-name', $message);
1811 # normally $currentval should be HEAD
1812 my ($currentval, $ff, $notff) =@_;
1814 $ff //= sub { print $_[0] or die $!; };
1817 my ($status, $message, $current, $ffq_prev, $gdrlast)
1818 = ffq_prev_branchinfo();
1819 return ($status, $message) unless $status eq 'branch';
1821 my $exists = git_get_ref $ffq_prev;
1822 return ('exists',"$ffq_prev already exists") if $exists;
1824 return ('not-branch', 'HEAD symref is not to refs/heads/')
1825 unless $current =~ m{^refs/heads/};
1828 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1831 printdebug "ffq check_specs @check_specs\n";
1834 my ($lrref, $desc) = @_;
1835 printdebug "ffq might check $lrref ($desc)\n";
1837 for my $chk (@check_specs) {
1839 $invert = $glob =~ s{^[!^]}{};
1840 last if fnmatch $glob, $lrref;
1843 my $lrval = git_get_ref $lrref;
1844 return unless length $lrval;
1846 if (is_fast_fwd $lrval, $currentval) {
1847 $ff->("OK, you are ahead of $lrref\n");
1848 $checked{$lrref} = 1;
1849 } elsif (is_fast_fwd $currentval, $lrval) {
1850 $checked{$lrref} = -1;
1851 $notff->('behind', "you are behind $lrref, divergence risk");
1853 $checked{$lrref} = -1;
1854 $notff->('diverged', "you have diverged from $lrref");
1858 my $merge = cfg "branch.$branch.merge",1;
1859 if (defined $merge and $merge =~ m{^refs/heads/}) {
1861 printdebug "ffq merge $rhs\n";
1862 my $check_remote = sub {
1863 my ($remote, $desc) = @_;
1864 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1865 return unless defined $remote;
1866 $check->("refs/remotes/$remote/$rhs", $desc);
1868 $check_remote->((scalar cfg "branch.$branch.remote",1),
1869 'remote fetch/merge branch');
1870 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1871 (scalar cfg "branch.$branch.pushDefault",1),
1872 'remote push branch');
1874 if ($branch =~ m{^dgit/}) {
1875 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1876 } elsif ($branch =~ m{^master$}) {
1877 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1879 return (undef, undef, $ffq_prev, $gdrlast);
1882 sub record_ffq_prev_deferred () {
1883 # => ('status', "message")
1885 # deferred message is undef
1890 # if not ff from some branch we should be ff from, is an snag
1891 # if "deferred", will have added something about that to
1892 # @deferred_update_messages, and also maybe printed (already)
1893 # some messages about ff checks
1895 my $currentval = get_head();
1897 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1898 return ($status,$message) if defined $status;
1902 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1903 push @deferred_updates, "delete $gdrlast";
1904 push @deferred_update_messages, "Recorded previous head for preservation";
1905 return ('deferred', undef);
1908 sub record_ffq_auto () {
1909 my ($status, $message) = record_ffq_prev_deferred();
1910 if ($status eq 'deferred' || $status eq 'exists') {
1912 snag $status, "could not record ffq-prev: $message";
1917 sub ffq_prev_info () {
1919 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1920 my ($status, $message, $current, $ffq_prev, $gdrlast)
1921 = ffq_prev_branchinfo();
1922 if ($status ne 'branch') {
1923 snag $status, "could not check ffq-prev: $message";
1926 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1927 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1930 sub stitch ($$$$$) {
1931 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1933 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1935 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1936 my $differs = get_differs $old_head, $ffq_prev_commitish;
1937 unless ($differs & ~D_PAT_ADD) {
1938 # ffq-prev is ahead of us, and the only tree changes it has
1939 # are possibly addition of things in debian/patches/.
1940 # Just wind forwards rather than making a pointless pseudomerge.
1941 record_gdrlast $gdrlast, $ffq_prev_commitish;
1942 update_head_checkout $old_head, $ffq_prev_commitish,
1943 "stitch (fast forward)";
1948 # We make pseudomerges with L as the contributing parent.
1949 # This makes git rev-list --first-parent work properly.
1950 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1951 'Declare fast forward / record previous work',
1952 "[git-debrebase pseudomerge: $prose]",
1954 record_gdrlast $gdrlast, $new_head;
1955 update_head $old_head, $new_head, "stitch: $prose";
1958 sub do_stitch ($;$) {
1959 my ($prose, $unclean) = @_;
1961 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1962 if (!$ffq_prev_commitish) {
1963 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1966 my $dangling_head = get_head();
1968 keycommits $dangling_head, $unclean,$unclean,$unclean;
1971 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1974 sub upstream_commitish_search ($$) {
1975 my ($upstream_version, $tried) = @_;
1976 # todo: at some point maybe use git-deborig to do this
1977 foreach my $tagpfx ('', 'v', 'upstream/') {
1978 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1979 my $new_upstream = git_get_ref "refs/tags/$tag";
1981 return $new_upstream if length $new_upstream;
1985 sub resolve_upstream_version ($$) {
1986 my ($new_upstream, $upstream_version) = @_;
1988 if (!defined $new_upstream) {
1990 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1991 if (!length $new_upstream) {
1992 fail "Could not determine appropriate upstream commitish.\n".
1993 " (Tried these tags: @tried)\n".
1994 " Check version, and specify upstream commitish explicitly.";
1997 $new_upstream = git_rev_parse $new_upstream;
1999 return $new_upstream;
2002 sub cmd_new_upstream () {
2003 # automatically and unconditionally launders before rebasing
2004 # if rebase --abort is used, laundering has still been done
2008 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
2010 # parse args - low commitment
2011 my $spec_version = shift @ARGV;
2012 my $new_version = (new Dpkg::Version $spec_version, check => 1);
2013 fail "bad version number \`$spec_version'" unless defined $new_version;
2014 if ($new_version->is_native()) {
2015 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
2018 my $new_upstream = shift @ARGV;
2019 my $new_upstream_version = upstreamversion $new_version;
2021 resolve_upstream_version $new_upstream, $new_upstream_version;
2026 my ($n, @x) = @_; # may be ''
2027 my $pc = $pieces{$n} //= {
2029 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
2031 while (my $k = shift @x) { $pc->{$k} = shift @x; }
2036 my $newpiece = sub {
2037 my ($n, @x) = @_; # may be ''
2038 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2039 push @newpieces, $pc;
2044 New => $new_upstream,
2046 while (@ARGV && $ARGV[0] !~ m{^-}) {
2047 my $n = shift @ARGV;
2049 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2050 unless @ARGV && $ARGV[0] !~ m{^-};
2052 my $c = git_rev_parse shift @ARGV;
2053 die unless $n =~ m/^$extra_orig_namepart_re$/;
2054 $newpiece->($n, New => $c);
2057 # now we need to investigate the branch this generates the
2058 # laundered version but we don't switch to it yet
2059 my $old_head = get_head();
2060 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2062 my $old_bw_cl = classify $old_bw;
2063 my $old_anchor_cl = classify $old_anchor;
2065 if (!$old_anchor_cl->{OrigParents}) {
2066 snag 'anchor-treated',
2067 'old anchor is recognised due to --anchor, cannot check upstream';
2069 $old_upstream = parsecommit
2070 $old_anchor_cl->{OrigParents}[0]{CommitId};
2071 $piece->('', Old => $old_upstream->{CommitId});
2074 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2075 if ($old_upstream->{Msg} =~
2076 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2078 my @oldpieces = (split / /, $1);
2079 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2080 if ($old_n_parents != @oldpieces &&
2081 $old_n_parents != @oldpieces + 1) {
2082 snag 'upstream-confusing', sprintf
2083 "previous upstream combine %s".
2084 " mentions %d pieces (each implying one parent)".
2085 " but has %d parents".
2086 " (one per piece plus maybe a previous combine)",
2087 $old_upstream->{CommitId},
2088 (scalar @oldpieces),
2090 } elsif ($oldpieces[0] ne '.') {
2091 snag 'upstream-confusing', sprintf
2092 "previous upstream combine %s".
2093 " first piece is not \`.'",
2097 foreach my $i (0..$#oldpieces) {
2098 my $n = $oldpieces[$i];
2099 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2100 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2104 snag 'upstream-confusing',
2105 "previous upstream $old_upstream->{CommitId} is from".
2106 " git-debrebase but not an \`upstream-combine' commit";
2110 foreach my $pc (values %pieces) {
2111 if (!$old_upstream) {
2112 # we have complained already
2113 } elsif (!$pc->{Old}) {
2114 snag 'upstream-new-piece',
2115 "introducing upstream piece \`$pc->{Name}'";
2116 } elsif (!$pc->{New}) {
2117 snag 'upstream-rm-piece',
2118 "dropping upstream piece \`$pc->{Name}'";
2119 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2120 snag 'upstream-not-ff',
2121 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2125 printdebug "%pieces = ", (dd \%pieces), "\n";
2126 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2134 my @upstream_merge_parents;
2137 push @upstream_merge_parents, $old_upstream->{CommitId};
2140 foreach my $pc (@newpieces) { # always has '' first
2142 read_tree_subdir $pc->{Name}, $pc->{New};
2144 runcmd @git, qw(read-tree), $pc->{New};
2146 push @upstream_merge_parents, $pc->{New};
2149 # index now contains the new upstream
2151 if (@newpieces > 1) {
2152 # need to make the upstream subtree merge commit
2153 $new_upstream = make_commit \@upstream_merge_parents,
2154 [ "Combine upstreams for $new_upstream_version",
2155 ("[git-debrebase upstream-combine . ".
2156 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2161 # $new_upstream is either the single upstream commit, or the
2162 # combined commit we just made. Either way it will be the
2163 # "upstream" parent of the anchor merge.
2165 read_tree_subdir 'debian', "$old_bw:debian";
2167 # index now contains the anchor merge contents
2168 $new_bw = make_commit [ $old_bw, $new_upstream ],
2169 [ "Update to upstream $new_upstream_version",
2170 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2173 my $clogsignoff = cmdoutput qw(git show),
2174 '--pretty=format:%an <%ae> %aD',
2177 # Now we have to add a changelog stanza so the Debian version
2179 die if unlink "debian";
2180 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2181 unlink "debian/changelog" or $!==ENOENT or die $!;
2182 mkdir "debian" or die $!;
2183 open CN, ">", "debian/changelog" or die $!;
2184 my $oldclog = git_cat_file ":debian/changelog";
2185 $oldclog =~ m/^($package_re) \(\S+\) / or
2186 fail "cannot parse old changelog to get package name";
2188 print CN <<END, $oldclog or die $!;
2189 $p ($new_version) UNRELEASED; urgency=medium
2191 * Update to new upstream version $new_upstream_version.
2197 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2199 # Now we have the final new breakwater branch in the index
2200 $new_bw = make_commit [ $new_bw ],
2201 [ "Update changelog for new upstream $new_upstream_version",
2202 "[git-debrebase changelog: new upstream $new_upstream_version]",
2206 # we have constructed the new breakwater. we now need to commit to
2207 # the laundering output, because git-rebase can't easily be made
2208 # to make a replay list which is based on some other branch
2210 update_head_postlaunder $old_head, $old_laundered_tip,
2211 'launder for new upstream';
2213 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2214 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2215 "debrebase new-upstream $new_version: rebase";
2217 # now it's for the user to sort out
2220 sub cmd_record_ffq_prev () {
2221 badusage "no arguments allowed" if @ARGV;
2222 my ($status, $msg) = record_ffq_prev_deferred();
2223 if ($status eq 'exists' && $opt_noop_ok) {
2224 print "Previous head already recorded\n" or die $!;
2225 } elsif ($status eq 'deferred') {
2226 run_deferred_updates 'record-ffq-prev';
2228 fail "Could not preserve: $msg";
2233 badusage "no arguments allowed" if @ARGV;
2234 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2235 print "$bw\n" or die $!;
2238 sub cmd_breakwater () {
2239 badusage "no arguments allowed" if @ARGV;
2240 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2241 print "$bw\n" or die $!;
2245 badusage "no arguments allowed" if @ARGV;
2247 # todo: gdr status should print divergence info
2248 # todo: gdr status should print upstream component(s) info
2249 # todo: gdr should leave/maintain some refs with this kind of info ?
2251 my $oldest = { Badness => 0 };
2254 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2255 if ($oldest->{Badness} < $badness) {
2256 $oldest = $newest = undef;
2259 Badness => $badness,
2260 CommitId => $cl->{CommitId},
2264 $newest //= $oldest;
2266 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2267 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2268 sub { $note->(2, 'branch is unlaundered', @_); },
2269 sub { $note->(3, 'branch needs laundering', @_); },
2270 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2272 my $prcommitinfo = sub {
2274 flush STDOUT or die $!;
2275 runcmd @git, qw(--no-pager log -n1),
2276 '--pretty=format: %h %s%n',
2280 print "current branch contents, in git-debrebase terms:\n";
2281 if (!$oldest->{Badness}) {
2282 print " branch is laundered\n";
2284 print " $oldest->{OurMsg}\n";
2286 foreach my $info ($oldest, $newest) {
2287 my $cid = $info->{CommitId};
2288 next if $cid eq $printed;
2290 print " $info->{KcMsg}\n";
2291 $prcommitinfo->($cid);
2296 my ($cid, $what) = @_;
2297 if (!defined $cid) {
2298 print " $what is not well-defined\n";
2301 $prcommitinfo->($cid);
2304 print "key git-debrebase commits:\n";
2305 $prab->($anchor, 'anchor');
2306 $prab->($bw, 'breakwater');
2308 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2309 ffq_prev_branchinfo();
2311 print "branch and ref status, in git-debrebase terms:\n";
2313 print " $ffq_msg\n";
2315 $ffq_prev = git_get_ref $ffq_prev;
2316 $gdrlast = git_get_ref $gdrlast;
2318 print " unstitched; previous tip was:\n";
2319 $prcommitinfo->($ffq_prev);
2320 } elsif (!$gdrlast) {
2321 print " stitched? (no record of git-debrebase work)\n";
2322 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2323 print " stitched\n";
2325 print " not git-debrebase (diverged since last stitch)\n"
2328 print "you are currently rebasing\n" if currently_rebasing();
2332 my $prose = 'stitch';
2333 getoptions("stitch",
2334 'prose=s', \$prose);
2335 badusage "no arguments allowed" if @ARGV;
2336 do_stitch $prose, 0;
2338 sub cmd_prepush () {
2344 badusage "no arguments allowed" if @ARGV;
2345 do_launder_head 'launder for git-debrebase quick';
2349 sub cmd_conclude () {
2350 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2351 if (!$ffq_prev_commitish) {
2352 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2355 my $dangling_head = get_head();
2357 badusage "no arguments allowed" if @ARGV;
2358 do_launder_head 'launder for git-debrebase quick';
2363 if (currently_rebasing()) {
2364 runcmd @git, qw(rebase --abort);
2365 push @deferred_updates, 'verify HEAD HEAD';
2366 # noop, but stops us complaining that scrap was a noop
2368 badusage "no arguments allowed" if @ARGV;
2369 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2371 if ($ffq_prev_commitish) {
2372 $scrapping_head = get_head();
2373 push @deferred_updates,
2374 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2375 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2377 if (git_get_ref $merge_cache_ref) {
2378 push @deferred_updates,
2379 "delete $merge_cache_ref";
2381 if (!@deferred_updates) {
2382 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2386 if ($scrapping_head) {
2387 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2389 run_deferred_updates "scrap";
2393 sub make_patches_staged ($) {
2395 # Produces the patches that would result from $head if it were
2397 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2401 $any = gbp_pq_export 'bw', $secret_bw, $secret_head;
2406 sub make_patches ($) {
2408 keycommits $head, 0, \&snag;
2409 my $any = make_patches_staged $head;
2412 my $ptree = !$any ? undef :
2413 cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2414 runcmd @git, qw(read-tree), $head;
2416 read_tree_subdir 'debian/patches', $ptree;
2418 rm_subdir_cached 'debian/patches';
2420 $out = make_commit [$head], [
2421 'Commit patch queue (exported by git-debrebase)',
2422 '[git-debrebase make-patches: export and commit patches]',
2428 sub cmd_make_patches () {
2429 my $opt_quiet_would_amend;
2430 getoptions("make-patches",
2431 'quiet-would-amend!', \$opt_quiet_would_amend);
2432 badusage "no arguments allowed" if @ARGV;
2434 my $old_head = get_head();
2435 my $new = make_patches $old_head;
2436 my $d = get_differs $old_head, $new;
2438 fail "No (more) patches to export." unless $opt_noop_ok;
2440 } elsif ($d == D_PAT_ADD) {
2442 update_head_checkout $old_head, $new, 'make-patches';
2444 print STDERR failmsg
2445 "Patch export produced patch amendments".
2446 " (abandoned output commit $new).".
2447 " Try laundering first."
2448 unless $opt_quiet_would_amend;
2453 sub check_series_has_all_patches ($) {
2455 my $seriesfn = 'debian/patches/series';
2456 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2460 our $comments_snagged;
2461 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2462 if ($f =~ m/^\s*\#/) {
2463 snag 'series-comments',
2464 "$seriesfn contains comments, which will be discarded"
2465 unless $comments_snagged++;
2468 fail "patch $f repeated in $seriesfn !" if $series{$f}++;
2470 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2471 my ($f,$i) = @$patchfile;
2472 next if $series{$f};
2473 next if $f eq 'series';
2474 snag 'unused-patches', "Unused patch file $f will be discarded";
2478 sub begin_convert_from () {
2479 my $head = get_head();
2480 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2482 fail "ffq-prev exists, this is already managed by git-debrebase!"
2483 if $ffq_prev && git_get_ref $ffq_prev;
2485 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2486 snag 'already-converted',
2487 "ahead of debrebase-last, this is already managed by git-debrebase!"
2488 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2489 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2492 sub complete_convert_from ($$$$) {
2493 my ($old_head, $new_head, $gi, $mrest) = @_;
2494 ffq_check $new_head;
2495 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2498 update_head_checkout $old_head, $new_head, $mrest;
2501 sub cmd_convert_from_gbp () {
2502 badusage "want only 1 optional argument, the upstream git commitish"
2505 my $clogp = parsechangelog();
2506 my $version = $clogp->{'Version'}
2507 // die "missing Version from changelog";
2509 my ($upstream_spec) = @ARGV;
2511 my $upstream_version = upstreamversion $version;
2513 resolve_upstream_version($upstream_spec, $upstream_version);
2515 my ($old_head, $gdrlastinfo) = begin_convert_from();
2517 my $upsdiff = get_differs $upstream, $old_head;
2518 if ($upsdiff & D_UPS) {
2519 runcmd @git, qw(--no-pager diff --stat),
2520 $upstream, $old_head,
2521 qw( -- :!/debian :/);
2523 upstream ($upstream_spec) and HEAD are not
2524 identical in upstream files. See diffstat above, or run
2525 git diff $upstream_spec HEAD -- :!/debian :/
2529 if (!is_fast_fwd $upstream, $old_head) {
2530 snag 'upstream-not-ancestor',
2531 "upstream ($upstream) is not an ancestor of HEAD";
2533 my $wrong = cmdoutput
2534 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2535 qw(-- :/ :!/debian));
2536 if (length $wrong) {
2537 snag 'unexpected-upstream-changes',
2538 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2539 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2543 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2544 snag 'upstream-has-debian',
2545 "upstream ($upstream) contains debian/ directory";
2548 check_series_has_all_patches $old_head;
2550 my $previous_dgit_view = eval {
2551 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2553 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2554 my ($stz, $desc) = @_;
2555 no warnings qw(exiting);
2556 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2557 next unless $stz->{Date};
2558 next unless $stz->{Distribution} ne 'UNRELEASED';
2559 $lvsn = $stz->{Version};
2560 $suite = $stz->{Distribution};
2563 die "neither of the first two changelog entries are released\n"
2564 unless defined $lvsn;
2565 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2566 my $mtag_pat = debiantag_maintview $lvsn, '*';
2567 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2569 die "could not find suitable maintainer view tag $mtag_pat\n"
2570 unless $mtag =~ m{/};
2571 is_fast_fwd $mtag, 'HEAD' or
2572 die "HEAD is not FF from maintainer tag $mtag!";
2573 my $dtag = "archive/$mtag";
2574 git_get_ref "refs/tags/$dtag" or
2575 die "dgit view tag $dtag not found\n";
2576 is_fast_fwd $mtag, $dtag or
2577 die "dgit view tag $dtag is not FF from maintainer tag $mtag\n";
2578 print "will stitch in dgit view, $dtag\n";
2579 git_rev_parse $dtag;
2581 if (!$previous_dgit_view) {
2585 Cannot confirm dgit view: $@
2586 Failed to stitch in dgit view (see messages above).
2587 dgit --overwrite will be needed on the first dgit push after conversion.
2591 snags_maybe_bail_early();
2597 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2598 # make a branch out of the patch queue - we'll want this in a mo
2599 runcmd qw(gbp pq import);
2600 # strip the patches out
2601 runcmd @git, qw(checkout -q gdr-internal~0);
2602 rm_subdir_cached 'debian/patches';
2603 $work = make_commit ['HEAD'], [
2604 'git-debrebase convert-from-gbp: drop patches from tree',
2605 'Delete debian/patches, as part of converting to git-debrebase format.',
2606 '[git-debrebase convert-from-gbp: drop patches from tree]'
2608 # make the anchor merge
2609 # the tree is already exactly right
2610 $work = make_commit [$work, $upstream], [
2611 'git-debrebase import: declare upstream',
2612 'First breakwater merge.',
2613 '[git-debrebase anchor: declare upstream]'
2616 # rebase the patch queue onto the new breakwater
2617 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2618 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2619 $work = git_rev_parse 'HEAD';
2621 if ($previous_dgit_view) {
2622 $work = make_commit [$work, $previous_dgit_view], [
2623 'git-debrebase import: declare ff from dgit archive view',
2624 '[git-debrebase pseudomerge: import-from-gbp]',
2629 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2630 print <<END or die $!;
2631 git-debrebase: converted from patched-unapplied (gbp) branch format, OK
2635 sub cmd_convert_to_gbp () {
2636 badusage "no arguments allowed" if @ARGV;
2637 my $head = get_head();
2638 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2639 my ($anchor, $breakwater) = keycommits $head, 0;
2640 my $out = $breakwater;
2641 my $any = make_patches_staged $head;
2644 $out = make_commit [$out], [
2645 'Commit patch queue (converted from git-debrebase format)',
2646 '[git-debrebase convert-to-gbp: commit patches]',
2650 # in this case, it can be fast forward
2654 push @deferred_updates, "delete $ffq";
2655 push @deferred_updates, "delete $gdrlast";
2658 update_head_checkout $head, $out, "convert to gbp (v0)";
2659 print <<END or die $!;
2660 git-debrebase: converted to git-buildpackage branch format
2661 git-debrebase: WARNING: do not now run "git-debrebase" any more
2662 git-debrebase: WARNING: doing so would drop all upstream patches!
2666 sub cmd_convert_from_dgit_view () {
2667 my $clogp = parsechangelog();
2669 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2675 getoptions("convert-from-dgit-view",
2676 'diagnose!', \$diagnose,
2677 'build-products-dir:s', \$bpd,
2678 'origs!', \$do_origs,
2680 'always-convert-anyway!', \$always);
2681 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2686 my $spec = shift @ARGV;
2687 my $commit = git_rev_parse "$spec^{commit}";
2688 push @upstreams, { Commit => $commit,
2689 Source => "$ARGV[0], from command line",
2694 my ($head, $gdrlastinfo) = begin_convert_from();
2698 my $trouble = sub { $troubles++; };
2699 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2700 printdebug "troubles=$troubles\n";
2703 $us: Branch already seems to be in git-debrebase format!
2704 $us: --always-convert-anyway would do the conversion operation anyway
2705 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2707 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2712 check_series_has_all_patches $head;
2714 snags_maybe_bail_early();
2716 my $version = upstreamversion $clogp->{Version};
2717 print STDERR "Considering possible commits corresponding to upstream:\n";
2722 my $ups_tag = upstream_commitish_search $version, \@tried;
2724 my $this = "git tag $tried[-1]";
2725 push @upstreams, { Commit => $ups_tag,
2730 " git tag: no suitable tag found (tried %s)\n",
2735 my $p = $clogp->{'Source'};
2736 # we do a quick check to see if there are plausible origs
2738 if (!opendir BPD, $bpd) {
2739 die "$bpd: opendir: $!" unless $!==ENOENT;
2741 while ($!=0, my $f = readdir BPD) {
2742 next unless is_orig_file_of_p_v $f, $p, $version;
2744 " orig: found what looks like a .orig, %s\n",
2749 die "read $bpd: $!" if $!;
2753 my $tree = cmdoutput
2754 @dgit, qw(--build-products-dir), $bpd,
2755 qw(print-unapplied-treeish);
2758 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2759 rm_subdir_cached 'debian';
2760 $tree = cmdoutput @git, qw(write-tree);
2761 my $ups_synth = make_commit [], [ <<END, <<END,
2762 Import effective orig tree for upstream version $version
2764 This includes the contents of the .orig(s), minus any debian/ directory.
2766 [git-debrebase convert-from-dgit-view upstream-import-convert: $version]
2769 push @upstreams, { Commit => $ups_synth,
2770 Source => "orig(s) imported via dgit",
2775 " orig: no suitable origs found (looked for %s in %s)\n",
2776 "${p}_".(stripeoch $version)."...", $bpd;
2781 my $some_patches = stat_exists 'debian/patches/series';
2783 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2786 foreach my $u (@upstreams) {
2790 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2791 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2792 runcmd @git, qw(clean -xdff);
2793 runcmd @git, qw(checkout), $head, qw(-- debian);
2794 if ($some_patches) {
2795 rm_subdir_cached 'debian/patches';
2796 $work = make_commit [ $work ], [
2797 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2798 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2799 "to git-debrebase format. Upstream changes will appear as commits.",
2800 '[git-debrebase convert-from-dgit-view drop-patches]'
2803 $work = make_commit [ $work, $u->{Commit} ], [
2804 'git-debrebase convert-from-dgit-view: declare upstream',
2805 '(Re)constructed breakwater merge.',
2806 '[git-debrebase anchor: declare upstream]'
2808 runcmd @git, qw(checkout --quiet -b mk), $work;
2809 if ($some_patches) {
2810 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2811 runcmd @git, qw(reset --quiet);
2812 my @gbp_cmd = (qw(gbp pq import));
2814 my $gbp_err = "../gbp-pq-err";
2815 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2817 my $r = system @gbp_cmd;
2820 " %s: couldn't apply patches: gbp pq %s",
2821 $u->{Source}, waitstatusmsg();
2825 my $work = git_rev_parse qw(HEAD);
2826 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2827 if (length $diffout) {
2829 " $u->{Source}: applying patches gives different tree\n";
2830 print STDERR $diffout if $diagnose;
2834 $u->{Result} = $work;
2842 Could not find or construct a suitable upstream commit.
2843 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2844 upstream commmit explicitly or provide suitable origs.
2848 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2850 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2851 'convert-from-dgit-view';
2854 sub cmd_forget_was_ever_debrebase () {
2855 badusage "forget-was-ever-debrebase takes no further arguments" if @ARGV;
2856 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2857 ffq_prev_branchinfo();
2858 fail "Not suitable for recording git-debrebaseness anyway: $ffq_msg"
2859 if defined $ffq_msg;
2860 push @deferred_updates, "delete $ffq_prev";
2861 push @deferred_updates, "delete $gdrlast";
2863 run_deferred_updates "forget-was-ever-debrebase";
2866 sub cmd_record_resolved_merge () {
2867 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2868 # MERGE-TODO needs documentation
2869 my $new = get_head();
2872 print "Checking how you have resolved the merge problem\n";
2873 my $nope = sub { print "Not $method: @_"; 0; };
2875 my $maybe = sub { print "Seems to be $method.\n"; };
2877 my ($key, $ref) = @_;
2878 reflog_cache_insert $merge_cache_ref, $key, $ref;
2879 print "OK. You can switch branches and try git-debrebase again.\n";
2883 fresh_workarea 'merge';
2885 $method = 'vanilla-merge patchqueue';
2886 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2887 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2888 foreach my $lr (qw(left right)) {
2889 my $n = "$wrecknoteprefix/$lr-patchqueue";
2890 my $lrpq = git_get_ref $n;
2891 $lrpq or return $nope->("wreckage did not contain patchqueues");
2892 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2895 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2896 or die "wreckage element $wrecknoteprefix/new-base missing";
2897 my $result = merge_series_patchqueue_convert
2899 $yes->("vanilla-merge $vanilla", $result);
2902 fail "No resolved merge method seems applicable.\n";
2906 sub cmd_downstream_rebase_launder_v0 () {
2907 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2909 $base = git_rev_parse $base;
2910 my $old_head = get_head();
2911 my $current = $old_head;
2914 if ($current eq $base) {
2915 $topmost_keep //= $current;
2916 print " $current BASE stop\n";
2919 my $cl = classify $current;
2920 print " $current $cl->{Type}";
2922 my $p0 = $cl->{Parents}[0]{CommitId};
2924 if ($cl->{Type} eq 'Pseudomerge') {
2925 print " ^".($cl->{Contributor}{Ix}+1);
2926 $next = $cl->{Contributor}{CommitId};
2927 } elsif ($cl->{Type} eq 'AddPatches' or
2928 $cl->{Type} eq 'Changelog') {
2938 $topmost_keep //= $current;
2940 die "to-be stripped changes not on top of the branch\n"
2945 if ($topmost_keep eq $old_head) {
2946 print "unchanged\n";
2948 print "updating to $topmost_keep\n";
2949 update_head_checkout
2950 $old_head, $topmost_keep,
2951 'downstream-rebase-launder-v0';
2957 "D+" => \$debuglevel,
2958 'noop-ok', => \$opt_noop_ok,
2959 'f=s' => \@snag_force_opts,
2960 'anchor=s' => \@opt_anchors,
2961 '--dgit=s' => \($dgit[0]),
2963 'experimental-merge-resolution!', \$opt_merges,
2965 my ($opt,$val) = @_;
2966 badusage "git-debrebase: no cuddling to -i for git-rebase"
2968 die if $opt_defaultcmd_interactive; # should not happen
2969 $opt_defaultcmd_interactive = [ qw(-i) ];
2970 # This access to @ARGV is excessive familiarity with
2971 # Getopt::Long, but there isn't another sensible
2972 # approach. '-i=s{0,}' does not work with bundling.
2973 push @$opt_defaultcmd_interactive, @ARGV;
2976 'help' => sub { print $usage_message or die $!; finish 0; },
2979 initdebug('git-debrebase ');
2980 enabledebug if $debuglevel;
2982 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2983 chdir $toplevel or die "chdir $toplevel: $!";
2985 $rd = fresh_playground "$playprefix/misc";
2987 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2989 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2990 defaultcmd_rebase();
2992 my $cmd = shift @ARGV;
2995 $cmdfn = ${*::}{"cmd_$cmdfn"};
2997 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";