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 $xp, $yp, sub {
314 my ($n,$ix,$iy) = @_;
316 # analyse difference in debian/patches
319 if ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
321 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
322 my $x_s = (git_cat_file "$xp/series", 'blob');
323 my $y_s = (git_cat_file "$yp/series", 'blob');
324 chomp $x_s; $x_s .= "\n";
325 $ok = $x_s eq substr($y_s, 0, length $x_s);
329 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
334 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
339 sub commit_pr_info ($) {
341 return Data::Dumper->dump([$r], [qw(commit)]);
344 sub calculate_committer_authline () {
345 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
346 'DUMMY COMMIT (git-debrebase)', "HEAD:";
347 my ($h,$m) = get_commit $c;
348 $h =~ m/^committer .*$/m or confess "($h) ?";
352 sub rm_subdir_cached ($) {
354 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
357 sub read_tree_subdir ($$) {
358 my ($subdir, $new_tree_object) = @_;
359 rm_subdir_cached $subdir;
360 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
363 sub read_tree_debian ($) {
365 read_tree_subdir 'debian', "$treeish:debian";
366 rm_subdir_cached 'debian/patches';
369 sub read_tree_upstream ($;$$) {
370 my ($treeish, $keep_patches, $tree_with_debian) = @_;
371 # if $tree_with_debian is supplied, will use that for debian/
372 # otherwise will save and restore it.
374 $tree_with_debian ? "$tree_with_debian:debian"
375 : cmdoutput @git, qw(write-tree --prefix=debian/);
376 runcmd @git, qw(read-tree), $treeish;
377 read_tree_subdir 'debian', $debian;
378 rm_subdir_cached 'debian/patches' unless $keep_patches;
381 sub make_commit ($$) {
382 my ($parents, $message_paras) = @_;
383 my $tree = cmdoutput @git, qw(write-tree);
384 my @cmd = (@git, qw(commit-tree), $tree);
385 push @cmd, qw(-p), $_ foreach @$parents;
386 push @cmd, qw(-m), $_ foreach @$message_paras;
387 return cmdoutput @cmd;
390 our @snag_force_opts;
392 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
393 if (grep { $_ eq $tag } @snag_force_opts) {
395 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
398 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
402 # Important: all mainline code must call snags_maybe_bail after
403 # any point where snag might be called, but before making changes
404 # (eg before any call to run_deferred_updates). snags_maybe_bail
405 # may be called more than once if necessary (but this is not ideal
406 # because then the messages about number of snags may be confusing).
407 sub snags_maybe_bail () {
408 return if all_snags_summarised();
411 "%s: snags: %d overriden by individual -f options\n",
414 if ($snags_tripped) {
417 "%s: snags: %d overriden by global --force\n",
421 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
425 $snags_summarised = $snags_forced + $snags_tripped;
427 sub snags_maybe_bail_early () {
428 # useful to bail out early without doing a lot of work;
429 # not a substitute for snags_maybe_bail.
430 snags_maybe_bail() if $snags_tripped && !$opt_force;
433 return $snags_forced || $snags_tripped;
436 sub ffq_prev_branchinfo () {
437 my $current = git_get_symref();
438 return gdr_ffq_prev_branchinfo($current);
441 sub record_gdrlast ($$;$) {
442 my ($gdrlast, $newvalue, $oldvalue) = @_;
443 $oldvalue ||= $git_null_obj;
444 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
447 sub fail_unprocessable ($) {
450 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
453 Branch/history seems mangled - no longer in gdr format.
454 See ILLEGAL OPERATIONS in git-debrebase(5).
461 Is this meant to be a gdr branch? $ffqm
463 } elsif (git_get_ref $ffq_prev) {
467 Consider git-debrebase scrap, to throw away your recent work.
469 } elsif (!git_get_ref $gdrlast) {
472 Branch does not seem to be meant to be a git-debrebase branch?
473 Wrong branch, or maybe you needed git-debrebase convert-from-*.
475 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
483 Branch/history mangled, and diverged since last git-debrebase.
484 Maybe you reset to, or rebased from, somewhere inappropriate.
489 sub gbp_pq_export ($$$) {
490 my ($bname, $base, $tip) = @_;
491 # must be run in a workarea. $bname and patch-queue/$bname
492 # ought not to exist. Leaves you on patch-queue/$bname with
493 # the patches staged but not committed.
494 printdebug "gbp_pq_export $bname $base $tip\n";
495 runcmd @git, qw(checkout -q -b), $bname, $base;
496 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
497 my @gbp_cmd = (qw(gbp pq export));
498 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
500 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
503 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
507 # MERGE-TODO allow merge resolution separately from laundering, before git merge
510 # use git-format-patch?
511 # our own patch identification algorithm?
512 # this is an alternative strategy
514 sub merge_failed ($$;@) {
515 my ($wrecknotes, $emsg, @xmsgs) = @_;
517 push @m, "Merge resolution failed: $emsg";
523 merge_wreckage_cleaning \@updates;
524 run_ref_updates_now "merge failed", \@updates;
528 while (my ($k,$v) = each %$wrecknotes) {
529 push @updates, "create $wrecknoteprefix/$k $v";
531 run_ref_updates_now "merge failed", \@updates;
532 push @m, "Wreckage left in $wrecknoteprefix/*.";
534 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
536 # use finish rather than fail, in case we are within an eval
537 # (that can happen inside walk!)
539 print STDERR "$us: $_\n" foreach @m;
543 sub mwrecknote ($$$) {
544 my ($wrecknotes, $reftail, $commitish) = @_;
545 confess unless defined $commitish;
546 printdebug "mwrecknote $reftail $commitish\n";
547 $wrecknotes->{$reftail} = $commitish;
550 sub merge_attempt_cmd {
551 my $wrecknotes = shift @_;
555 merge_failed $wrecknotes,
556 failedcmd_waitstatus(),
557 "failed command: @_";
561 sub merge_series_patchqueue_convert ($$$);
563 sub merge_series ($$$;@) {
564 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
565 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
566 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
567 # ^ specifies several patch series (currently we only support exactly 2)
568 # return value is a commit which is the result of
569 # merging the two versions of the same topic branch
570 # $input_q[0] and $input_q[1]
571 # with respect to the old version
575 # Creates, in *_q, a key MR for its private use
577 printdebug "merge_series newbase=$newbase\n";
579 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
580 $base_q->{MR}{S} = 'base';
583 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
584 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
585 # $prereq{<patch filename>} exists or not (even later)
589 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
591 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
594 fresh_workarea "merge";
595 my $seriesfile = "debian/patches/series";
598 foreach my $q ($base_q, reverse @input_qs) {
600 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
602 if (open S, $seriesfile) {
603 while (my $patch = <S>) {
604 chomp $patch or die $!;
605 $prereq{$patch} //= {};
606 foreach my $earlier (@earlier) {
607 $prereq{$patch}{$earlier}{$s}++ and die;
609 push @earlier, $patch;
610 stat "debian/patches/$patch" or die "$patch ?";
612 S->error and die "$seriesfile $!";
615 die "$seriesfile $!" unless $!==ENOENT;
617 read_tree_upstream $newbase, 1;
618 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
619 "Convert $s to patch queue for merging",
620 "[git-debrebase merge-innards patch-queue import:".
623 printdebug "merge_series pec $pec ";
624 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
625 $pec = make_commit [ $pec ], [
626 "Drop series file from $s to avoid merge trouble",
627 "[git-debrebase merge-innards patch-queue prep:".
631 read_tree_debian $newbase;
633 read_tree_subdir 'debian/patches', "$pec:debian/patches";
635 rm_subdir_cached 'debian/patches';
637 $pec = make_commit [ $pec ], [
638 "Update debian/ (excluding patches) to final to avoid re-merging",
639 "debian/ was already merged and we need to just take that.",
640 "[git-debrebase merge-innards patch-queue packaging:".
644 printdebug "pec' $pec\n";
645 runcmd @git, qw(reset -q --hard), $pec;
646 $q->{MR}{PEC} = $pec;
647 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
649 # now, because of reverse, we are on $input_q->{MR}{OQC}
650 runcmd @git, qw(checkout -q -b merge);
651 printdebug "merge_series merging...\n";
652 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
654 $attempt_cmd->(@mergecmd);
656 printdebug "merge_series merge ok, series...\n";
657 # We need to construct a new series file
658 # Firstly, resolve prereq
659 foreach my $f (sort keys %prereq) {
660 printdebug "merge_series patch\t$f\t";
661 if (!stat_exists "debian/patches/$f") {
662 print DEBUG " drop\n" if $debuglevel;
663 # git merge deleted it; that's how we tell it's not wanted
667 print DEBUG " keep\n" if $debuglevel;
668 foreach my $g (sort keys %{ $prereq{$f} }) {
669 my $gfp = $prereq{$f}{$g};
670 printdebug "merge_series prereq\t$f\t-> $g\t";
671 if (!!$gfp->{0} == !!$gfp->{1}
674 print DEBUG "\tkeep\n" if $debuglevel;
676 print DEBUG "\tdrop\n" if $debuglevel;
677 delete $prereq{$f}{$g};
684 return scalar keys %{ $prereq{$f} };
687 my $nodate = time + 1;
689 # $authordate{<patch filename>};
690 my $authordate = sub {
692 $authordate{$f} //= do {
693 open PF, "<", "debian/patches/$f" or die "$f $!";
695 return $nodate if m/^$/;
696 last if s{^Date: }{};
699 return cmdoutput qw(date +%s -d), $_;
703 open NS, '>', $seriesfile or die $!;
705 while (keys %prereq) {
707 foreach my $try (sort keys %prereq) {
710 $unsat->($try) <=> $unsat->($best) or
711 $authordate->($try) <=> $authordate->($best) or
717 printdebug "merge_series series next $best\n";
718 print NS "$best\n" or die $!;
719 delete $prereq{$best};
720 foreach my $gp (values %prereq) {
725 runcmd @git, qw(add), $seriesfile;
726 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
727 $merged_pq = git_rev_parse 'HEAD';
728 $mwrecknote->('merged-patchqueue', $merged_pq);
730 return merge_series_patchqueue_convert
731 $wrecknotes, $newbase, $merged_pq;
734 sub merge_series_patchqueue_convert ($$$) {
735 my ($wrecknotes, $newbase, $merged_pq) = @_;
740 printdebug "merge_series series gbp pq import\n";
741 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
743 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
744 # MERGE-TODO consider git-format-patch etc. instead,
745 # since gbp pq doesn't always round-trip :-/
747 # OK now we are on patch-queue/merge, and we need to rebase
748 # onto the intended parent and drop the patches from each one
750 printdebug "merge_series series ok, building...\n";
751 my $build = $newbase;
752 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
753 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
754 my $commit = git_cat_file $c, 'commit';
755 printdebug "merge_series series ok, building $c\n";
756 read_tree_upstream $c, 0, $newbase;
757 my $tree = cmdoutput @git, qw(write-tree);
758 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
759 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
760 open C, ">", "../mcommit" or die $!;
761 print C $commit or die $!;
763 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
766 mwrecknote($wrecknotes, 'merged-result', $result);
768 runcmd @git, qw(update-ref refs/heads/result), $result;
770 runcmd @git, qw(checkout -q -b debug);
771 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
772 runcmd @git, qw(add .);
773 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
774 my $mdebug = git_rev_parse 'HEAD';
775 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
776 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
778 printdebug "merge_series returns $result\n";
782 # classify returns an info hash like this
784 # Hdr => # commit headers, including 1 final newline
785 # Msg => # commit message (so one newline is dropped)
787 # Type => (see below)
789 # Ix => $index # ie 0, 1, 2, ...
791 # Differs => return value from get_differs
793 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
795 # NewMsg => # commit message, but with any [dgit import ...] edited
796 # # to say "[was: ...]"
806 # has additional entres in classification result
807 # Overwritten = [ subset of Parents ]
808 # Contributor = $the_remaining_Parent
810 # DgitImportUnpatched
811 # has additional entry in classification result
812 # OrigParents = [ subset of Parents ]
815 # has additional entry in classification result
816 # OrigParents = [ subset of Parents ] # singleton list
823 # has additional entry in classification result
826 sub parsecommit ($;$) {
827 my ($objid, $p_ref) = @_;
828 # => hash with CommitId Hdr Msg Tree Parents
829 # Parents entries have only Ix CommitId
830 # $p_ref, if provided, must be [] and is used as a base for Parents
835 my ($h,$m) = get_commit $objid;
837 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
838 my (@ph) = $h =~ m/^parent (\w+)$/mg;
848 foreach my $ph (@ph) {
850 Ix => scalar @$p_ref,
862 my $r = parsecommit($objid, \@p);
866 $p->{Differs} = (get_differs $p->{CommitId}, $t),
869 printdebug "classify $objid \$t=$t \@p",
870 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
874 my ($type, @rest) = @_;
875 $r = { %$r, Type => $type, @rest };
877 printdebug " = $type ".(dd $r)."\n";
883 $r = { %$r, Type => qw(Unknown), Why => $why };
884 printdebug " ** Unknown\n";
888 if (grep { $_ eq $objid } @opt_anchors) {
889 return $classify->('TreatAsAnchor');
892 my @identical = grep { !$_->{Differs} } @p;
893 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
894 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
896 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
897 # multi-orig upstreams are represented with an anchor merge
898 # from a single upstream commit which combines the orig tarballs
900 # Every anchor tagged this way must be a merge.
901 # We are relying on the
902 # [git-debrebase anchor: ...]
903 # commit message annotation in "declare" anchor merges (which
904 # do not have any upstream changes), to distinguish those
905 # anchor merges from ordinary pseudomerges (which we might
906 # just try to strip).
908 # However, the user is going to be doing git-rebase a lot. We
909 # really don't want them to rewrite an anchor commit.
910 # git-rebase trips up on merges, so that is a useful safety
913 # BreakwaterStart commits are also anchors in the terminology
914 # of git-debrebase(5), but they are untagged (and always
915 # manually generated).
917 # We cannot not tolerate any tagged linear commit (ie,
918 # BreakwaterStart commits tagged `[anchor:') because such a
919 # thing could result from an erroneous linearising raw git
920 # rebase of a merge anchor. That would represent a corruption
921 # of the branch. and we want to detect and reject the results
922 # of such corruption before it makes it out anywhere. If we
923 # reject it here then we avoid making the pseudomerge which
924 # would be needed to push it.
926 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
927 @p == 2 or return $badanchor->("has other than two parents");
928 $haspatches and return $badanchor->("contains debian/patches");
930 # How to decide about l/r ordering of anchors ? git
931 # --topo-order prefers to expand 2nd parent first. There's
932 # already an easy rune to look for debian/ history anyway (git log
933 # debian/) so debian breakwater branch should be 1st parent; that
934 # way also there's also an easy rune to look for the upstream
935 # patches (--topo-order).
937 # Also this makes --first-parent be slightly more likely to
938 # be useful - it makes it provide a linearised breakwater history.
940 # Of course one can say somthing like
941 # gitk -- ':/' ':!/debian'
942 # to get _just_ the commits touching upstream files, and by
943 # the TREESAME logic in git-rev-list this will leave the
944 # breakwater into upstream at the first anchor. But that
945 # doesn't report debian/ changes at all.
947 # Other observations about gitk: by default, gitk seems to
948 # produce output in a different order to git-rev-list. I
949 # can't seem to find this documented anywhere. gitk
950 # --date-order DTRT. But, gitk always seems to put the
951 # parents from left to right, in order, so it's easy to see
952 # which way round a pseudomerge is.
954 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
955 $p[1]{Differs} & ~DS_DEB and
956 $badanchor->("upstream files differ from left parent");
957 $p[0]{Differs} & ~D_UPS and
958 $badanchor->("debian/ differs from right parent");
960 return $classify->(qw(Anchor),
961 OrigParents => [ $p[1] ]);
965 my $d = $r->{Parents}[0]{Differs};
966 if ($d == D_PAT_ADD) {
967 return $classify->(qw(AddPatches));
968 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
969 return $unknown->("edits debian/patches");
970 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
971 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
973 if ($d == D_DEB_CLOG) {
974 return $classify->(qw(Changelog));
976 return $classify->(qw(Packaging));
978 } elsif ($ty eq 'missing') {
979 return $classify->(qw(BreakwaterStart));
981 return $unknown->("parent's debian is not a directory");
983 } elsif ($d == D_UPS) {
984 return $classify->(qw(Upstream));
985 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
986 return $classify->(qw(Mixed));
988 return $unknown->("no changes");
990 confess "internal error $objid ?";
994 return $unknown->("origin commit");
997 if (@p == 2 && @identical == 1) {
998 my @overwritten = grep { $_->{Differs} } @p;
999 confess "internal error $objid ?" unless @overwritten==1;
1000 return $classify->(qw(Pseudomerge),
1001 Overwritten => [ $overwritten[0] ],
1002 Contributor => $identical[0]);
1004 if (@p == 2 && @identical == 2) {
1006 my ($ph,$pm) = get_commit $_[0]{CommitId};
1007 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
1011 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
1012 if ($order > 0) { # newer first
1013 } elsif ($order < 0) {
1014 @bytime = reverse @bytime;
1016 # same age, default to order made by -s ours
1017 # that is, commit was made by someone who preferred L
1019 return $classify->(qw(Pseudomerge),
1020 SubType => qw(Ambiguous),
1021 Contributor => $bytime[0],
1022 Overwritten => [ $bytime[1] ]);
1024 foreach my $p (@p) {
1025 my ($p_h, $p_m) = get_commit $p->{CommitId};
1026 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1027 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1029 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1031 if (!(grep { !$_->{IsOrigin} } @p) and
1032 (@orig_ps >= @p - 1) and
1033 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1035 return $classify->(qw(DgitImportUnpatched),
1036 OrigParents => \@orig_ps);
1040 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1041 return $classify->("MergedBreakwaters");
1043 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1044 return $unknown->("unknown kind of merge from $1");
1047 return $unknown->("octopus merge");
1051 return $unknown->("general two-parent merge");
1054 return $classify->("VanillaMerge");
1057 sub keycommits ($;$$$$$);
1059 sub mergedbreakwaters_anchor ($) {
1062 foreach my $p (@{ $cl->{Parents} }) {
1063 my ($panchor, $pbw) = keycommits $p->{CommitId},
1064 undef,undef,undef,undef, 1;
1065 $best_anchor = $panchor
1066 if !defined $best_anchor
1067 or is_fast_fwd $best_anchor, $panchor;
1068 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
1069 unless is_fast_fwd $panchor, $best_anchor;
1071 return $best_anchor;
1074 sub keycommits ($;$$$$$) {
1075 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1076 # => ($anchor, $breakwater)
1078 # $unclean->("unclean-$tagsfx", $msg, $cl)
1079 # $furniture->("unclean-$tagsfx", $msg, $cl)
1080 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
1081 # is callled for each situation or commit that
1082 # wouldn't be found in a laundered branch
1083 # $furniture is for furniture commits such as might be found on an
1084 # interchange branch (pseudomerge, d/patches, changelog)
1085 # $trouble is for things whnich prevent the return of
1086 # anchor and breakwater information; if that is ignored,
1087 # then keycommits returns (undef, undef) instead.
1088 # $fatal is for unprocessable commits, and should normally cause
1089 # a failure. If ignored, agaion, (undef, undef) is returned.
1091 # If $claimed_bw, this is supposed to be a breakwater commit.
1093 # If a callback is undef, fail is called instead.
1094 # If a callback is defined but false, the situation is ignored.
1095 # Callbacks may say:
1096 # no warnings qw(exiting); last;
1097 # if the answer is no longer wanted.
1099 my ($anchor, $breakwater);
1100 $breakwater = $head if $claimed_bw;
1104 $fatal //= sub { fail_unprocessable $_[1]; };
1106 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1107 my $why = $mainwhy.$xwhy;
1108 my $m = "branch needs laundering (run git-debrebase): $why";
1109 fail $m unless defined $cb;
1111 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1113 my $found_anchor = sub {
1115 $breakwater //= $clogonly;
1116 $breakwater //= $head;
1117 no warnings qw(exiting);
1121 $cl = classify $head;
1122 my $ty = $cl->{Type};
1123 if ($ty eq 'Packaging') {
1124 $breakwater //= $clogonly;
1125 $breakwater //= $head;
1126 } elsif ($ty eq 'Changelog') {
1127 # this is going to count as the tip of the breakwater
1128 # only if it has no upstream stuff before it
1129 $clogonly //= $head;
1130 } elsif ($ty eq 'Anchor' or
1131 $ty eq 'TreatAsAnchor' or
1132 $ty eq 'BreakwaterStart') {
1133 $found_anchor->($head);
1134 } elsif ($ty eq 'Upstream') {
1135 $x->($unclean, 'ordering',
1136 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1137 if defined $breakwater;
1139 $breakwater = undef;
1140 } elsif ($ty eq 'Mixed') {
1141 $x->($unclean, 'mixed',
1142 "found mixed upstream/packaging commit"," ($head)");
1144 $breakwater = undef;
1145 } elsif ($ty eq 'Pseudomerge' or
1146 $ty eq 'AddPatches') {
1148 $x->($furniture, (lc $ty),
1149 "found interchange bureaucracy commit ($ty)"," ($head)");
1150 } elsif ($ty eq 'DgitImportUnpatched') {
1152 $x->($trouble, 'dgitimport',
1153 "found dgit dsc import"," ($head)");
1154 return (undef,undef);
1156 $x->($fatal, 'unprocessable',
1157 "found bare dgit dsc import with no prior history",
1159 return (undef,undef);
1161 } elsif ($ty eq 'VanillaMerge') {
1162 $x->($trouble, 'vanillamerge',
1163 "found vanilla merge"," ($head)");
1164 return (undef,undef);
1165 } elsif ($ty eq 'MergedBreakwaters') {
1166 $found_anchor->(mergedbreakwaters_anchor $cl);
1168 $x->($fatal, 'unprocessable',
1169 "found unprocessable commit, cannot cope: $cl->{Why}",
1171 return (undef,undef);
1173 $head = $cl->{Parents}[0]{CommitId};
1175 return ($anchor, $breakwater);
1181 $nogenerate,$report, $report_lprefix) = @_;
1182 # => ($tip, $breakwater_tip, $last_anchor)
1183 # (or nothing, if $nogenerate)
1185 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1186 $report_lprefix //= '';
1188 # go through commits backwards
1189 # we generate two lists of commits to apply:
1190 # breakwater branch and upstream patches
1191 my (@brw_cl, @upp_cl, @processed);
1198 my ($prose, $info) = @_;
1199 my $ms = $cl->{Msg};
1202 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1203 return (Msg => $ms);
1205 my $rewrite_from_here = sub {
1207 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1209 push @processed, $sp_cl;
1214 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1217 return unless $report;
1218 print $report $prdelim, $report_lprefix, @_;
1222 my $bomb = sub { # usage: return $bomb->();
1223 print $report " Unprocessable" if $report;
1224 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1227 return (undef,undef);
1229 fail_unprocessable "found unprocessable commit, cannot cope".
1230 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1231 " (commit $cur) (d.".
1232 (join ' ', map { sprintf "%#x", $_->{Differs} }
1233 @{ $cl->{Parents} }).
1240 my $build_start = sub {
1241 my ($msg, $parent) = @_;
1244 no warnings qw(exiting); last;
1249 merge_failed $cl->{MergeWreckNotes}, $emsg;
1252 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1257 $cl = classify $cur;
1258 $cl->{MergeWreckNotes} //= {};
1259 my $ty = $cl->{Type};
1260 my $st = $cl->{SubType};
1261 $prline->("$cl->{CommitId} $cl->{Type}");
1262 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1263 push @processed, $cl;
1264 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1265 if ($ty eq 'AddPatches') {
1267 $rewrite_from_here->(\@upp_cl);
1269 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1273 } elsif ($ty eq 'BreakwaterStart') {
1274 $last_anchor = $cur;
1275 $build_start->('FirstPackaging', $cur);
1276 } elsif ($ty eq 'Upstream') {
1280 } elsif ($ty eq 'Mixed') {
1283 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1286 $queue->(\@brw_cl, "debian");
1287 $queue->(\@upp_cl, "upstream");
1288 $rewrite_from_here->(\@brw_cl);
1291 } elsif ($ty eq 'Pseudomerge') {
1292 my $contrib = $cl->{Contributor}{CommitId};
1293 print $report " Contributor=$contrib" if $report;
1294 push @pseudomerges, $cl;
1295 $rewrite_from_here->(\@upp_cl);
1298 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1299 $last_anchor = $cur;
1300 $build_start->("Anchor", $cur);
1301 } elsif ($ty eq 'DgitImportUnpatched') {
1302 my $pm = $pseudomerges[-1];
1304 # To an extent, this is heuristic. Imports don't have
1305 # a useful history of the debian/ branch. We assume
1306 # that the first pseudomerge after an import has a
1307 # useful history of debian/, and ignore the histories
1308 # from later pseudomerges. Often the first pseudomerge
1309 # will be the dgit import of the upload to the actual
1310 # suite intended by the non-dgit NMUer, and later
1311 # pseudomerges may represent in-archive copies.
1312 my $ovwrs = $pm->{Overwritten};
1313 printf $report " PM=%s \@Overwr:%d",
1314 $pm->{CommitId}, (scalar @$ovwrs)
1317 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1320 my $ovwr = $ovwrs->[0]{CommitId};
1321 printf $report " Overwr=%s", $ovwr if $report;
1322 # This import has a tree which is just like a
1323 # breakwater tree, but it has the wrong history. It
1324 # ought to have the previous breakwater (which the
1325 # pseudomerge overwrote) as an ancestor. That will
1326 # make the history of the debian/ files correct. As
1327 # for the upstream version: either it's the same as
1328 # was ovewritten (ie, same as the previous
1329 # breakwater), in which case that history is precisely
1330 # right; or, otherwise, it was a non-gitish upload of a
1331 # new upstream version. We can tell these apart by
1332 # looking at the tree of the supposed upstream.
1335 SpecialMethod => 'DgitImportDebianUpdate',
1336 $xmsg->("convert dgit import: debian changes")
1339 SpecialMethod => 'DgitImportUpstreamUpdate',
1340 $xmsg->("convert dgit import: upstream update",
1343 $prline->(" Import");
1344 $rewrite_from_here->(\@brw_cl);
1345 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1349 # Everything is from this import. This kind of import
1350 # is already nearly in valid breakwater format, with the
1351 # patches as commits. Unfortunately it contains
1353 printdebug "*** WALK BOMB bare dgit import\n";
1354 $cl->{Why} = "bare dgit dsc import";
1358 } elsif ($ty eq 'MergedBreakwaters') {
1359 $last_anchor = mergedbreakwaters_anchor $cl;
1360 $build_start->(' MergedBreakwaters', $cur);
1362 } elsif ($ty eq 'VanillaMerge') {
1363 # User may have merged unstitched branch(es). We will
1364 # have now lost what ffq-prev was then (since the later
1365 # pseudomerge may introduce further changes). The effect
1366 # of resolving such a merge is that we may have to go back
1367 # further in history to find a merge base, since the one
1368 # which was reachable via ffq-prev is no longer findable.
1369 # This is suboptimal, but if it all works we'll have done
1371 # MERGE-TODO we should warn the user in the docs about this
1375 # We expect to find a dominating anchor amongst the
1376 # inputs' anchors. That will be the new anchor.
1378 # More complicated is finding a merge base for the
1379 # breakwaters. We need a merge base that is a breakwater
1380 # commit. The ancestors of breakwater commits are more
1381 # breakwater commits and possibly upstream commits and the
1382 # ancestors of those upstream. Upstreams might have
1383 # arbitrary ancestors. But any upstream commit U is
1384 # either included in both anchors, in which case the
1385 # earlier anchor is a better merge base than any of U's
1386 # ancestors; or U is not included in the older anchor, in
1387 # which case U is not an ancestor of the vanilla merge at
1388 # all. So no upstream commit, nor any ancestor thereof,
1389 # is a best merge base. As for non-breakwater Debian
1390 # commits: these are never ancestors of any breakwater.
1392 # So any best merge base as found by git-merge-base
1393 # is a suitable breakwater anchor. Usually there will
1396 printdebug "*** MERGE\n";
1398 my @bwbcmd = (@git, qw(merge-base));
1399 my @ibcmd = (@git, qw(merge-base --all));
1400 my $might_be_in_bw = 1;
1402 my $ps = $cl->{Parents};
1404 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1406 foreach my $p (@$ps) {
1407 $prline->(" VanillaMerge ".$p->{Ix});
1409 my ($ptip, $pbw, $panchor) =
1410 walk $p->{CommitId}, 0, $report,
1411 $report_lprefix.' ';
1412 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1413 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1414 $p->{Anchor} = $panchor;
1416 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1417 $mwrecknote->("$lr-input", $p->{CommitId});
1419 my $mwrecknote_parent = sub {
1421 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1423 $mwrecknote_parent->('Laundered');
1424 $mwrecknote_parent->('Breakwater');
1425 $mwrecknote_parent->('Anchor');
1427 $best_anchor = $panchor if
1428 !defined $best_anchor or
1429 is_fast_fwd $best_anchor, $panchor;
1431 printdebug " MERGE BA best=".($best_anchor//'-').
1435 $mwrecknote->('result-anchor', $best_anchor);
1437 foreach my $p (@$ps) {
1438 $prline->(" VanillaMerge ".$p->{Ix});
1439 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1440 $nomerge->('divergent anchors');
1441 } elsif ($p->{Anchor} eq $best_anchor) {
1442 print $report " SameAnchor" if $report;
1444 print $report " SupersededAnchor" if $report;
1446 if ($p->{Breakwater} eq $p->{CommitId}) {
1447 # this parent commit was its own breakwater,
1448 # ie it is part of the breakwater
1449 print $report " Breakwater" if $report;
1451 $might_be_in_bw = 0;
1453 push @bwbcmd, $p->{Breakwater};
1454 push @ibcmd, $p->{CommitId};
1457 if ($ok && $might_be_in_bw) {
1458 # We could rewrite this to contaion the metadata
1459 # declaring it to be MergedBreakwaters, but
1460 # unnecessarily rewriting a merge seems unhelpful.
1461 $prline->(" VanillaMerge MergedBreakwaters");
1462 $last_anchor = $best_anchor;
1463 $build_start->('MergedBreakwaters', $cur);
1466 my $bwb = cmdoutput @bwbcmd;
1468 # OK, now we have a breakwater base, but we need the merge
1469 # base for the interchange branch because we need the delta
1472 # This a the best merge base of our inputs which has the
1473 # breakwater merge base as an ancestor.
1480 @ibs or confess 'internal error, expected anchor at least ?';
1484 foreach my $tibix (0..$#ibs) {
1485 my $tib = $ibs[$tibix];
1486 my $ff = is_fast_fwd $bwb, $tib;
1487 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1488 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1489 $mwrecknote->($tibleaf, $tib);
1496 $ib or $nomerge->("no suitable interchange merge base");
1498 $prline->(" VanillaMerge Base");
1500 my ($btip, $bbw, $banchor) = eval {
1501 walk $ib, 0, $report, $report_lprefix.' ';
1503 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1507 $mwrecknote->("mergebase-laundered", $btip);
1508 $mwrecknote->("mergebase-breakwater", $bbw);
1509 $mwrecknote->("mergebase-anchor", $banchor);
1511 my $ibinfo = { SeriesTip => $btip,
1514 LeftRight => 'mergebase' };
1517 or $nomerge->("interchange merge-base ($ib)'s".
1518 " breakwater ($bbw)".
1519 " != breakwaters' merge-base ($bwb)");
1521 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1522 or $nomerge->("interchange merge-base ($ib)'s".
1523 " anchor ($ibinfo->{SeriesBase})".
1524 " != any merge input's anchor (".
1525 (join ' ', map { $_->{Anchor} } @$ps).
1528 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1529 $cl->{MergeBestAnchor} = $best_anchor;
1532 SpecialMethod => 'MergeCreateMergedBreakwaters',
1533 $xmsg->('constructed from vanilla merge',
1534 ' merged-breakwater'),
1538 SpecialMethod => 'MergeMergeSeries',
1540 $build_start->('MergeBreakwaters', $cur);
1542 printdebug "*** WALK BOMB unrecognised\n";
1548 printdebug "*** WALK prep done cur=$cur".
1549 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1551 return if $nogenerate;
1553 # Now we build it back up again
1559 $#upp_cl = $upp_limit if defined $upp_limit;
1561 my $committer_authline = calculate_committer_authline();
1563 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1565 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1568 mkdir $rd or $!==EEXIST or die $!;
1570 my $want_debian = $build;
1571 my $want_upstream = $build;
1573 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1574 my $read_tree_debian = sub { ($want_debian) = @_; };
1576 foreach my $cl (qw(Debian), (reverse @brw_cl),
1577 { SpecialMethod => 'RecordBreakwaterTip' },
1578 qw(Upstream), (reverse @upp_cl)) {
1580 $current_method = $cl;
1583 my $method = $cl->{SpecialMethod} // $current_method;
1584 my @parents = ($build);
1585 my $cltree = $cl->{CommitId};
1586 printdebug "WALK BUILD ".($cltree//'undef').
1587 " $method (rewriting=$rewriting)\n";
1588 if ($method eq 'Debian') {
1589 $read_tree_debian->($cltree);
1590 } elsif ($method eq 'Upstream') {
1591 $read_tree_upstream->($cltree);
1592 } elsif ($method eq 'StartRewrite') {
1595 } elsif ($method eq 'RecordBreakwaterTip') {
1596 $breakwater = $build;
1598 } elsif ($method eq 'DgitImportDebianUpdate') {
1599 $read_tree_debian->($cltree);
1600 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1601 confess unless $rewriting;
1602 my $differs = (get_differs $build, $cltree);
1603 next unless $differs & D_UPS;
1604 $read_tree_upstream->($cltree);
1605 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1606 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1607 print "Found a general merge, will try to tidy it up.\n";
1609 $read_tree_upstream->($cl->{MergeBestAnchor});
1610 $read_tree_debian->($cltree);
1611 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1612 } elsif ($method eq 'MergeMergeSeries') {
1613 my $cachehit = reflog_cache_lookup
1614 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1616 print "Using supplied resolution for $cl->{CommitId}...\n";
1618 $mwrecknote->('cached-resolution', $build);
1620 print "Running merge resolution for $cl->{CommitId}...\n";
1621 $mwrecknote->('new-base', $build);
1622 $build = merge_series
1623 $build, $cl->{MergeWreckNotes},
1624 $cl->{MergeInterchangeBaseInfo},
1625 @{ $cl->{Parents} };
1627 $last_anchor = $cl->{MergeBestAnchor};
1629 # Check for mismerges:
1631 my ($against, $allow, $what) = @_;
1632 my $differs = get_differs $build, $against;
1634 "merge misresolved: %s are not the same (%s %s d.%#x)",
1635 $what, $against, $build, $differs)
1636 if $differs & ~($allow | D_PAT_ADD);
1639 # Breakwater changes which were in each side of the
1640 # merge will have been incorporated into the
1641 # MergeCreateMergedBreakwaters output. Because the
1642 # upstream series was rebased onto the new breakwater,
1643 # so should all of the packaging changes which were in
1645 $check->($input, D_UPS, 'debian files');
1647 # Upstream files are merge_series, which ought to
1648 # have been identical to the original merge.
1649 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1651 print "Merge resolution successful.\n";
1654 confess "$method ?";
1657 my $procd = (pop @processed) // 'UNDEF';
1658 if ($cl ne $procd) {
1660 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1664 read_tree_upstream $want_upstream, 0, $want_debian;
1666 my $newtree = cmdoutput @git, qw(write-tree);
1667 my $ch = $cl->{Hdr};
1668 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1669 $ch =~ s{^parent .*\n}{}mg;
1670 $ch =~ s{(?=^author)}{
1671 join '', map { "parent $_\n" } @parents
1672 }me or confess "$ch ?";
1674 $ch =~ s{^committer .*$}{$committer_authline}m
1677 my $cf = "$rd/m$rewriting";
1678 open CD, ">", $cf or die $!;
1679 print CD $ch, "\n", $cl->{Msg} or die $!;
1681 my @cmd = (@git, qw(hash-object));
1682 push @cmd, qw(-w) if $rewriting;
1683 push @cmd, qw(-t commit), $cf;
1684 my $newcommit = cmdoutput @cmd;
1685 confess "$ch ?" unless $rewriting
1686 or $newcommit eq $cl->{CommitId};
1687 $build = $newcommit;
1689 $build = $cl->{CommitId};
1690 trees_diff_walk "$want_upstream:", "$build:", sub {
1692 no warnings qw(exiting);
1693 next if $n eq 'debian/';
1694 confess "mismatch @_ ?";
1696 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1697 confess "mismatch @_ ?";
1699 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1700 confess "mismatch @parents != @old_parents ?"
1701 unless "@parents" eq "@old_parents";
1703 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1704 $last_anchor = $cur;
1709 my $final_check = get_differs $build, $input;
1710 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1711 if $final_check & ~D_PAT_ADD;
1713 my @r = ($build, $breakwater, $last_anchor);
1714 printdebug "*** WALK RETURN @r\n";
1719 git_check_unmodified();
1720 return git_rev_parse qw(HEAD);
1723 sub update_head ($$$) {
1724 my ($old, $new, $mrest) = @_;
1725 push @deferred_updates, "update HEAD $new $old";
1726 run_deferred_updates $mrest;
1729 sub update_head_checkout ($$$) {
1730 my ($old, $new, $mrest) = @_;
1731 update_head $old, $new, $mrest;
1732 runcmd @git, qw(reset --hard);
1735 sub update_head_postlaunder ($$$) {
1736 my ($old, $tip, $reflogmsg) = @_;
1737 return if $tip eq $old && !@deferred_updates;
1738 print "git-debrebase: laundered (head was $old)\n";
1739 update_head $old, $tip, $reflogmsg;
1740 # no tree changes except debian/patches
1741 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1744 sub currently_rebasing() {
1745 foreach (qw(rebase-merge rebase-apply)) {
1746 return 1 if stat_exists "$maindir_gitdir/$_";
1751 sub bail_if_rebasing() {
1752 fail "you are in the middle of a git-rebase already"
1753 if currently_rebasing();
1756 sub do_launder_head ($) {
1757 my ($reflogmsg) = @_;
1758 my $old = get_head();
1760 my ($tip,$breakwater) = walk $old;
1762 update_head_postlaunder $old, $tip, $reflogmsg;
1763 return ($tip,$breakwater);
1766 sub cmd_launder_v0 () {
1767 badusage "no arguments to launder-v0 allowed" if @ARGV;
1768 my $old = get_head();
1769 my ($tip,$breakwater,$last_anchor) = walk $old;
1770 update_head_postlaunder $old, $tip, 'launder';
1771 printf "# breakwater tip\n%s\n", $breakwater;
1772 printf "# working tip\n%s\n", $tip;
1773 printf "# last anchor\n%s\n", $last_anchor;
1776 sub defaultcmd_rebase () {
1777 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1778 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1779 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1782 sub cmd_analyse () {
1783 badusage "analyse does not support any options"
1784 if @ARGV and $ARGV[0] =~ m/^-/;
1785 badusage "too many arguments to analyse" if @ARGV>1;
1788 $old = git_rev_parse $old;
1790 $old = git_rev_parse 'HEAD';
1792 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1793 STDOUT->error and die $!;
1796 sub ffq_check ($;$$) {
1797 # calls $ff and/or $notff zero or more times
1798 # then returns either (status,message) where status is
1803 # or (undef,undef, $ffq_prev,$gdrlast)
1804 # $ff and $notff are called like this:
1805 # $ff->("message for stdout\n");
1806 # $notff->('snag-name', $message);
1807 # normally $currentval should be HEAD
1808 my ($currentval, $ff, $notff) =@_;
1810 $ff //= sub { print $_[0] or die $!; };
1813 my ($status, $message, $current, $ffq_prev, $gdrlast)
1814 = ffq_prev_branchinfo();
1815 return ($status, $message) unless $status eq 'branch';
1817 my $exists = git_get_ref $ffq_prev;
1818 return ('exists',"$ffq_prev already exists") if $exists;
1820 return ('not-branch', 'HEAD symref is not to refs/heads/')
1821 unless $current =~ m{^refs/heads/};
1824 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1827 printdebug "ffq check_specs @check_specs\n";
1830 my ($lrref, $desc) = @_;
1831 printdebug "ffq might check $lrref ($desc)\n";
1833 for my $chk (@check_specs) {
1835 $invert = $glob =~ s{^[!^]}{};
1836 last if fnmatch $glob, $lrref;
1839 my $lrval = git_get_ref $lrref;
1840 return unless length $lrval;
1842 if (is_fast_fwd $lrval, $currentval) {
1843 $ff->("OK, you are ahead of $lrref\n");
1844 $checked{$lrref} = 1;
1845 } elsif (is_fast_fwd $currentval, $lrval) {
1846 $checked{$lrref} = -1;
1847 $notff->('behind', "you are behind $lrref, divergence risk");
1849 $checked{$lrref} = -1;
1850 $notff->('diverged', "you have diverged from $lrref");
1854 my $merge = cfg "branch.$branch.merge",1;
1855 if (defined $merge and $merge =~ m{^refs/heads/}) {
1857 printdebug "ffq merge $rhs\n";
1858 my $check_remote = sub {
1859 my ($remote, $desc) = @_;
1860 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1861 return unless defined $remote;
1862 $check->("refs/remotes/$remote/$rhs", $desc);
1864 $check_remote->((scalar cfg "branch.$branch.remote",1),
1865 'remote fetch/merge branch');
1866 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1867 (scalar cfg "branch.$branch.pushDefault",1),
1868 'remote push branch');
1870 if ($branch =~ m{^dgit/}) {
1871 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1872 } elsif ($branch =~ m{^master$}) {
1873 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1875 return (undef, undef, $ffq_prev, $gdrlast);
1878 sub record_ffq_prev_deferred () {
1879 # => ('status', "message")
1881 # deferred message is undef
1886 # if not ff from some branch we should be ff from, is an snag
1887 # if "deferred", will have added something about that to
1888 # @deferred_update_messages, and also maybe printed (already)
1889 # some messages about ff checks
1891 my $currentval = get_head();
1893 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1894 return ($status,$message) if defined $status;
1898 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1899 push @deferred_updates, "delete $gdrlast";
1900 push @deferred_update_messages, "Recorded previous head for preservation";
1901 return ('deferred', undef);
1904 sub record_ffq_auto () {
1905 my ($status, $message) = record_ffq_prev_deferred();
1906 if ($status eq 'deferred' || $status eq 'exists') {
1908 snag $status, "could not record ffq-prev: $message";
1913 sub ffq_prev_info () {
1915 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1916 my ($status, $message, $current, $ffq_prev, $gdrlast)
1917 = ffq_prev_branchinfo();
1918 if ($status ne 'branch') {
1919 snag $status, "could not check ffq-prev: $message";
1922 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1923 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1926 sub stitch ($$$$$) {
1927 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1929 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1931 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1932 my $differs = get_differs $old_head, $ffq_prev_commitish;
1933 unless ($differs & ~D_PAT_ADD) {
1934 # ffq-prev is ahead of us, and the only tree changes it has
1935 # are possibly addition of things in debian/patches/.
1936 # Just wind forwards rather than making a pointless pseudomerge.
1937 record_gdrlast $gdrlast, $ffq_prev_commitish;
1938 update_head_checkout $old_head, $ffq_prev_commitish,
1939 "stitch (fast forward)";
1944 # We make pseudomerges with L as the contributing parent.
1945 # This makes git rev-list --first-parent work properly.
1946 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1947 'Declare fast forward / record previous work',
1948 "[git-debrebase pseudomerge: $prose]",
1950 record_gdrlast $gdrlast, $new_head;
1951 update_head $old_head, $new_head, "stitch: $prose";
1954 sub do_stitch ($;$) {
1955 my ($prose, $unclean) = @_;
1957 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1958 if (!$ffq_prev_commitish) {
1959 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1962 my $dangling_head = get_head();
1964 keycommits $dangling_head, $unclean,$unclean,$unclean;
1967 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1970 sub upstream_commitish_search ($$) {
1971 my ($upstream_version, $tried) = @_;
1972 # todo: at some point maybe use git-deborig to do this
1973 foreach my $tagpfx ('', 'v', 'upstream/') {
1974 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1975 my $new_upstream = git_get_ref "refs/tags/$tag";
1977 return $new_upstream if length $new_upstream;
1981 sub resolve_upstream_version ($$) {
1982 my ($new_upstream, $upstream_version) = @_;
1984 if (!defined $new_upstream) {
1986 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1987 if (!length $new_upstream) {
1988 fail "Could not determine appropriate upstream commitish.\n".
1989 " (Tried these tags: @tried)\n".
1990 " Check version, and specify upstream commitish explicitly.";
1993 $new_upstream = git_rev_parse $new_upstream;
1995 return $new_upstream;
1998 sub cmd_new_upstream () {
1999 # automatically and unconditionally launders before rebasing
2000 # if rebase --abort is used, laundering has still been done
2004 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
2006 # parse args - low commitment
2007 my $spec_version = shift @ARGV;
2008 my $new_version = (new Dpkg::Version $spec_version, check => 1);
2009 fail "bad version number \`$spec_version'" unless defined $new_version;
2010 if ($new_version->is_native()) {
2011 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
2014 my $new_upstream = shift @ARGV;
2015 my $new_upstream_version = upstreamversion $new_version;
2017 resolve_upstream_version $new_upstream, $new_upstream_version;
2022 my ($n, @x) = @_; # may be ''
2023 my $pc = $pieces{$n} //= {
2025 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
2027 while (my $k = shift @x) { $pc->{$k} = shift @x; }
2032 my $newpiece = sub {
2033 my ($n, @x) = @_; # may be ''
2034 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2035 push @newpieces, $pc;
2040 New => $new_upstream,
2042 while (@ARGV && $ARGV[0] !~ m{^-}) {
2043 my $n = shift @ARGV;
2045 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2046 unless @ARGV && $ARGV[0] !~ m{^-};
2048 my $c = git_rev_parse shift @ARGV;
2049 die unless $n =~ m/^$extra_orig_namepart_re$/;
2050 $newpiece->($n, New => $c);
2053 # now we need to investigate the branch this generates the
2054 # laundered version but we don't switch to it yet
2055 my $old_head = get_head();
2056 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2058 my $old_bw_cl = classify $old_bw;
2059 my $old_anchor_cl = classify $old_anchor;
2061 if (!$old_anchor_cl->{OrigParents}) {
2062 snag 'anchor-treated',
2063 'old anchor is recognised due to --anchor, cannot check upstream';
2065 $old_upstream = parsecommit
2066 $old_anchor_cl->{OrigParents}[0]{CommitId};
2067 $piece->('', Old => $old_upstream->{CommitId});
2070 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2071 if ($old_upstream->{Msg} =~
2072 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2074 my @oldpieces = (split / /, $1);
2075 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2076 if ($old_n_parents != @oldpieces &&
2077 $old_n_parents != @oldpieces + 1) {
2078 snag 'upstream-confusing', sprintf
2079 "previous upstream combine %s".
2080 " mentions %d pieces (each implying one parent)".
2081 " but has %d parents".
2082 " (one per piece plus maybe a previous combine)",
2083 $old_upstream->{CommitId},
2084 (scalar @oldpieces),
2086 } elsif ($oldpieces[0] ne '.') {
2087 snag 'upstream-confusing', sprintf
2088 "previous upstream combine %s".
2089 " first piece is not \`.'",
2093 foreach my $i (0..$#oldpieces) {
2094 my $n = $oldpieces[$i];
2095 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2096 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2100 snag 'upstream-confusing',
2101 "previous upstream $old_upstream->{CommitId} is from".
2102 " git-debrebase but not an \`upstream-combine' commit";
2106 foreach my $pc (values %pieces) {
2107 if (!$old_upstream) {
2108 # we have complained already
2109 } elsif (!$pc->{Old}) {
2110 snag 'upstream-new-piece',
2111 "introducing upstream piece \`$pc->{Name}'";
2112 } elsif (!$pc->{New}) {
2113 snag 'upstream-rm-piece',
2114 "dropping upstream piece \`$pc->{Name}'";
2115 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2116 snag 'upstream-not-ff',
2117 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2121 printdebug "%pieces = ", (dd \%pieces), "\n";
2122 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2130 my @upstream_merge_parents;
2133 push @upstream_merge_parents, $old_upstream->{CommitId};
2136 foreach my $pc (@newpieces) { # always has '' first
2138 read_tree_subdir $pc->{Name}, $pc->{New};
2140 runcmd @git, qw(read-tree), $pc->{New};
2142 push @upstream_merge_parents, $pc->{New};
2145 # index now contains the new upstream
2147 if (@newpieces > 1) {
2148 # need to make the upstream subtree merge commit
2149 $new_upstream = make_commit \@upstream_merge_parents,
2150 [ "Combine upstreams for $new_upstream_version",
2151 ("[git-debrebase upstream-combine . ".
2152 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2157 # $new_upstream is either the single upstream commit, or the
2158 # combined commit we just made. Either way it will be the
2159 # "upstream" parent of the anchor merge.
2161 read_tree_subdir 'debian', "$old_bw:debian";
2163 # index now contains the anchor merge contents
2164 $new_bw = make_commit [ $old_bw, $new_upstream ],
2165 [ "Update to upstream $new_upstream_version",
2166 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2169 my $clogsignoff = cmdoutput qw(git show),
2170 '--pretty=format:%an <%ae> %aD',
2173 # Now we have to add a changelog stanza so the Debian version
2175 die if unlink "debian";
2176 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2177 unlink "debian/changelog" or $!==ENOENT or die $!;
2178 mkdir "debian" or die $!;
2179 open CN, ">", "debian/changelog" or die $!;
2180 my $oldclog = git_cat_file ":debian/changelog";
2181 $oldclog =~ m/^($package_re) \(\S+\) / or
2182 fail "cannot parse old changelog to get package name";
2184 print CN <<END, $oldclog or die $!;
2185 $p ($new_version) UNRELEASED; urgency=medium
2187 * Update to new upstream version $new_upstream_version.
2193 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2195 # Now we have the final new breakwater branch in the index
2196 $new_bw = make_commit [ $new_bw ],
2197 [ "Update changelog for new upstream $new_upstream_version",
2198 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2202 # we have constructed the new breakwater. we now need to commit to
2203 # the laundering output, because git-rebase can't easily be made
2204 # to make a replay list which is based on some other branch
2206 update_head_postlaunder $old_head, $old_laundered_tip,
2207 'launder for new upstream';
2209 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2210 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2211 "debrebase new-upstream $new_version: rebase";
2213 # now it's for the user to sort out
2216 sub cmd_record_ffq_prev () {
2217 badusage "no arguments allowed" if @ARGV;
2218 my ($status, $msg) = record_ffq_prev_deferred();
2219 if ($status eq 'exists' && $opt_noop_ok) {
2220 print "Previous head already recorded\n" or die $!;
2221 } elsif ($status eq 'deferred') {
2222 run_deferred_updates 'record-ffq-prev';
2224 fail "Could not preserve: $msg";
2229 badusage "no arguments allowed" if @ARGV;
2230 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2231 print "$bw\n" or die $!;
2234 sub cmd_breakwater () {
2235 badusage "no arguments allowed" if @ARGV;
2236 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2237 print "$bw\n" or die $!;
2241 badusage "no arguments allowed" if @ARGV;
2243 # todo: gdr status should print divergence info
2244 # todo: gdr status should print upstream component(s) info
2245 # todo: gdr should leave/maintain some refs with this kind of info ?
2247 my $oldest = { Badness => 0 };
2250 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2251 if ($oldest->{Badness} < $badness) {
2252 $oldest = $newest = undef;
2255 Badness => $badness,
2256 CommitId => $cl->{CommitId},
2260 $newest //= $oldest;
2262 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2263 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2264 sub { $note->(2, 'branch is unlaundered', @_); },
2265 sub { $note->(3, 'branch needs laundering', @_); },
2266 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2268 my $prcommitinfo = sub {
2270 flush STDOUT or die $!;
2271 runcmd @git, qw(--no-pager log -n1),
2272 '--pretty=format: %h %s%n',
2276 print "current branch contents, in git-debrebase terms:\n";
2277 if (!$oldest->{Badness}) {
2278 print " branch is laundered\n";
2280 print " $oldest->{OurMsg}\n";
2282 foreach my $info ($oldest, $newest) {
2283 my $cid = $info->{CommitId};
2284 next if $cid eq $printed;
2286 print " $info->{KcMsg}\n";
2287 $prcommitinfo->($cid);
2292 my ($cid, $what) = @_;
2293 if (!defined $cid) {
2294 print " $what is not well-defined\n";
2297 $prcommitinfo->($cid);
2300 print "key git-debrebase commits:\n";
2301 $prab->($anchor, 'anchor');
2302 $prab->($bw, 'breakwater');
2304 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2305 ffq_prev_branchinfo();
2307 print "branch and ref status, in git-debrebase terms:\n";
2309 print " $ffq_msg\n";
2311 $ffq_prev = git_get_ref $ffq_prev;
2312 $gdrlast = git_get_ref $gdrlast;
2314 print " unstitched; previous tip was:\n";
2315 $prcommitinfo->($ffq_prev);
2316 } elsif (!$gdrlast) {
2317 print " stitched? (no record of git-debrebase work)\n";
2318 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2319 print " stitched\n";
2321 print " not git-debrebase (diverged since last stitch)\n"
2324 print "you are currently rebasing\n" if currently_rebasing();
2328 my $prose = 'stitch';
2329 getoptions("stitch",
2330 'prose=s', \$prose);
2331 badusage "no arguments allowed" if @ARGV;
2332 do_stitch $prose, 0;
2334 sub cmd_prepush () {
2340 badusage "no arguments allowed" if @ARGV;
2341 do_launder_head 'launder for git-debrebase quick';
2345 sub cmd_conclude () {
2346 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2347 if (!$ffq_prev_commitish) {
2348 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2351 my $dangling_head = get_head();
2353 badusage "no arguments allowed" if @ARGV;
2354 do_launder_head 'launder for git-debrebase quick';
2359 if (currently_rebasing()) {
2360 runcmd @git, qw(rebase --abort);
2361 push @deferred_updates, 'verify HEAD HEAD';
2362 # noop, but stops us complaining that scrap was a noop
2364 badusage "no arguments allowed" if @ARGV;
2365 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2367 if ($ffq_prev_commitish) {
2368 $scrapping_head = get_head();
2369 push @deferred_updates,
2370 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2371 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2373 if (git_get_ref $merge_cache_ref) {
2374 push @deferred_updates,
2375 "delete $merge_cache_ref";
2377 if (!@deferred_updates) {
2378 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2382 if ($scrapping_head) {
2383 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2385 run_deferred_updates "scrap";
2389 sub make_patches_staged ($) {
2391 # Produces the patches that would result from $head if it were
2393 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2396 gbp_pq_export 'bw', $secret_bw, $secret_head;
2400 sub make_patches ($) {
2402 keycommits $head, 0, \&snag;
2403 make_patches_staged $head;
2406 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2407 runcmd @git, qw(read-tree), $head;
2408 read_tree_subdir 'debian/patches', $ptree;
2409 $out = make_commit [$head], [
2410 'Commit patch queue (exported by git-debrebase)',
2411 '[git-debrebase: export and commit patches]',
2417 sub cmd_make_patches () {
2418 my $opt_quiet_would_amend;
2419 getoptions("make-patches",
2420 'quiet-would-amend!', \$opt_quiet_would_amend);
2421 badusage "no arguments allowed" if @ARGV;
2423 my $old_head = get_head();
2424 my $new = make_patches $old_head;
2425 my $d = get_differs $old_head, $new;
2427 fail "No (more) patches to export." unless $opt_noop_ok;
2429 } elsif ($d == D_PAT_ADD) {
2431 update_head_checkout $old_head, $new, 'make-patches';
2433 print STDERR failmsg
2434 "Patch export produced patch amendments".
2435 " (abandoned output commit $new).".
2436 " Try laundering first."
2437 unless $opt_quiet_would_amend;
2442 sub check_series_has_all_patches ($) {
2444 my $seriesfn = 'debian/patches/series';
2445 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2449 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2450 fail "patch $f repeated in $seriesfn !" if $series{$f}++;
2452 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2453 my ($f,$i) = @$patchfile;
2454 next if $series{$f};
2455 next if $f eq 'series';
2456 snag 'unused-patches', "Unused patch file $f will be discarded";
2460 sub begin_convert_from () {
2461 my $head = get_head();
2462 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2464 fail "ffq-prev exists, this is already managed by git-debrebase!"
2465 if $ffq_prev && git_get_ref $ffq_prev;
2467 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2468 snag 'already-converted',
2469 "ahead of debrebase-last, this is already managed by git-debrebase!"
2470 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2471 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2474 sub complete_convert_from ($$$$) {
2475 my ($old_head, $new_head, $gi, $mrest) = @_;
2476 ffq_check $new_head;
2477 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2480 update_head_checkout $old_head, $new_head, $mrest;
2483 sub cmd_convert_from_gbp () {
2484 badusage "want only 1 optional argument, the upstream git commitish"
2487 my $clogp = parsechangelog();
2488 my $version = $clogp->{'Version'}
2489 // die "missing Version from changelog";
2491 my ($upstream_spec) = @ARGV;
2493 my $upstream_version = upstreamversion $version;
2495 resolve_upstream_version($upstream_spec, $upstream_version);
2497 my ($old_head, $gdrlastinfo) = begin_convert_from();
2499 my $upsdiff = get_differs $upstream, $old_head;
2500 if ($upsdiff & D_UPS) {
2501 runcmd @git, qw(--no-pager diff --stat),
2502 $upstream, $old_head,
2503 qw( -- :!/debian :/);
2505 upstream ($upstream_spec) and HEAD are not
2506 identical in upstream files. See diffstat above, or run
2507 git diff $upstream_spec HEAD -- :!/debian :/
2511 if (!is_fast_fwd $upstream, $old_head) {
2512 snag 'upstream-not-ancestor',
2513 "upstream ($upstream) is not an ancestor of HEAD";
2515 my $wrong = cmdoutput
2516 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2517 qw(-- :/ :!/debian));
2518 if (length $wrong) {
2519 snag 'unexpected-upstream-changes',
2520 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2521 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2525 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2526 snag 'upstream-has-debian',
2527 "upstream ($upstream) contains debian/ directory";
2530 check_series_has_all_patches $old_head;
2532 my $previous_dgit_view = eval {
2533 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2535 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2536 my ($stz, $desc) = @_;
2537 no warnings qw(exiting);
2538 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2539 next unless $stz->{Date};
2540 next unless $stz->{Distribution} ne 'UNRELEASED';
2541 $lvsn = $stz->{Version};
2542 $suite = $stz->{Distribution};
2545 die "neither of the first two changelog entries are released\n"
2546 unless defined $lvsn;
2547 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2548 my $mtag_pat = debiantag_maintview $lvsn, '*';
2549 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2551 die "could not find suitable maintainer view tag $mtag_pat\n"
2552 unless $mtag =~ m{/};
2553 is_fast_fwd $mtag, 'HEAD' or
2554 die "HEAD is not FF from maintainer tag $mtag!";
2555 my $dtag = "archive/$mtag";
2556 git_get_ref "refs/tags/$dtag" or
2557 die "dgit view tag $dtag not found\n";
2558 is_fast_fwd $mtag, $dtag or
2559 die "dgit view tag $dtag is not FF from maintainer tag $mtag\n";
2560 print "will stitch in dgit view, $dtag\n";
2561 git_rev_parse $dtag;
2563 if (!$previous_dgit_view) {
2567 Cannot confirm dgit view: $@
2568 Failed to stitch in dgit view (see messages above).
2569 dgit --overwrite will be needed on the first dgit push after conversion.
2573 snags_maybe_bail_early();
2579 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2580 # make a branch out of the patch queue - we'll want this in a mo
2581 runcmd qw(gbp pq import);
2582 # strip the patches out
2583 runcmd @git, qw(checkout -q gdr-internal~0);
2584 rm_subdir_cached 'debian/patches';
2585 $work = make_commit ['HEAD'], [
2586 'git-debrebase convert-from-gbp: drop patches from tree',
2587 'Delete debian/patches, as part of converting to git-debrebase format.',
2588 '[git-debrebase convert-from-gbp: drop patches from tree]'
2590 # make the anchor merge
2591 # the tree is already exactly right
2592 $work = make_commit [$work, $upstream], [
2593 'git-debrebase import: declare upstream',
2594 'First breakwater merge.',
2595 '[git-debrebase anchor: declare upstream]'
2598 # rebase the patch queue onto the new breakwater
2599 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2600 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2601 $work = git_rev_parse 'HEAD';
2603 if ($previous_dgit_view) {
2604 $work = make_commit [$work, $previous_dgit_view], [
2605 'git-debrebase import: declare ff from dgit archive view',
2606 '[git-debrebase pseudomerge: import-from-gbp]',
2611 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2612 print <<END or die $!;
2613 git-debrebase: converted from patched-unapplied (gbp) branch format, OK
2617 sub cmd_convert_to_gbp () {
2618 badusage "no arguments allowed" if @ARGV;
2619 my $head = get_head();
2620 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2621 keycommits $head, 0;
2623 make_patches_staged $head;
2625 $out = make_commit ['HEAD'], [
2626 'Commit patch queue (converted from git-debrebase format)',
2627 '[git-debrebase convert-to-gbp: commit patches]',
2631 push @deferred_updates, "delete $ffq";
2632 push @deferred_updates, "delete $gdrlast";
2635 update_head_checkout $head, $out, "convert to gbp (v0)";
2636 print <<END or die $!;
2637 git-debrebase: converted to git-buildpackage branch format
2638 git-debrebase: WARNING: do not now run "git-debrebase" any more
2639 git-debrebase: WARNING: doing so would drop all upstream patches!
2643 sub cmd_convert_from_dgit_view () {
2644 my $clogp = parsechangelog();
2646 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2652 getoptions("convert-from-dgit-view",
2653 'diagnose!', \$diagnose,
2654 'build-products-dir:s', \$bpd,
2655 'origs!', \$do_origs,
2657 'always-convert-anyway!', \$always);
2658 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2663 my $spec = shift @ARGV;
2664 my $commit = git_rev_parse "$spec^{commit}";
2665 push @upstreams, { Commit => $commit,
2666 Source => "$ARGV[0], from command line",
2671 my ($head, $gdrlastinfo) = begin_convert_from();
2675 my $trouble = sub { $troubles++; };
2676 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2677 printdebug "troubles=$troubles\n";
2680 $us: Branch already seems to be in git-debrebase format!
2681 $us: --always-convert-anyway would do the conversion operation anyway
2682 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2684 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2689 check_series_has_all_patches $head;
2691 snags_maybe_bail_early();
2693 my $version = upstreamversion $clogp->{Version};
2694 print STDERR "Considering possible commits corresponding to upstream:\n";
2699 my $ups_tag = upstream_commitish_search $version, \@tried;
2701 my $this = "git tag $tried[-1]";
2702 push @upstreams, { Commit => $ups_tag,
2707 " git tag: no suitable tag found (tried %s)\n",
2712 my $p = $clogp->{'Source'};
2713 # we do a quick check to see if there are plausible origs
2715 if (!opendir BPD, $bpd) {
2716 die "$bpd: opendir: $!" unless $!==ENOENT;
2718 while ($!=0, my $f = readdir BPD) {
2719 next unless is_orig_file_of_p_v $f, $p, $version;
2721 " orig: found what looks like a .orig, %s\n",
2726 die "read $bpd: $!" if $!;
2730 my $tree = cmdoutput
2731 @dgit, qw(--build-products-dir), $bpd,
2732 qw(print-unapplied-treeish);
2735 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2736 rm_subdir_cached 'debian';
2737 $tree = cmdoutput @git, qw(write-tree);
2738 my $ups_synth = make_commit [], [ <<END, <<END,
2739 Import effective orig tree for upstream version $version
2741 This includes the contents of the .orig(s), minus any debian/ directory.
2743 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2746 push @upstreams, { Commit => $ups_synth,
2747 Source => "orig(s) imported via dgit",
2752 " orig: no suitable origs found (looked for %s in %s)\n",
2753 "${p}_".(stripeoch $version)."...", $bpd;
2758 my $some_patches = stat_exists 'debian/patches/series';
2760 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2763 foreach my $u (@upstreams) {
2767 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2768 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2769 runcmd @git, qw(clean -xdff);
2770 runcmd @git, qw(checkout), $head, qw(-- debian);
2771 if ($some_patches) {
2772 rm_subdir_cached 'debian/patches';
2773 $work = make_commit [ $work ], [
2774 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2775 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2776 "to git-debrebase format. Upstream changes will appear as commits.",
2777 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2780 $work = make_commit [ $work, $u->{Commit} ], [
2781 'git-debrebase convert-from-dgit-view: declare upstream',
2782 '(Re)constructed breakwater merge.',
2783 '[git-debrebase anchor: declare upstream]'
2785 runcmd @git, qw(checkout --quiet -b mk), $work;
2786 if ($some_patches) {
2787 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2788 runcmd @git, qw(reset --quiet);
2789 my @gbp_cmd = (qw(gbp pq import));
2791 my $gbp_err = "../gbp-pq-err";
2792 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2794 my $r = system @gbp_cmd;
2797 " %s: couldn't apply patches: gbp pq %s",
2798 $u->{Source}, waitstatusmsg();
2802 my $work = git_rev_parse qw(HEAD);
2803 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2804 if (length $diffout) {
2806 " $u->{Source}: applying patches gives different tree\n";
2807 print STDERR $diffout if $diagnose;
2811 $u->{Result} = $work;
2819 Could not find or construct a suitable upstream commit.
2820 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2821 upstream commmit explicitly or provide suitable origs.
2825 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2827 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2828 'convert-from-dgit-view';
2831 sub cmd_record_resolved_merge () {
2832 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2833 # MERGE-TODO needs documentation
2834 my $new = get_head();
2837 print "Checking how you have resolved the merge problem\n";
2838 my $nope = sub { print "Not $method: @_"; 0; };
2840 my $maybe = sub { print "Seems to be $method.\n"; };
2842 my ($key, $ref) = @_;
2843 reflog_cache_insert $merge_cache_ref, $key, $ref;
2844 print "OK. You can switch branches and try git-debrebase again.\n";
2848 fresh_workarea 'merge';
2850 $method = 'vanilla-merge patchqueue';
2851 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2852 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2853 foreach my $lr (qw(left right)) {
2854 my $n = "$wrecknoteprefix/$lr-patchqueue";
2855 my $lrpq = git_get_ref $n;
2856 $lrpq or return $nope->("wreckage did not contain patchqueues");
2857 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2860 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2861 or die "wreckage element $wrecknoteprefix/new-base missing";
2862 my $result = merge_series_patchqueue_convert
2864 $yes->("vanilla-merge $vanilla", $result);
2867 fail "No resolved merge method seems applicable.\n";
2871 sub cmd_downstream_rebase_launder_v0 () {
2872 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2874 $base = git_rev_parse $base;
2875 my $old_head = get_head();
2876 my $current = $old_head;
2879 if ($current eq $base) {
2880 $topmost_keep //= $current;
2881 print " $current BASE stop\n";
2884 my $cl = classify $current;
2885 print " $current $cl->{Type}";
2887 my $p0 = $cl->{Parents}[0]{CommitId};
2889 if ($cl->{Type} eq 'Pseudomerge') {
2890 print " ^".($cl->{Contributor}{Ix}+1);
2891 $next = $cl->{Contributor}{CommitId};
2892 } elsif ($cl->{Type} eq 'AddPatches' or
2893 $cl->{Type} eq 'Changelog') {
2903 $topmost_keep //= $current;
2905 die "to-be stripped changes not on top of the branch\n"
2910 if ($topmost_keep eq $old_head) {
2911 print "unchanged\n";
2913 print "updating to $topmost_keep\n";
2914 update_head_checkout
2915 $old_head, $topmost_keep,
2916 'downstream-rebase-launder-v0';
2922 "D+" => \$debuglevel,
2923 'noop-ok', => \$opt_noop_ok,
2924 'f=s' => \@snag_force_opts,
2925 'anchor=s' => \@opt_anchors,
2926 '--dgit=s' => \($dgit[0]),
2928 'experimental-merge-resolution!', \$opt_merges,
2930 my ($opt,$val) = @_;
2931 badusage "git-debrebase: no cuddling to -i for git-rebase"
2933 die if $opt_defaultcmd_interactive; # should not happen
2934 $opt_defaultcmd_interactive = [ qw(-i) ];
2935 # This access to @ARGV is excessive familiarity with
2936 # Getopt::Long, but there isn't another sensible
2937 # approach. '-i=s{0,}' does not work with bundling.
2938 push @$opt_defaultcmd_interactive, @ARGV;
2941 'help' => sub { print $usage_message or die $!; finish 0; },
2944 initdebug('git-debrebase ');
2945 enabledebug if $debuglevel;
2947 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2948 chdir $toplevel or die "chdir $toplevel: $!";
2950 $rd = fresh_playground "$playprefix/misc";
2952 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2954 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2955 defaultcmd_rebase();
2957 my $cmd = shift @ARGV;
2960 $cmdfn = ${*::}{"cmd_$cmdfn"};
2962 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";