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) = i_ <<'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 f_ "%s: bad usage: %s\n", $us, $m;
73 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
74 GetOptions @_ or badusage $m;
78 getoptions_main +(f_ "bad options follow \`git-debrebase %s'", $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 f_ "missing required git config %s", $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 confess "$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 confess $!;
148 foreach (@$updates) {
149 printdebug ">= ", $_, "\n";
150 print U $_, "\n" or confess $!;
153 close U or failedcmd @upd_cmd;
156 our $snags_forced = 0;
157 our $snags_tripped = 0;
158 our $snags_summarised = 0;
159 our @deferred_updates;
160 our @deferred_update_messages;
162 sub merge_wreckage_cleaning ($) {
164 git_for_each_ref("$wrecknoteprefix/*", sub {
165 my ($objid,$objtype,$fullrefname,$reftail) = @_;
166 push @$updates, "delete $fullrefname";
170 sub all_snags_summarised () {
171 $snags_forced + $snags_tripped == $snags_summarised;
173 sub run_deferred_updates ($) {
176 my $m = 'dangerous internal error';
177 confess $m.' - '.__ $m unless all_snags_summarised();
179 merge_wreckage_cleaning \@deferred_updates;
180 run_ref_updates_now $mrest, \@deferred_updates;
181 print $_, "\n" foreach @deferred_update_messages;
183 @deferred_updates = ();
184 @deferred_update_messages = ();
187 sub get_tree ($;$$) {
188 # tree object name => ([ $name, $info ], ...)
189 # where $name is the sort key, ie has / at end for subtrees
190 # $info is the LHS from git-ls-tree (<mode> <type> <hash>)
191 # without $precheck, will crash if $x does not exist, so don't do that;
192 # instead pass '' to get ().
193 my ($x, $precheck, $recurse) = @_;
195 return () if !length $x;
198 my ($type, $dummy) = git_cat_file $x, [qw(tree missing)];
199 return () if $type eq 'missing';
202 $recurse = !!$recurse;
204 confess "get_tree needs object not $x ?" unless $x =~ m{^[0-9a-f]+\:};
206 our (@get_tree_memo, %get_tree_memo);
207 my $memo = $get_tree_memo{$recurse,$x};
208 return @$memo if $memo;
210 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
212 my @cmd = (qw(git ls-tree -z --full-tree));
213 push @cmd, qw(-r) if $recurse;
214 push @cmd, qw(--), $x;
215 my $o = cmdoutput @cmd;
218 foreach my $l (split /\0/, $o) {
219 my ($i, $n) = split /\t/, $l, 2;
220 $n .= '/' if $i =~ m/^\d+ tree /;
222 confess "$x need $last < $n ?" unless $last lt $n;
224 $get_tree_memo{$recurse,$x} = \@l;
225 push @get_tree_memo, $x;
226 if (@get_tree_memo > 10) {
227 delete $get_tree_memo{ shift @get_tree_memo };
232 sub trees_diff_walk ($$$;$) {
233 # trees_diff_walk [{..opts...},] $x, $y, sub {... }
234 # calls sub->($name, $ix, $iy) for each difference
235 # $x and $y are as for get_tree
236 # where $name, $ix, $iy are $name and $info from get_tree
237 # opts are all call even for names same in both
238 # recurse call even for names same in both
239 my $opts = shift @_ if @_>=4;
240 my ($x,$y,$call) = @_;
241 my $all = $opts->{all};
242 return if !$all and $x eq $y;
243 my @x = get_tree $x, 0, $opts->{recurse};
244 my @y = get_tree $y, 0, $opts->{recurse};
245 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
248 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
249 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
250 my ($n, $ix, $iy); # all same? $cmp=0, use both
252 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
254 ($n, $ix) = @{ shift @x } if $cmp <= 0;
255 ($n, $iy) = @{ shift @y } if $cmp >= 0;
256 next if !$all and $ix eq $iy;
258 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
259 !!$all,$x,$y, $n,$ix,$iy
261 $call->($n, $ix, $iy);
265 sub get_differs ($$) {
267 # This does a similar job to quiltify_trees_differ, in dgit, a bit.
268 # But we don't care about modes, or dpkg-source-unrepresentable
269 # changes, and we don't need the plethora of different modes.
270 # Conversely we need to distinguish different kinds of changes to
271 # debian/ and debian/patches/.
272 # Also, here we have, and want to use, trees_diff_walk, because
273 # we may be calling this an awful lot and we want it to be fast.
278 no warnings qw(exiting);
280 my $plain = sub { $_[0] =~ m{^(100|0*)644 blob }s; };
282 trees_diff_walk "$x:", "$y:", sub {
283 my ($n,$ix,$iy) = @_;
285 # analyse difference at the toplevel
287 if ($n ne 'debian/') {
291 if ($n eq 'debian') {
292 # one side has a non-tree for ./debian !
293 $differs |= D_DEB_OTH;
297 my $xd = $ix && "$x:debian";
298 my $yd = $iy && "$y:debian";
299 trees_diff_walk $xd, $yd, sub {
300 my ($n,$ix,$iy) = @_;
302 # analyse difference in debian/
304 if ($n eq 'changelog' && (!$ix || $plain->($ix))
306 $differs |= D_DEB_CLOG;
309 if ($n ne 'patches/') {
310 $differs |= D_DEB_OTH;
314 my $xp = $ix && "$xd/patches";
315 my $yp = $iy && "$yd/patches";
316 trees_diff_walk { recurse=>1 }, $xp, $yp, sub {
317 my ($n,$ix,$iy) = @_;
319 # analyse difference in debian/patches
323 # we are recursing; directories may appear and disappear
325 } elsif ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
327 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
328 my $x_s = (git_cat_file "$xp/series", 'blob');
329 my $y_s = (git_cat_file "$yp/series", 'blob');
330 chomp $x_s; $x_s .= "\n";
331 $ok = $x_s eq substr($y_s, 0, length $x_s);
335 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
340 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
345 sub commit_pr_info ($) {
347 return Data::Dumper->dump([$r], [qw(commit)]);
350 sub calculate_committer_authline () {
351 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
352 'DUMMY COMMIT (git-debrebase)', "HEAD:";
353 my ($h,$m) = get_commit $c;
354 $h =~ m/^committer .*$/m or confess "($h) ?";
358 sub rm_subdir_cached ($) {
360 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
363 sub read_tree_subdir ($$) {
364 my ($subdir, $new_tree_object) = @_;
365 rm_subdir_cached $subdir;
366 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
369 sub read_tree_debian ($) {
371 read_tree_subdir 'debian', "$treeish:debian";
372 rm_subdir_cached 'debian/patches';
375 sub read_tree_upstream ($;$$) {
376 my ($treeish, $keep_patches, $tree_with_debian) = @_;
377 # if $tree_with_debian is supplied, will use that for debian/
378 # otherwise will save and restore it.
380 $tree_with_debian ? "$tree_with_debian:debian"
381 : cmdoutput @git, qw(write-tree --prefix=debian/);
382 runcmd @git, qw(read-tree), $treeish;
383 read_tree_subdir 'debian', $debian;
384 rm_subdir_cached 'debian/patches' unless $keep_patches;
387 sub make_commit ($$) {
388 my ($parents, $message_paras) = @_;
389 my $tree = cmdoutput @git, qw(write-tree);
390 my @cmd = (@git, qw(commit-tree), $tree);
391 push @cmd, qw(-p), $_ foreach @$parents;
392 push @cmd, qw(-m), $_ foreach @$message_paras;
393 return cmdoutput @cmd;
396 our @snag_force_opts;
398 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
399 if (grep { $_ eq $tag } @snag_force_opts) {
401 print STDERR f_ "%s: snag ignored (-f%s): %s\n", $us, $tag, $msg;
404 print STDERR f_ "%s: snag detected (-f%s): %s\n", $us, $tag, $msg;
408 # Important: all mainline code must call snags_maybe_bail after
409 # any point where snag might be called, but before making changes
410 # (eg before any call to run_deferred_updates). snags_maybe_bail
411 # may be called more than once if necessary (but this is not ideal
412 # because then the messages about number of snags may be confusing).
413 sub snags_maybe_bail () {
414 return if all_snags_summarised();
417 "%s: snags: %d overriden by individual -f options\n",
420 if ($snags_tripped) {
423 "%s: snags: %d overriden by global --force\n",
427 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
431 $snags_summarised = $snags_forced + $snags_tripped;
433 sub snags_maybe_bail_early () {
434 # useful to bail out early without doing a lot of work;
435 # not a substitute for snags_maybe_bail.
436 snags_maybe_bail() if $snags_tripped && !$opt_force;
439 return $snags_forced || $snags_tripped;
442 sub ffq_prev_branchinfo () {
443 my $current = git_get_symref();
444 return gdr_ffq_prev_branchinfo($current);
447 sub record_gdrlast ($$;$) {
448 my ($gdrlast, $newvalue, $oldvalue) = @_;
449 $oldvalue ||= $git_null_obj;
450 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
453 sub fail_unprocessable ($) {
456 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
458 my $mangled = __ <<END;
459 Branch/history seems mangled - no longer in gdr format.
460 See ILLEGAL OPERATIONS in git-debrebase(5).
465 fail f_ <<END, $msg, $ffqm;
467 Is this meant to be a gdr branch? %s
469 } elsif (git_get_ref $ffq_prev) {
470 fail f_ <<END, $msg, $mangled;
473 Consider git-debrebase scrap, to throw away your recent work.
475 } elsif (!git_get_ref $gdrlast) {
478 Branch does not seem to be meant to be a git-debrebase branch?
479 Wrong branch, or maybe you needed git-debrebase convert-from-*.
481 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
489 Branch/history mangled, and diverged since last git-debrebase.
490 Maybe you reset to, or rebased from, somewhere inappropriate.
495 sub gbp_pq_export ($$$) {
496 my ($bname, $base, $tip) = @_;
497 # must be run in a workarea. $bname and patch-queue/$bname
498 # ought not to exist. Leaves you on patch-queue/$bname with
499 # the patches staged but not committed.
500 # returns 1 if there were any patches
501 printdebug "gbp_pq_export $bname $base $tip\n";
502 runcmd @git, qw(checkout -q -b), $bname, $base;
503 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
504 my @gbp_cmd = (qw(gbp pq export));
505 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
507 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
510 return 0 unless stat_exists 'debian/patches';
511 runcmd @git, qw(add -f debian/patches);
516 # MERGE-TODO allow merge resolution separately from laundering, before git merge
519 # use git-format-patch?
520 # our own patch identification algorithm?
521 # this is an alternative strategy
523 sub merge_failed ($$;@) {
524 my ($wrecknotes, $emsg, @xmsgs) = @_;
526 push @m, "Merge resolution failed: $emsg";
532 merge_wreckage_cleaning \@updates;
533 run_ref_updates_now "merge failed", \@updates;
537 while (my ($k,$v) = each %$wrecknotes) {
538 push @updates, "create $wrecknoteprefix/$k $v";
540 run_ref_updates_now "merge failed", \@updates;
541 push @m, "Wreckage left in $wrecknoteprefix/*.";
543 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
545 # use finish rather than fail, in case we are within an eval
546 # (that can happen inside walk!)
548 print STDERR "$us: $_\n" foreach @m;
552 sub mwrecknote ($$$) {
553 my ($wrecknotes, $reftail, $commitish) = @_;
554 confess unless defined $commitish;
555 printdebug "mwrecknote $reftail $commitish\n";
556 $wrecknotes->{$reftail} = $commitish;
559 sub merge_attempt_cmd {
560 my $wrecknotes = shift @_;
564 merge_failed $wrecknotes,
565 failedcmd_waitstatus(),
566 "failed command: @_";
570 sub merge_series_patchqueue_convert ($$$);
572 sub merge_series ($$$;@) {
573 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
574 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
575 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
576 # ^ specifies several patch series (currently we only support exactly 2)
577 # return value is a commit which is the result of
578 # merging the two versions of the same topic branch
579 # $input_q[0] and $input_q[1]
580 # with respect to the old version
584 # Creates, in *_q, a key MR for its private use
586 printdebug "merge_series newbase=$newbase\n";
588 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
589 $base_q->{MR}{S} = 'base';
592 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
593 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
594 # $prereq{<patch filename>} exists or not (even later)
598 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
600 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
603 fresh_workarea "merge";
604 my $seriesfile = "debian/patches/series";
607 foreach my $q ($base_q, reverse @input_qs) {
609 my $any = gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
612 open S, $seriesfile or confess "$seriesfile $!";
613 while (my $patch = <S>) {
614 chomp $patch or confess $!;
615 $prereq{$patch} //= {};
616 foreach my $earlier (@earlier) {
617 $prereq{$patch}{$earlier}{$s}++ and confess;
619 push @earlier, $patch;
620 stat "debian/patches/$patch" or confess "$patch ?";
622 S->error and confess "$seriesfile $!";
625 read_tree_upstream $newbase, 1;
626 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
627 "Convert $s to patch queue for merging",
628 "[git-debrebase merge-innards patch-queue import:".
631 printdebug "merge_series pec $pec ";
632 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
633 $pec = make_commit [ $pec ], [
634 "Drop series file from $s to avoid merge trouble",
635 "[git-debrebase merge-innards patch-queue prep:".
639 read_tree_debian $newbase;
641 read_tree_subdir 'debian/patches', "$pec:debian/patches";
643 rm_subdir_cached 'debian/patches';
645 $pec = make_commit [ $pec ], [
646 "Update debian/ (excluding patches) to final to avoid re-merging",
647 "debian/ was already merged and we need to just take that.",
648 "[git-debrebase merge-innards patch-queue packaging:".
652 printdebug "pec' $pec\n";
653 runcmd @git, qw(reset -q --hard), $pec;
654 $q->{MR}{PEC} = $pec;
655 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
657 # now, because of reverse, we are on $input_q->{MR}{OQC}
658 runcmd @git, qw(checkout -q -b merge);
659 printdebug "merge_series merging...\n";
660 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
662 $attempt_cmd->(@mergecmd);
664 printdebug "merge_series merge ok, series...\n";
665 # We need to construct a new series file
666 # Firstly, resolve prereq
667 foreach my $f (sort keys %prereq) {
668 printdebug "merge_series patch\t$f\t";
669 if (!stat_exists "debian/patches/$f") {
670 print DEBUG " drop\n" if $debuglevel;
671 # git merge deleted it; that's how we tell it's not wanted
675 print DEBUG " keep\n" if $debuglevel;
676 foreach my $g (sort keys %{ $prereq{$f} }) {
677 my $gfp = $prereq{$f}{$g};
678 printdebug "merge_series prereq\t$f\t-> $g\t";
679 if (!!$gfp->{0} == !!$gfp->{1}
682 print DEBUG "\tkeep\n" if $debuglevel;
684 print DEBUG "\tdrop\n" if $debuglevel;
685 delete $prereq{$f}{$g};
692 return scalar keys %{ $prereq{$f} };
695 my $nodate = time + 1;
697 # $authordate{<patch filename>};
698 my $authordate = sub {
700 $authordate{$f} //= do {
701 open PF, "<", "debian/patches/$f" or confess "$f $!";
703 return $nodate if m/^$/;
704 last if s{^Date: }{};
707 return cmdoutput qw(date +%s -d), $_;
711 open NS, '>', $seriesfile or confess $!;
713 while (keys %prereq) {
715 foreach my $try (sort keys %prereq) {
718 $unsat->($try) <=> $unsat->($best) or
719 $authordate->($try) <=> $authordate->($best) or
725 printdebug "merge_series series next $best\n";
726 print NS "$best\n" or confess $!;
727 delete $prereq{$best};
728 foreach my $gp (values %prereq) {
733 runcmd @git, qw(add), $seriesfile;
734 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
735 $merged_pq = git_rev_parse 'HEAD';
736 $mwrecknote->('merged-patchqueue', $merged_pq);
738 return merge_series_patchqueue_convert
739 $wrecknotes, $newbase, $merged_pq;
742 sub merge_series_patchqueue_convert ($$$) {
743 my ($wrecknotes, $newbase, $merged_pq) = @_;
748 printdebug "merge_series series gbp pq import\n";
749 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
751 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
752 # MERGE-TODO consider git-format-patch etc. instead,
753 # since gbp pq doesn't always round-trip :-/
755 # OK now we are on patch-queue/merge, and we need to rebase
756 # onto the intended parent and drop the patches from each one
758 printdebug "merge_series series ok, building...\n";
759 my $build = $newbase;
760 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
761 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
762 my $commit = git_cat_file $c, 'commit';
763 printdebug "merge_series series ok, building $c\n";
764 read_tree_upstream $c, 0, $newbase;
765 my $tree = cmdoutput @git, qw(write-tree);
766 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
767 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
768 open C, ">", "../mcommit" or confess $!;
769 print C $commit or confess $!;
770 close C or confess $!;
771 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
774 mwrecknote($wrecknotes, 'merged-result', $result);
776 runcmd @git, qw(update-ref refs/heads/result), $result;
778 runcmd @git, qw(checkout -q -b debug);
779 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
780 runcmd @git, qw(add .);
781 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
782 my $mdebug = git_rev_parse 'HEAD';
783 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
784 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
786 printdebug "merge_series returns $result\n";
790 # classify returns an info hash like this
792 # Hdr => # commit headers, including 1 final newline
793 # Msg => # commit message (so one newline is dropped)
795 # Type => (see below)
797 # Ix => $index # ie 0, 1, 2, ...
799 # Differs => return value from get_differs
801 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
803 # NewMsg => # commit message, but with any [dgit import ...] edited
804 # # to say "[was: ...]"
814 # has additional entres in classification result
815 # Overwritten = [ subset of Parents ]
816 # Contributor = $the_remaining_Parent
818 # DgitImportUnpatched
819 # has additional entry in classification result
820 # OrigParents = [ subset of Parents ]
823 # has additional entry in classification result
824 # OrigParents = [ subset of Parents ] # singleton list
831 # has additional entry in classification result
834 sub parsecommit ($;$) {
835 my ($objid, $p_ref) = @_;
836 # => hash with CommitId Hdr Msg Tree Parents
837 # Parents entries have only Ix CommitId
838 # $p_ref, if provided, must be [] and is used as a base for Parents
843 my ($h,$m) = get_commit $objid;
845 my ($t) = $h =~ m/^tree (\w+)$/m or confess $objid;
846 my (@ph) = $h =~ m/^parent (\w+)$/mg;
856 foreach my $ph (@ph) {
858 Ix => scalar @$p_ref,
870 my $r = parsecommit($objid, \@p);
874 $p->{Differs} = (get_differs $p->{CommitId}, $t),
877 printdebug "classify $objid \$t=$t \@p",
878 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
882 my ($type, @rest) = @_;
883 $r = { %$r, Type => $type, @rest };
885 printdebug " = $type ".(dd $r)."\n";
891 $r = { %$r, Type => qw(Unknown), Why => $why };
892 printdebug " ** Unknown\n";
896 if (grep { $_ eq $objid } @opt_anchors) {
897 return $classify->('TreatAsAnchor');
900 my @identical = grep { !$_->{Differs} } @p;
901 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
902 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
904 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
905 # multi-orig upstreams are represented with an anchor merge
906 # from a single upstream commit which combines the orig tarballs
908 # Every anchor tagged this way must be a merge.
909 # We are relying on the
910 # [git-debrebase anchor: ...]
911 # commit message annotation in "declare" anchor merges (which
912 # do not have any upstream changes), to distinguish those
913 # anchor merges from ordinary pseudomerges (which we might
914 # just try to strip).
916 # However, the user is going to be doing git-rebase a lot. We
917 # really don't want them to rewrite an anchor commit.
918 # git-rebase trips up on merges, so that is a useful safety
921 # BreakwaterStart commits are also anchors in the terminology
922 # of git-debrebase(5), but they are untagged (and always
923 # manually generated).
925 # We cannot not tolerate any tagged linear commit (ie,
926 # BreakwaterStart commits tagged `[anchor:') because such a
927 # thing could result from an erroneous linearising raw git
928 # rebase of a merge anchor. That would represent a corruption
929 # of the branch. and we want to detect and reject the results
930 # of such corruption before it makes it out anywhere. If we
931 # reject it here then we avoid making the pseudomerge which
932 # would be needed to push it.
934 my $badanchor = sub {
935 $unknown->(f_ "git-debrebase \`anchor' but %s", "@_");
937 @p == 2 or return $badanchor->(__ "has other than two parents");
938 $haspatches and return $badanchor->(__ "contains debian/patches");
940 # How to decide about l/r ordering of anchors ? git
941 # --topo-order prefers to expand 2nd parent first. There's
942 # already an easy rune to look for debian/ history anyway (git log
943 # debian/) so debian breakwater branch should be 1st parent; that
944 # way also there's also an easy rune to look for the upstream
945 # patches (--topo-order).
947 # Also this makes --first-parent be slightly more likely to
948 # be useful - it makes it provide a linearised breakwater history.
950 # Of course one can say somthing like
951 # gitk -- ':/' ':!/debian'
952 # to get _just_ the commits touching upstream files, and by
953 # the TREESAME logic in git-rev-list this will leave the
954 # breakwater into upstream at the first anchor. But that
955 # doesn't report debian/ changes at all.
957 # Other observations about gitk: by default, gitk seems to
958 # produce output in a different order to git-rev-list. I
959 # can't seem to find this documented anywhere. gitk
960 # --date-order DTRT. But, gitk always seems to put the
961 # parents from left to right, in order, so it's easy to see
962 # which way round a pseudomerge is.
964 $p[0]{IsOrigin} and $badanchor->(__ "is an origin commit");
965 $p[1]{Differs} & ~DS_DEB and
966 $badanchor->(__ "upstream files differ from left parent");
967 $p[0]{Differs} & ~D_UPS and
968 $badanchor->(__ "debian/ differs from right parent");
970 return $classify->(qw(Anchor),
971 OrigParents => [ $p[1] ]);
975 my $d = $r->{Parents}[0]{Differs};
976 if ($d == D_PAT_ADD) {
977 return $classify->(qw(AddPatches));
978 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
979 return $unknown->(__ "edits debian/patches");
980 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
981 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
983 if ($d == D_DEB_CLOG) {
984 return $classify->(qw(Changelog));
986 return $classify->(qw(Packaging));
988 } elsif ($ty eq 'missing') {
989 return $classify->(qw(BreakwaterStart));
991 return $unknown->(__ "parent's debian is not a directory");
993 } elsif ($d == D_UPS) {
994 return $classify->(qw(Upstream));
995 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
996 return $classify->(qw(Mixed));
998 return $unknown->(__ "no changes");
1000 confess "internal error $objid ?";
1004 return $unknown->(__ "origin commit");
1007 if (@p == 2 && @identical == 1) {
1008 my @overwritten = grep { $_->{Differs} } @p;
1009 confess "internal error $objid ?" unless @overwritten==1;
1010 return $classify->(qw(Pseudomerge),
1011 Overwritten => [ $overwritten[0] ],
1012 Contributor => $identical[0]);
1014 if (@p == 2 && @identical == 2) {
1016 my ($ph,$pm) = get_commit $_[0]{CommitId};
1017 $ph =~ m/^committer .* (\d+) [-+]\d+$/m
1018 or confess "$_->{CommitId} ?";
1022 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
1023 if ($order > 0) { # newer first
1024 } elsif ($order < 0) {
1025 @bytime = reverse @bytime;
1027 # same age, default to order made by -s ours
1028 # that is, commit was made by someone who preferred L
1030 return $classify->(qw(Pseudomerge),
1031 SubType => qw(Ambiguous),
1032 Contributor => $bytime[0],
1033 Overwritten => [ $bytime[1] ]);
1035 foreach my $p (@p) {
1036 my ($p_h, $p_m) = get_commit $p->{CommitId};
1037 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1038 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1040 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1042 if (!(grep { !$_->{IsOrigin} } @p) and
1043 (@orig_ps >= @p - 1) and
1044 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1046 return $classify->(qw(DgitImportUnpatched),
1047 OrigParents => \@orig_ps);
1051 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1052 return $classify->("MergedBreakwaters");
1054 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1055 return $unknown->(f_ "unknown kind of merge from %s", $1);
1058 return $unknown->(__ "octopus merge");
1062 return $unknown->(__ "general two-parent merge");
1065 return $classify->("VanillaMerge");
1068 sub keycommits ($;$$$$$);
1070 sub mergedbreakwaters_anchor ($) {
1073 foreach my $p (@{ $cl->{Parents} }) {
1074 my ($panchor, $pbw) = keycommits $p->{CommitId},
1075 undef,undef,undef,undef, 1;
1076 $best_anchor = $panchor
1077 if !defined $best_anchor
1078 or is_fast_fwd $best_anchor, $panchor;
1079 fail f_ "inconsistent anchors in merged-breakwaters %s",
1081 unless is_fast_fwd $panchor, $best_anchor;
1083 return $best_anchor;
1086 sub keycommits ($;$$$$$) {
1087 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1088 # => ($anchor, $breakwater)
1090 # $furniture->("unclean-$tagsfx", $msg, $cl)
1091 # $unclean->("unclean-$tagsfx", $msg, $cl)
1092 # is callled for each situation or commit that
1093 # wouldn't be found in a laundered branch
1094 # $furniture is for furniture commits such as might be found on an
1095 # interchange branch (pseudomerge, d/patches, changelog)
1096 # $trouble is for things whnich prevent the return of
1097 # anchor and breakwater information; if that is ignored,
1098 # then keycommits returns (undef, undef) instead.
1099 # $fatal is for unprocessable commits, and should normally cause
1100 # a failure. If ignored, agaion, (undef, undef) is returned.
1102 # If $claimed_bw, this is supposed to be a breakwater commit.
1104 # If a callback is undef, fail is called instead.
1105 # If a callback is defined but false, the situation is ignored.
1106 # Callbacks may say:
1107 # no warnings qw(exiting); last;
1108 # if the answer is no longer wanted.
1110 my ($anchor, $breakwater);
1111 $breakwater = $head if $claimed_bw;
1115 $fatal //= sub { fail_unprocessable $_[1]; };
1117 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1118 my $why = $mainwhy.$xwhy;
1119 my $m = f_ "branch needs laundering (run git-debrebase): %s", $why;
1120 fail $m unless defined $cb;
1122 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1124 my $found_anchor = sub {
1126 $breakwater //= $clogonly;
1127 $breakwater //= $head;
1128 no warnings qw(exiting);
1132 $cl = classify $head;
1133 my $ty = $cl->{Type};
1134 if ($ty eq 'Packaging') {
1135 $breakwater //= $clogonly;
1136 $breakwater //= $head;
1137 } elsif ($ty eq 'Changelog') {
1138 # this is going to count as the tip of the breakwater
1139 # only if it has no upstream stuff before it
1140 $clogonly //= $head;
1141 } elsif ($ty eq 'Anchor' or
1142 $ty eq 'TreatAsAnchor' or
1143 $ty eq 'BreakwaterStart') {
1144 $found_anchor->($head);
1145 } elsif ($ty eq 'Upstream') {
1146 $x->($unclean, 'ordering',
1147 (f_ "packaging change (%s) follows upstream change", $breakwater),
1148 (f_ " (eg %s)", $head))
1149 if defined $breakwater;
1151 $breakwater = undef;
1152 } elsif ($ty eq 'Mixed') {
1153 $x->($unclean, 'mixed',
1154 (__ "found mixed upstream/packaging commit"),
1155 (f_ " (%s)", $head));
1157 $breakwater = undef;
1158 } elsif ($ty eq 'Pseudomerge' or
1159 $ty eq 'AddPatches') {
1161 $x->($furniture, (lc $ty),
1162 (f_ "found interchange bureaucracy commit (%s)", $ty),
1163 (f_ " (%s)", $head));
1164 } elsif ($ty eq 'DgitImportUnpatched') {
1166 $x->($trouble, 'dgitimport',
1167 (__ "found dgit dsc import"),
1168 (f_ " (%s)", $head));
1169 return (undef,undef);
1171 $x->($fatal, 'unprocessable',
1172 (__ "found bare dgit dsc import with no prior history"),
1173 (f_ " (%s)", $head));
1174 return (undef,undef);
1176 } elsif ($ty eq 'VanillaMerge') {
1177 $x->($trouble, 'vanillamerge',
1178 (__ "found vanilla merge"),
1179 (f_ " (%s)", $head));
1180 return (undef,undef);
1181 } elsif ($ty eq 'MergedBreakwaters') {
1182 $found_anchor->(mergedbreakwaters_anchor $cl);
1184 $x->($fatal, 'unprocessable',
1185 (f_ "found unprocessable commit, cannot cope: %s",
1187 (f_ " (%s)", $head));
1188 return (undef,undef);
1190 $head = $cl->{Parents}[0]{CommitId};
1192 return ($anchor, $breakwater);
1198 $nogenerate,$report, $report_lprefix) = @_;
1199 # => ($tip, $breakwater_tip, $last_anchor)
1200 # (or nothing, if $nogenerate)
1202 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1203 $report_lprefix //= '';
1205 # go through commits backwards
1206 # we generate two lists of commits to apply:
1207 # breakwater branch and upstream patches
1208 my (@brw_cl, @upp_cl, @processed);
1215 my ($prose, $info) = @_;
1216 my $ms = $cl->{Msg};
1218 confess unless defined $info;
1219 $ms .= "\n\n[git-debrebase $info: $prose]\n";
1220 return (Msg => $ms);
1222 my $rewrite_from_here = sub {
1224 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1226 push @processed, $sp_cl;
1231 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1234 return unless $report;
1235 print $report $prdelim, $report_lprefix, @_;
1239 my $bomb = sub { # usage: return $bomb->();
1240 print $report " Unprocessable" if $report;
1241 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1244 return (undef,undef);
1248 map { sprintf "%#x", $_->{Differs} }
1249 @{ $cl->{Parents} };
1250 fail_unprocessable sprintf +(defined $cl->{Why}
1251 ? 'found unprocessable commit, cannot cope; %3$s: (commit %1$s) (d.%2$s)'
1252 : 'found unprocessable commit, cannot cope: (commit %1$s) (d.%2$s)'),
1253 $cur, $d, $cl->{Why};
1259 my $build_start = sub {
1260 my ($msg, $parent) = @_;
1263 no warnings qw(exiting); last;
1268 merge_failed $cl->{MergeWreckNotes}, $emsg;
1271 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1276 $cl = classify $cur;
1277 $cl->{MergeWreckNotes} //= {};
1278 my $ty = $cl->{Type};
1279 my $st = $cl->{SubType};
1280 $prline->("$cl->{CommitId} $cl->{Type}");
1281 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1282 push @processed, $cl;
1283 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1284 if ($ty eq 'AddPatches') {
1286 $rewrite_from_here->(\@upp_cl);
1288 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1292 } elsif ($ty eq 'BreakwaterStart') {
1293 $last_anchor = $cur;
1294 $build_start->('FirstPackaging', $cur);
1295 } elsif ($ty eq 'Upstream') {
1299 } elsif ($ty eq 'Mixed') {
1302 my $cls = { %$cl, $xmsg->("mixed commit: $wh part",'split') };
1305 $queue->(\@brw_cl, "debian");
1306 $queue->(\@upp_cl, "upstream");
1307 $rewrite_from_here->(\@brw_cl);
1310 } elsif ($ty eq 'Pseudomerge') {
1311 my $contrib = $cl->{Contributor}{CommitId};
1312 print $report " Contributor=$contrib" if $report;
1313 push @pseudomerges, $cl;
1314 $rewrite_from_here->(\@upp_cl);
1317 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1318 $last_anchor = $cur;
1319 $build_start->("Anchor", $cur);
1320 } elsif ($ty eq 'DgitImportUnpatched') {
1321 my $pm = $pseudomerges[-1];
1323 # To an extent, this is heuristic. Imports don't have
1324 # a useful history of the debian/ branch. We assume
1325 # that the first pseudomerge after an import has a
1326 # useful history of debian/, and ignore the histories
1327 # from later pseudomerges. Often the first pseudomerge
1328 # will be the dgit import of the upload to the actual
1329 # suite intended by the non-dgit NMUer, and later
1330 # pseudomerges may represent in-archive copies.
1331 my $ovwrs = $pm->{Overwritten};
1332 printf $report " PM=%s \@Overwr:%d",
1333 $pm->{CommitId}, (scalar @$ovwrs)
1336 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1339 my $ovwr = $ovwrs->[0]{CommitId};
1340 printf $report " Overwr=%s", $ovwr if $report;
1341 # This import has a tree which is just like a
1342 # breakwater tree, but it has the wrong history. It
1343 # ought to have the previous breakwater (which the
1344 # pseudomerge overwrote) as an ancestor. That will
1345 # make the history of the debian/ files correct. As
1346 # for the upstream version: either it's the same as
1347 # was ovewritten (ie, same as the previous
1348 # breakwater), in which case that history is precisely
1349 # right; or, otherwise, it was a non-gitish upload of a
1350 # new upstream version. We can tell these apart by
1351 # looking at the tree of the supposed upstream.
1354 SpecialMethod => 'DgitImportDebianUpdate',
1355 $xmsg->("debian changes", 'convert dgit import')
1358 SpecialMethod => 'DgitImportUpstreamUpdate',
1359 $xmsg->("convert dgit import: upstream update",
1362 $prline->(" Import");
1363 $rewrite_from_here->(\@brw_cl);
1364 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1368 # Everything is from this import. This kind of import
1369 # is already nearly in valid breakwater format, with the
1370 # patches as commits. Unfortunately it contains
1372 printdebug "*** WALK BOMB bare dgit import\n";
1373 $cl->{Why} = "bare dgit dsc import";
1377 } elsif ($ty eq 'MergedBreakwaters') {
1378 $last_anchor = mergedbreakwaters_anchor $cl;
1379 $build_start->(' MergedBreakwaters', $cur);
1381 } elsif ($ty eq 'VanillaMerge') {
1382 # User may have merged unstitched branch(es). We will
1383 # have now lost what ffq-prev was then (since the later
1384 # pseudomerge may introduce further changes). The effect
1385 # of resolving such a merge is that we may have to go back
1386 # further in history to find a merge base, since the one
1387 # which was reachable via ffq-prev is no longer findable.
1388 # This is suboptimal, but if it all works we'll have done
1390 # MERGE-TODO we should warn the user in the docs about this
1394 # We expect to find a dominating anchor amongst the
1395 # inputs' anchors. That will be the new anchor.
1397 # More complicated is finding a merge base for the
1398 # breakwaters. We need a merge base that is a breakwater
1399 # commit. The ancestors of breakwater commits are more
1400 # breakwater commits and possibly upstream commits and the
1401 # ancestors of those upstream. Upstreams might have
1402 # arbitrary ancestors. But any upstream commit U is
1403 # either included in both anchors, in which case the
1404 # earlier anchor is a better merge base than any of U's
1405 # ancestors; or U is not included in the older anchor, in
1406 # which case U is not an ancestor of the vanilla merge at
1407 # all. So no upstream commit, nor any ancestor thereof,
1408 # is a best merge base. As for non-breakwater Debian
1409 # commits: these are never ancestors of any breakwater.
1411 # So any best merge base as found by git-merge-base
1412 # is a suitable breakwater anchor. Usually there will
1415 printdebug "*** MERGE\n";
1417 my @bwbcmd = (@git, qw(merge-base));
1418 my @ibcmd = (@git, qw(merge-base --all));
1419 my $might_be_in_bw = 1;
1421 my $ps = $cl->{Parents};
1423 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1425 foreach my $p (@$ps) {
1426 $prline->(" VanillaMerge ".$p->{Ix});
1428 my ($ptip, $pbw, $panchor) =
1429 walk $p->{CommitId}, 0, $report,
1430 $report_lprefix.' ';
1431 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1432 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1433 $p->{Anchor} = $panchor;
1435 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1436 $mwrecknote->("$lr-input", $p->{CommitId});
1438 my $mwrecknote_parent = sub {
1440 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1442 $mwrecknote_parent->('Laundered');
1443 $mwrecknote_parent->('Breakwater');
1444 $mwrecknote_parent->('Anchor');
1446 $best_anchor = $panchor if
1447 !defined $best_anchor or
1448 is_fast_fwd $best_anchor, $panchor;
1450 printdebug " MERGE BA best=".($best_anchor//'-').
1454 $mwrecknote->('result-anchor', $best_anchor);
1456 foreach my $p (@$ps) {
1457 $prline->(" VanillaMerge ".$p->{Ix});
1458 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1459 $nomerge->('divergent anchors');
1460 } elsif ($p->{Anchor} eq $best_anchor) {
1461 print $report " SameAnchor" if $report;
1463 print $report " SupersededAnchor" if $report;
1465 if ($p->{Breakwater} eq $p->{CommitId}) {
1466 # this parent commit was its own breakwater,
1467 # ie it is part of the breakwater
1468 print $report " Breakwater" if $report;
1470 $might_be_in_bw = 0;
1472 push @bwbcmd, $p->{Breakwater};
1473 push @ibcmd, $p->{CommitId};
1476 if ($ok && $might_be_in_bw) {
1477 # We could rewrite this to contaion the metadata
1478 # declaring it to be MergedBreakwaters, but
1479 # unnecessarily rewriting a merge seems unhelpful.
1480 $prline->(" VanillaMerge MergedBreakwaters");
1481 $last_anchor = $best_anchor;
1482 $build_start->('MergedBreakwaters', $cur);
1485 my $bwb = cmdoutput @bwbcmd;
1487 # OK, now we have a breakwater base, but we need the merge
1488 # base for the interchange branch because we need the delta
1491 # This a the best merge base of our inputs which has the
1492 # breakwater merge base as an ancestor.
1499 @ibs or confess 'internal error, expected anchor at least ?';
1503 foreach my $tibix (0..$#ibs) {
1504 my $tib = $ibs[$tibix];
1505 my $ff = is_fast_fwd $bwb, $tib;
1506 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1507 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1508 $mwrecknote->($tibleaf, $tib);
1515 $ib or $nomerge->("no suitable interchange merge base");
1517 $prline->(" VanillaMerge Base");
1519 my ($btip, $bbw, $banchor) = eval {
1520 walk $ib, 0, $report, $report_lprefix.' ';
1522 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1526 $mwrecknote->("mergebase-laundered", $btip);
1527 $mwrecknote->("mergebase-breakwater", $bbw);
1528 $mwrecknote->("mergebase-anchor", $banchor);
1530 my $ibinfo = { SeriesTip => $btip,
1533 LeftRight => 'mergebase' };
1536 or $nomerge->("interchange merge-base ($ib)'s".
1537 " breakwater ($bbw)".
1538 " != breakwaters' merge-base ($bwb)");
1540 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1541 or $nomerge->("interchange merge-base ($ib)'s".
1542 " anchor ($ibinfo->{SeriesBase})".
1543 " != any merge input's anchor (".
1544 (join ' ', map { $_->{Anchor} } @$ps).
1547 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1548 $cl->{MergeBestAnchor} = $best_anchor;
1551 SpecialMethod => 'MergeCreateMergedBreakwaters',
1552 $xmsg->('constructed from vanilla merge',
1553 'merged-breakwater'),
1557 SpecialMethod => 'MergeMergeSeries',
1559 $build_start->('MergeBreakwaters', $cur);
1561 printdebug "*** WALK BOMB unrecognised\n";
1567 printdebug "*** WALK prep done cur=$cur".
1568 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1570 return if $nogenerate;
1572 # Now we build it back up again
1578 $#upp_cl = $upp_limit if defined $upp_limit;
1580 my $committer_authline = calculate_committer_authline();
1582 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1584 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1587 mkdir $rd or $!==EEXIST or confess $!;
1589 my $want_debian = $build;
1590 my $want_upstream = $build;
1592 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1593 my $read_tree_debian = sub { ($want_debian) = @_; };
1595 foreach my $cl (qw(Debian), (reverse @brw_cl),
1596 { SpecialMethod => 'RecordBreakwaterTip' },
1597 qw(Upstream), (reverse @upp_cl)) {
1599 $current_method = $cl;
1602 my $method = $cl->{SpecialMethod} // $current_method;
1603 my @parents = ($build);
1604 my $cltree = $cl->{CommitId};
1605 printdebug "WALK BUILD ".($cltree//'undef').
1606 " $method (rewriting=$rewriting)\n";
1607 if ($method eq 'Debian') {
1608 $read_tree_debian->($cltree);
1609 } elsif ($method eq 'Upstream') {
1610 $read_tree_upstream->($cltree);
1611 } elsif ($method eq 'StartRewrite') {
1614 } elsif ($method eq 'RecordBreakwaterTip') {
1615 $breakwater = $build;
1617 } elsif ($method eq 'DgitImportDebianUpdate') {
1618 $read_tree_debian->($cltree);
1619 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1620 confess unless $rewriting;
1621 my $differs = (get_differs $build, $cltree);
1622 next unless $differs & D_UPS;
1623 $read_tree_upstream->($cltree);
1624 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1625 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1626 print "Found a general merge, will try to tidy it up.\n";
1628 $read_tree_upstream->($cl->{MergeBestAnchor});
1629 $read_tree_debian->($cltree);
1630 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1631 } elsif ($method eq 'MergeMergeSeries') {
1632 my $cachehit = reflog_cache_lookup
1633 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1635 print "Using supplied resolution for $cl->{CommitId}...\n";
1637 $mwrecknote->('cached-resolution', $build);
1639 print "Running merge resolution for $cl->{CommitId}...\n";
1640 $mwrecknote->('new-base', $build);
1641 $build = merge_series
1642 $build, $cl->{MergeWreckNotes},
1643 $cl->{MergeInterchangeBaseInfo},
1644 @{ $cl->{Parents} };
1646 $last_anchor = $cl->{MergeBestAnchor};
1648 # Check for mismerges:
1650 my ($against, $allow, $what) = @_;
1651 my $differs = get_differs $build, $against;
1653 "merge misresolved: %s are not the same (%s %s d.%#x)",
1654 $what, $against, $build, $differs)
1655 if $differs & ~($allow | D_PAT_ADD);
1658 # Breakwater changes which were in each side of the
1659 # merge will have been incorporated into the
1660 # MergeCreateMergedBreakwaters output. Because the
1661 # upstream series was rebased onto the new breakwater,
1662 # so should all of the packaging changes which were in
1664 $check->($input, D_UPS, 'debian files');
1666 # Upstream files are merge_series, which ought to
1667 # have been identical to the original merge.
1668 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1670 print "Merge resolution successful.\n";
1673 confess "$method ?";
1676 my $procd = (pop @processed) // 'UNDEF';
1677 if ($cl ne $procd) {
1679 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1683 read_tree_upstream $want_upstream, 0, $want_debian;
1685 my $newtree = cmdoutput @git, qw(write-tree);
1686 my $ch = $cl->{Hdr};
1687 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1688 $ch =~ s{^parent .*\n}{}mg;
1689 $ch =~ s{(?=^author)}{
1690 join '', map { "parent $_\n" } @parents
1691 }me or confess "$ch ?";
1693 $ch =~ s{^committer .*$}{$committer_authline}m
1696 my $cf = "$rd/m$rewriting";
1697 open CD, ">", $cf or confess $!;
1698 print CD $ch, "\n", $cl->{Msg} or confess $!;
1699 close CD or confess $!;
1700 my @cmd = (@git, qw(hash-object));
1701 push @cmd, qw(-w) if $rewriting;
1702 push @cmd, qw(-t commit), $cf;
1703 my $newcommit = cmdoutput @cmd;
1704 confess "$ch ?" unless $rewriting
1705 or $newcommit eq $cl->{CommitId};
1706 $build = $newcommit;
1708 $build = $cl->{CommitId};
1709 trees_diff_walk "$want_upstream:", "$build:", sub {
1711 no warnings qw(exiting);
1712 next if $n eq 'debian/';
1713 confess "mismatch @_ ?";
1715 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1716 confess "mismatch @_ ?";
1718 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1719 confess "mismatch @parents != @old_parents ?"
1720 unless "@parents" eq "@old_parents";
1722 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1723 $last_anchor = $cur;
1728 my $final_check = get_differs $build, $input;
1729 confess sprintf "internal error %#x %s %s", $final_check, $input, $build
1730 if $final_check & ~D_PAT_ADD;
1732 my @r = ($build, $breakwater, $last_anchor);
1733 printdebug "*** WALK RETURN @r\n";
1738 git_check_unmodified();
1739 return git_rev_parse qw(HEAD);
1742 sub update_head ($$$) {
1743 my ($old, $new, $mrest) = @_;
1744 push @deferred_updates, "update HEAD $new $old";
1745 run_deferred_updates $mrest;
1748 sub update_head_checkout ($$$) {
1749 my ($old, $new, $mrest) = @_;
1750 update_head $old, $new, $mrest;
1751 runcmd @git, qw(reset --hard);
1754 sub update_head_postlaunder ($$$) {
1755 my ($old, $tip, $reflogmsg) = @_;
1756 return if $tip eq $old && !@deferred_updates;
1757 print "$us: laundered (head was $old)\n";
1758 update_head $old, $tip, $reflogmsg;
1759 # no tree changes except debian/patches
1760 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1763 sub currently_rebasing() {
1764 foreach (qw(rebase-merge rebase-apply)) {
1765 return 1 if stat_exists "$maindir_gitdir/$_";
1770 sub bail_if_rebasing() {
1771 fail "you are in the middle of a git-rebase already"
1772 if currently_rebasing();
1775 sub do_launder_head ($) {
1776 my ($reflogmsg) = @_;
1777 my $old = get_head();
1779 my ($tip,$breakwater) = walk $old;
1781 update_head_postlaunder $old, $tip, $reflogmsg;
1782 return ($tip,$breakwater);
1785 sub cmd_launder_v0 () {
1786 badusage "no arguments to launder-v0 allowed" if @ARGV;
1787 my $old = get_head();
1788 my ($tip,$breakwater,$last_anchor) = walk $old;
1789 update_head_postlaunder $old, $tip, 'launder';
1790 printf "# breakwater tip\n%s\n", $breakwater;
1791 printf "# working tip\n%s\n", $tip;
1792 printf "# last anchor\n%s\n", $last_anchor;
1795 sub defaultcmd_rebase () {
1796 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1797 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1798 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1801 sub cmd_analyse () {
1802 badusage "analyse does not support any options"
1803 if @ARGV and $ARGV[0] =~ m/^-/;
1804 badusage "too many arguments to analyse" if @ARGV>1;
1807 $old = git_rev_parse $old;
1809 $old = git_rev_parse 'HEAD';
1811 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1812 STDOUT->error and confess $!;
1815 sub ffq_check ($;$$) {
1816 # calls $ff and/or $notff zero or more times
1817 # then returns either (status,message) where status is
1822 # or (undef,undef, $ffq_prev,$gdrlast)
1823 # $ff and $notff are called like this:
1824 # $ff->("message for stdout\n");
1825 # $notff->('snag-name', $message);
1826 # normally $currentval should be HEAD
1827 my ($currentval, $ff, $notff) =@_;
1829 $ff //= sub { print $_[0] or confess $!; };
1832 my ($status, $message, $current, $ffq_prev, $gdrlast)
1833 = ffq_prev_branchinfo();
1834 return ($status, $message) unless $status eq 'branch';
1836 my $exists = git_get_ref $ffq_prev;
1837 return ('exists',"$ffq_prev already exists") if $exists;
1839 return ('not-branch', 'HEAD symref is not to refs/heads/')
1840 unless $current =~ m{^refs/heads/};
1843 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1846 printdebug "ffq check_specs @check_specs\n";
1849 my ($lrref, $desc) = @_;
1850 printdebug "ffq might check $lrref ($desc)\n";
1852 for my $chk (@check_specs) {
1854 $invert = $glob =~ s{^[!^]}{};
1855 last if fnmatch $glob, $lrref;
1858 my $lrval = git_get_ref $lrref;
1859 return unless length $lrval;
1861 if (is_fast_fwd $lrval, $currentval) {
1862 $ff->("OK, you are ahead of $lrref\n");
1863 $checked{$lrref} = 1;
1864 } elsif (is_fast_fwd $currentval, $lrval) {
1865 $checked{$lrref} = -1;
1866 $notff->('behind', "you are behind $lrref, divergence risk");
1868 $checked{$lrref} = -1;
1869 $notff->('diverged', "you have diverged from $lrref");
1873 my $merge = cfg "branch.$branch.merge",1;
1874 if (defined $merge and $merge =~ m{^refs/heads/}) {
1876 printdebug "ffq merge $rhs\n";
1877 my $check_remote = sub {
1878 my ($remote, $desc) = @_;
1879 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1880 return unless defined $remote;
1881 $check->("refs/remotes/$remote/$rhs", $desc);
1883 $check_remote->((scalar cfg "branch.$branch.remote",1),
1884 'remote fetch/merge branch');
1885 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1886 (scalar cfg "branch.$branch.pushDefault",1),
1887 'remote push branch');
1889 if ($branch =~ m{^dgit/}) {
1890 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1891 } elsif ($branch =~ m{^master$}) {
1892 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1894 return (undef, undef, $ffq_prev, $gdrlast);
1897 sub record_ffq_prev_deferred () {
1898 # => ('status', "message")
1900 # deferred message is undef
1905 # if not ff from some branch we should be ff from, is an snag
1906 # if "deferred", will have added something about that to
1907 # @deferred_update_messages, and also maybe printed (already)
1908 # some messages about ff checks
1910 my $currentval = get_head();
1912 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1913 return ($status,$message) if defined $status;
1917 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1918 push @deferred_updates, "delete $gdrlast";
1919 push @deferred_update_messages, "Recorded previous head for preservation";
1920 return ('deferred', undef);
1923 sub record_ffq_auto () {
1924 my ($status, $message) = record_ffq_prev_deferred();
1925 if ($status eq 'deferred' || $status eq 'exists') {
1927 snag $status, "could not record ffq-prev: $message";
1932 sub ffq_prev_info () {
1934 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1935 my ($status, $message, $current, $ffq_prev, $gdrlast)
1936 = ffq_prev_branchinfo();
1937 if ($status ne 'branch') {
1938 snag $status, "could not check ffq-prev: $message";
1941 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1942 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1945 sub stitch ($$$$$) {
1946 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1948 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1950 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1951 my $differs = get_differs $old_head, $ffq_prev_commitish;
1952 unless ($differs & ~D_PAT_ADD) {
1953 # ffq-prev is ahead of us, and the only tree changes it has
1954 # are possibly addition of things in debian/patches/.
1955 # Just wind forwards rather than making a pointless pseudomerge.
1956 record_gdrlast $gdrlast, $ffq_prev_commitish;
1957 update_head_checkout $old_head, $ffq_prev_commitish,
1958 "stitch (fast forward)";
1963 # We make pseudomerges with L as the contributing parent.
1964 # This makes git rev-list --first-parent work properly.
1965 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1966 'Declare fast forward / record previous work',
1967 "[git-debrebase pseudomerge: $prose]",
1969 record_gdrlast $gdrlast, $new_head;
1970 update_head $old_head, $new_head, "stitch: $prose";
1973 sub do_stitch ($;$) {
1974 my ($prose, $unclean) = @_;
1976 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1977 if (!$ffq_prev_commitish) {
1978 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1981 my $dangling_head = get_head();
1983 keycommits $dangling_head, $unclean,$unclean,$unclean;
1986 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1989 sub upstream_commitish_search ($$) {
1990 my ($upstream_version, $tried) = @_;
1991 # todo: at some point maybe use git-deborig to do this
1992 foreach my $tagpfx ('', 'v', 'upstream/') {
1993 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1994 my $new_upstream = git_get_ref "refs/tags/$tag";
1996 return $new_upstream if length $new_upstream;
2000 sub resolve_upstream_version ($$) {
2001 my ($new_upstream, $upstream_version) = @_;
2003 if (!defined $new_upstream) {
2005 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
2006 if (!length $new_upstream) {
2007 fail "Could not determine appropriate upstream commitish.\n".
2008 " (Tried these tags: @tried)\n".
2009 " Check version, and specify upstream commitish explicitly.";
2012 $new_upstream = git_rev_parse $new_upstream;
2014 return $new_upstream;
2017 sub cmd_new_upstream () {
2018 # automatically and unconditionally launders before rebasing
2019 # if rebase --abort is used, laundering has still been done
2023 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
2025 # parse args - low commitment
2026 my $spec_version = shift @ARGV;
2027 my $new_version = (new Dpkg::Version $spec_version, check => 1);
2028 fail "bad version number \`$spec_version'" unless defined $new_version;
2029 if ($new_version->is_native()) {
2030 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
2033 my $new_upstream = shift @ARGV;
2034 my $new_upstream_version = upstreamversion $new_version;
2036 resolve_upstream_version $new_upstream, $new_upstream_version;
2041 my ($n, @x) = @_; # may be ''
2042 my $pc = $pieces{$n} //= {
2044 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
2046 while (my $k = shift @x) { $pc->{$k} = shift @x; }
2051 my $newpiece = sub {
2052 my ($n, @x) = @_; # may be ''
2053 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2054 push @newpieces, $pc;
2059 New => $new_upstream,
2061 while (@ARGV && $ARGV[0] !~ m{^-}) {
2062 my $n = shift @ARGV;
2064 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2065 unless @ARGV && $ARGV[0] !~ m{^-};
2067 my $c = git_rev_parse shift @ARGV;
2068 confess unless $n =~ m/^$extra_orig_namepart_re$/;
2069 $newpiece->($n, New => $c);
2072 # now we need to investigate the branch this generates the
2073 # laundered version but we don't switch to it yet
2074 my $old_head = get_head();
2075 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2077 my $old_bw_cl = classify $old_bw;
2078 my $old_anchor_cl = classify $old_anchor;
2080 if (!$old_anchor_cl->{OrigParents}) {
2081 snag 'anchor-treated',
2082 __ 'old anchor is recognised due to --anchor, cannot check upstream';
2084 $old_upstream = parsecommit
2085 $old_anchor_cl->{OrigParents}[0]{CommitId};
2086 $piece->('', Old => $old_upstream->{CommitId});
2089 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2090 if ($old_upstream->{Msg} =~
2091 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2093 my @oldpieces = (split / /, $1);
2094 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2095 if ($old_n_parents != @oldpieces &&
2096 $old_n_parents != @oldpieces + 1) {
2097 snag 'upstream-confusing', sprintf
2098 "previous upstream combine %s".
2099 " mentions %d pieces (each implying one parent)".
2100 " but has %d parents".
2101 " (one per piece plus maybe a previous combine)",
2102 $old_upstream->{CommitId},
2103 (scalar @oldpieces),
2105 } elsif ($oldpieces[0] ne '.') {
2106 snag 'upstream-confusing', sprintf
2107 "previous upstream combine %s".
2108 " first piece is not \`.'",
2112 foreach my $i (0..$#oldpieces) {
2113 my $n = $oldpieces[$i];
2114 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2115 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2119 snag 'upstream-confusing',
2120 "previous upstream $old_upstream->{CommitId} is from".
2121 " git-debrebase but not an \`upstream-combine' commit";
2125 foreach my $pc (values %pieces) {
2126 if (!$old_upstream) {
2127 # we have complained already
2128 } elsif (!$pc->{Old}) {
2129 snag 'upstream-new-piece',
2130 "introducing upstream piece \`$pc->{Name}'";
2131 } elsif (!$pc->{New}) {
2132 snag 'upstream-rm-piece',
2133 "dropping upstream piece \`$pc->{Name}'";
2134 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2135 snag 'upstream-not-ff',
2136 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2140 printdebug "%pieces = ", (dd \%pieces), "\n";
2141 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2149 my @upstream_merge_parents;
2152 push @upstream_merge_parents, $old_upstream->{CommitId};
2155 foreach my $pc (@newpieces) { # always has '' first
2157 read_tree_subdir $pc->{Name}, $pc->{New};
2159 runcmd @git, qw(read-tree), $pc->{New};
2161 push @upstream_merge_parents, $pc->{New};
2164 # index now contains the new upstream
2166 if (@newpieces > 1) {
2167 # need to make the upstream subtree merge commit
2168 $new_upstream = make_commit \@upstream_merge_parents,
2169 [ "Combine upstreams for $new_upstream_version",
2170 ("[git-debrebase upstream-combine . ".
2171 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2176 # $new_upstream is either the single upstream commit, or the
2177 # combined commit we just made. Either way it will be the
2178 # "upstream" parent of the anchor merge.
2180 read_tree_subdir 'debian', "$old_bw:debian";
2182 # index now contains the anchor merge contents
2183 $new_bw = make_commit [ $old_bw, $new_upstream ],
2184 [ "Update to upstream $new_upstream_version",
2185 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2188 # Now we have to add a changelog stanza so the Debian version
2189 # is right. We use debchange to do this. Invoking debchange
2190 # here is a bit fiddly because it has a lot of optional
2191 # exciting behaviours, some of which will break stuff, and
2192 # some of which won't work in a playtree.
2194 # Make debchange use git's idea of the user's identity.
2195 # That way, if the user never uses debchange et al, configuring
2200 defined $v or return;
2203 $usetup->('DEBEMAIL', 'user.email');
2204 $usetup->('DEBFULLNAME', 'user.name');
2208 my @dch = (qw(debchange
2209 --allow-lower-version .*
2212 --vendor=Unknown-Vendor
2213 --changelog debian/changelog
2214 --check-dirname-level 0
2215 --release-heuristic=changelog
2217 "Update to new upstream version $new_upstream_version.");
2219 runcmd @git, qw(checkout -q debian/changelog);
2221 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2223 # Now we have the final new breakwater branch in the index
2224 $new_bw = make_commit [ $new_bw ],
2225 [ "Update changelog for new upstream $new_upstream_version",
2226 "[git-debrebase changelog: new upstream $new_upstream_version]",
2230 # we have constructed the new breakwater. we now need to commit to
2231 # the laundering output, because git-rebase can't easily be made
2232 # to make a replay list which is based on some other branch
2234 update_head_postlaunder $old_head, $old_laundered_tip,
2235 'launder for new upstream';
2237 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2238 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2239 "debrebase new-upstream $new_version: rebase";
2241 # now it's for the user to sort out
2244 sub cmd_record_ffq_prev () {
2245 badusage "no arguments allowed" if @ARGV;
2246 my ($status, $msg) = record_ffq_prev_deferred();
2247 if ($status eq 'exists' && $opt_noop_ok) {
2248 print "Previous head already recorded\n" or confess $!;
2249 } elsif ($status eq 'deferred') {
2250 run_deferred_updates 'record-ffq-prev';
2252 fail "Could not preserve: $msg";
2257 badusage "no arguments allowed" if @ARGV;
2258 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2259 print "$bw\n" or confess $!;
2262 sub cmd_breakwater () {
2263 badusage "no arguments allowed" if @ARGV;
2264 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2265 print "$bw\n" or confess $!;
2269 badusage "no arguments allowed" if @ARGV;
2271 # todo: gdr status should print divergence info
2272 # todo: gdr status should print upstream component(s) info
2273 # todo: gdr should leave/maintain some refs with this kind of info ?
2275 my $oldest = { Badness => 0 };
2278 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2279 if ($oldest->{Badness} < $badness) {
2280 $oldest = $newest = undef;
2283 Badness => $badness,
2284 CommitId => $cl->{CommitId},
2288 $newest //= $oldest;
2290 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2291 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2292 sub { $note->(2, 'branch is unlaundered', @_); },
2293 sub { $note->(3, 'branch needs laundering', @_); },
2294 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2296 my $prcommitinfo = sub {
2298 flush STDOUT or confess $!;
2299 runcmd @git, qw(--no-pager log -n1),
2300 '--pretty=format: %h %s%n',
2304 print "current branch contents, in git-debrebase terms:\n";
2305 if (!$oldest->{Badness}) {
2306 print " branch is laundered\n";
2308 print " $oldest->{OurMsg}\n";
2310 foreach my $info ($oldest, $newest) {
2311 my $cid = $info->{CommitId};
2312 next if $cid eq $printed;
2314 print " $info->{KcMsg}\n";
2315 $prcommitinfo->($cid);
2320 my ($cid, $what) = @_;
2321 if (!defined $cid) {
2322 print " $what is not well-defined\n";
2325 $prcommitinfo->($cid);
2328 print "key git-debrebase commits:\n";
2329 $prab->($anchor, 'anchor');
2330 $prab->($bw, 'breakwater');
2332 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2333 ffq_prev_branchinfo();
2335 print "branch and ref status, in git-debrebase terms:\n";
2337 print " $ffq_msg\n";
2339 $ffq_prev = git_get_ref $ffq_prev;
2340 $gdrlast = git_get_ref $gdrlast;
2342 print " unstitched; previous tip was:\n";
2343 $prcommitinfo->($ffq_prev);
2344 } elsif (!$gdrlast) {
2345 print " stitched? (no record of git-debrebase work)\n";
2346 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2347 print " stitched\n";
2349 print " not git-debrebase (diverged since last stitch)\n"
2352 print "you are currently rebasing\n" if currently_rebasing();
2356 my $prose = 'stitch';
2357 getoptions("stitch",
2358 'prose=s', \$prose);
2359 badusage "no arguments allowed" if @ARGV;
2360 do_stitch $prose, 0;
2362 sub cmd_prepush () {
2368 badusage "no arguments allowed" if @ARGV;
2369 do_launder_head 'launder for git-debrebase quick';
2373 sub cmd_conclude () {
2374 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2375 if (!$ffq_prev_commitish) {
2376 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2379 my $dangling_head = get_head();
2381 badusage "no arguments allowed" if @ARGV;
2382 do_launder_head 'launder for git-debrebase quick';
2387 if (currently_rebasing()) {
2388 runcmd @git, qw(rebase --abort);
2389 push @deferred_updates, 'verify HEAD HEAD';
2390 # noop, but stops us complaining that scrap was a noop
2392 badusage "no arguments allowed" if @ARGV;
2393 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2395 if ($ffq_prev_commitish) {
2396 $scrapping_head = get_head();
2397 push @deferred_updates,
2398 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2399 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2401 if (git_get_ref $merge_cache_ref) {
2402 push @deferred_updates,
2403 "delete $merge_cache_ref";
2405 if (!@deferred_updates) {
2406 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2410 if ($scrapping_head) {
2411 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2413 run_deferred_updates "scrap";
2417 sub make_patches_staged ($) {
2419 # Produces the patches that would result from $head if it were
2421 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2425 $any = gbp_pq_export 'bw', $secret_bw, $secret_head;
2430 sub make_patches ($) {
2432 keycommits $head, 0, \&snag;
2433 my $any = make_patches_staged $head;
2436 my $ptree = !$any ? undef :
2437 cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2438 runcmd @git, qw(read-tree), $head;
2440 read_tree_subdir 'debian/patches', $ptree;
2442 rm_subdir_cached 'debian/patches';
2444 $out = make_commit [$head], [
2445 'Commit patch queue (exported by git-debrebase)',
2446 '[git-debrebase make-patches: export and commit patches]',
2452 sub cmd_make_patches () {
2453 my $opt_quiet_would_amend;
2454 getoptions("make-patches",
2455 'quiet-would-amend!', \$opt_quiet_would_amend);
2456 badusage "no arguments allowed" if @ARGV;
2458 my $old_head = get_head();
2459 my $new = make_patches $old_head;
2460 my $d = get_differs $old_head, $new;
2462 fail "No (more) patches to export." unless $opt_noop_ok;
2464 } elsif ($d == D_PAT_ADD) {
2466 update_head_checkout $old_head, $new, 'make-patches';
2468 print STDERR failmsg
2469 "Patch export produced patch amendments".
2470 " (abandoned output commit $new).".
2471 " Try laundering first."
2472 unless $opt_quiet_would_amend;
2477 sub check_series_has_all_patches ($) {
2479 my $seriesfn = 'debian/patches/series';
2480 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2484 our $comments_snagged;
2485 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2486 if ($f =~ m/^\s*\#/) {
2487 snag 'series-comments',
2488 "$seriesfn contains comments, which will be discarded"
2489 unless $comments_snagged++;
2492 fail "patch $f repeated in $seriesfn !" if $series{$f}++;
2494 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2495 my ($f,$i) = @$patchfile;
2496 next if $series{$f};
2497 next if $f eq 'series';
2498 snag 'unused-patches', "Unused patch file $f will be discarded";
2502 sub begin_convert_from () {
2503 my $head = get_head();
2504 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2506 fail "ffq-prev exists, this is already managed by git-debrebase!"
2507 if $ffq_prev && git_get_ref $ffq_prev;
2509 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2510 snag 'already-converted',
2511 "ahead of debrebase-last, this is already managed by git-debrebase!"
2512 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2513 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2516 sub complete_convert_from ($$$$) {
2517 my ($old_head, $new_head, $gi, $mrest) = @_;
2518 ffq_check $new_head;
2519 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2522 update_head_checkout $old_head, $new_head, $mrest;
2525 sub cmd_convert_from_gbp () {
2526 badusage "want only 1 optional argument, the upstream git commitish"
2529 my $clogp = parsechangelog();
2530 my $version = $clogp->{'Version'}
2531 // die "missing Version from changelog\n";
2533 my ($upstream_spec) = @ARGV;
2535 my $upstream_version = upstreamversion $version;
2537 resolve_upstream_version($upstream_spec, $upstream_version);
2539 my ($old_head, $gdrlastinfo) = begin_convert_from();
2541 my $upsdiff = get_differs $upstream, $old_head;
2542 if ($upsdiff & D_UPS) {
2543 runcmd @git, qw(--no-pager diff --stat),
2544 $upstream, $old_head,
2545 qw( -- :!/debian :/);
2547 upstream ($upstream_spec) and HEAD are not
2548 identical in upstream files. See diffstat above, or run
2549 git diff $upstream_spec HEAD -- :!/debian :/
2553 if (!is_fast_fwd $upstream, $old_head) {
2554 snag 'upstream-not-ancestor',
2555 "upstream ($upstream) is not an ancestor of HEAD";
2557 my $wrong = cmdoutput
2558 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2559 qw(-- :/ :!/debian));
2560 if (length $wrong) {
2561 snag 'unexpected-upstream-changes',
2562 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2563 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2567 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2568 snag 'upstream-has-debian',
2569 "upstream ($upstream) contains debian/ directory";
2572 check_series_has_all_patches $old_head;
2574 my $previous_dgit_view = eval {
2575 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2577 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2578 my ($stz, $desc) = @_;
2579 no warnings qw(exiting);
2580 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2581 next unless $stz->{Date};
2582 next unless $stz->{Distribution} ne 'UNRELEASED';
2583 $lvsn = $stz->{Version};
2584 $suite = $stz->{Distribution};
2587 die "neither of the first two changelog entries are released\n"
2588 unless defined $lvsn;
2589 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2590 my $mtag_pat = debiantag_maintview $lvsn, '*';
2591 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2593 die "could not find suitable maintainer view tag $mtag_pat\n"
2594 unless $mtag =~ m{/};
2595 is_fast_fwd $mtag, 'HEAD' or
2596 die "HEAD is not FF from maintainer tag $mtag!";
2597 my $dtag = "archive/$mtag";
2598 git_get_ref "refs/tags/$dtag" or
2599 die "dgit view tag $dtag not found\n";
2600 is_fast_fwd $mtag, $dtag or
2601 die "dgit view tag $dtag is not FF from maintainer tag $mtag\n";
2602 print "will stitch in dgit view, $dtag\n";
2603 git_rev_parse $dtag;
2605 if (!$previous_dgit_view) {
2609 Cannot confirm dgit view: $@
2610 Failed to stitch in dgit view (see messages above).
2611 dgit --overwrite will be needed on the first dgit push after conversion.
2615 snags_maybe_bail_early();
2621 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2622 # make a branch out of the patch queue - we'll want this in a mo
2623 runcmd qw(gbp pq import);
2624 # strip the patches out
2625 runcmd @git, qw(checkout -q gdr-internal~0);
2626 rm_subdir_cached 'debian/patches';
2627 $work = make_commit ['HEAD'], [
2628 'git-debrebase convert-from-gbp: drop patches from tree',
2629 'Delete debian/patches, as part of converting to git-debrebase format.',
2630 '[git-debrebase convert-from-gbp: drop patches from tree]'
2632 # make the anchor merge
2633 # the tree is already exactly right
2634 $work = make_commit [$work, $upstream], [
2635 'git-debrebase import: declare upstream',
2636 'First breakwater merge.',
2637 '[git-debrebase anchor: declare upstream]'
2640 # rebase the patch queue onto the new breakwater
2641 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2642 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2643 $work = git_rev_parse 'HEAD';
2645 if ($previous_dgit_view) {
2646 $work = make_commit [$work, $previous_dgit_view], [
2647 'git-debrebase import: declare ff from dgit archive view',
2648 '[git-debrebase pseudomerge: import-from-gbp]',
2653 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2654 print <<END or confess $!;
2655 $us: converted from patched-unapplied (gbp) branch format, OK
2659 sub cmd_convert_to_gbp () {
2660 badusage "no arguments allowed" if @ARGV;
2661 my $head = get_head();
2662 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2663 my ($anchor, $breakwater) = keycommits $head, 0;
2664 my $out = $breakwater;
2665 my $any = make_patches_staged $head;
2668 $out = make_commit [$out], [
2669 'Commit patch queue (converted from git-debrebase format)',
2670 '[git-debrebase convert-to-gbp: commit patches]',
2674 # in this case, it can be fast forward
2678 push @deferred_updates, "delete $ffq";
2679 push @deferred_updates, "delete $gdrlast";
2682 update_head_checkout $head, $out, "convert to gbp (v0)";
2683 print <<END or confess $!;
2684 $us: converted to git-buildpackage branch format
2685 $us: WARNING: do not now run "git-debrebase" any more
2686 $us: WARNING: doing so would drop all upstream patches!
2690 sub cmd_convert_from_dgit_view () {
2691 my $clogp = parsechangelog();
2693 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2699 getoptions("convert-from-dgit-view",
2700 'diagnose!', \$diagnose,
2701 'build-products-dir:s', \$bpd,
2702 'origs!', \$do_origs,
2704 'always-convert-anyway!', \$always);
2705 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2710 my $spec = shift @ARGV;
2711 my $commit = git_rev_parse "$spec^{commit}";
2712 push @upstreams, { Commit => $commit,
2713 Source => "$ARGV[0], from command line",
2718 my ($head, $gdrlastinfo) = begin_convert_from();
2722 my $trouble = sub { $troubles++; };
2723 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2724 printdebug "troubles=$troubles\n";
2727 $us: Branch already seems to be in git-debrebase format!
2728 $us: --always-convert-anyway would do the conversion operation anyway
2729 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2731 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2736 check_series_has_all_patches $head;
2738 snags_maybe_bail_early();
2740 my $version = upstreamversion $clogp->{Version};
2741 print STDERR "Considering possible commits corresponding to upstream:\n";
2746 my $ups_tag = upstream_commitish_search $version, \@tried;
2748 my $this = "git tag $tried[-1]";
2749 push @upstreams, { Commit => $ups_tag,
2754 " git tag: no suitable tag found (tried %s)\n",
2759 my $p = $clogp->{'Source'};
2760 # we do a quick check to see if there are plausible origs
2762 if (!opendir BPD, $bpd) {
2763 die "opendir build-products-dir $bpd: $!" unless $!==ENOENT;
2765 while ($!=0, my $f = readdir BPD) {
2766 next unless is_orig_file_of_p_v $f, $p, $version;
2768 " orig: found what looks like a .orig, %s\n",
2773 confess "read $bpd: $!" if $!;
2777 my $tree = cmdoutput
2778 @dgit, qw(--build-products-dir), $bpd,
2779 qw(print-unapplied-treeish);
2782 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2783 rm_subdir_cached 'debian';
2784 $tree = cmdoutput @git, qw(write-tree);
2785 my $ups_synth = make_commit [], [ <<END, <<END,
2786 Import effective orig tree for upstream version $version
2788 This includes the contents of the .orig(s), minus any debian/ directory.
2790 [git-debrebase convert-from-dgit-view upstream-import-convert: $version]
2793 push @upstreams, { Commit => $ups_synth,
2794 Source => "orig(s) imported via dgit",
2799 " orig: no suitable origs found (looked for %s in %s)\n",
2800 "${p}_".(stripeoch $version)."...", $bpd;
2805 my $some_patches = stat_exists 'debian/patches/series';
2807 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2810 foreach my $u (@upstreams) {
2814 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2815 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2816 runcmd @git, qw(clean -xdff);
2817 runcmd @git, qw(checkout), $head, qw(-- debian);
2818 if ($some_patches) {
2819 rm_subdir_cached 'debian/patches';
2820 $work = make_commit [ $work ], [
2821 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2822 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2823 "to git-debrebase format. Upstream changes will appear as commits.",
2824 '[git-debrebase convert-from-dgit-view drop-patches]'
2827 $work = make_commit [ $work, $u->{Commit} ], [
2828 'git-debrebase convert-from-dgit-view: declare upstream',
2829 '(Re)constructed breakwater merge.',
2830 '[git-debrebase anchor: declare upstream]'
2832 runcmd @git, qw(checkout --quiet -b mk), $work;
2833 if ($some_patches) {
2834 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2835 runcmd @git, qw(reset --quiet);
2836 my @gbp_cmd = (qw(gbp pq import));
2838 my $gbp_err = "../gbp-pq-err";
2839 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2841 my $r = system @gbp_cmd;
2844 " %s: couldn't apply patches: gbp pq %s",
2845 $u->{Source}, waitstatusmsg();
2849 my $work = git_rev_parse qw(HEAD);
2850 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2851 if (length $diffout) {
2853 " $u->{Source}: applying patches gives different tree\n";
2854 print STDERR $diffout if $diagnose;
2858 $u->{Result} = $work;
2866 Could not find or construct a suitable upstream commit.
2867 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2868 upstream commmit explicitly or provide suitable origs.
2872 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2874 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2875 'convert-from-dgit-view';
2878 sub cmd_forget_was_ever_debrebase () {
2879 badusage "forget-was-ever-debrebase takes no further arguments" if @ARGV;
2880 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2881 ffq_prev_branchinfo();
2882 fail "Not suitable for recording git-debrebaseness anyway: $ffq_msg"
2883 if defined $ffq_msg;
2884 push @deferred_updates, "delete $ffq_prev";
2885 push @deferred_updates, "delete $gdrlast";
2887 run_deferred_updates "forget-was-ever-debrebase";
2890 sub cmd_record_resolved_merge () {
2891 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2892 # MERGE-TODO needs documentation
2893 my $new = get_head();
2896 print "Checking how you have resolved the merge problem\n";
2897 my $nope = sub { print "Not $method: @_"; 0; };
2899 my $maybe = sub { print "Seems to be $method.\n"; };
2901 my ($key, $ref) = @_;
2902 reflog_cache_insert $merge_cache_ref, $key, $ref;
2903 print "OK. You can switch branches and try git-debrebase again.\n";
2907 fresh_workarea 'merge';
2909 $method = 'vanilla-merge patchqueue';
2910 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2911 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2912 foreach my $lr (qw(left right)) {
2913 my $n = "$wrecknoteprefix/$lr-patchqueue";
2914 my $lrpq = git_get_ref $n;
2915 $lrpq or return $nope->("wreckage did not contain patchqueues");
2916 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2919 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2920 or die "wreckage element $wrecknoteprefix/new-base missing";
2921 my $result = merge_series_patchqueue_convert
2923 $yes->("vanilla-merge $vanilla", $result);
2926 fail "No resolved merge method seems applicable.\n";
2930 sub cmd_downstream_rebase_launder_v0 () {
2931 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2933 $base = git_rev_parse $base;
2934 my $old_head = get_head();
2935 my $current = $old_head;
2938 if ($current eq $base) {
2939 $topmost_keep //= $current;
2940 print " $current BASE stop\n";
2943 my $cl = classify $current;
2944 print " $current $cl->{Type}";
2946 my $p0 = $cl->{Parents}[0]{CommitId};
2948 if ($cl->{Type} eq 'Pseudomerge') {
2949 print " ^".($cl->{Contributor}{Ix}+1);
2950 $next = $cl->{Contributor}{CommitId};
2951 } elsif ($cl->{Type} eq 'AddPatches' or
2952 $cl->{Type} eq 'Changelog') {
2962 $topmost_keep //= $current;
2964 die "to-be stripped changes not on top of the branch\n"
2969 if ($topmost_keep eq $old_head) {
2970 print "unchanged\n";
2972 print "updating to $topmost_keep\n";
2973 update_head_checkout
2974 $old_head, $topmost_keep,
2975 'downstream-rebase-launder-v0';
2979 setlocale(LC_MESSAGES, "");
2980 textdomain("git-debrebase");
2984 "D+" => \$debuglevel,
2985 'noop-ok', => \$opt_noop_ok,
2986 'f=s' => \@snag_force_opts,
2987 'anchor=s' => \@opt_anchors,
2988 '--dgit=s' => \($dgit[0]),
2990 'experimental-merge-resolution!', \$opt_merges,
2992 my ($opt,$val) = @_;
2993 badusage f_ "%s: no cuddling to -i for git-rebase", $us
2995 confess if $opt_defaultcmd_interactive; # should not happen
2996 $opt_defaultcmd_interactive = [ qw(-i) ];
2997 # This access to @ARGV is excessive familiarity with
2998 # Getopt::Long, but there isn't another sensible
2999 # approach. '-i=s{0,}' does not work with bundling.
3000 push @$opt_defaultcmd_interactive, @ARGV;
3003 'help' => sub { print __ $usage_message or confess $!; finish 0; },
3006 initdebug('git-debrebase ');
3007 enabledebug if $debuglevel;
3009 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
3010 chdir $toplevel or fail "chdir toplevel $toplevel: $!\n";
3012 $rd = fresh_playground "$playprefix/misc";
3014 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
3016 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
3017 defaultcmd_rebase();
3019 my $cmd = shift @ARGV;
3022 $cmdfn = ${*::}{"cmd_$cmdfn"};
3024 $cmdfn or badusage f_ "unknown git-debrebase sub-operation %s", $cmd;