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;
24 use Debian::Dgit::I18n;
28 use Debian::Dgit qw(:DEFAULT :playground);
36 use Getopt::Long qw(:config posix_default gnu_compat bundling);
38 use File::FnMatch qw(:fnmatch);
41 $debugcmd_when_debuglevel = 2;
43 our ($usage_message) = <<'END';
45 git-debrebase [<options>] [--|-i <git rebase options...>]
46 git-debrebase [<options>] status
47 git-debrebase [<options>] prepush [--prose=...]
48 git-debrebase [<options>] quick|conclude
49 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
50 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
52 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
55 our ($opt_force, $opt_noop_ok, $opt_merges, @opt_anchors);
56 our ($opt_defaultcmd_interactive);
58 our $us = qw(git-debrebase);
60 our $wrecknoteprefix = 'refs/debrebase/wreckage';
61 our $merge_cache_ref = 'refs/debrebase/merge-resolutions';
67 print STDERR "$us: bad usage: $m\n";
73 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
74 GetOptions @_ or badusage $m;
78 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
82 my ($k, $optional) = @_;
84 my @cmd = qw(git config -z);
85 push @cmd, qw(--get-all) if wantarray;
87 my $out = cmdoutput_errok @cmd;
89 fail "missing required git config $k" unless $optional;
92 my @l = split /\0/, $out;
93 return wantarray ? @l : $l[0];
100 my $dd = new Data::Dumper [ $v ];
101 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
107 my $data = (git_cat_file $objid, 'commit');
108 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
112 sub D_UPS () { 0x02; } # upstream files
113 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
114 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
115 sub D_DEB_CLOG () { 0x10; } # debian/changelog
116 sub D_DEB_OTH () { 0x20; } # debian/ (not patches/ or changelog)
117 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
119 our $playprefix = 'debrebase';
124 our @dgit = qw(dgit);
126 sub in_workarea ($) {
129 my $r = eval { $sub->(); };
130 { local $@; changedir $maindir; }
134 sub fresh_workarea (;$) {
137 $workarea = fresh_playground "$playprefix/$subdir";
138 in_workarea sub { playtree_setup };
141 sub run_ref_updates_now ($$) {
142 my ($mrest, $updates) = @_;
143 # @$updates is a list of lines for git-update-ref, without \ns
145 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
146 debugcmd '>|', @upd_cmd;
147 open U, "|-", @upd_cmd or die $!;
148 foreach (@$updates) {
149 printdebug ">= ", $_, "\n";
150 print U $_, "\n" or die $!;
153 close U or failedcmd @upd_cmd;
156 our $snags_forced = 0;
157 our $snags_tripped = 0;
158 our $snags_summarised = 0;
159 our @deferred_updates;
160 our @deferred_update_messages;
162 sub merge_wreckage_cleaning ($) {
164 git_for_each_ref("$wrecknoteprefix/*", sub {
165 my ($objid,$objtype,$fullrefname,$reftail) = @_;
166 push @$updates, "delete $fullrefname";
170 sub all_snags_summarised () {
171 $snags_forced + $snags_tripped == $snags_summarised;
173 sub run_deferred_updates ($) {
176 confess 'dangerous internal error' unless all_snags_summarised();
178 merge_wreckage_cleaning \@deferred_updates;
179 run_ref_updates_now $mrest, \@deferred_updates;
180 print $_, "\n" foreach @deferred_update_messages;
182 @deferred_updates = ();
183 @deferred_update_messages = ();
186 sub get_tree ($;$$) {
187 # tree object name => ([ $name, $info ], ...)
188 # where $name is the sort key, ie has / at end for subtrees
189 # $info is the LHS from git-ls-tree (<mode> <type> <hash>)
190 # without $precheck, will crash if $x does not exist, so don't do that;
191 # instead pass '' to get ().
192 my ($x, $precheck, $recurse) = @_;
194 return () if !length $x;
197 my ($type, $dummy) = git_cat_file $x, [qw(tree missing)];
198 return () if $type eq 'missing';
201 $recurse = !!$recurse;
203 confess "get_tree needs object not $x ?" unless $x =~ m{^[0-9a-f]+\:};
205 our (@get_tree_memo, %get_tree_memo);
206 my $memo = $get_tree_memo{$recurse,$x};
207 return @$memo if $memo;
209 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
211 my @cmd = (qw(git ls-tree -z --full-tree));
212 push @cmd, qw(-r) if $recurse;
213 push @cmd, qw(--), $x;
214 my $o = cmdoutput @cmd;
217 foreach my $l (split /\0/, $o) {
218 my ($i, $n) = split /\t/, $l, 2;
219 $n .= '/' if $i =~ m/^\d+ tree /;
221 confess "$x need $last < $n ?" unless $last lt $n;
223 $get_tree_memo{$recurse,$x} = \@l;
224 push @get_tree_memo, $x;
225 if (@get_tree_memo > 10) {
226 delete $get_tree_memo{ shift @get_tree_memo };
231 sub trees_diff_walk ($$$;$) {
232 # trees_diff_walk [{..opts...},] $x, $y, sub {... }
233 # calls sub->($name, $ix, $iy) for each difference
234 # $x and $y are as for get_tree
235 # where $name, $ix, $iy are $name and $info from get_tree
236 # opts are all call even for names same in both
237 # recurse call even for names same in both
238 my $opts = shift @_ if @_>=4;
239 my ($x,$y,$call) = @_;
240 my $all = $opts->{all};
241 return if !$all and $x eq $y;
242 my @x = get_tree $x, 0, $opts->{recurse};
243 my @y = get_tree $y, 0, $opts->{recurse};
244 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
247 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
248 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
249 my ($n, $ix, $iy); # all same? $cmp=0, use both
251 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
253 ($n, $ix) = @{ shift @x } if $cmp <= 0;
254 ($n, $iy) = @{ shift @y } if $cmp >= 0;
255 next if !$all and $ix eq $iy;
257 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
258 !!$all,$x,$y, $n,$ix,$iy
260 $call->($n, $ix, $iy);
264 sub get_differs ($$) {
266 # This does a similar job to quiltify_trees_differ, in dgit, a bit.
267 # But we don't care about modes, or dpkg-source-unrepresentable
268 # changes, and we don't need the plethora of different modes.
269 # Conversely we need to distinguish different kinds of changes to
270 # debian/ and debian/patches/.
271 # Also, here we have, and want to use, trees_diff_walk, because
272 # we may be calling this an awful lot and we want it to be fast.
277 no warnings qw(exiting);
279 my $plain = sub { $_[0] =~ m{^(100|0*)644 blob }s; };
281 trees_diff_walk "$x:", "$y:", sub {
282 my ($n,$ix,$iy) = @_;
284 # analyse difference at the toplevel
286 if ($n ne 'debian/') {
290 if ($n eq 'debian') {
291 # one side has a non-tree for ./debian !
292 $differs |= D_DEB_OTH;
296 my $xd = $ix && "$x:debian";
297 my $yd = $iy && "$y:debian";
298 trees_diff_walk $xd, $yd, sub {
299 my ($n,$ix,$iy) = @_;
301 # analyse difference in debian/
303 if ($n eq 'changelog' && (!$ix || $plain->($ix))
305 $differs |= D_DEB_CLOG;
308 if ($n ne 'patches/') {
309 $differs |= D_DEB_OTH;
313 my $xp = $ix && "$xd/patches";
314 my $yp = $iy && "$yd/patches";
315 trees_diff_walk { recurse=>1 }, $xp, $yp, sub {
316 my ($n,$ix,$iy) = @_;
318 # analyse difference in debian/patches
322 # we are recursing; directories may appear and disappear
324 } elsif ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
326 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
327 my $x_s = (git_cat_file "$xp/series", 'blob');
328 my $y_s = (git_cat_file "$yp/series", 'blob');
329 chomp $x_s; $x_s .= "\n";
330 $ok = $x_s eq substr($y_s, 0, length $x_s);
334 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
339 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
344 sub commit_pr_info ($) {
346 return Data::Dumper->dump([$r], [qw(commit)]);
349 sub calculate_committer_authline () {
350 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
351 'DUMMY COMMIT (git-debrebase)', "HEAD:";
352 my ($h,$m) = get_commit $c;
353 $h =~ m/^committer .*$/m or confess "($h) ?";
357 sub rm_subdir_cached ($) {
359 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
362 sub read_tree_subdir ($$) {
363 my ($subdir, $new_tree_object) = @_;
364 rm_subdir_cached $subdir;
365 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
368 sub read_tree_debian ($) {
370 read_tree_subdir 'debian', "$treeish:debian";
371 rm_subdir_cached 'debian/patches';
374 sub read_tree_upstream ($;$$) {
375 my ($treeish, $keep_patches, $tree_with_debian) = @_;
376 # if $tree_with_debian is supplied, will use that for debian/
377 # otherwise will save and restore it.
379 $tree_with_debian ? "$tree_with_debian:debian"
380 : cmdoutput @git, qw(write-tree --prefix=debian/);
381 runcmd @git, qw(read-tree), $treeish;
382 read_tree_subdir 'debian', $debian;
383 rm_subdir_cached 'debian/patches' unless $keep_patches;
386 sub make_commit ($$) {
387 my ($parents, $message_paras) = @_;
388 my $tree = cmdoutput @git, qw(write-tree);
389 my @cmd = (@git, qw(commit-tree), $tree);
390 push @cmd, qw(-p), $_ foreach @$parents;
391 push @cmd, qw(-m), $_ foreach @$message_paras;
392 return cmdoutput @cmd;
395 our @snag_force_opts;
397 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
398 if (grep { $_ eq $tag } @snag_force_opts) {
400 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
403 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
407 # Important: all mainline code must call snags_maybe_bail after
408 # any point where snag might be called, but before making changes
409 # (eg before any call to run_deferred_updates). snags_maybe_bail
410 # may be called more than once if necessary (but this is not ideal
411 # because then the messages about number of snags may be confusing).
412 sub snags_maybe_bail () {
413 return if all_snags_summarised();
416 "%s: snags: %d overriden by individual -f options\n",
419 if ($snags_tripped) {
422 "%s: snags: %d overriden by global --force\n",
426 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
430 $snags_summarised = $snags_forced + $snags_tripped;
432 sub snags_maybe_bail_early () {
433 # useful to bail out early without doing a lot of work;
434 # not a substitute for snags_maybe_bail.
435 snags_maybe_bail() if $snags_tripped && !$opt_force;
438 return $snags_forced || $snags_tripped;
441 sub ffq_prev_branchinfo () {
442 my $current = git_get_symref();
443 return gdr_ffq_prev_branchinfo($current);
446 sub record_gdrlast ($$;$) {
447 my ($gdrlast, $newvalue, $oldvalue) = @_;
448 $oldvalue ||= $git_null_obj;
449 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
452 sub fail_unprocessable ($) {
455 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
458 Branch/history seems mangled - no longer in gdr format.
459 See ILLEGAL OPERATIONS in git-debrebase(5).
466 Is this meant to be a gdr branch? $ffqm
468 } elsif (git_get_ref $ffq_prev) {
472 Consider git-debrebase scrap, to throw away your recent work.
474 } elsif (!git_get_ref $gdrlast) {
477 Branch does not seem to be meant to be a git-debrebase branch?
478 Wrong branch, or maybe you needed git-debrebase convert-from-*.
480 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
488 Branch/history mangled, and diverged since last git-debrebase.
489 Maybe you reset to, or rebased from, somewhere inappropriate.
494 sub gbp_pq_export ($$$) {
495 my ($bname, $base, $tip) = @_;
496 # must be run in a workarea. $bname and patch-queue/$bname
497 # ought not to exist. Leaves you on patch-queue/$bname with
498 # the patches staged but not committed.
499 # returns 1 if there were any patches
500 printdebug "gbp_pq_export $bname $base $tip\n";
501 runcmd @git, qw(checkout -q -b), $bname, $base;
502 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
503 my @gbp_cmd = (qw(gbp pq export));
504 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
506 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
509 return 0 unless stat_exists 'debian/patches';
510 runcmd @git, qw(add -f debian/patches);
515 # MERGE-TODO allow merge resolution separately from laundering, before git merge
518 # use git-format-patch?
519 # our own patch identification algorithm?
520 # this is an alternative strategy
522 sub merge_failed ($$;@) {
523 my ($wrecknotes, $emsg, @xmsgs) = @_;
525 push @m, "Merge resolution failed: $emsg";
531 merge_wreckage_cleaning \@updates;
532 run_ref_updates_now "merge failed", \@updates;
536 while (my ($k,$v) = each %$wrecknotes) {
537 push @updates, "create $wrecknoteprefix/$k $v";
539 run_ref_updates_now "merge failed", \@updates;
540 push @m, "Wreckage left in $wrecknoteprefix/*.";
542 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
544 # use finish rather than fail, in case we are within an eval
545 # (that can happen inside walk!)
547 print STDERR "$us: $_\n" foreach @m;
551 sub mwrecknote ($$$) {
552 my ($wrecknotes, $reftail, $commitish) = @_;
553 confess unless defined $commitish;
554 printdebug "mwrecknote $reftail $commitish\n";
555 $wrecknotes->{$reftail} = $commitish;
558 sub merge_attempt_cmd {
559 my $wrecknotes = shift @_;
563 merge_failed $wrecknotes,
564 failedcmd_waitstatus(),
565 "failed command: @_";
569 sub merge_series_patchqueue_convert ($$$);
571 sub merge_series ($$$;@) {
572 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
573 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
574 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
575 # ^ specifies several patch series (currently we only support exactly 2)
576 # return value is a commit which is the result of
577 # merging the two versions of the same topic branch
578 # $input_q[0] and $input_q[1]
579 # with respect to the old version
583 # Creates, in *_q, a key MR for its private use
585 printdebug "merge_series newbase=$newbase\n";
587 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
588 $base_q->{MR}{S} = 'base';
591 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
592 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
593 # $prereq{<patch filename>} exists or not (even later)
597 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
599 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
602 fresh_workarea "merge";
603 my $seriesfile = "debian/patches/series";
606 foreach my $q ($base_q, reverse @input_qs) {
608 my $any = gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
611 open S, $seriesfile or die "$seriesfile $!";
612 while (my $patch = <S>) {
613 chomp $patch or die $!;
614 $prereq{$patch} //= {};
615 foreach my $earlier (@earlier) {
616 $prereq{$patch}{$earlier}{$s}++ and die;
618 push @earlier, $patch;
619 stat "debian/patches/$patch" or die "$patch ?";
621 S->error and die "$seriesfile $!";
624 read_tree_upstream $newbase, 1;
625 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
626 "Convert $s to patch queue for merging",
627 "[git-debrebase merge-innards patch-queue import:".
630 printdebug "merge_series pec $pec ";
631 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
632 $pec = make_commit [ $pec ], [
633 "Drop series file from $s to avoid merge trouble",
634 "[git-debrebase merge-innards patch-queue prep:".
638 read_tree_debian $newbase;
640 read_tree_subdir 'debian/patches', "$pec:debian/patches";
642 rm_subdir_cached 'debian/patches';
644 $pec = make_commit [ $pec ], [
645 "Update debian/ (excluding patches) to final to avoid re-merging",
646 "debian/ was already merged and we need to just take that.",
647 "[git-debrebase merge-innards patch-queue packaging:".
651 printdebug "pec' $pec\n";
652 runcmd @git, qw(reset -q --hard), $pec;
653 $q->{MR}{PEC} = $pec;
654 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
656 # now, because of reverse, we are on $input_q->{MR}{OQC}
657 runcmd @git, qw(checkout -q -b merge);
658 printdebug "merge_series merging...\n";
659 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
661 $attempt_cmd->(@mergecmd);
663 printdebug "merge_series merge ok, series...\n";
664 # We need to construct a new series file
665 # Firstly, resolve prereq
666 foreach my $f (sort keys %prereq) {
667 printdebug "merge_series patch\t$f\t";
668 if (!stat_exists "debian/patches/$f") {
669 print DEBUG " drop\n" if $debuglevel;
670 # git merge deleted it; that's how we tell it's not wanted
674 print DEBUG " keep\n" if $debuglevel;
675 foreach my $g (sort keys %{ $prereq{$f} }) {
676 my $gfp = $prereq{$f}{$g};
677 printdebug "merge_series prereq\t$f\t-> $g\t";
678 if (!!$gfp->{0} == !!$gfp->{1}
681 print DEBUG "\tkeep\n" if $debuglevel;
683 print DEBUG "\tdrop\n" if $debuglevel;
684 delete $prereq{$f}{$g};
691 return scalar keys %{ $prereq{$f} };
694 my $nodate = time + 1;
696 # $authordate{<patch filename>};
697 my $authordate = sub {
699 $authordate{$f} //= do {
700 open PF, "<", "debian/patches/$f" or die "$f $!";
702 return $nodate if m/^$/;
703 last if s{^Date: }{};
706 return cmdoutput qw(date +%s -d), $_;
710 open NS, '>', $seriesfile or die $!;
712 while (keys %prereq) {
714 foreach my $try (sort keys %prereq) {
717 $unsat->($try) <=> $unsat->($best) or
718 $authordate->($try) <=> $authordate->($best) or
724 printdebug "merge_series series next $best\n";
725 print NS "$best\n" or die $!;
726 delete $prereq{$best};
727 foreach my $gp (values %prereq) {
732 runcmd @git, qw(add), $seriesfile;
733 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
734 $merged_pq = git_rev_parse 'HEAD';
735 $mwrecknote->('merged-patchqueue', $merged_pq);
737 return merge_series_patchqueue_convert
738 $wrecknotes, $newbase, $merged_pq;
741 sub merge_series_patchqueue_convert ($$$) {
742 my ($wrecknotes, $newbase, $merged_pq) = @_;
747 printdebug "merge_series series gbp pq import\n";
748 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
750 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
751 # MERGE-TODO consider git-format-patch etc. instead,
752 # since gbp pq doesn't always round-trip :-/
754 # OK now we are on patch-queue/merge, and we need to rebase
755 # onto the intended parent and drop the patches from each one
757 printdebug "merge_series series ok, building...\n";
758 my $build = $newbase;
759 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
760 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
761 my $commit = git_cat_file $c, 'commit';
762 printdebug "merge_series series ok, building $c\n";
763 read_tree_upstream $c, 0, $newbase;
764 my $tree = cmdoutput @git, qw(write-tree);
765 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
766 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
767 open C, ">", "../mcommit" or die $!;
768 print C $commit or die $!;
770 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
773 mwrecknote($wrecknotes, 'merged-result', $result);
775 runcmd @git, qw(update-ref refs/heads/result), $result;
777 runcmd @git, qw(checkout -q -b debug);
778 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
779 runcmd @git, qw(add .);
780 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
781 my $mdebug = git_rev_parse 'HEAD';
782 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
783 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
785 printdebug "merge_series returns $result\n";
789 # classify returns an info hash like this
791 # Hdr => # commit headers, including 1 final newline
792 # Msg => # commit message (so one newline is dropped)
794 # Type => (see below)
796 # Ix => $index # ie 0, 1, 2, ...
798 # Differs => return value from get_differs
800 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
802 # NewMsg => # commit message, but with any [dgit import ...] edited
803 # # to say "[was: ...]"
813 # has additional entres in classification result
814 # Overwritten = [ subset of Parents ]
815 # Contributor = $the_remaining_Parent
817 # DgitImportUnpatched
818 # has additional entry in classification result
819 # OrigParents = [ subset of Parents ]
822 # has additional entry in classification result
823 # OrigParents = [ subset of Parents ] # singleton list
830 # has additional entry in classification result
833 sub parsecommit ($;$) {
834 my ($objid, $p_ref) = @_;
835 # => hash with CommitId Hdr Msg Tree Parents
836 # Parents entries have only Ix CommitId
837 # $p_ref, if provided, must be [] and is used as a base for Parents
842 my ($h,$m) = get_commit $objid;
844 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
845 my (@ph) = $h =~ m/^parent (\w+)$/mg;
855 foreach my $ph (@ph) {
857 Ix => scalar @$p_ref,
869 my $r = parsecommit($objid, \@p);
873 $p->{Differs} = (get_differs $p->{CommitId}, $t),
876 printdebug "classify $objid \$t=$t \@p",
877 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
881 my ($type, @rest) = @_;
882 $r = { %$r, Type => $type, @rest };
884 printdebug " = $type ".(dd $r)."\n";
890 $r = { %$r, Type => qw(Unknown), Why => $why };
891 printdebug " ** Unknown\n";
895 if (grep { $_ eq $objid } @opt_anchors) {
896 return $classify->('TreatAsAnchor');
899 my @identical = grep { !$_->{Differs} } @p;
900 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
901 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
903 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
904 # multi-orig upstreams are represented with an anchor merge
905 # from a single upstream commit which combines the orig tarballs
907 # Every anchor tagged this way must be a merge.
908 # We are relying on the
909 # [git-debrebase anchor: ...]
910 # commit message annotation in "declare" anchor merges (which
911 # do not have any upstream changes), to distinguish those
912 # anchor merges from ordinary pseudomerges (which we might
913 # just try to strip).
915 # However, the user is going to be doing git-rebase a lot. We
916 # really don't want them to rewrite an anchor commit.
917 # git-rebase trips up on merges, so that is a useful safety
920 # BreakwaterStart commits are also anchors in the terminology
921 # of git-debrebase(5), but they are untagged (and always
922 # manually generated).
924 # We cannot not tolerate any tagged linear commit (ie,
925 # BreakwaterStart commits tagged `[anchor:') because such a
926 # thing could result from an erroneous linearising raw git
927 # rebase of a merge anchor. That would represent a corruption
928 # of the branch. and we want to detect and reject the results
929 # of such corruption before it makes it out anywhere. If we
930 # reject it here then we avoid making the pseudomerge which
931 # would be needed to push it.
933 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
934 @p == 2 or return $badanchor->("has other than two parents");
935 $haspatches and return $badanchor->("contains debian/patches");
937 # How to decide about l/r ordering of anchors ? git
938 # --topo-order prefers to expand 2nd parent first. There's
939 # already an easy rune to look for debian/ history anyway (git log
940 # debian/) so debian breakwater branch should be 1st parent; that
941 # way also there's also an easy rune to look for the upstream
942 # patches (--topo-order).
944 # Also this makes --first-parent be slightly more likely to
945 # be useful - it makes it provide a linearised breakwater history.
947 # Of course one can say somthing like
948 # gitk -- ':/' ':!/debian'
949 # to get _just_ the commits touching upstream files, and by
950 # the TREESAME logic in git-rev-list this will leave the
951 # breakwater into upstream at the first anchor. But that
952 # doesn't report debian/ changes at all.
954 # Other observations about gitk: by default, gitk seems to
955 # produce output in a different order to git-rev-list. I
956 # can't seem to find this documented anywhere. gitk
957 # --date-order DTRT. But, gitk always seems to put the
958 # parents from left to right, in order, so it's easy to see
959 # which way round a pseudomerge is.
961 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
962 $p[1]{Differs} & ~DS_DEB and
963 $badanchor->("upstream files differ from left parent");
964 $p[0]{Differs} & ~D_UPS and
965 $badanchor->("debian/ differs from right parent");
967 return $classify->(qw(Anchor),
968 OrigParents => [ $p[1] ]);
972 my $d = $r->{Parents}[0]{Differs};
973 if ($d == D_PAT_ADD) {
974 return $classify->(qw(AddPatches));
975 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
976 return $unknown->("edits debian/patches");
977 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
978 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
980 if ($d == D_DEB_CLOG) {
981 return $classify->(qw(Changelog));
983 return $classify->(qw(Packaging));
985 } elsif ($ty eq 'missing') {
986 return $classify->(qw(BreakwaterStart));
988 return $unknown->("parent's debian is not a directory");
990 } elsif ($d == D_UPS) {
991 return $classify->(qw(Upstream));
992 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
993 return $classify->(qw(Mixed));
995 return $unknown->("no changes");
997 confess "internal error $objid ?";
1001 return $unknown->("origin commit");
1004 if (@p == 2 && @identical == 1) {
1005 my @overwritten = grep { $_->{Differs} } @p;
1006 confess "internal error $objid ?" unless @overwritten==1;
1007 return $classify->(qw(Pseudomerge),
1008 Overwritten => [ $overwritten[0] ],
1009 Contributor => $identical[0]);
1011 if (@p == 2 && @identical == 2) {
1013 my ($ph,$pm) = get_commit $_[0]{CommitId};
1014 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
1018 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
1019 if ($order > 0) { # newer first
1020 } elsif ($order < 0) {
1021 @bytime = reverse @bytime;
1023 # same age, default to order made by -s ours
1024 # that is, commit was made by someone who preferred L
1026 return $classify->(qw(Pseudomerge),
1027 SubType => qw(Ambiguous),
1028 Contributor => $bytime[0],
1029 Overwritten => [ $bytime[1] ]);
1031 foreach my $p (@p) {
1032 my ($p_h, $p_m) = get_commit $p->{CommitId};
1033 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1034 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1036 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1038 if (!(grep { !$_->{IsOrigin} } @p) and
1039 (@orig_ps >= @p - 1) and
1040 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1042 return $classify->(qw(DgitImportUnpatched),
1043 OrigParents => \@orig_ps);
1047 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1048 return $classify->("MergedBreakwaters");
1050 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1051 return $unknown->("unknown kind of merge from $1");
1054 return $unknown->("octopus merge");
1058 return $unknown->("general two-parent merge");
1061 return $classify->("VanillaMerge");
1064 sub keycommits ($;$$$$$);
1066 sub mergedbreakwaters_anchor ($) {
1069 foreach my $p (@{ $cl->{Parents} }) {
1070 my ($panchor, $pbw) = keycommits $p->{CommitId},
1071 undef,undef,undef,undef, 1;
1072 $best_anchor = $panchor
1073 if !defined $best_anchor
1074 or is_fast_fwd $best_anchor, $panchor;
1075 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
1076 unless is_fast_fwd $panchor, $best_anchor;
1078 return $best_anchor;
1081 sub keycommits ($;$$$$$) {
1082 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1083 # => ($anchor, $breakwater)
1085 # $furniture->("unclean-$tagsfx", $msg, $cl)
1086 # $unclean->("unclean-$tagsfx", $msg, $cl)
1087 # is callled for each situation or commit that
1088 # wouldn't be found in a laundered branch
1089 # $furniture is for furniture commits such as might be found on an
1090 # interchange branch (pseudomerge, d/patches, changelog)
1091 # $trouble is for things whnich prevent the return of
1092 # anchor and breakwater information; if that is ignored,
1093 # then keycommits returns (undef, undef) instead.
1094 # $fatal is for unprocessable commits, and should normally cause
1095 # a failure. If ignored, agaion, (undef, undef) is returned.
1097 # If $claimed_bw, this is supposed to be a breakwater commit.
1099 # If a callback is undef, fail is called instead.
1100 # If a callback is defined but false, the situation is ignored.
1101 # Callbacks may say:
1102 # no warnings qw(exiting); last;
1103 # if the answer is no longer wanted.
1105 my ($anchor, $breakwater);
1106 $breakwater = $head if $claimed_bw;
1110 $fatal //= sub { fail_unprocessable $_[1]; };
1112 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1113 my $why = $mainwhy.$xwhy;
1114 my $m = "branch needs laundering (run git-debrebase): $why";
1115 fail $m unless defined $cb;
1117 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1119 my $found_anchor = sub {
1121 $breakwater //= $clogonly;
1122 $breakwater //= $head;
1123 no warnings qw(exiting);
1127 $cl = classify $head;
1128 my $ty = $cl->{Type};
1129 if ($ty eq 'Packaging') {
1130 $breakwater //= $clogonly;
1131 $breakwater //= $head;
1132 } elsif ($ty eq 'Changelog') {
1133 # this is going to count as the tip of the breakwater
1134 # only if it has no upstream stuff before it
1135 $clogonly //= $head;
1136 } elsif ($ty eq 'Anchor' or
1137 $ty eq 'TreatAsAnchor' or
1138 $ty eq 'BreakwaterStart') {
1139 $found_anchor->($head);
1140 } elsif ($ty eq 'Upstream') {
1141 $x->($unclean, 'ordering',
1142 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1143 if defined $breakwater;
1145 $breakwater = undef;
1146 } elsif ($ty eq 'Mixed') {
1147 $x->($unclean, 'mixed',
1148 "found mixed upstream/packaging commit"," ($head)");
1150 $breakwater = undef;
1151 } elsif ($ty eq 'Pseudomerge' or
1152 $ty eq 'AddPatches') {
1154 $x->($furniture, (lc $ty),
1155 "found interchange bureaucracy commit ($ty)"," ($head)");
1156 } elsif ($ty eq 'DgitImportUnpatched') {
1158 $x->($trouble, 'dgitimport',
1159 "found dgit dsc import"," ($head)");
1160 return (undef,undef);
1162 $x->($fatal, 'unprocessable',
1163 "found bare dgit dsc import with no prior history",
1165 return (undef,undef);
1167 } elsif ($ty eq 'VanillaMerge') {
1168 $x->($trouble, 'vanillamerge',
1169 "found vanilla merge"," ($head)");
1170 return (undef,undef);
1171 } elsif ($ty eq 'MergedBreakwaters') {
1172 $found_anchor->(mergedbreakwaters_anchor $cl);
1174 $x->($fatal, 'unprocessable',
1175 "found unprocessable commit, cannot cope: $cl->{Why}",
1177 return (undef,undef);
1179 $head = $cl->{Parents}[0]{CommitId};
1181 return ($anchor, $breakwater);
1187 $nogenerate,$report, $report_lprefix) = @_;
1188 # => ($tip, $breakwater_tip, $last_anchor)
1189 # (or nothing, if $nogenerate)
1191 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1192 $report_lprefix //= '';
1194 # go through commits backwards
1195 # we generate two lists of commits to apply:
1196 # breakwater branch and upstream patches
1197 my (@brw_cl, @upp_cl, @processed);
1204 my ($prose, $info) = @_;
1205 my $ms = $cl->{Msg};
1207 confess unless defined $info;
1208 $ms .= "\n\n[git-debrebase $info: $prose]\n";
1209 return (Msg => $ms);
1211 my $rewrite_from_here = sub {
1213 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1215 push @processed, $sp_cl;
1220 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1223 return unless $report;
1224 print $report $prdelim, $report_lprefix, @_;
1228 my $bomb = sub { # usage: return $bomb->();
1229 print $report " Unprocessable" if $report;
1230 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1233 return (undef,undef);
1235 fail_unprocessable "found unprocessable commit, cannot cope".
1236 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1237 " (commit $cur) (d.".
1238 (join ' ', map { sprintf "%#x", $_->{Differs} }
1239 @{ $cl->{Parents} }).
1246 my $build_start = sub {
1247 my ($msg, $parent) = @_;
1250 no warnings qw(exiting); last;
1255 merge_failed $cl->{MergeWreckNotes}, $emsg;
1258 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1263 $cl = classify $cur;
1264 $cl->{MergeWreckNotes} //= {};
1265 my $ty = $cl->{Type};
1266 my $st = $cl->{SubType};
1267 $prline->("$cl->{CommitId} $cl->{Type}");
1268 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1269 push @processed, $cl;
1270 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1271 if ($ty eq 'AddPatches') {
1273 $rewrite_from_here->(\@upp_cl);
1275 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1279 } elsif ($ty eq 'BreakwaterStart') {
1280 $last_anchor = $cur;
1281 $build_start->('FirstPackaging', $cur);
1282 } elsif ($ty eq 'Upstream') {
1286 } elsif ($ty eq 'Mixed') {
1289 my $cls = { %$cl, $xmsg->("mixed commit: $wh part",'split') };
1292 $queue->(\@brw_cl, "debian");
1293 $queue->(\@upp_cl, "upstream");
1294 $rewrite_from_here->(\@brw_cl);
1297 } elsif ($ty eq 'Pseudomerge') {
1298 my $contrib = $cl->{Contributor}{CommitId};
1299 print $report " Contributor=$contrib" if $report;
1300 push @pseudomerges, $cl;
1301 $rewrite_from_here->(\@upp_cl);
1304 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1305 $last_anchor = $cur;
1306 $build_start->("Anchor", $cur);
1307 } elsif ($ty eq 'DgitImportUnpatched') {
1308 my $pm = $pseudomerges[-1];
1310 # To an extent, this is heuristic. Imports don't have
1311 # a useful history of the debian/ branch. We assume
1312 # that the first pseudomerge after an import has a
1313 # useful history of debian/, and ignore the histories
1314 # from later pseudomerges. Often the first pseudomerge
1315 # will be the dgit import of the upload to the actual
1316 # suite intended by the non-dgit NMUer, and later
1317 # pseudomerges may represent in-archive copies.
1318 my $ovwrs = $pm->{Overwritten};
1319 printf $report " PM=%s \@Overwr:%d",
1320 $pm->{CommitId}, (scalar @$ovwrs)
1323 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1326 my $ovwr = $ovwrs->[0]{CommitId};
1327 printf $report " Overwr=%s", $ovwr if $report;
1328 # This import has a tree which is just like a
1329 # breakwater tree, but it has the wrong history. It
1330 # ought to have the previous breakwater (which the
1331 # pseudomerge overwrote) as an ancestor. That will
1332 # make the history of the debian/ files correct. As
1333 # for the upstream version: either it's the same as
1334 # was ovewritten (ie, same as the previous
1335 # breakwater), in which case that history is precisely
1336 # right; or, otherwise, it was a non-gitish upload of a
1337 # new upstream version. We can tell these apart by
1338 # looking at the tree of the supposed upstream.
1341 SpecialMethod => 'DgitImportDebianUpdate',
1342 $xmsg->("debian changes", 'convert dgit import')
1345 SpecialMethod => 'DgitImportUpstreamUpdate',
1346 $xmsg->("convert dgit import: upstream update",
1349 $prline->(" Import");
1350 $rewrite_from_here->(\@brw_cl);
1351 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1355 # Everything is from this import. This kind of import
1356 # is already nearly in valid breakwater format, with the
1357 # patches as commits. Unfortunately it contains
1359 printdebug "*** WALK BOMB bare dgit import\n";
1360 $cl->{Why} = "bare dgit dsc import";
1364 } elsif ($ty eq 'MergedBreakwaters') {
1365 $last_anchor = mergedbreakwaters_anchor $cl;
1366 $build_start->(' MergedBreakwaters', $cur);
1368 } elsif ($ty eq 'VanillaMerge') {
1369 # User may have merged unstitched branch(es). We will
1370 # have now lost what ffq-prev was then (since the later
1371 # pseudomerge may introduce further changes). The effect
1372 # of resolving such a merge is that we may have to go back
1373 # further in history to find a merge base, since the one
1374 # which was reachable via ffq-prev is no longer findable.
1375 # This is suboptimal, but if it all works we'll have done
1377 # MERGE-TODO we should warn the user in the docs about this
1381 # We expect to find a dominating anchor amongst the
1382 # inputs' anchors. That will be the new anchor.
1384 # More complicated is finding a merge base for the
1385 # breakwaters. We need a merge base that is a breakwater
1386 # commit. The ancestors of breakwater commits are more
1387 # breakwater commits and possibly upstream commits and the
1388 # ancestors of those upstream. Upstreams might have
1389 # arbitrary ancestors. But any upstream commit U is
1390 # either included in both anchors, in which case the
1391 # earlier anchor is a better merge base than any of U's
1392 # ancestors; or U is not included in the older anchor, in
1393 # which case U is not an ancestor of the vanilla merge at
1394 # all. So no upstream commit, nor any ancestor thereof,
1395 # is a best merge base. As for non-breakwater Debian
1396 # commits: these are never ancestors of any breakwater.
1398 # So any best merge base as found by git-merge-base
1399 # is a suitable breakwater anchor. Usually there will
1402 printdebug "*** MERGE\n";
1404 my @bwbcmd = (@git, qw(merge-base));
1405 my @ibcmd = (@git, qw(merge-base --all));
1406 my $might_be_in_bw = 1;
1408 my $ps = $cl->{Parents};
1410 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1412 foreach my $p (@$ps) {
1413 $prline->(" VanillaMerge ".$p->{Ix});
1415 my ($ptip, $pbw, $panchor) =
1416 walk $p->{CommitId}, 0, $report,
1417 $report_lprefix.' ';
1418 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1419 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1420 $p->{Anchor} = $panchor;
1422 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1423 $mwrecknote->("$lr-input", $p->{CommitId});
1425 my $mwrecknote_parent = sub {
1427 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1429 $mwrecknote_parent->('Laundered');
1430 $mwrecknote_parent->('Breakwater');
1431 $mwrecknote_parent->('Anchor');
1433 $best_anchor = $panchor if
1434 !defined $best_anchor or
1435 is_fast_fwd $best_anchor, $panchor;
1437 printdebug " MERGE BA best=".($best_anchor//'-').
1441 $mwrecknote->('result-anchor', $best_anchor);
1443 foreach my $p (@$ps) {
1444 $prline->(" VanillaMerge ".$p->{Ix});
1445 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1446 $nomerge->('divergent anchors');
1447 } elsif ($p->{Anchor} eq $best_anchor) {
1448 print $report " SameAnchor" if $report;
1450 print $report " SupersededAnchor" if $report;
1452 if ($p->{Breakwater} eq $p->{CommitId}) {
1453 # this parent commit was its own breakwater,
1454 # ie it is part of the breakwater
1455 print $report " Breakwater" if $report;
1457 $might_be_in_bw = 0;
1459 push @bwbcmd, $p->{Breakwater};
1460 push @ibcmd, $p->{CommitId};
1463 if ($ok && $might_be_in_bw) {
1464 # We could rewrite this to contaion the metadata
1465 # declaring it to be MergedBreakwaters, but
1466 # unnecessarily rewriting a merge seems unhelpful.
1467 $prline->(" VanillaMerge MergedBreakwaters");
1468 $last_anchor = $best_anchor;
1469 $build_start->('MergedBreakwaters', $cur);
1472 my $bwb = cmdoutput @bwbcmd;
1474 # OK, now we have a breakwater base, but we need the merge
1475 # base for the interchange branch because we need the delta
1478 # This a the best merge base of our inputs which has the
1479 # breakwater merge base as an ancestor.
1486 @ibs or confess 'internal error, expected anchor at least ?';
1490 foreach my $tibix (0..$#ibs) {
1491 my $tib = $ibs[$tibix];
1492 my $ff = is_fast_fwd $bwb, $tib;
1493 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1494 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1495 $mwrecknote->($tibleaf, $tib);
1502 $ib or $nomerge->("no suitable interchange merge base");
1504 $prline->(" VanillaMerge Base");
1506 my ($btip, $bbw, $banchor) = eval {
1507 walk $ib, 0, $report, $report_lprefix.' ';
1509 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1513 $mwrecknote->("mergebase-laundered", $btip);
1514 $mwrecknote->("mergebase-breakwater", $bbw);
1515 $mwrecknote->("mergebase-anchor", $banchor);
1517 my $ibinfo = { SeriesTip => $btip,
1520 LeftRight => 'mergebase' };
1523 or $nomerge->("interchange merge-base ($ib)'s".
1524 " breakwater ($bbw)".
1525 " != breakwaters' merge-base ($bwb)");
1527 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1528 or $nomerge->("interchange merge-base ($ib)'s".
1529 " anchor ($ibinfo->{SeriesBase})".
1530 " != any merge input's anchor (".
1531 (join ' ', map { $_->{Anchor} } @$ps).
1534 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1535 $cl->{MergeBestAnchor} = $best_anchor;
1538 SpecialMethod => 'MergeCreateMergedBreakwaters',
1539 $xmsg->('constructed from vanilla merge',
1540 'merged-breakwater'),
1544 SpecialMethod => 'MergeMergeSeries',
1546 $build_start->('MergeBreakwaters', $cur);
1548 printdebug "*** WALK BOMB unrecognised\n";
1554 printdebug "*** WALK prep done cur=$cur".
1555 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1557 return if $nogenerate;
1559 # Now we build it back up again
1565 $#upp_cl = $upp_limit if defined $upp_limit;
1567 my $committer_authline = calculate_committer_authline();
1569 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1571 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1574 mkdir $rd or $!==EEXIST or die $!;
1576 my $want_debian = $build;
1577 my $want_upstream = $build;
1579 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1580 my $read_tree_debian = sub { ($want_debian) = @_; };
1582 foreach my $cl (qw(Debian), (reverse @brw_cl),
1583 { SpecialMethod => 'RecordBreakwaterTip' },
1584 qw(Upstream), (reverse @upp_cl)) {
1586 $current_method = $cl;
1589 my $method = $cl->{SpecialMethod} // $current_method;
1590 my @parents = ($build);
1591 my $cltree = $cl->{CommitId};
1592 printdebug "WALK BUILD ".($cltree//'undef').
1593 " $method (rewriting=$rewriting)\n";
1594 if ($method eq 'Debian') {
1595 $read_tree_debian->($cltree);
1596 } elsif ($method eq 'Upstream') {
1597 $read_tree_upstream->($cltree);
1598 } elsif ($method eq 'StartRewrite') {
1601 } elsif ($method eq 'RecordBreakwaterTip') {
1602 $breakwater = $build;
1604 } elsif ($method eq 'DgitImportDebianUpdate') {
1605 $read_tree_debian->($cltree);
1606 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1607 confess unless $rewriting;
1608 my $differs = (get_differs $build, $cltree);
1609 next unless $differs & D_UPS;
1610 $read_tree_upstream->($cltree);
1611 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1612 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1613 print "Found a general merge, will try to tidy it up.\n";
1615 $read_tree_upstream->($cl->{MergeBestAnchor});
1616 $read_tree_debian->($cltree);
1617 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1618 } elsif ($method eq 'MergeMergeSeries') {
1619 my $cachehit = reflog_cache_lookup
1620 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1622 print "Using supplied resolution for $cl->{CommitId}...\n";
1624 $mwrecknote->('cached-resolution', $build);
1626 print "Running merge resolution for $cl->{CommitId}...\n";
1627 $mwrecknote->('new-base', $build);
1628 $build = merge_series
1629 $build, $cl->{MergeWreckNotes},
1630 $cl->{MergeInterchangeBaseInfo},
1631 @{ $cl->{Parents} };
1633 $last_anchor = $cl->{MergeBestAnchor};
1635 # Check for mismerges:
1637 my ($against, $allow, $what) = @_;
1638 my $differs = get_differs $build, $against;
1640 "merge misresolved: %s are not the same (%s %s d.%#x)",
1641 $what, $against, $build, $differs)
1642 if $differs & ~($allow | D_PAT_ADD);
1645 # Breakwater changes which were in each side of the
1646 # merge will have been incorporated into the
1647 # MergeCreateMergedBreakwaters output. Because the
1648 # upstream series was rebased onto the new breakwater,
1649 # so should all of the packaging changes which were in
1651 $check->($input, D_UPS, 'debian files');
1653 # Upstream files are merge_series, which ought to
1654 # have been identical to the original merge.
1655 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1657 print "Merge resolution successful.\n";
1660 confess "$method ?";
1663 my $procd = (pop @processed) // 'UNDEF';
1664 if ($cl ne $procd) {
1666 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1670 read_tree_upstream $want_upstream, 0, $want_debian;
1672 my $newtree = cmdoutput @git, qw(write-tree);
1673 my $ch = $cl->{Hdr};
1674 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1675 $ch =~ s{^parent .*\n}{}mg;
1676 $ch =~ s{(?=^author)}{
1677 join '', map { "parent $_\n" } @parents
1678 }me or confess "$ch ?";
1680 $ch =~ s{^committer .*$}{$committer_authline}m
1683 my $cf = "$rd/m$rewriting";
1684 open CD, ">", $cf or die $!;
1685 print CD $ch, "\n", $cl->{Msg} or die $!;
1687 my @cmd = (@git, qw(hash-object));
1688 push @cmd, qw(-w) if $rewriting;
1689 push @cmd, qw(-t commit), $cf;
1690 my $newcommit = cmdoutput @cmd;
1691 confess "$ch ?" unless $rewriting
1692 or $newcommit eq $cl->{CommitId};
1693 $build = $newcommit;
1695 $build = $cl->{CommitId};
1696 trees_diff_walk "$want_upstream:", "$build:", sub {
1698 no warnings qw(exiting);
1699 next if $n eq 'debian/';
1700 confess "mismatch @_ ?";
1702 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1703 confess "mismatch @_ ?";
1705 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1706 confess "mismatch @parents != @old_parents ?"
1707 unless "@parents" eq "@old_parents";
1709 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1710 $last_anchor = $cur;
1715 my $final_check = get_differs $build, $input;
1716 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1717 if $final_check & ~D_PAT_ADD;
1719 my @r = ($build, $breakwater, $last_anchor);
1720 printdebug "*** WALK RETURN @r\n";
1725 git_check_unmodified();
1726 return git_rev_parse qw(HEAD);
1729 sub update_head ($$$) {
1730 my ($old, $new, $mrest) = @_;
1731 push @deferred_updates, "update HEAD $new $old";
1732 run_deferred_updates $mrest;
1735 sub update_head_checkout ($$$) {
1736 my ($old, $new, $mrest) = @_;
1737 update_head $old, $new, $mrest;
1738 runcmd @git, qw(reset --hard);
1741 sub update_head_postlaunder ($$$) {
1742 my ($old, $tip, $reflogmsg) = @_;
1743 return if $tip eq $old && !@deferred_updates;
1744 print "git-debrebase: laundered (head was $old)\n";
1745 update_head $old, $tip, $reflogmsg;
1746 # no tree changes except debian/patches
1747 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1750 sub currently_rebasing() {
1751 foreach (qw(rebase-merge rebase-apply)) {
1752 return 1 if stat_exists "$maindir_gitdir/$_";
1757 sub bail_if_rebasing() {
1758 fail "you are in the middle of a git-rebase already"
1759 if currently_rebasing();
1762 sub do_launder_head ($) {
1763 my ($reflogmsg) = @_;
1764 my $old = get_head();
1766 my ($tip,$breakwater) = walk $old;
1768 update_head_postlaunder $old, $tip, $reflogmsg;
1769 return ($tip,$breakwater);
1772 sub cmd_launder_v0 () {
1773 badusage "no arguments to launder-v0 allowed" if @ARGV;
1774 my $old = get_head();
1775 my ($tip,$breakwater,$last_anchor) = walk $old;
1776 update_head_postlaunder $old, $tip, 'launder';
1777 printf "# breakwater tip\n%s\n", $breakwater;
1778 printf "# working tip\n%s\n", $tip;
1779 printf "# last anchor\n%s\n", $last_anchor;
1782 sub defaultcmd_rebase () {
1783 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1784 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1785 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1788 sub cmd_analyse () {
1789 badusage "analyse does not support any options"
1790 if @ARGV and $ARGV[0] =~ m/^-/;
1791 badusage "too many arguments to analyse" if @ARGV>1;
1794 $old = git_rev_parse $old;
1796 $old = git_rev_parse 'HEAD';
1798 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1799 STDOUT->error and die $!;
1802 sub ffq_check ($;$$) {
1803 # calls $ff and/or $notff zero or more times
1804 # then returns either (status,message) where status is
1809 # or (undef,undef, $ffq_prev,$gdrlast)
1810 # $ff and $notff are called like this:
1811 # $ff->("message for stdout\n");
1812 # $notff->('snag-name', $message);
1813 # normally $currentval should be HEAD
1814 my ($currentval, $ff, $notff) =@_;
1816 $ff //= sub { print $_[0] or die $!; };
1819 my ($status, $message, $current, $ffq_prev, $gdrlast)
1820 = ffq_prev_branchinfo();
1821 return ($status, $message) unless $status eq 'branch';
1823 my $exists = git_get_ref $ffq_prev;
1824 return ('exists',"$ffq_prev already exists") if $exists;
1826 return ('not-branch', 'HEAD symref is not to refs/heads/')
1827 unless $current =~ m{^refs/heads/};
1830 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1833 printdebug "ffq check_specs @check_specs\n";
1836 my ($lrref, $desc) = @_;
1837 printdebug "ffq might check $lrref ($desc)\n";
1839 for my $chk (@check_specs) {
1841 $invert = $glob =~ s{^[!^]}{};
1842 last if fnmatch $glob, $lrref;
1845 my $lrval = git_get_ref $lrref;
1846 return unless length $lrval;
1848 if (is_fast_fwd $lrval, $currentval) {
1849 $ff->("OK, you are ahead of $lrref\n");
1850 $checked{$lrref} = 1;
1851 } elsif (is_fast_fwd $currentval, $lrval) {
1852 $checked{$lrref} = -1;
1853 $notff->('behind', "you are behind $lrref, divergence risk");
1855 $checked{$lrref} = -1;
1856 $notff->('diverged', "you have diverged from $lrref");
1860 my $merge = cfg "branch.$branch.merge",1;
1861 if (defined $merge and $merge =~ m{^refs/heads/}) {
1863 printdebug "ffq merge $rhs\n";
1864 my $check_remote = sub {
1865 my ($remote, $desc) = @_;
1866 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1867 return unless defined $remote;
1868 $check->("refs/remotes/$remote/$rhs", $desc);
1870 $check_remote->((scalar cfg "branch.$branch.remote",1),
1871 'remote fetch/merge branch');
1872 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1873 (scalar cfg "branch.$branch.pushDefault",1),
1874 'remote push branch');
1876 if ($branch =~ m{^dgit/}) {
1877 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1878 } elsif ($branch =~ m{^master$}) {
1879 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1881 return (undef, undef, $ffq_prev, $gdrlast);
1884 sub record_ffq_prev_deferred () {
1885 # => ('status', "message")
1887 # deferred message is undef
1892 # if not ff from some branch we should be ff from, is an snag
1893 # if "deferred", will have added something about that to
1894 # @deferred_update_messages, and also maybe printed (already)
1895 # some messages about ff checks
1897 my $currentval = get_head();
1899 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1900 return ($status,$message) if defined $status;
1904 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1905 push @deferred_updates, "delete $gdrlast";
1906 push @deferred_update_messages, "Recorded previous head for preservation";
1907 return ('deferred', undef);
1910 sub record_ffq_auto () {
1911 my ($status, $message) = record_ffq_prev_deferred();
1912 if ($status eq 'deferred' || $status eq 'exists') {
1914 snag $status, "could not record ffq-prev: $message";
1919 sub ffq_prev_info () {
1921 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1922 my ($status, $message, $current, $ffq_prev, $gdrlast)
1923 = ffq_prev_branchinfo();
1924 if ($status ne 'branch') {
1925 snag $status, "could not check ffq-prev: $message";
1928 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1929 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1932 sub stitch ($$$$$) {
1933 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1935 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1937 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1938 my $differs = get_differs $old_head, $ffq_prev_commitish;
1939 unless ($differs & ~D_PAT_ADD) {
1940 # ffq-prev is ahead of us, and the only tree changes it has
1941 # are possibly addition of things in debian/patches/.
1942 # Just wind forwards rather than making a pointless pseudomerge.
1943 record_gdrlast $gdrlast, $ffq_prev_commitish;
1944 update_head_checkout $old_head, $ffq_prev_commitish,
1945 "stitch (fast forward)";
1950 # We make pseudomerges with L as the contributing parent.
1951 # This makes git rev-list --first-parent work properly.
1952 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1953 'Declare fast forward / record previous work',
1954 "[git-debrebase pseudomerge: $prose]",
1956 record_gdrlast $gdrlast, $new_head;
1957 update_head $old_head, $new_head, "stitch: $prose";
1960 sub do_stitch ($;$) {
1961 my ($prose, $unclean) = @_;
1963 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1964 if (!$ffq_prev_commitish) {
1965 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1968 my $dangling_head = get_head();
1970 keycommits $dangling_head, $unclean,$unclean,$unclean;
1973 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1976 sub upstream_commitish_search ($$) {
1977 my ($upstream_version, $tried) = @_;
1978 # todo: at some point maybe use git-deborig to do this
1979 foreach my $tagpfx ('', 'v', 'upstream/') {
1980 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1981 my $new_upstream = git_get_ref "refs/tags/$tag";
1983 return $new_upstream if length $new_upstream;
1987 sub resolve_upstream_version ($$) {
1988 my ($new_upstream, $upstream_version) = @_;
1990 if (!defined $new_upstream) {
1992 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1993 if (!length $new_upstream) {
1994 fail "Could not determine appropriate upstream commitish.\n".
1995 " (Tried these tags: @tried)\n".
1996 " Check version, and specify upstream commitish explicitly.";
1999 $new_upstream = git_rev_parse $new_upstream;
2001 return $new_upstream;
2004 sub cmd_new_upstream () {
2005 # automatically and unconditionally launders before rebasing
2006 # if rebase --abort is used, laundering has still been done
2010 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
2012 # parse args - low commitment
2013 my $spec_version = shift @ARGV;
2014 my $new_version = (new Dpkg::Version $spec_version, check => 1);
2015 fail "bad version number \`$spec_version'" unless defined $new_version;
2016 if ($new_version->is_native()) {
2017 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
2020 my $new_upstream = shift @ARGV;
2021 my $new_upstream_version = upstreamversion $new_version;
2023 resolve_upstream_version $new_upstream, $new_upstream_version;
2028 my ($n, @x) = @_; # may be ''
2029 my $pc = $pieces{$n} //= {
2031 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
2033 while (my $k = shift @x) { $pc->{$k} = shift @x; }
2038 my $newpiece = sub {
2039 my ($n, @x) = @_; # may be ''
2040 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2041 push @newpieces, $pc;
2046 New => $new_upstream,
2048 while (@ARGV && $ARGV[0] !~ m{^-}) {
2049 my $n = shift @ARGV;
2051 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2052 unless @ARGV && $ARGV[0] !~ m{^-};
2054 my $c = git_rev_parse shift @ARGV;
2055 die unless $n =~ m/^$extra_orig_namepart_re$/;
2056 $newpiece->($n, New => $c);
2059 # now we need to investigate the branch this generates the
2060 # laundered version but we don't switch to it yet
2061 my $old_head = get_head();
2062 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2064 my $old_bw_cl = classify $old_bw;
2065 my $old_anchor_cl = classify $old_anchor;
2067 if (!$old_anchor_cl->{OrigParents}) {
2068 snag 'anchor-treated',
2069 __ 'old anchor is recognised due to --anchor, cannot check upstream';
2071 $old_upstream = parsecommit
2072 $old_anchor_cl->{OrigParents}[0]{CommitId};
2073 $piece->('', Old => $old_upstream->{CommitId});
2076 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2077 if ($old_upstream->{Msg} =~
2078 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2080 my @oldpieces = (split / /, $1);
2081 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2082 if ($old_n_parents != @oldpieces &&
2083 $old_n_parents != @oldpieces + 1) {
2084 snag 'upstream-confusing', sprintf
2085 "previous upstream combine %s".
2086 " mentions %d pieces (each implying one parent)".
2087 " but has %d parents".
2088 " (one per piece plus maybe a previous combine)",
2089 $old_upstream->{CommitId},
2090 (scalar @oldpieces),
2092 } elsif ($oldpieces[0] ne '.') {
2093 snag 'upstream-confusing', sprintf
2094 "previous upstream combine %s".
2095 " first piece is not \`.'",
2099 foreach my $i (0..$#oldpieces) {
2100 my $n = $oldpieces[$i];
2101 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2102 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2106 snag 'upstream-confusing',
2107 "previous upstream $old_upstream->{CommitId} is from".
2108 " git-debrebase but not an \`upstream-combine' commit";
2112 foreach my $pc (values %pieces) {
2113 if (!$old_upstream) {
2114 # we have complained already
2115 } elsif (!$pc->{Old}) {
2116 snag 'upstream-new-piece',
2117 "introducing upstream piece \`$pc->{Name}'";
2118 } elsif (!$pc->{New}) {
2119 snag 'upstream-rm-piece',
2120 "dropping upstream piece \`$pc->{Name}'";
2121 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2122 snag 'upstream-not-ff',
2123 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2127 printdebug "%pieces = ", (dd \%pieces), "\n";
2128 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2136 my @upstream_merge_parents;
2139 push @upstream_merge_parents, $old_upstream->{CommitId};
2142 foreach my $pc (@newpieces) { # always has '' first
2144 read_tree_subdir $pc->{Name}, $pc->{New};
2146 runcmd @git, qw(read-tree), $pc->{New};
2148 push @upstream_merge_parents, $pc->{New};
2151 # index now contains the new upstream
2153 if (@newpieces > 1) {
2154 # need to make the upstream subtree merge commit
2155 $new_upstream = make_commit \@upstream_merge_parents,
2156 [ "Combine upstreams for $new_upstream_version",
2157 ("[git-debrebase upstream-combine . ".
2158 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2163 # $new_upstream is either the single upstream commit, or the
2164 # combined commit we just made. Either way it will be the
2165 # "upstream" parent of the anchor merge.
2167 read_tree_subdir 'debian', "$old_bw:debian";
2169 # index now contains the anchor merge contents
2170 $new_bw = make_commit [ $old_bw, $new_upstream ],
2171 [ "Update to upstream $new_upstream_version",
2172 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2175 # Now we have to add a changelog stanza so the Debian version
2176 # is right. We use debchange to do this. Invoking debchange
2177 # here is a bit fiddly because it has a lot of optional
2178 # exciting behaviours, some of which will break stuff, and
2179 # some of which won't work in a playtree.
2181 # Make debchange use git's idea of the user's identity.
2182 # That way, if the user never uses debchange et al, configuring
2187 defined $v or return;
2190 $usetup->('DEBEMAIL', 'user.email');
2191 $usetup->('DEBFULLNAME', 'user.name');
2195 my @dch = (qw(debchange
2196 --allow-lower-version .*
2199 --vendor=Unknown-Vendor
2200 --changelog debian/changelog
2201 --check-dirname-level 0
2202 --release-heuristic=changelog
2204 "Update to new upstream version $new_upstream_version.");
2206 runcmd @git, qw(checkout -q debian/changelog);
2208 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2210 # Now we have the final new breakwater branch in the index
2211 $new_bw = make_commit [ $new_bw ],
2212 [ "Update changelog for new upstream $new_upstream_version",
2213 "[git-debrebase changelog: new upstream $new_upstream_version]",
2217 # we have constructed the new breakwater. we now need to commit to
2218 # the laundering output, because git-rebase can't easily be made
2219 # to make a replay list which is based on some other branch
2221 update_head_postlaunder $old_head, $old_laundered_tip,
2222 'launder for new upstream';
2224 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2225 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2226 "debrebase new-upstream $new_version: rebase";
2228 # now it's for the user to sort out
2231 sub cmd_record_ffq_prev () {
2232 badusage "no arguments allowed" if @ARGV;
2233 my ($status, $msg) = record_ffq_prev_deferred();
2234 if ($status eq 'exists' && $opt_noop_ok) {
2235 print "Previous head already recorded\n" or die $!;
2236 } elsif ($status eq 'deferred') {
2237 run_deferred_updates 'record-ffq-prev';
2239 fail "Could not preserve: $msg";
2244 badusage "no arguments allowed" if @ARGV;
2245 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2246 print "$bw\n" or die $!;
2249 sub cmd_breakwater () {
2250 badusage "no arguments allowed" if @ARGV;
2251 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2252 print "$bw\n" or die $!;
2256 badusage "no arguments allowed" if @ARGV;
2258 # todo: gdr status should print divergence info
2259 # todo: gdr status should print upstream component(s) info
2260 # todo: gdr should leave/maintain some refs with this kind of info ?
2262 my $oldest = { Badness => 0 };
2265 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2266 if ($oldest->{Badness} < $badness) {
2267 $oldest = $newest = undef;
2270 Badness => $badness,
2271 CommitId => $cl->{CommitId},
2275 $newest //= $oldest;
2277 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2278 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2279 sub { $note->(2, 'branch is unlaundered', @_); },
2280 sub { $note->(3, 'branch needs laundering', @_); },
2281 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2283 my $prcommitinfo = sub {
2285 flush STDOUT or die $!;
2286 runcmd @git, qw(--no-pager log -n1),
2287 '--pretty=format: %h %s%n',
2291 print "current branch contents, in git-debrebase terms:\n";
2292 if (!$oldest->{Badness}) {
2293 print " branch is laundered\n";
2295 print " $oldest->{OurMsg}\n";
2297 foreach my $info ($oldest, $newest) {
2298 my $cid = $info->{CommitId};
2299 next if $cid eq $printed;
2301 print " $info->{KcMsg}\n";
2302 $prcommitinfo->($cid);
2307 my ($cid, $what) = @_;
2308 if (!defined $cid) {
2309 print " $what is not well-defined\n";
2312 $prcommitinfo->($cid);
2315 print "key git-debrebase commits:\n";
2316 $prab->($anchor, 'anchor');
2317 $prab->($bw, 'breakwater');
2319 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2320 ffq_prev_branchinfo();
2322 print "branch and ref status, in git-debrebase terms:\n";
2324 print " $ffq_msg\n";
2326 $ffq_prev = git_get_ref $ffq_prev;
2327 $gdrlast = git_get_ref $gdrlast;
2329 print " unstitched; previous tip was:\n";
2330 $prcommitinfo->($ffq_prev);
2331 } elsif (!$gdrlast) {
2332 print " stitched? (no record of git-debrebase work)\n";
2333 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2334 print " stitched\n";
2336 print " not git-debrebase (diverged since last stitch)\n"
2339 print "you are currently rebasing\n" if currently_rebasing();
2343 my $prose = 'stitch';
2344 getoptions("stitch",
2345 'prose=s', \$prose);
2346 badusage "no arguments allowed" if @ARGV;
2347 do_stitch $prose, 0;
2349 sub cmd_prepush () {
2355 badusage "no arguments allowed" if @ARGV;
2356 do_launder_head 'launder for git-debrebase quick';
2360 sub cmd_conclude () {
2361 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2362 if (!$ffq_prev_commitish) {
2363 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2366 my $dangling_head = get_head();
2368 badusage "no arguments allowed" if @ARGV;
2369 do_launder_head 'launder for git-debrebase quick';
2374 if (currently_rebasing()) {
2375 runcmd @git, qw(rebase --abort);
2376 push @deferred_updates, 'verify HEAD HEAD';
2377 # noop, but stops us complaining that scrap was a noop
2379 badusage "no arguments allowed" if @ARGV;
2380 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2382 if ($ffq_prev_commitish) {
2383 $scrapping_head = get_head();
2384 push @deferred_updates,
2385 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2386 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2388 if (git_get_ref $merge_cache_ref) {
2389 push @deferred_updates,
2390 "delete $merge_cache_ref";
2392 if (!@deferred_updates) {
2393 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2397 if ($scrapping_head) {
2398 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2400 run_deferred_updates "scrap";
2404 sub make_patches_staged ($) {
2406 # Produces the patches that would result from $head if it were
2408 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2412 $any = gbp_pq_export 'bw', $secret_bw, $secret_head;
2417 sub make_patches ($) {
2419 keycommits $head, 0, \&snag;
2420 my $any = make_patches_staged $head;
2423 my $ptree = !$any ? undef :
2424 cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2425 runcmd @git, qw(read-tree), $head;
2427 read_tree_subdir 'debian/patches', $ptree;
2429 rm_subdir_cached 'debian/patches';
2431 $out = make_commit [$head], [
2432 'Commit patch queue (exported by git-debrebase)',
2433 '[git-debrebase make-patches: export and commit patches]',
2439 sub cmd_make_patches () {
2440 my $opt_quiet_would_amend;
2441 getoptions("make-patches",
2442 'quiet-would-amend!', \$opt_quiet_would_amend);
2443 badusage "no arguments allowed" if @ARGV;
2445 my $old_head = get_head();
2446 my $new = make_patches $old_head;
2447 my $d = get_differs $old_head, $new;
2449 fail "No (more) patches to export." unless $opt_noop_ok;
2451 } elsif ($d == D_PAT_ADD) {
2453 update_head_checkout $old_head, $new, 'make-patches';
2455 print STDERR failmsg
2456 "Patch export produced patch amendments".
2457 " (abandoned output commit $new).".
2458 " Try laundering first."
2459 unless $opt_quiet_would_amend;
2464 sub check_series_has_all_patches ($) {
2466 my $seriesfn = 'debian/patches/series';
2467 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2471 our $comments_snagged;
2472 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2473 if ($f =~ m/^\s*\#/) {
2474 snag 'series-comments',
2475 "$seriesfn contains comments, which will be discarded"
2476 unless $comments_snagged++;
2479 fail "patch $f repeated in $seriesfn !" if $series{$f}++;
2481 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2482 my ($f,$i) = @$patchfile;
2483 next if $series{$f};
2484 next if $f eq 'series';
2485 snag 'unused-patches', "Unused patch file $f will be discarded";
2489 sub begin_convert_from () {
2490 my $head = get_head();
2491 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2493 fail "ffq-prev exists, this is already managed by git-debrebase!"
2494 if $ffq_prev && git_get_ref $ffq_prev;
2496 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2497 snag 'already-converted',
2498 "ahead of debrebase-last, this is already managed by git-debrebase!"
2499 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2500 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2503 sub complete_convert_from ($$$$) {
2504 my ($old_head, $new_head, $gi, $mrest) = @_;
2505 ffq_check $new_head;
2506 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2509 update_head_checkout $old_head, $new_head, $mrest;
2512 sub cmd_convert_from_gbp () {
2513 badusage "want only 1 optional argument, the upstream git commitish"
2516 my $clogp = parsechangelog();
2517 my $version = $clogp->{'Version'}
2518 // die "missing Version from changelog";
2520 my ($upstream_spec) = @ARGV;
2522 my $upstream_version = upstreamversion $version;
2524 resolve_upstream_version($upstream_spec, $upstream_version);
2526 my ($old_head, $gdrlastinfo) = begin_convert_from();
2528 my $upsdiff = get_differs $upstream, $old_head;
2529 if ($upsdiff & D_UPS) {
2530 runcmd @git, qw(--no-pager diff --stat),
2531 $upstream, $old_head,
2532 qw( -- :!/debian :/);
2534 upstream ($upstream_spec) and HEAD are not
2535 identical in upstream files. See diffstat above, or run
2536 git diff $upstream_spec HEAD -- :!/debian :/
2540 if (!is_fast_fwd $upstream, $old_head) {
2541 snag 'upstream-not-ancestor',
2542 "upstream ($upstream) is not an ancestor of HEAD";
2544 my $wrong = cmdoutput
2545 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2546 qw(-- :/ :!/debian));
2547 if (length $wrong) {
2548 snag 'unexpected-upstream-changes',
2549 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2550 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2554 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2555 snag 'upstream-has-debian',
2556 "upstream ($upstream) contains debian/ directory";
2559 check_series_has_all_patches $old_head;
2561 my $previous_dgit_view = eval {
2562 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2564 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2565 my ($stz, $desc) = @_;
2566 no warnings qw(exiting);
2567 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2568 next unless $stz->{Date};
2569 next unless $stz->{Distribution} ne 'UNRELEASED';
2570 $lvsn = $stz->{Version};
2571 $suite = $stz->{Distribution};
2574 die "neither of the first two changelog entries are released\n"
2575 unless defined $lvsn;
2576 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2577 my $mtag_pat = debiantag_maintview $lvsn, '*';
2578 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2580 die "could not find suitable maintainer view tag $mtag_pat\n"
2581 unless $mtag =~ m{/};
2582 is_fast_fwd $mtag, 'HEAD' or
2583 die "HEAD is not FF from maintainer tag $mtag!";
2584 my $dtag = "archive/$mtag";
2585 git_get_ref "refs/tags/$dtag" or
2586 die "dgit view tag $dtag not found\n";
2587 is_fast_fwd $mtag, $dtag or
2588 die "dgit view tag $dtag is not FF from maintainer tag $mtag\n";
2589 print "will stitch in dgit view, $dtag\n";
2590 git_rev_parse $dtag;
2592 if (!$previous_dgit_view) {
2596 Cannot confirm dgit view: $@
2597 Failed to stitch in dgit view (see messages above).
2598 dgit --overwrite will be needed on the first dgit push after conversion.
2602 snags_maybe_bail_early();
2608 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2609 # make a branch out of the patch queue - we'll want this in a mo
2610 runcmd qw(gbp pq import);
2611 # strip the patches out
2612 runcmd @git, qw(checkout -q gdr-internal~0);
2613 rm_subdir_cached 'debian/patches';
2614 $work = make_commit ['HEAD'], [
2615 'git-debrebase convert-from-gbp: drop patches from tree',
2616 'Delete debian/patches, as part of converting to git-debrebase format.',
2617 '[git-debrebase convert-from-gbp: drop patches from tree]'
2619 # make the anchor merge
2620 # the tree is already exactly right
2621 $work = make_commit [$work, $upstream], [
2622 'git-debrebase import: declare upstream',
2623 'First breakwater merge.',
2624 '[git-debrebase anchor: declare upstream]'
2627 # rebase the patch queue onto the new breakwater
2628 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2629 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2630 $work = git_rev_parse 'HEAD';
2632 if ($previous_dgit_view) {
2633 $work = make_commit [$work, $previous_dgit_view], [
2634 'git-debrebase import: declare ff from dgit archive view',
2635 '[git-debrebase pseudomerge: import-from-gbp]',
2640 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2641 print <<END or die $!;
2642 git-debrebase: converted from patched-unapplied (gbp) branch format, OK
2646 sub cmd_convert_to_gbp () {
2647 badusage "no arguments allowed" if @ARGV;
2648 my $head = get_head();
2649 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2650 my ($anchor, $breakwater) = keycommits $head, 0;
2651 my $out = $breakwater;
2652 my $any = make_patches_staged $head;
2655 $out = make_commit [$out], [
2656 'Commit patch queue (converted from git-debrebase format)',
2657 '[git-debrebase convert-to-gbp: commit patches]',
2661 # in this case, it can be fast forward
2665 push @deferred_updates, "delete $ffq";
2666 push @deferred_updates, "delete $gdrlast";
2669 update_head_checkout $head, $out, "convert to gbp (v0)";
2670 print <<END or die $!;
2671 git-debrebase: converted to git-buildpackage branch format
2672 git-debrebase: WARNING: do not now run "git-debrebase" any more
2673 git-debrebase: WARNING: doing so would drop all upstream patches!
2677 sub cmd_convert_from_dgit_view () {
2678 my $clogp = parsechangelog();
2680 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2686 getoptions("convert-from-dgit-view",
2687 'diagnose!', \$diagnose,
2688 'build-products-dir:s', \$bpd,
2689 'origs!', \$do_origs,
2691 'always-convert-anyway!', \$always);
2692 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2697 my $spec = shift @ARGV;
2698 my $commit = git_rev_parse "$spec^{commit}";
2699 push @upstreams, { Commit => $commit,
2700 Source => "$ARGV[0], from command line",
2705 my ($head, $gdrlastinfo) = begin_convert_from();
2709 my $trouble = sub { $troubles++; };
2710 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2711 printdebug "troubles=$troubles\n";
2714 $us: Branch already seems to be in git-debrebase format!
2715 $us: --always-convert-anyway would do the conversion operation anyway
2716 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2718 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2723 check_series_has_all_patches $head;
2725 snags_maybe_bail_early();
2727 my $version = upstreamversion $clogp->{Version};
2728 print STDERR "Considering possible commits corresponding to upstream:\n";
2733 my $ups_tag = upstream_commitish_search $version, \@tried;
2735 my $this = "git tag $tried[-1]";
2736 push @upstreams, { Commit => $ups_tag,
2741 " git tag: no suitable tag found (tried %s)\n",
2746 my $p = $clogp->{'Source'};
2747 # we do a quick check to see if there are plausible origs
2749 if (!opendir BPD, $bpd) {
2750 die "$bpd: opendir: $!" unless $!==ENOENT;
2752 while ($!=0, my $f = readdir BPD) {
2753 next unless is_orig_file_of_p_v $f, $p, $version;
2755 " orig: found what looks like a .orig, %s\n",
2760 die "read $bpd: $!" if $!;
2764 my $tree = cmdoutput
2765 @dgit, qw(--build-products-dir), $bpd,
2766 qw(print-unapplied-treeish);
2769 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2770 rm_subdir_cached 'debian';
2771 $tree = cmdoutput @git, qw(write-tree);
2772 my $ups_synth = make_commit [], [ <<END, <<END,
2773 Import effective orig tree for upstream version $version
2775 This includes the contents of the .orig(s), minus any debian/ directory.
2777 [git-debrebase convert-from-dgit-view upstream-import-convert: $version]
2780 push @upstreams, { Commit => $ups_synth,
2781 Source => "orig(s) imported via dgit",
2786 " orig: no suitable origs found (looked for %s in %s)\n",
2787 "${p}_".(stripeoch $version)."...", $bpd;
2792 my $some_patches = stat_exists 'debian/patches/series';
2794 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2797 foreach my $u (@upstreams) {
2801 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2802 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2803 runcmd @git, qw(clean -xdff);
2804 runcmd @git, qw(checkout), $head, qw(-- debian);
2805 if ($some_patches) {
2806 rm_subdir_cached 'debian/patches';
2807 $work = make_commit [ $work ], [
2808 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2809 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2810 "to git-debrebase format. Upstream changes will appear as commits.",
2811 '[git-debrebase convert-from-dgit-view drop-patches]'
2814 $work = make_commit [ $work, $u->{Commit} ], [
2815 'git-debrebase convert-from-dgit-view: declare upstream',
2816 '(Re)constructed breakwater merge.',
2817 '[git-debrebase anchor: declare upstream]'
2819 runcmd @git, qw(checkout --quiet -b mk), $work;
2820 if ($some_patches) {
2821 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2822 runcmd @git, qw(reset --quiet);
2823 my @gbp_cmd = (qw(gbp pq import));
2825 my $gbp_err = "../gbp-pq-err";
2826 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2828 my $r = system @gbp_cmd;
2831 " %s: couldn't apply patches: gbp pq %s",
2832 $u->{Source}, waitstatusmsg();
2836 my $work = git_rev_parse qw(HEAD);
2837 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2838 if (length $diffout) {
2840 " $u->{Source}: applying patches gives different tree\n";
2841 print STDERR $diffout if $diagnose;
2845 $u->{Result} = $work;
2853 Could not find or construct a suitable upstream commit.
2854 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2855 upstream commmit explicitly or provide suitable origs.
2859 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2861 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2862 'convert-from-dgit-view';
2865 sub cmd_forget_was_ever_debrebase () {
2866 badusage "forget-was-ever-debrebase takes no further arguments" if @ARGV;
2867 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2868 ffq_prev_branchinfo();
2869 fail "Not suitable for recording git-debrebaseness anyway: $ffq_msg"
2870 if defined $ffq_msg;
2871 push @deferred_updates, "delete $ffq_prev";
2872 push @deferred_updates, "delete $gdrlast";
2874 run_deferred_updates "forget-was-ever-debrebase";
2877 sub cmd_record_resolved_merge () {
2878 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2879 # MERGE-TODO needs documentation
2880 my $new = get_head();
2883 print "Checking how you have resolved the merge problem\n";
2884 my $nope = sub { print "Not $method: @_"; 0; };
2886 my $maybe = sub { print "Seems to be $method.\n"; };
2888 my ($key, $ref) = @_;
2889 reflog_cache_insert $merge_cache_ref, $key, $ref;
2890 print "OK. You can switch branches and try git-debrebase again.\n";
2894 fresh_workarea 'merge';
2896 $method = 'vanilla-merge patchqueue';
2897 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2898 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2899 foreach my $lr (qw(left right)) {
2900 my $n = "$wrecknoteprefix/$lr-patchqueue";
2901 my $lrpq = git_get_ref $n;
2902 $lrpq or return $nope->("wreckage did not contain patchqueues");
2903 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2906 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2907 or die "wreckage element $wrecknoteprefix/new-base missing";
2908 my $result = merge_series_patchqueue_convert
2910 $yes->("vanilla-merge $vanilla", $result);
2913 fail "No resolved merge method seems applicable.\n";
2917 sub cmd_downstream_rebase_launder_v0 () {
2918 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2920 $base = git_rev_parse $base;
2921 my $old_head = get_head();
2922 my $current = $old_head;
2925 if ($current eq $base) {
2926 $topmost_keep //= $current;
2927 print " $current BASE stop\n";
2930 my $cl = classify $current;
2931 print " $current $cl->{Type}";
2933 my $p0 = $cl->{Parents}[0]{CommitId};
2935 if ($cl->{Type} eq 'Pseudomerge') {
2936 print " ^".($cl->{Contributor}{Ix}+1);
2937 $next = $cl->{Contributor}{CommitId};
2938 } elsif ($cl->{Type} eq 'AddPatches' or
2939 $cl->{Type} eq 'Changelog') {
2949 $topmost_keep //= $current;
2951 die "to-be stripped changes not on top of the branch\n"
2956 if ($topmost_keep eq $old_head) {
2957 print "unchanged\n";
2959 print "updating to $topmost_keep\n";
2960 update_head_checkout
2961 $old_head, $topmost_keep,
2962 'downstream-rebase-launder-v0';
2966 setlocale(LC_MESSAGES, "");
2967 textdomain("git-debrebase");
2971 "D+" => \$debuglevel,
2972 'noop-ok', => \$opt_noop_ok,
2973 'f=s' => \@snag_force_opts,
2974 'anchor=s' => \@opt_anchors,
2975 '--dgit=s' => \($dgit[0]),
2977 'experimental-merge-resolution!', \$opt_merges,
2979 my ($opt,$val) = @_;
2980 badusage __ "git-debrebase: no cuddling to -i for git-rebase"
2982 die if $opt_defaultcmd_interactive; # should not happen
2983 $opt_defaultcmd_interactive = [ qw(-i) ];
2984 # This access to @ARGV is excessive familiarity with
2985 # Getopt::Long, but there isn't another sensible
2986 # approach. '-i=s{0,}' does not work with bundling.
2987 push @$opt_defaultcmd_interactive, @ARGV;
2990 'help' => sub { print $usage_message or die $!; finish 0; },
2993 initdebug('git-debrebase ');
2994 enabledebug if $debuglevel;
2996 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2997 chdir $toplevel or die "chdir $toplevel: $!";
2999 $rd = fresh_playground "$playprefix/misc";
3001 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
3003 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
3004 defaultcmd_rebase();
3006 my $cmd = shift @ARGV;
3009 $cmdfn = ${*::}{"cmd_$cmdfn"};
3011 $cmdfn or badusage f_ "unknown git-debrebase sub-operation %s", $cmd;