3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
6 # Copyright (C)2017-2019 Ian Jackson
7 # Copyright (C)2019 Niko Tyni
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
23 use Debian::Dgit::GDR;
24 use Debian::Dgit::ExitStatus;
25 use Debian::Dgit::I18n;
29 use Debian::Dgit qw(:DEFAULT :playground);
37 use Getopt::Long qw(:config posix_default gnu_compat bundling);
39 use File::FnMatch qw(:fnmatch);
42 $debugcmd_when_debuglevel = 2;
44 our ($usage_message) = i_ <<'END';
46 git-debrebase [<options>] [--|-i <git rebase options...>]
47 git-debrebase [<options>] status
48 git-debrebase [<options>] prepush [--prose=...]
49 git-debrebase [<options>] quick|conclude
50 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
51 git-debrebase [<options>] convert-from-* ...
53 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
56 our ($opt_force, $opt_noop_ok, $opt_merges, @opt_anchors);
57 our ($opt_defaultcmd_interactive);
59 our $us = qw(git-debrebase);
61 our $wrecknoteprefix = 'refs/debrebase/wreckage';
62 our $merge_cache_ref = 'refs/debrebase/merge-resolutions';
68 print STDERR f_ "%s: bad usage: %s\n", $us, $m;
74 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
75 GetOptions @_ or badusage $m;
79 getoptions_main +(f_ "bad options follow \`git-debrebase %s'", $sc), @_;
83 my ($k, $optional) = @_;
85 my @cmd = qw(git config -z);
86 push @cmd, qw(--get-all) if wantarray;
88 my $out = cmdoutput_errok @cmd;
90 fail f_ "missing required git config %s", $k unless $optional;
93 my @l = split /\0/, $out;
94 return wantarray ? @l : $l[0];
101 my $dd = new Data::Dumper [ $v ];
102 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
108 my $data = (git_cat_file $objid, 'commit');
109 $data =~ m/(?<=\n)\n/ or confess "$objid ($data) ?";
113 sub D_UPS () { 0x02; } # upstream files
114 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
115 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
116 sub D_DEB_CLOG () { 0x10; } # debian/changelog
117 sub D_DEB_OTH () { 0x20; } # debian/ (not patches/ or changelog)
118 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
120 our $playprefix = 'debrebase';
125 our @dgit = qw(dgit);
127 sub in_workarea ($) {
130 my $r = eval { $sub->(); };
131 { local $@; changedir $maindir; }
135 sub fresh_workarea (;$) {
138 $workarea = fresh_playground "$playprefix/$subdir";
139 in_workarea sub { playtree_setup };
142 sub run_ref_updates_now ($$) {
143 my ($mrest, $updates) = @_;
144 # @$updates is a list of lines for git-update-ref, without \ns
146 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
147 debugcmd '>|', @upd_cmd;
148 open U, "|-", @upd_cmd or confess "$!";
149 foreach (@$updates) {
150 printdebug ">= ", $_, "\n";
151 print U $_, "\n" or confess "$!";
154 close U or failedcmd @upd_cmd;
157 our $snags_forced = 0;
158 our $snags_tripped = 0;
159 our $snags_summarised = 0;
160 our @deferred_updates;
161 our @deferred_update_messages;
163 sub merge_wreckage_cleaning ($) {
165 git_for_each_ref("$wrecknoteprefix/*", sub {
166 my ($objid,$objtype,$fullrefname,$reftail) = @_;
167 push @$updates, "delete $fullrefname";
171 sub all_snags_summarised () {
172 $snags_forced + $snags_tripped == $snags_summarised;
174 sub run_deferred_updates ($) {
177 my $m = 'dangerous internal error';
178 confess $m.' - '.__ $m unless all_snags_summarised();
180 merge_wreckage_cleaning \@deferred_updates;
181 run_ref_updates_now $mrest, \@deferred_updates;
182 print $_, "\n" foreach @deferred_update_messages;
184 @deferred_updates = ();
185 @deferred_update_messages = ();
188 sub get_tree ($;$$) {
189 # tree object name => ([ $name, $info ], ...)
190 # where $name is the sort key, ie has / at end for subtrees
191 # $info is the LHS from git-ls-tree (<mode> <type> <hash>)
192 # without $precheck, will crash if $x does not exist, so don't do that;
193 # instead pass '' to get ().
194 my ($x, $precheck, $recurse) = @_;
196 return () if !length $x;
199 my ($type, $dummy) = git_cat_file $x, [qw(tree missing)];
200 return () if $type eq 'missing';
203 $recurse = !!$recurse;
205 confess "get_tree needs object not $x ?" unless $x =~ m{^[0-9a-f]+\:};
207 our (@get_tree_memo, %get_tree_memo);
208 my $memo = $get_tree_memo{$recurse,$x};
209 return @$memo if $memo;
211 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
213 my @cmd = (qw(git ls-tree -z --full-tree));
214 push @cmd, qw(-r) if $recurse;
215 push @cmd, qw(--), $x;
216 my $o = cmdoutput @cmd;
219 foreach my $l (split /\0/, $o) {
220 my ($i, $n) = split /\t/, $l, 2;
221 $n .= '/' if $i =~ m/^\d+ tree /;
223 confess "$x need $last < $n ?" unless $last lt $n;
225 $get_tree_memo{$recurse,$x} = \@l;
226 push @get_tree_memo, $x;
227 if (@get_tree_memo > 10) {
228 delete $get_tree_memo{ shift @get_tree_memo };
233 sub trees_diff_walk ($$$;$) {
234 # trees_diff_walk [{..opts...},] $x, $y, sub {... }
235 # calls sub->($name, $ix, $iy) for each difference
236 # $x and $y are as for get_tree
237 # where $name, $ix, $iy are $name and $info from get_tree
238 # opts are all call even for names same in both
239 # recurse call even for names same in both
240 my $opts = shift @_ if @_>=4;
241 my ($x,$y,$call) = @_;
242 my $all = $opts->{all};
243 return if !$all and $x eq $y;
244 my @x = get_tree $x, 0, $opts->{recurse};
245 my @y = get_tree $y, 0, $opts->{recurse};
246 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
249 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
250 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
251 my ($n, $ix, $iy); # all same? $cmp=0, use both
253 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
255 ($n, $ix) = @{ shift @x } if $cmp <= 0;
256 ($n, $iy) = @{ shift @y } if $cmp >= 0;
257 next if !$all and $ix eq $iy;
259 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
260 !!$all,$x,$y, $n,$ix,$iy
262 $call->($n, $ix, $iy);
266 sub get_differs ($$) {
268 # This does a similar job to quiltify_trees_differ, in dgit, a bit.
269 # But we don't care about modes, or dpkg-source-unrepresentable
270 # changes, and we don't need the plethora of different modes.
271 # Conversely we need to distinguish different kinds of changes to
272 # debian/ and debian/patches/.
273 # Also, here we have, and want to use, trees_diff_walk, because
274 # we may be calling this an awful lot and we want it to be fast.
279 no warnings qw(exiting);
281 my $plain = sub { $_[0] =~ m{^(100|0*)644 blob }s; };
283 trees_diff_walk "$x:", "$y:", sub {
284 my ($n,$ix,$iy) = @_;
286 # analyse difference at the toplevel
288 if ($n ne 'debian/') {
292 if ($n eq 'debian') {
293 # one side has a non-tree for ./debian !
294 $differs |= D_DEB_OTH;
298 my $xd = $ix && "$x:debian";
299 my $yd = $iy && "$y:debian";
300 trees_diff_walk $xd, $yd, sub {
301 my ($n,$ix,$iy) = @_;
303 # analyse difference in debian/
305 if ($n eq 'changelog' && (!$ix || $plain->($ix))
307 $differs |= D_DEB_CLOG;
310 if ($n ne 'patches/') {
311 $differs |= D_DEB_OTH;
315 my $xp = $ix && "$xd/patches";
316 my $yp = $iy && "$yd/patches";
317 trees_diff_walk { recurse=>1 }, $xp, $yp, sub {
318 my ($n,$ix,$iy) = @_;
320 # analyse difference in debian/patches
324 # we are recursing; directories may appear and disappear
326 } elsif ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
328 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
329 my $x_s = (git_cat_file "$xp/series", 'blob');
330 my $y_s = (git_cat_file "$yp/series", 'blob');
331 chomp $x_s; $x_s .= "\n";
332 $ok = $x_s eq substr($y_s, 0, length $x_s);
336 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
341 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
346 sub commit_pr_info ($) {
348 return Data::Dumper->dump([$r], [qw(commit)]);
351 sub calculate_committer_authline () {
352 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
353 'DUMMY COMMIT (git-debrebase)', "HEAD:";
354 my ($h,$m) = get_commit $c;
355 $h =~ m/^committer .*$/m or confess "($h) ?";
359 our @snag_force_opts;
361 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
362 if (grep { $_ eq $tag } @snag_force_opts) {
364 print STDERR f_ "%s: snag ignored (-f%s): %s\n", $us, $tag, $msg;
367 print STDERR f_ "%s: snag detected (-f%s): %s\n", $us, $tag, $msg;
371 # Important: all mainline code must call snags_maybe_bail after
372 # any point where snag might be called, but before making changes
373 # (eg before any call to run_deferred_updates). snags_maybe_bail
374 # may be called more than once if necessary (but this is not ideal
375 # because then the messages about number of snags may be confusing).
376 sub snags_maybe_bail () {
377 return if all_snags_summarised();
380 "%s: snags: %d overriden by individual -f options\n",
383 if ($snags_tripped) {
386 "%s: snags: %d overriden by global --force\n",
390 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
394 $snags_summarised = $snags_forced + $snags_tripped;
396 sub snags_maybe_bail_early () {
397 # useful to bail out early without doing a lot of work;
398 # not a substitute for snags_maybe_bail.
399 snags_maybe_bail() if $snags_tripped && !$opt_force;
402 return $snags_forced || $snags_tripped;
405 sub ffq_prev_branchinfo () {
406 my $current = git_get_symref();
407 return gdr_ffq_prev_branchinfo($current);
410 sub record_gdrlast ($$;$) {
411 my ($gdrlast, $newvalue, $oldvalue) = @_;
412 $oldvalue ||= $git_null_obj;
413 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
416 sub fail_unprocessable ($) {
419 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
421 my $mangled = __ <<END;
422 Branch/history seems mangled - no longer in gdr format.
423 See ILLEGAL OPERATIONS in git-debrebase(5).
428 fail f_ <<END, $msg, $ffqm;
430 Is this meant to be a gdr branch? %s
432 } elsif (git_get_ref $ffq_prev) {
433 fail f_ <<END, $msg, $mangled;
436 Consider git-debrebase scrap, to throw away your recent work.
438 } elsif (!git_get_ref $gdrlast) {
441 Branch does not seem to be meant to be a git-debrebase branch?
442 Wrong branch, or maybe you needed git-debrebase convert-from-*.
444 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
452 Branch/history mangled, and diverged since last git-debrebase.
453 Maybe you reset to, or rebased from, somewhere inappropriate.
458 sub gbp_pq_export ($$$) {
459 my ($bname, $base, $tip) = @_;
460 # must be run in a workarea. $bname and patch-queue/$bname
461 # ought not to exist. Leaves you on patch-queue/$bname with
462 # the patches staged but not committed.
463 # returns 1 if there were any patches
464 printdebug "gbp_pq_export $bname $base $tip\n";
465 runcmd @git, qw(checkout -q -b), $bname, $base;
466 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
467 my @gbp_cmd = (qw(gbp pq export));
468 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
470 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
473 return 0 unless stat_exists 'debian/patches';
474 runcmd @git, qw(add -f debian/patches);
479 # MERGE-TODO allow merge resolution separately from laundering, before git merge
482 # use git-format-patch?
483 # our own patch identification algorithm?
484 # this is an alternative strategy
486 sub merge_failed ($$;@) {
487 my ($wrecknotes, $emsg, @xmsgs) = @_;
489 push @m, "Merge resolution failed: $emsg";
495 merge_wreckage_cleaning \@updates;
496 run_ref_updates_now "merge failed", \@updates;
500 while (my ($k,$v) = each %$wrecknotes) {
501 push @updates, "create $wrecknoteprefix/$k $v";
503 run_ref_updates_now "merge failed", \@updates;
504 push @m, "Wreckage left in $wrecknoteprefix/*.";
506 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
508 # use finish rather than fail, in case we are within an eval
509 # (that can happen inside walk!)
511 print STDERR "$us: $_\n" foreach @m;
515 sub mwrecknote ($$$) {
516 my ($wrecknotes, $reftail, $commitish) = @_;
517 confess unless defined $commitish;
518 printdebug "mwrecknote $reftail $commitish\n";
519 $wrecknotes->{$reftail} = $commitish;
522 sub merge_attempt_cmd {
523 my $wrecknotes = shift @_;
527 merge_failed $wrecknotes,
528 failedcmd_waitstatus(),
529 "failed command: @_";
533 sub merge_series_patchqueue_convert ($$$);
535 sub merge_series ($$$;@) {
536 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
537 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
538 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
539 # ^ specifies several patch series (currently we only support exactly 2)
540 # return value is a commit which is the result of
541 # merging the two versions of the same topic branch
542 # $input_q[0] and $input_q[1]
543 # with respect to the old version
547 # Creates, in *_q, a key MR for its private use
549 printdebug "merge_series newbase=$newbase\n";
551 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
552 $base_q->{MR}{S} = 'base';
555 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
556 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
557 # $prereq{<patch filename>} exists or not (even later)
561 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
563 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
566 fresh_workarea "merge";
567 my $seriesfile = "debian/patches/series";
570 foreach my $q ($base_q, reverse @input_qs) {
572 my $any = gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
575 open S, $seriesfile or confess "$seriesfile $!";
576 while (my $patch = <S>) {
577 chomp $patch or confess "$!";
578 $prereq{$patch} //= {};
579 foreach my $earlier (@earlier) {
580 $prereq{$patch}{$earlier}{$s}++ and confess;
582 push @earlier, $patch;
583 stat "debian/patches/$patch" or confess "$patch ?";
585 S->error and confess "$seriesfile $!";
588 read_tree_upstream $newbase, 1;
589 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
590 "Convert $s to patch queue for merging",
591 "[git-debrebase merge-innards patch-queue import:".
594 printdebug "merge_series pec $pec ";
595 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
596 $pec = make_commit [ $pec ], [
597 "Drop series file from $s to avoid merge trouble",
598 "[git-debrebase merge-innards patch-queue prep:".
602 read_tree_debian $newbase;
604 read_tree_subdir 'debian/patches', "$pec:debian/patches";
606 rm_subdir_cached 'debian/patches';
608 $pec = make_commit [ $pec ], [
609 "Update debian/ (excluding patches) to final to avoid re-merging",
610 "debian/ was already merged and we need to just take that.",
611 "[git-debrebase merge-innards patch-queue packaging:".
615 printdebug "pec' $pec\n";
616 runcmd @git, qw(reset -q --hard), $pec;
617 $q->{MR}{PEC} = $pec;
618 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
620 # now, because of reverse, we are on $input_q->{MR}{OQC}
621 runcmd @git, qw(checkout -q -b merge);
622 printdebug "merge_series merging...\n";
623 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
625 $attempt_cmd->(@mergecmd);
627 printdebug "merge_series merge ok, series...\n";
628 # We need to construct a new series file
629 # Firstly, resolve prereq
630 foreach my $f (sort keys %prereq) {
631 printdebug "merge_series patch\t$f\t";
632 if (!stat_exists "debian/patches/$f") {
633 print DEBUG " drop\n" if $debuglevel;
634 # git merge deleted it; that's how we tell it's not wanted
638 print DEBUG " keep\n" if $debuglevel;
639 foreach my $g (sort keys %{ $prereq{$f} }) {
640 my $gfp = $prereq{$f}{$g};
641 printdebug "merge_series prereq\t$f\t-> $g\t";
642 if (!!$gfp->{0} == !!$gfp->{1}
645 print DEBUG "\tkeep\n" if $debuglevel;
647 print DEBUG "\tdrop\n" if $debuglevel;
648 delete $prereq{$f}{$g};
655 return scalar keys %{ $prereq{$f} };
658 my $nodate = time + 1;
660 # $authordate{<patch filename>};
661 my $authordate = sub {
663 $authordate{$f} //= do {
664 open PF, "<", "debian/patches/$f" or confess "$f $!";
666 return $nodate if m/^$/;
667 last if s{^Date: }{};
670 return cmdoutput qw(date +%s -d), $_;
674 open NS, '>', $seriesfile or confess "$!";
676 while (keys %prereq) {
678 foreach my $try (sort keys %prereq) {
681 $unsat->($try) <=> $unsat->($best) or
682 $authordate->($try) <=> $authordate->($best) or
688 printdebug "merge_series series next $best\n";
689 print NS "$best\n" or confess "$!";
690 delete $prereq{$best};
691 foreach my $gp (values %prereq) {
696 runcmd @git, qw(add), $seriesfile;
697 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
698 $merged_pq = git_rev_parse 'HEAD';
699 $mwrecknote->('merged-patchqueue', $merged_pq);
701 return merge_series_patchqueue_convert
702 $wrecknotes, $newbase, $merged_pq;
705 sub merge_series_patchqueue_convert ($$$) {
706 my ($wrecknotes, $newbase, $merged_pq) = @_;
711 printdebug "merge_series series gbp pq import\n";
712 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
714 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
715 # MERGE-TODO consider git-format-patch etc. instead,
716 # since gbp pq doesn't always round-trip :-/
718 # OK now we are on patch-queue/merge, and we need to rebase
719 # onto the intended parent and drop the patches from each one
721 printdebug "merge_series series ok, building...\n";
722 my $build = $newbase;
723 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
724 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
725 my $commit = git_cat_file $c, 'commit';
726 printdebug "merge_series series ok, building $c\n";
727 read_tree_upstream $c, 0, $newbase;
728 my $tree = cmdoutput @git, qw(write-tree);
729 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
730 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
731 open C, ">", "../mcommit" or confess "$!";
732 print C $commit or confess "$!";
733 close C or confess "$!";
734 $build = hash_commit '../mcommit';
737 mwrecknote($wrecknotes, 'merged-result', $result);
739 runcmd @git, qw(update-ref refs/heads/result), $result;
741 runcmd @git, qw(checkout -q -b debug);
742 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
743 runcmd @git, qw(add .);
744 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
745 my $mdebug = git_rev_parse 'HEAD';
746 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
747 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
749 printdebug "merge_series returns $result\n";
753 # classify returns an info hash like this
755 # Hdr => # commit headers, including 1 final newline
756 # Msg => # commit message (so one newline is dropped)
758 # Type => (see below)
760 # Ix => $index # ie 0, 1, 2, ...
762 # Differs => return value from get_differs
764 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
766 # NewMsg => # commit message, but with any [dgit import ...] edited
767 # # to say "[was: ...]"
777 # has additional entres in classification result
778 # Overwritten = [ subset of Parents ]
779 # Contributor = $the_remaining_Parent
781 # DgitImportUnpatched
782 # has additional entry in classification result
783 # OrigParents = [ subset of Parents ]
786 # has additional entry in classification result
787 # OrigParents = [ subset of Parents ] # singleton list
794 # has additional entry in classification result
797 sub parsecommit ($;$) {
798 my ($objid, $p_ref) = @_;
799 # => hash with CommitId Hdr Msg Tree Parents
800 # Parents entries have only Ix CommitId
801 # $p_ref, if provided, must be [] and is used as a base for Parents
806 my ($h,$m) = get_commit $objid;
808 my ($t) = $h =~ m/^tree (\w+)$/m or confess $objid;
809 my (@ph) = $h =~ m/^parent (\w+)$/mg;
819 foreach my $ph (@ph) {
821 Ix => scalar @$p_ref,
833 my $r = parsecommit($objid, \@p);
837 $p->{Differs} = (get_differs $p->{CommitId}, $t),
840 printdebug "classify $objid \$t=$t \@p",
841 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
845 my ($type, @rest) = @_;
846 $r = { %$r, Type => $type, @rest };
848 printdebug " = $type ".(dd $r)."\n";
854 $r = { %$r, Type => qw(Unknown), Why => $why };
855 printdebug " ** Unknown\n";
859 if (grep { $_ eq $objid } @opt_anchors) {
860 return $classify->('TreatAsAnchor');
863 my @identical = grep { !$_->{Differs} } @p;
864 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
865 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
867 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
868 # multi-orig upstreams are represented with an anchor merge
869 # from a single upstream commit which combines the orig tarballs
871 # Every anchor tagged this way must be a merge.
872 # We are relying on the
873 # [git-debrebase anchor: ...]
874 # commit message annotation in "declare" anchor merges (which
875 # do not have any upstream changes), to distinguish those
876 # anchor merges from ordinary pseudomerges (which we might
877 # just try to strip).
879 # However, the user is going to be doing git-rebase a lot. We
880 # really don't want them to rewrite an anchor commit.
881 # git-rebase trips up on merges, so that is a useful safety
884 # BreakwaterStart commits are also anchors in the terminology
885 # of git-debrebase(5), but they are untagged (and always
886 # manually generated).
888 # We cannot not tolerate any tagged linear commit (ie,
889 # BreakwaterStart commits tagged `[anchor:') because such a
890 # thing could result from an erroneous linearising raw git
891 # rebase of a merge anchor. That would represent a corruption
892 # of the branch. and we want to detect and reject the results
893 # of such corruption before it makes it out anywhere. If we
894 # reject it here then we avoid making the pseudomerge which
895 # would be needed to push it.
897 my $badanchor = sub {
898 $unknown->(f_ "git-debrebase \`anchor' but %s", "@_");
900 @p == 2 or return $badanchor->(__ "has other than two parents");
901 $haspatches and return $badanchor->(__ "contains debian/patches");
903 # How to decide about l/r ordering of anchors ? git
904 # --topo-order prefers to expand 2nd parent first. There's
905 # already an easy rune to look for debian/ history anyway (git log
906 # debian/) so debian breakwater branch should be 1st parent; that
907 # way also there's also an easy rune to look for the upstream
908 # patches (--topo-order).
910 # Also this makes --first-parent be slightly more likely to
911 # be useful - it makes it provide a linearised breakwater history.
913 # Of course one can say somthing like
914 # gitk -- ':/' ':!/debian'
915 # to get _just_ the commits touching upstream files, and by
916 # the TREESAME logic in git-rev-list this will leave the
917 # breakwater into upstream at the first anchor. But that
918 # doesn't report debian/ changes at all.
920 # Other observations about gitk: by default, gitk seems to
921 # produce output in a different order to git-rev-list. I
922 # can't seem to find this documented anywhere. gitk
923 # --date-order DTRT. But, gitk always seems to put the
924 # parents from left to right, in order, so it's easy to see
925 # which way round a pseudomerge is.
927 $p[0]{IsOrigin} and $badanchor->(__ "is an origin commit");
928 $p[1]{Differs} & ~DS_DEB and
929 $badanchor->(__ "upstream files differ from left parent");
930 $p[0]{Differs} & ~D_UPS and
931 $badanchor->(__ "debian/ differs from right parent");
933 return $classify->(qw(Anchor),
934 OrigParents => [ $p[1] ]);
938 my $d = $r->{Parents}[0]{Differs};
939 if ($d == D_PAT_ADD) {
940 return $classify->(qw(AddPatches));
941 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
942 return $unknown->(__ "edits debian/patches");
943 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
944 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
946 if ($d == D_DEB_CLOG) {
947 return $classify->(qw(Changelog));
949 return $classify->(qw(Packaging));
951 } elsif ($ty eq 'missing') {
952 return $classify->(qw(BreakwaterStart));
954 return $unknown->(__ "parent's debian is not a directory");
956 } elsif ($d == D_UPS) {
957 return $classify->(qw(Upstream));
958 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
959 return $classify->(qw(Mixed));
961 return $unknown->(__ "no changes");
963 confess "internal error $objid ?";
967 return $unknown->(__ "origin commit");
970 if (@p == 2 && @identical == 1) {
971 my @overwritten = grep { $_->{Differs} } @p;
972 confess "internal error $objid ?" unless @overwritten==1;
973 return $classify->(qw(Pseudomerge),
974 Overwritten => [ $overwritten[0] ],
975 Contributor => $identical[0]);
977 if (@p == 2 && @identical == 2) {
979 my ($ph,$pm) = get_commit $_[0]{CommitId};
980 $ph =~ m/^committer .* (\d+) [-+]\d+$/m
981 or confess "$_->{CommitId} ?";
985 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
986 if ($order > 0) { # newer first
987 } elsif ($order < 0) {
988 @bytime = reverse @bytime;
990 # same age, default to order made by -s ours
991 # that is, commit was made by someone who preferred L
993 return $classify->(qw(Pseudomerge),
994 SubType => qw(Ambiguous),
995 Contributor => $bytime[0],
996 Overwritten => [ $bytime[1] ]);
999 my ($p_h, $p_m) = get_commit $p->{CommitId};
1000 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1001 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1003 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1005 if (!(grep { !$_->{IsOrigin} } @p) and
1006 (@orig_ps >= @p - 1) and
1007 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1009 return $classify->(qw(DgitImportUnpatched),
1010 OrigParents => \@orig_ps);
1014 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1015 return $classify->("MergedBreakwaters");
1017 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1018 return $unknown->(f_ "unknown kind of merge from %s", $1);
1021 return $unknown->(__ "octopus merge");
1025 return $unknown->(__ "general two-parent merge");
1028 return $classify->("VanillaMerge");
1031 sub keycommits ($;$$$$$);
1033 sub mergedbreakwaters_anchor ($) {
1036 foreach my $p (@{ $cl->{Parents} }) {
1037 my ($panchor, $pbw) = keycommits $p->{CommitId},
1038 undef,undef,undef,undef, 1;
1039 $best_anchor = $panchor
1040 if !defined $best_anchor
1041 or is_fast_fwd $best_anchor, $panchor;
1042 fail f_ "inconsistent anchors in merged-breakwaters %s",
1044 unless is_fast_fwd $panchor, $best_anchor;
1046 return $best_anchor;
1049 sub keycommits ($;$$$$$) {
1050 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1051 # => ($anchor, $breakwater)
1053 # $furniture->("unclean-$tagsfx", $msg, $cl)
1054 # $unclean->("unclean-$tagsfx", $msg, $cl)
1055 # is callled for each situation or commit that
1056 # wouldn't be found in a laundered branch
1057 # $furniture is for furniture commits such as might be found on an
1058 # interchange branch (pseudomerge, d/patches, changelog)
1059 # $trouble is for things whnich prevent the return of
1060 # anchor and breakwater information; if that is ignored,
1061 # then keycommits returns (undef, undef) instead.
1062 # $fatal is for unprocessable commits, and should normally cause
1063 # a failure. If ignored, agaion, (undef, undef) is returned.
1065 # If $claimed_bw, this is supposed to be a breakwater commit.
1067 # If a callback is undef, fail is called instead.
1068 # If a callback is defined but false, the situation is ignored.
1069 # Callbacks may say:
1070 # no warnings qw(exiting); last;
1071 # if the answer is no longer wanted.
1073 my ($anchor, $breakwater);
1074 $breakwater = $head if $claimed_bw;
1078 $fatal //= sub { fail_unprocessable $_[1]; };
1080 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1081 my $why = $mainwhy.$xwhy;
1082 my $m = f_ "branch needs laundering (run git-debrebase): %s", $why;
1083 fail $m unless defined $cb;
1085 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1087 my $found_anchor = sub {
1089 $breakwater //= $clogonly;
1090 $breakwater //= $head;
1091 no warnings qw(exiting);
1095 $cl = classify $head;
1096 my $ty = $cl->{Type};
1097 if ($ty eq 'Packaging') {
1098 $breakwater //= $clogonly;
1099 $breakwater //= $head;
1100 } elsif ($ty eq 'Changelog') {
1101 # this is going to count as the tip of the breakwater
1102 # only if it has no upstream stuff before it
1103 $clogonly //= $head;
1104 } elsif ($ty eq 'Anchor' or
1105 $ty eq 'TreatAsAnchor' or
1106 $ty eq 'BreakwaterStart') {
1107 $found_anchor->($head);
1108 } elsif ($ty eq 'Upstream') {
1109 $x->($unclean, 'ordering',
1110 (f_ "packaging change (%s) follows upstream change", $breakwater),
1111 (f_ " (eg %s)", $head))
1112 if defined $breakwater;
1114 $breakwater = undef;
1115 } elsif ($ty eq 'Mixed') {
1116 $x->($unclean, 'mixed',
1117 (__ "found mixed upstream/packaging commit"),
1118 (f_ " (%s)", $head));
1120 $breakwater = undef;
1121 } elsif ($ty eq 'Pseudomerge' or
1122 $ty eq 'AddPatches') {
1124 $x->($furniture, (lc $ty),
1125 (f_ "found interchange bureaucracy commit (%s)", $ty),
1126 (f_ " (%s)", $head));
1127 } elsif ($ty eq 'DgitImportUnpatched') {
1129 $x->($trouble, 'dgitimport',
1130 (__ "found dgit dsc import"),
1131 (f_ " (%s)", $head));
1132 return (undef,undef);
1134 $x->($fatal, 'unprocessable',
1135 (__ "found bare dgit dsc import with no prior history"),
1136 (f_ " (%s)", $head));
1137 return (undef,undef);
1139 } elsif ($ty eq 'VanillaMerge') {
1140 $x->($trouble, 'vanillamerge',
1141 (__ "found vanilla merge"),
1142 (f_ " (%s)", $head));
1143 return (undef,undef);
1144 } elsif ($ty eq 'MergedBreakwaters') {
1145 $found_anchor->(mergedbreakwaters_anchor $cl);
1147 $x->($fatal, 'unprocessable',
1148 (f_ "found unprocessable commit, cannot cope: %s",
1150 (f_ " (%s)", $head));
1151 return (undef,undef);
1153 $head = $cl->{Parents}[0]{CommitId};
1155 return ($anchor, $breakwater);
1161 $nogenerate,$report, $report_lprefix) = @_;
1162 # => ($tip, $breakwater_tip, $last_anchor)
1163 # (or nothing, if $nogenerate)
1165 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1166 $report_lprefix //= '';
1168 # go through commits backwards
1169 # we generate two lists of commits to apply:
1170 # breakwater branch and upstream patches
1171 my (@brw_cl, @upp_cl, @processed);
1178 my ($prose, $info) = @_;
1179 # We deliberately do not translate $prose, since this mostly
1180 # appears in commits in Debian and they should be in English.
1181 my $ms = $cl->{Msg};
1183 confess unless defined $info;
1184 $ms .= "\n\n[git-debrebase $info: $prose]\n";
1185 return (Msg => $ms);
1187 my $rewrite_from_here = sub {
1189 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1191 push @processed, $sp_cl;
1196 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1199 return unless $report;
1200 print $report $prdelim, $report_lprefix, @_;
1204 my $bomb = sub { # usage: return $bomb->();
1205 print $report " Unprocessable" if $report;
1206 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1209 return (undef,undef);
1213 map { sprintf "%#x", $_->{Differs} }
1214 @{ $cl->{Parents} };
1215 fail_unprocessable f_ +(defined $cl->{Why}
1216 ? i_ 'found unprocessable commit, cannot cope; %3$s: (commit %1$s) (d.%2$s)'
1217 : i_ 'found unprocessable commit, cannot cope: (commit %1$s) (d.%2$s)'),
1218 $cur, $d, $cl->{Why};
1224 my $build_start = sub {
1225 my ($msg, $parent) = @_;
1228 no warnings qw(exiting); last;
1233 merge_failed $cl->{MergeWreckNotes}, $emsg;
1236 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1241 $cl = classify $cur;
1242 $cl->{MergeWreckNotes} //= {};
1243 my $ty = $cl->{Type};
1244 my $st = $cl->{SubType};
1245 $prline->("$cl->{CommitId} $cl->{Type}");
1246 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1247 push @processed, $cl;
1248 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1249 if ($ty eq 'AddPatches') {
1251 $rewrite_from_here->(\@upp_cl);
1253 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1257 } elsif ($ty eq 'BreakwaterStart') {
1258 $last_anchor = $cur;
1259 $build_start->('FirstPackaging', $cur);
1260 } elsif ($ty eq 'Upstream') {
1264 } elsif ($ty eq 'Mixed') {
1267 my $cls = { %$cl, $xmsg->("mixed commit: $wh part",'split') };
1270 $queue->(\@brw_cl, "debian");
1271 $queue->(\@upp_cl, "upstream");
1272 $rewrite_from_here->(\@brw_cl);
1275 } elsif ($ty eq 'Pseudomerge') {
1276 my $contrib = $cl->{Contributor}{CommitId};
1277 print $report " Contributor=$contrib" if $report;
1278 push @pseudomerges, $cl;
1279 $rewrite_from_here->(\@upp_cl);
1282 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1283 $last_anchor = $cur;
1284 $build_start->("Anchor", $cur);
1285 } elsif ($ty eq 'DgitImportUnpatched') {
1286 my $pm = $pseudomerges[-1];
1288 # To an extent, this is heuristic. Imports don't have
1289 # a useful history of the debian/ branch. We assume
1290 # that the first pseudomerge after an import has a
1291 # useful history of debian/, and ignore the histories
1292 # from later pseudomerges. Often the first pseudomerge
1293 # will be the dgit import of the upload to the actual
1294 # suite intended by the non-dgit NMUer, and later
1295 # pseudomerges may represent in-archive copies.
1296 my $ovwrs = $pm->{Overwritten};
1297 printf $report " PM=%s \@Overwr:%d",
1298 $pm->{CommitId}, (scalar @$ovwrs)
1301 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1304 my $ovwr = $ovwrs->[0]{CommitId};
1305 printf $report " Overwr=%s", $ovwr if $report;
1306 # This import has a tree which is just like a
1307 # breakwater tree, but it has the wrong history. It
1308 # ought to have the previous breakwater (which the
1309 # pseudomerge overwrote) as an ancestor. That will
1310 # make the history of the debian/ files correct. As
1311 # for the upstream version: either it's the same as
1312 # was ovewritten (ie, same as the previous
1313 # breakwater), in which case that history is precisely
1314 # right; or, otherwise, it was a non-gitish upload of a
1315 # new upstream version. We can tell these apart by
1316 # looking at the tree of the supposed upstream.
1319 SpecialMethod => 'DgitImportDebianUpdate',
1320 $xmsg->("debian changes", 'convert dgit import')
1323 SpecialMethod => 'DgitImportUpstreamUpdate',
1324 $xmsg->("convert dgit import: upstream update",
1327 $prline->(" Import");
1328 $rewrite_from_here->(\@brw_cl);
1329 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1333 # Everything is from this import. This kind of import
1334 # is already nearly in valid breakwater format, with the
1335 # patches as commits. Unfortunately it contains
1337 printdebug "*** WALK BOMB bare dgit import\n";
1338 $cl->{Why} = __ "bare dgit dsc import";
1342 } elsif ($ty eq 'MergedBreakwaters') {
1343 $last_anchor = mergedbreakwaters_anchor $cl;
1344 $build_start->(' MergedBreakwaters', $cur);
1346 } elsif ($ty eq 'VanillaMerge') {
1347 # User may have merged unstitched branch(es). We will
1348 # have now lost what ffq-prev was then (since the later
1349 # pseudomerge may introduce further changes). The effect
1350 # of resolving such a merge is that we may have to go back
1351 # further in history to find a merge base, since the one
1352 # which was reachable via ffq-prev is no longer findable.
1353 # This is suboptimal, but if it all works we'll have done
1355 # MERGE-TODO we should warn the user in the docs about this
1359 # We expect to find a dominating anchor amongst the
1360 # inputs' anchors. That will be the new anchor.
1362 # More complicated is finding a merge base for the
1363 # breakwaters. We need a merge base that is a breakwater
1364 # commit. The ancestors of breakwater commits are more
1365 # breakwater commits and possibly upstream commits and the
1366 # ancestors of those upstream. Upstreams might have
1367 # arbitrary ancestors. But any upstream commit U is
1368 # either included in both anchors, in which case the
1369 # earlier anchor is a better merge base than any of U's
1370 # ancestors; or U is not included in the older anchor, in
1371 # which case U is not an ancestor of the vanilla merge at
1372 # all. So no upstream commit, nor any ancestor thereof,
1373 # is a best merge base. As for non-breakwater Debian
1374 # commits: these are never ancestors of any breakwater.
1376 # So any best merge base as found by git-merge-base
1377 # is a suitable breakwater anchor. Usually there will
1380 printdebug "*** MERGE\n";
1382 my @bwbcmd = (@git, qw(merge-base));
1383 my @ibcmd = (@git, qw(merge-base --all));
1384 my $might_be_in_bw = 1;
1386 my $ps = $cl->{Parents};
1388 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1390 foreach my $p (@$ps) {
1391 $prline->(" VanillaMerge ".$p->{Ix});
1393 my ($ptip, $pbw, $panchor) =
1394 walk $p->{CommitId}, 0, $report,
1395 $report_lprefix.' ';
1396 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1397 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1398 $p->{Anchor} = $panchor;
1400 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1401 $mwrecknote->("$lr-input", $p->{CommitId});
1403 my $mwrecknote_parent = sub {
1405 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1407 $mwrecknote_parent->('Laundered');
1408 $mwrecknote_parent->('Breakwater');
1409 $mwrecknote_parent->('Anchor');
1411 $best_anchor = $panchor if
1412 !defined $best_anchor or
1413 is_fast_fwd $best_anchor, $panchor;
1415 printdebug " MERGE BA best=".($best_anchor//'-').
1419 $mwrecknote->('result-anchor', $best_anchor);
1421 foreach my $p (@$ps) {
1422 $prline->(" VanillaMerge ".$p->{Ix});
1423 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1424 $nomerge->('divergent anchors');
1425 } elsif ($p->{Anchor} eq $best_anchor) {
1426 print $report " SameAnchor" if $report;
1428 print $report " SupersededAnchor" if $report;
1430 if ($p->{Breakwater} eq $p->{CommitId}) {
1431 # this parent commit was its own breakwater,
1432 # ie it is part of the breakwater
1433 print $report " Breakwater" if $report;
1435 $might_be_in_bw = 0;
1437 push @bwbcmd, $p->{Breakwater};
1438 push @ibcmd, $p->{CommitId};
1441 if ($ok && $might_be_in_bw) {
1442 # We could rewrite this to contaion the metadata
1443 # declaring it to be MergedBreakwaters, but
1444 # unnecessarily rewriting a merge seems unhelpful.
1445 $prline->(" VanillaMerge MergedBreakwaters");
1446 $last_anchor = $best_anchor;
1447 $build_start->('MergedBreakwaters', $cur);
1450 my $bwb = cmdoutput @bwbcmd;
1452 # OK, now we have a breakwater base, but we need the merge
1453 # base for the interchange branch because we need the delta
1456 # This a the best merge base of our inputs which has the
1457 # breakwater merge base as an ancestor.
1464 @ibs or confess 'internal error, expected anchor at least ?';
1468 foreach my $tibix (0..$#ibs) {
1469 my $tib = $ibs[$tibix];
1470 my $ff = is_fast_fwd $bwb, $tib;
1471 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1472 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1473 $mwrecknote->($tibleaf, $tib);
1480 $ib or $nomerge->("no suitable interchange merge base");
1482 $prline->(" VanillaMerge Base");
1484 my ($btip, $bbw, $banchor) = eval {
1485 walk $ib, 0, $report, $report_lprefix.' ';
1487 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1491 $mwrecknote->("mergebase-laundered", $btip);
1492 $mwrecknote->("mergebase-breakwater", $bbw);
1493 $mwrecknote->("mergebase-anchor", $banchor);
1495 my $ibinfo = { SeriesTip => $btip,
1498 LeftRight => 'mergebase' };
1501 or $nomerge->("interchange merge-base ($ib)'s".
1502 " breakwater ($bbw)".
1503 " != breakwaters' merge-base ($bwb)");
1505 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1506 or $nomerge->("interchange merge-base ($ib)'s".
1507 " anchor ($ibinfo->{SeriesBase})".
1508 " != any merge input's anchor (".
1509 (join ' ', map { $_->{Anchor} } @$ps).
1512 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1513 $cl->{MergeBestAnchor} = $best_anchor;
1516 SpecialMethod => 'MergeCreateMergedBreakwaters',
1517 $xmsg->('constructed from vanilla merge',
1518 'merged-breakwater'),
1522 SpecialMethod => 'MergeMergeSeries',
1524 $build_start->('MergeBreakwaters', $cur);
1526 printdebug "*** WALK BOMB unrecognised\n";
1532 printdebug "*** WALK prep done cur=$cur".
1533 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1535 return if $nogenerate;
1537 # Now we build it back up again
1543 $#upp_cl = $upp_limit if defined $upp_limit;
1545 my $committer_authline = calculate_committer_authline();
1547 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1549 confess __ "internal error" unless $build eq (pop @processed)->{CommitId};
1552 mkdir $rd or $!==EEXIST or confess "$!";
1554 my $want_debian = $build;
1555 my $want_upstream = $build;
1557 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1558 my $read_tree_debian = sub { ($want_debian) = @_; };
1560 foreach my $cl (qw(Debian), (reverse @brw_cl),
1561 { SpecialMethod => 'RecordBreakwaterTip' },
1562 qw(Upstream), (reverse @upp_cl)) {
1564 $current_method = $cl;
1567 my $method = $cl->{SpecialMethod} // $current_method;
1568 my @parents = ($build);
1569 my $cltree = $cl->{CommitId};
1570 printdebug "WALK BUILD ".($cltree//'undef').
1571 " $method (rewriting=$rewriting)\n";
1572 if ($method eq 'Debian') {
1573 $read_tree_debian->($cltree);
1574 } elsif ($method eq 'Upstream') {
1575 $read_tree_upstream->($cltree);
1576 } elsif ($method eq 'StartRewrite') {
1579 } elsif ($method eq 'RecordBreakwaterTip') {
1580 $breakwater = $build;
1582 } elsif ($method eq 'DgitImportDebianUpdate') {
1583 $read_tree_debian->($cltree);
1584 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1585 confess unless $rewriting;
1586 my $differs = (get_differs $build, $cltree);
1587 next unless $differs & D_UPS;
1588 $read_tree_upstream->($cltree);
1589 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1590 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1591 print "Found a general merge, will try to tidy it up.\n";
1593 $read_tree_upstream->($cl->{MergeBestAnchor});
1594 $read_tree_debian->($cltree);
1595 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1596 } elsif ($method eq 'MergeMergeSeries') {
1597 my $cachehit = reflog_cache_lookup
1598 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1600 print "Using supplied resolution for $cl->{CommitId}...\n";
1602 $mwrecknote->('cached-resolution', $build);
1604 print "Running merge resolution for $cl->{CommitId}...\n";
1605 $mwrecknote->('new-base', $build);
1606 $build = merge_series
1607 $build, $cl->{MergeWreckNotes},
1608 $cl->{MergeInterchangeBaseInfo},
1609 @{ $cl->{Parents} };
1611 $last_anchor = $cl->{MergeBestAnchor};
1613 # Check for mismerges:
1615 my ($against, $allow, $what) = @_;
1616 my $differs = get_differs $build, $against;
1618 "merge misresolved: %s are not the same (%s %s d.%#x)",
1619 $what, $against, $build, $differs)
1620 if $differs & ~($allow | D_PAT_ADD);
1623 # Breakwater changes which were in each side of the
1624 # merge will have been incorporated into the
1625 # MergeCreateMergedBreakwaters output. Because the
1626 # upstream series was rebased onto the new breakwater,
1627 # so should all of the packaging changes which were in
1629 $check->($input, D_UPS, 'debian files');
1631 # Upstream files are merge_series, which ought to
1632 # have been identical to the original merge.
1633 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1635 print "Merge resolution successful.\n";
1638 confess "$method ?";
1641 my $procd = (pop @processed) // 'UNDEF';
1642 if ($cl ne $procd) {
1644 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1648 read_tree_upstream $want_upstream, 0, $want_debian;
1650 my $newtree = cmdoutput @git, qw(write-tree);
1651 my $ch = $cl->{Hdr};
1652 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1653 $ch =~ s{^parent .*\n}{}mg;
1654 $ch =~ s{(?=^author)}{
1655 join '', map { "parent $_\n" } @parents
1656 }me or confess "$ch ?";
1658 $ch =~ s{^committer .*$}{$committer_authline}m
1661 my $cf = "$rd/m$rewriting";
1662 open CD, ">", $cf or confess "$!";
1663 print CD $ch, "\n", $cl->{Msg} or confess "$!";
1664 close CD or confess "$!";
1665 my @cmd = (@git, qw(hash-object));
1666 push @cmd, qw(-w) if $rewriting;
1667 push @cmd, qw(-t commit), $cf;
1668 my $newcommit = cmdoutput @cmd;
1669 confess "$ch ?" unless $rewriting
1670 or $newcommit eq $cl->{CommitId};
1671 $build = $newcommit;
1673 $build = $cl->{CommitId};
1674 trees_diff_walk "$want_upstream:", "$build:", sub {
1676 no warnings qw(exiting);
1677 next if $n eq 'debian/';
1678 confess f_ "mismatch %s ?", "@_";
1680 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1681 confess f_ "mismatch %s ?", "@_";
1683 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1684 confess f_ "mismatch %s != %s ?", "@parents", "@old_parents"
1685 unless "@parents" eq "@old_parents";
1687 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1688 $last_anchor = $cur;
1693 my $final_check = get_differs $build, $input;
1694 confess f_ "internal error %#x %s %s", $final_check, $input, $build
1695 if $final_check & ~D_PAT_ADD;
1697 my @r = ($build, $breakwater, $last_anchor);
1698 printdebug "*** WALK RETURN @r\n";
1703 git_check_unmodified();
1704 return git_rev_parse qw(HEAD);
1707 sub update_head ($$$) {
1708 my ($old, $new, $mrest) = @_;
1709 push @deferred_updates, "update HEAD $new $old";
1710 run_deferred_updates $mrest;
1713 sub update_head_checkout ($$$) {
1714 my ($old, $new, $mrest) = @_;
1715 update_head $old, $new, $mrest;
1716 runcmd @git, qw(reset --hard);
1719 sub update_head_postlaunder ($$$) {
1720 my ($old, $tip, $reflogmsg) = @_;
1721 return if $tip eq $old && !@deferred_updates;
1722 print f_ "%s: laundered (head was %s)\n", $us, $old;
1723 update_head $old, $tip, $reflogmsg;
1724 # no tree changes except debian/patches
1725 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1728 sub currently_rebasing() {
1729 foreach (qw(rebase-merge rebase-apply)) {
1730 return 1 if stat_exists "$maindir_gitdir/$_";
1735 sub bail_if_rebasing() {
1736 fail __ "you are in the middle of a git-rebase already"
1737 if currently_rebasing();
1740 sub do_launder_head ($) {
1741 my ($reflogmsg) = @_;
1742 my $old = get_head();
1744 my ($tip,$breakwater) = walk $old;
1746 update_head_postlaunder $old, $tip, $reflogmsg;
1747 return ($tip,$breakwater);
1750 sub cmd_launder_v0 () {
1751 badusage "no arguments to launder-v0 allowed" if @ARGV;
1752 my $old = get_head();
1753 my ($tip,$breakwater,$last_anchor) = walk $old;
1754 update_head_postlaunder $old, $tip, 'launder';
1755 printf "# breakwater tip\n%s\n", $breakwater;
1756 printf "# working tip\n%s\n", $tip;
1757 printf "# last anchor\n%s\n", $last_anchor;
1760 sub defaultcmd_rebase () {
1761 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1762 my ($tip,$breakwater) = do_launder_head __ 'launder for rebase';
1763 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1766 sub cmd_analyse () {
1767 badusage __ "analyse does not support any options"
1768 if @ARGV and $ARGV[0] =~ m/^-/;
1769 badusage __ "too many arguments to analyse" if @ARGV>1;
1772 $old = git_rev_parse $old;
1774 $old = git_rev_parse 'HEAD';
1776 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1777 STDOUT->error and confess "$!";
1780 sub ffq_check ($;$$) {
1781 # calls $ff and/or $notff zero or more times
1782 # then returns either (status,message) where status is
1787 # or (undef,undef, $ffq_prev,$gdrlast)
1788 # $ff and $notff are called like this:
1789 # $ff->("message for stdout\n");
1790 # $notff->('snag-name', $message);
1791 # normally $currentval should be HEAD
1792 my ($currentval, $ff, $notff) =@_;
1794 $ff //= sub { print $_[0] or confess "$!"; };
1797 my ($status, $message, $current, $ffq_prev, $gdrlast)
1798 = ffq_prev_branchinfo();
1799 return ($status, $message) unless $status eq 'branch';
1801 my $exists = git_get_ref $ffq_prev;
1802 return ('exists', f_ "%s already exists", $ffq_prev) if $exists;
1804 return ('not-branch', __ 'HEAD symref is not to refs/heads/')
1805 unless $current =~ m{^refs/heads/};
1808 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1811 printdebug "ffq check_specs @check_specs\n";
1814 my ($lrref, $desc) = @_;
1815 printdebug "ffq might check $lrref ($desc)\n";
1817 for my $chk (@check_specs) {
1819 $invert = $glob =~ s{^[!^]}{};
1820 last if fnmatch $glob, $lrref;
1823 my $lrval = git_get_ref $lrref;
1824 return unless length $lrval;
1826 if (is_fast_fwd $lrval, $currentval) {
1827 $ff->(f_ "OK, you are ahead of %s\n", $lrref);
1828 $checked{$lrref} = 1;
1829 } elsif (is_fast_fwd $currentval, $lrval) {
1830 $checked{$lrref} = -1;
1831 $notff->('behind', f_ "you are behind %s, divergence risk",
1834 $checked{$lrref} = -1;
1835 $notff->('diverged', f_ "you have diverged from %s", $lrref);
1839 my $merge = cfg "branch.$branch.merge",1;
1840 if (defined $merge and $merge =~ m{^refs/heads/}) {
1842 printdebug "ffq merge $rhs\n";
1843 my $check_remote = sub {
1844 my ($remote, $desc) = @_;
1845 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1846 return unless defined $remote;
1847 $check->("refs/remotes/$remote/$rhs", $desc);
1849 $check_remote->((scalar cfg "branch.$branch.remote",1),
1850 'remote fetch/merge branch');
1851 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1852 (scalar cfg "branch.$branch.pushDefault",1),
1853 'remote push branch');
1855 if ($branch =~ m{^dgit/}) {
1856 $check->("refs/remotes/dgit/$branch",
1857 __ 'remote dgit branch');
1858 } elsif ($branch =~ m{^master$}) {
1859 $check->("refs/remotes/dgit/dgit/sid",
1860 __ 'remote dgit branch for sid');
1862 return (undef, undef, $ffq_prev, $gdrlast);
1865 sub record_ffq_prev_deferred () {
1866 # => ('status', "message")
1868 # deferred message is undef
1873 # if not ff from some branch we should be ff from, is an snag
1874 # if "deferred", will have added something about that to
1875 # @deferred_update_messages, and also maybe printed (already)
1876 # some messages about ff checks
1878 my $currentval = get_head();
1880 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1881 return ($status,$message) if defined $status;
1885 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1886 push @deferred_updates, "delete $gdrlast";
1887 push @deferred_update_messages,
1888 __ "Recorded previous head for preservation";
1889 return ('deferred', undef);
1892 sub record_ffq_auto () {
1893 my ($status, $message) = record_ffq_prev_deferred();
1894 if ($status eq 'deferred' || $status eq 'exists') {
1896 snag $status, f_ "could not record ffq-prev: %s", $message;
1901 sub ffq_prev_info () {
1903 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1904 my ($status, $message, $current, $ffq_prev, $gdrlast)
1905 = ffq_prev_branchinfo();
1906 if ($status ne 'branch') {
1907 snag $status, f_ "could not check ffq-prev: %s", $message;
1910 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1911 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1914 sub stitch ($$$$$) {
1915 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1917 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1919 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1920 my $differs = get_differs $old_head, $ffq_prev_commitish;
1921 unless ($differs & ~D_PAT_ADD) {
1922 # ffq-prev is ahead of us, and the only tree changes it has
1923 # are possibly addition of things in debian/patches/.
1924 # Just wind forwards rather than making a pointless pseudomerge.
1925 record_gdrlast $gdrlast, $ffq_prev_commitish;
1926 update_head_checkout $old_head, $ffq_prev_commitish,
1927 sprintf "stitch (%s)", __ 'fast forward';
1932 # We make pseudomerges with L as the contributing parent.
1933 # This makes git rev-list --first-parent work properly.
1934 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1935 # we translate this against the time when this same code is
1936 # used outside Debian, for downstreams and users
1937 (__ 'Declare fast forward / record previous work'),
1938 "[git-debrebase pseudomerge: $prose]",
1940 record_gdrlast $gdrlast, $new_head;
1941 update_head $old_head, $new_head, "stitch: $prose";
1944 sub do_stitch ($;$) {
1945 my ($prose, $unclean) = @_;
1947 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1948 if (!$ffq_prev_commitish) {
1949 fail __ "No ffq-prev to stitch." unless $opt_noop_ok;
1952 my $dangling_head = get_head();
1954 keycommits $dangling_head, $unclean,$unclean,$unclean;
1957 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1960 sub cmd_new_upstream () {
1961 # automatically and unconditionally launders before rebasing
1962 # if rebase --abort is used, laundering has still been done
1966 badusage __ "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1968 # parse args - low commitment
1969 my $spec_version = shift @ARGV;
1970 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1971 fail f_ "bad version number \`%s'", $spec_version
1972 unless defined $new_version;
1973 if ($new_version->is_native()) {
1974 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1977 my $new_upstream = shift @ARGV;
1978 my $new_upstream_version = upstreamversion $new_version;
1979 my $new_upstream_used;
1980 ($new_upstream, $new_upstream_used) =
1981 resolve_upstream_version $new_upstream, $new_upstream_version;
1986 my ($n, @x) = @_; # may be ''
1987 my $pc = $pieces{$n} //= {
1989 Desc => ($n ? (f_ "upstream piece \`%s'", $n)
1990 : (__ "upstream (main piece")),
1992 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1997 my $newpiece = sub {
1998 my ($n, @x) = @_; # may be ''
1999 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2000 push @newpieces, $pc;
2005 New => $new_upstream,
2007 while (@ARGV && $ARGV[0] !~ m{^-}) {
2008 my $n = shift @ARGV;
2010 badusage __ "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2011 unless @ARGV && $ARGV[0] !~ m{^-};
2013 my $c = git_rev_parse shift @ARGV;
2014 confess unless $n =~ m/^$extra_orig_namepart_re$/;
2015 $newpiece->($n, New => $c);
2018 # now we need to investigate the branch this generates the
2019 # laundered version but we don't switch to it yet
2020 my $old_head = get_head();
2021 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2023 my $old_bw_cl = classify $old_bw;
2024 my $old_anchor_cl = classify $old_anchor;
2026 if (!$old_anchor_cl->{OrigParents}) {
2027 snag 'anchor-treated',
2028 __ 'old anchor is recognised due to --anchor, cannot check upstream';
2030 $old_upstream = parsecommit
2031 $old_anchor_cl->{OrigParents}[0]{CommitId};
2032 $piece->('', Old => $old_upstream->{CommitId});
2035 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2036 if ($old_upstream->{Msg} =~
2037 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2039 my @oldpieces = (split / /, $1);
2040 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2041 if ($old_n_parents != @oldpieces &&
2042 $old_n_parents != @oldpieces + 1) {
2043 snag 'upstream-confusing', f_
2044 "previous upstream combine %s".
2045 " mentions %d pieces (each implying one parent)".
2046 " but has %d parents".
2047 " (one per piece plus maybe a previous combine)",
2048 $old_upstream->{CommitId},
2049 (scalar @oldpieces),
2051 } elsif ($oldpieces[0] ne '.') {
2052 snag 'upstream-confusing', f_
2053 "previous upstream combine %s".
2054 " first piece is not \`.'",
2058 foreach my $i (0..$#oldpieces) {
2059 my $n = $oldpieces[$i];
2060 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2061 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2065 snag 'upstream-confusing', f_
2066 "previous upstream %s is from".
2067 " git-debrebase but not an \`upstream-combine' commit",
2068 $old_upstream->{CommitId};
2072 foreach my $pc (values %pieces) {
2073 if (!$old_upstream) {
2074 # we have complained already
2075 } elsif (!$pc->{Old}) {
2076 snag 'upstream-new-piece',
2077 f_ "introducing upstream piece \`%s'", $pc->{Name};
2078 } elsif (!$pc->{New}) {
2079 snag 'upstream-rm-piece',
2080 f_ "dropping upstream piece \`%s'", $pc->{Name};
2081 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2082 snag 'upstream-not-ff',
2083 f_ "not fast forward: %s %s",
2084 $pc->{Name}, "$pc->{Old}..$pc->{New}";
2088 printdebug "%pieces = ", (dd \%pieces), "\n";
2089 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2097 my @upstream_merge_parents;
2100 push @upstream_merge_parents, $old_upstream->{CommitId};
2103 foreach my $pc (@newpieces) { # always has '' first
2105 read_tree_subdir $pc->{Name}, $pc->{New};
2107 runcmd @git, qw(read-tree), $pc->{New};
2109 push @upstream_merge_parents, $pc->{New};
2112 # index now contains the new upstream
2114 if (@newpieces > 1) {
2115 # need to make the upstream subtree merge commit
2116 $new_upstream = make_commit \@upstream_merge_parents,
2117 [ "Combine upstreams for $new_upstream_version",
2118 ("[git-debrebase upstream-combine . ".
2119 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2124 # $new_upstream is either the single upstream commit, or the
2125 # combined commit we just made. Either way it will be the
2126 # "upstream" parent of the anchor merge.
2128 read_tree_subdir 'debian', "$old_bw:debian";
2130 # index now contains the anchor merge contents
2131 $new_bw = make_commit [ $old_bw, $new_upstream ],
2132 [ "Update to upstream $new_upstream_version",
2133 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2136 # Now we have to add a changelog stanza so the Debian version
2137 # is right. We use debchange to do this. Invoking debchange
2138 # here is a bit fiddly because it has a lot of optional
2139 # exciting behaviours, some of which will break stuff, and
2140 # some of which won't work in a playtree.
2142 # Make debchange use git's idea of the user's identity.
2143 # That way, if the user never uses debchange et al, configuring
2148 defined $v or return;
2151 $usetup->('DEBEMAIL', 'user.email');
2152 $usetup->('DEBFULLNAME', 'user.name');
2154 my @dch = (qw(debchange
2155 --allow-lower-version .*
2158 --vendor=Unknown-Vendor
2159 --changelog debian/changelog
2160 --check-dirname-level 0
2161 --release-heuristic=changelog
2163 "Update to new upstream version $new_upstream_version.");
2165 runcmd @git, qw(checkout -q debian/changelog);
2167 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2169 # Now we have the final new breakwater branch in the index
2170 $new_bw = make_commit [ $new_bw ],
2171 [ "Update changelog for new upstream $new_upstream_version",
2172 "[git-debrebase changelog: new upstream $new_upstream_version]",
2176 # we have constructed the new breakwater. we now need to commit to
2177 # the laundering output, because git-rebase can't easily be made
2178 # to make a replay list which is based on some other branch
2180 update_head_postlaunder $old_head, $old_laundered_tip,
2181 'launder for new upstream';
2183 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2184 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2185 "debrebase new-upstream $new_version: rebase";
2187 # now it's for the user to sort out
2190 sub cmd_record_ffq_prev () {
2191 badusage "no arguments allowed" if @ARGV;
2192 my ($status, $msg) = record_ffq_prev_deferred();
2193 if ($status eq 'exists' && $opt_noop_ok) {
2194 print __ "Previous head already recorded\n" or confess "$!";
2195 } elsif ($status eq 'deferred') {
2196 run_deferred_updates 'record-ffq-prev';
2198 fail f_ "Could not preserve: %s", $msg;
2203 badusage __ "no arguments allowed" if @ARGV;
2204 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2205 print "$anchor\n" or confess "$!";
2208 sub cmd_breakwater () {
2209 badusage __ "no arguments allowed" if @ARGV;
2210 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2211 print "$bw\n" or confess "$!";
2215 badusage __ "no arguments allowed" if @ARGV;
2217 # todo: gdr status should print divergence info
2218 # todo: gdr status should print upstream component(s) info
2219 # todo: gdr should leave/maintain some refs with this kind of info ?
2221 my $oldest = { Badness => 0 };
2224 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2225 if ($oldest->{Badness} < $badness) {
2226 $oldest = $newest = undef;
2229 Badness => $badness,
2230 CommitId => $cl->{CommitId},
2234 $newest //= $oldest;
2236 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2237 sub { $note->(1, __ 'branch contains furniture (not laundered)',@_); },
2238 sub { $note->(2, __ 'branch is unlaundered', @_); },
2239 sub { $note->(3, __ 'branch needs laundering', @_); },
2240 sub { $note->(4, __ 'branch not in git-debrebase form', @_); };
2242 my $prcommitinfo = sub {
2244 flush STDOUT or confess "$!";
2245 runcmd @git, qw(--no-pager log -n1),
2246 '--pretty=format: %h %s%n',
2250 print __ "current branch contents, in git-debrebase terms:\n";
2251 if (!$oldest->{Badness}) {
2252 print __ " branch is laundered\n";
2254 print " $oldest->{OurMsg}\n";
2256 foreach my $info ($oldest, $newest) {
2257 my $cid = $info->{CommitId};
2258 next if $cid eq $printed;
2260 print " $info->{KcMsg}\n";
2261 $prcommitinfo->($cid);
2266 my ($cid, $what) = @_;
2267 if (!defined $cid) {
2268 print f_ " %s is not well-defined\n", $what;
2271 $prcommitinfo->($cid);
2274 print __ "key git-debrebase commits:\n";
2275 $prab->($anchor, __ 'anchor');
2276 $prab->($bw, __ 'breakwater');
2278 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2279 ffq_prev_branchinfo();
2281 print __ "branch and ref status, in git-debrebase terms:\n";
2283 print " $ffq_msg\n";
2285 $ffq_prev = git_get_ref $ffq_prev;
2286 $gdrlast = git_get_ref $gdrlast;
2288 print __ " unstitched; previous tip was:\n";
2289 $prcommitinfo->($ffq_prev);
2290 } elsif (!$gdrlast) {
2291 print __ " stitched? (no record of git-debrebase work)\n";
2292 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2293 print __ " stitched\n";
2295 print __ " not git-debrebase (diverged since last stitch)\n"
2298 print __ "you are currently rebasing\n" if currently_rebasing();
2302 my $prose = 'stitch';
2303 getoptions("stitch",
2304 'prose=s', \$prose);
2305 badusage __ "no arguments allowed" if @ARGV;
2306 do_stitch $prose, 0;
2308 sub cmd_prepush () {
2314 badusage __ "no arguments allowed" if @ARGV;
2315 do_launder_head __ 'launder for git-debrebase quick';
2319 sub cmd_conclude () {
2320 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2321 if (!$ffq_prev_commitish) {
2322 fail __ "No ongoing git-debrebase session." unless $opt_noop_ok;
2325 my $dangling_head = get_head();
2327 badusage "no arguments allowed" if @ARGV;
2328 do_launder_head __ 'launder for git-debrebase quick';
2333 if (currently_rebasing()) {
2334 runcmd @git, qw(rebase --abort);
2335 push @deferred_updates, 'verify HEAD HEAD';
2336 # noop, but stops us complaining that scrap was a noop
2338 badusage __ "no arguments allowed" if @ARGV;
2339 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2341 if ($ffq_prev_commitish) {
2342 $scrapping_head = get_head();
2343 push @deferred_updates,
2344 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2345 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2347 if (git_get_ref $merge_cache_ref) {
2348 push @deferred_updates,
2349 "delete $merge_cache_ref";
2351 if (!@deferred_updates) {
2352 fail __ "No ongoing git-debrebase session." unless $opt_noop_ok;
2356 if ($scrapping_head) {
2357 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2359 run_deferred_updates "scrap";
2363 sub make_patches_staged ($) {
2365 # Produces the patches that would result from $head if it were
2367 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2371 $any = gbp_pq_export 'bw', $secret_bw, $secret_head;
2376 sub make_patches ($) {
2378 keycommits $head, 0, \&snag;
2379 my $any = make_patches_staged $head;
2382 my $ptree = !$any ? undef :
2383 cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2384 runcmd @git, qw(read-tree), $head;
2386 read_tree_subdir 'debian/patches', $ptree;
2388 rm_subdir_cached 'debian/patches';
2390 $out = make_commit [$head], [
2391 (__ 'Commit patch queue (exported by git-debrebase)'),
2392 '[git-debrebase make-patches: export and commit patches]',
2398 sub cmd_make_patches () {
2399 my $opt_quiet_would_amend;
2400 getoptions("make-patches",
2401 'quiet-would-amend!', \$opt_quiet_would_amend);
2402 badusage __ "no arguments allowed" if @ARGV;
2404 my $old_head = get_head();
2405 my $new = make_patches $old_head;
2406 my $d = get_differs $old_head, $new;
2408 fail __ "No (more) patches to export." unless $opt_noop_ok;
2410 } elsif ($d == D_PAT_ADD) {
2412 update_head_checkout $old_head, $new, 'make-patches';
2414 print STDERR failmsg f_
2415 "Patch export produced patch amendments".
2416 " (abandoned output commit %s).".
2417 " Try laundering first.",
2419 unless $opt_quiet_would_amend;
2424 sub check_series_has_all_patches ($) {
2426 my $seriesfn = 'debian/patches/series';
2427 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2431 our $comments_snagged;
2432 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2433 if ($f =~ m/^\s*\#/) {
2434 snag 'series-comments', f_
2435 "%s contains comments, which will be discarded",
2437 unless $comments_snagged++;
2440 fail f_ "patch %s repeated in %s !", $f, $seriesfn if $series{$f}++;
2442 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2443 my ($f,$i) = @$patchfile;
2444 next if $series{$f};
2445 next if $f eq 'series';
2446 snag 'unused-patches', f_
2447 "Unused patch file %s will be discarded", $f;
2451 sub begin_convert_from () {
2452 my $head = get_head();
2453 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2455 fail __ "ffq-prev exists, this is already managed by git-debrebase!"
2456 if $ffq_prev && git_get_ref $ffq_prev;
2458 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2459 snag 'already-converted', __
2460 "ahead of debrebase-last, this is already managed by git-debrebase!"
2461 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2462 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2465 sub complete_convert_from ($$$$) {
2466 my ($old_head, $new_head, $gi, $mrest) = @_;
2467 ffq_check $new_head;
2468 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2471 update_head_checkout $old_head, $new_head, $mrest;
2474 sub cmd_convert_from_unapplied () { cmd_convert_from_gbp(); }
2475 sub cmd_convert_from_gbp () {
2476 badusage __ "want only 1 optional argument, the upstream git commitish"
2479 my $clogp = parsechangelog();
2480 my $version = $clogp->{'Version'}
2481 // fail __ "missing Version from changelog\n";
2483 my ($upstream_spec) = @ARGV;
2485 my $upstream_version = upstreamversion $version;
2486 my ($upstream, $upstream_used) =
2487 resolve_upstream_version($upstream_spec, $upstream_version);
2489 my ($old_head, $gdrlastinfo) = begin_convert_from();
2491 my $upsdiff = get_differs $upstream, $old_head;
2492 if ($upsdiff & D_UPS) {
2493 runcmd @git, qw(--no-pager diff --stat),
2494 $upstream, $old_head,
2495 qw( -- :!/debian :/);
2496 fail f_ <<END, $upstream_used, $upstream;
2497 upstream (%s) and HEAD are not
2498 identical in upstream files. See diffstat above, or run
2499 git diff %s HEAD -- :!/debian :/
2503 if (!is_fast_fwd $upstream, $old_head) {
2504 snag 'upstream-not-ancestor',
2505 f_ "upstream (%s) is not an ancestor of HEAD", $upstream;
2507 my $wrong = cmdoutput
2508 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2509 qw(-- :/ :!/debian));
2510 if (length $wrong) {
2511 snag 'unexpected-upstream-changes', f_
2512 "history between upstream (%s) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?",
2514 print STDERR f_ "list expected changes with: %s\n",
2515 "git log --stat --ancestry-path $upstream..HEAD -- :/ ':!/debian'";
2519 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2520 snag 'upstream-has-debian',
2521 f_ "upstream (%s) contains debian/ directory", $upstream;
2524 check_series_has_all_patches $old_head;
2526 my $previous_dgit_view = eval {
2527 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2529 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2530 my ($stz, $desc) = @_;
2531 no warnings qw(exiting);
2532 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2533 next unless $stz->{Date};
2534 next unless $stz->{Distribution} ne 'UNRELEASED';
2535 $lvsn = $stz->{Version};
2536 $suite = $stz->{Distribution};
2539 die __ "neither of the first two changelog entries are released\n"
2540 unless defined $lvsn;
2541 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2542 my $mtag_pat = debiantag_maintview $lvsn, '*';
2543 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2545 die f_ "could not find suitable maintainer view tag %s\n", $mtag_pat
2546 unless $mtag =~ m{/};
2547 is_fast_fwd $mtag, 'HEAD' or
2548 die f_ "HEAD is not FF from maintainer tag %s!", $mtag;
2549 my $dtag = "archive/$mtag";
2550 git_get_ref "refs/tags/$dtag" or
2551 die f_ "dgit view tag %s not found\n", $dtag;
2552 is_fast_fwd $mtag, $dtag or
2553 die f_ "dgit view tag %s is not FF from maintainer tag %s\n",
2555 print f_ "will stitch in dgit view, %s\n", $dtag;
2556 git_rev_parse $dtag;
2558 if (!$previous_dgit_view) {
2561 print STDERR f_ <<END, "$@";
2562 Cannot confirm dgit view: %s
2563 Failed to stitch in dgit view (see messages above).
2564 dgit --overwrite will be needed on the first dgit push after conversion.
2568 snags_maybe_bail_early();
2574 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2575 # make a branch out of the patch queue - we'll want this in a mo
2576 runcmd qw(gbp pq import);
2577 # strip the patches out
2578 runcmd @git, qw(checkout -q gdr-internal~0);
2579 rm_subdir_cached 'debian/patches';
2580 $work = make_commit ['HEAD'], [
2581 'git-debrebase convert-from-gbp: drop patches from tree',
2582 'Delete debian/patches, as part of converting to git-debrebase format.',
2583 '[git-debrebase convert-from-gbp: drop patches from tree]'
2585 # make the anchor merge
2586 # the tree is already exactly right
2587 $work = make_commit [$work, $upstream], [
2588 'git-debrebase import: declare upstream',
2589 'First breakwater merge.',
2590 '[git-debrebase anchor: declare upstream]'
2593 # rebase the patch queue onto the new breakwater
2594 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2595 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2596 $work = git_rev_parse 'HEAD';
2598 if ($previous_dgit_view) {
2599 $work = make_commit [$work, $previous_dgit_view], [
2600 'git-debrebase import: declare ff from dgit archive view',
2601 '[git-debrebase pseudomerge: import-from-gbp]',
2606 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2607 print f_ <<END, $us or confess "$!";
2608 %s: converted from patched-unapplied (gbp) branch format, OK
2612 sub cmd_convert_to_gbp () {
2613 badusage "no arguments allowed" if @ARGV;
2614 my $head = get_head();
2615 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2616 my ($anchor, $breakwater) = keycommits $head, 0;
2617 my $out = $breakwater;
2618 my $any = make_patches_staged $head;
2621 $out = make_commit [$out], [
2622 'Commit patch queue (converted from git-debrebase format)',
2623 '[git-debrebase convert-to-gbp: commit patches]',
2627 # in this case, it can be fast forward
2631 push @deferred_updates, "delete $ffq";
2632 push @deferred_updates, "delete $gdrlast";
2635 update_head_checkout $head, $out, "convert to gbp (v0)";
2636 print f_ <<END, $us,$us,$us or confess "$!";
2637 %s: converted to git-buildpackage branch format
2638 %s: WARNING: do not now run "git-debrebase" any more
2639 %s: WARNING: doing so would drop all upstream patches!
2643 sub cmd_convert_from_dgit_view () {
2644 my $clogp = parsechangelog();
2646 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2652 getoptions("convert-from-dgit-view",
2653 'diagnose!', \$diagnose,
2654 'build-products-dir:s', \$bpd,
2655 'origs!', \$do_origs,
2657 'always-convert-anyway!', \$always);
2658 fail __ "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2663 my $spec = shift @ARGV;
2664 my $commit = git_rev_parse "$spec^{commit}";
2665 push @upstreams, { Commit => $commit,
2666 Source => (f_ "%s, from command line", $spec),
2671 my ($head, $gdrlastinfo) = begin_convert_from();
2675 my $trouble = sub { $troubles++; };
2676 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2677 printdebug "troubles=$troubles\n";
2679 print STDERR f_ <<END, $us,$us,$us;
2680 %s: Branch already seems to be in git-debrebase format!
2681 %s: --always-convert-anyway would do the conversion operation anyway
2682 %s: but is probably a bad idea. Probably, you wanted to do nothing.
2684 fail __ "Branch already in git-debrebase format."
2685 unless $opt_noop_ok;
2690 check_series_has_all_patches $head;
2692 snags_maybe_bail_early();
2694 my $version = upstreamversion $clogp->{Version};
2696 "Considering possible commits corresponding to upstream:\n";
2701 my $ups_tag = upstream_commitish_search $version, \@tried;
2703 my $this = f_ "git tag %s", $tried[-1];
2704 push @upstreams, { Commit => $ups_tag,
2709 " git tag: no suitable tag found (tried %s)\n",
2714 my $p = $clogp->{'Source'};
2715 # we do a quick check to see if there are plausible origs
2717 if (!opendir BPD, $bpd) {
2718 die f_ "opendir build-products-dir %s: %s", $bpd, $!
2721 while ($!=0, my $f = readdir BPD) {
2722 next unless is_orig_file_of_p_v $f, $p, $version;
2724 " orig: found what looks like a .orig, %s\n",
2729 confess "read $bpd: $!" if $!;
2733 my $tree = cmdoutput
2734 @dgit, qw(--build-products-dir), $bpd,
2735 qw(print-unapplied-treeish);
2738 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2739 rm_subdir_cached 'debian';
2740 $tree = cmdoutput @git, qw(write-tree);
2741 my $ups_synth = make_commit [], [ <<END, <<END,
2742 Import effective orig tree for upstream version $version
2744 This includes the contents of the .orig(s), minus any debian/ directory.
2746 [git-debrebase convert-from-dgit-view upstream-import-convert: $version]
2749 push @upstreams, { Commit => $ups_synth,
2750 Source => "orig(s) imported via dgit",
2755 " orig: no suitable origs found (looked for %s in %s)\n",
2756 "${p}_".(stripeoch $version)."...", $bpd;
2761 my $some_patches = stat_exists 'debian/patches/series';
2764 "Evaluating possible commits corresponding to upstream:\n";
2767 foreach my $u (@upstreams) {
2771 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2772 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2773 runcmd @git, qw(clean -xdff);
2774 runcmd @git, qw(checkout), $head, qw(-- debian);
2775 if ($some_patches) {
2776 rm_subdir_cached 'debian/patches';
2777 $work = make_commit [ $work ], [
2778 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2779 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2780 "to git-debrebase format. Upstream changes will appear as commits.",
2781 '[git-debrebase convert-from-dgit-view drop-patches]'
2784 $work = make_commit [ $work, $u->{Commit} ], [
2785 'git-debrebase convert-from-dgit-view: declare upstream',
2786 '(Re)constructed breakwater merge.',
2787 '[git-debrebase anchor: declare upstream]'
2789 runcmd @git, qw(checkout --quiet -b mk), $work;
2790 if ($some_patches) {
2791 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2792 runcmd @git, qw(reset --quiet);
2793 my @gbp_cmd = (qw(gbp pq import));
2795 my $gbp_err = "../gbp-pq-err";
2796 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2798 my $r = system @gbp_cmd;
2801 " %s: couldn't apply patches: gbp pq %s",
2802 $u->{Source}, waitstatusmsg();
2806 my $work = git_rev_parse qw(HEAD);
2807 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2808 if (length $diffout) {
2810 " %s: applying patches gives different tree\n",
2812 print STDERR $diffout if $diagnose;
2816 $u->{Result} = $work;
2824 Could not find or construct a suitable upstream commit.
2825 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2826 upstream commmit explicitly or provide suitable origs.
2830 print STDERR f_ "Yes, will base new branch on %s\n", $result->{Source};
2832 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2833 'convert-from-dgit-view';
2836 sub cmd_forget_was_ever_debrebase () {
2837 badusage __ "forget-was-ever-debrebase takes no further arguments"
2839 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2840 ffq_prev_branchinfo();
2841 fail f_ "Not suitable for recording git-debrebaseness anyway: %s",
2843 if defined $ffq_msg;
2844 push @deferred_updates, "delete $ffq_prev";
2845 push @deferred_updates, "delete $gdrlast";
2847 run_deferred_updates "forget-was-ever-debrebase";
2850 sub cmd_record_resolved_merge () {
2851 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2852 # MERGE-TODO needs documentation
2853 my $new = get_head();
2856 print "Checking how you have resolved the merge problem\n";
2857 my $nope = sub { print "Not $method: @_"; 0; };
2859 my $maybe = sub { print "Seems to be $method.\n"; };
2861 my ($key, $ref) = @_;
2862 reflog_cache_insert $merge_cache_ref, $key, $ref;
2863 print "OK. You can switch branches and try git-debrebase again.\n";
2867 fresh_workarea 'merge';
2869 $method = 'vanilla-merge patchqueue';
2870 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2871 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2872 foreach my $lr (qw(left right)) {
2873 my $n = "$wrecknoteprefix/$lr-patchqueue";
2874 my $lrpq = git_get_ref $n;
2875 $lrpq or return $nope->("wreckage did not contain patchqueues");
2876 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2879 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2880 or die "wreckage element $wrecknoteprefix/new-base missing";
2881 my $result = merge_series_patchqueue_convert
2883 $yes->("vanilla-merge $vanilla", $result);
2886 fail "No resolved merge method seems applicable.\n";
2890 sub cmd_downstream_rebase_launder_v0 () {
2891 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2893 $base = git_rev_parse $base;
2894 my $old_head = get_head();
2895 my $current = $old_head;
2898 if ($current eq $base) {
2899 $topmost_keep //= $current;
2900 print " $current BASE stop\n";
2903 my $cl = classify $current;
2904 print " $current $cl->{Type}";
2906 my $p0 = $cl->{Parents}[0]{CommitId};
2908 if ($cl->{Type} eq 'Pseudomerge') {
2909 print " ^".($cl->{Contributor}{Ix}+1);
2910 $next = $cl->{Contributor}{CommitId};
2911 } elsif ($cl->{Type} eq 'AddPatches' or
2912 $cl->{Type} eq 'Changelog') {
2922 $topmost_keep //= $current;
2924 die "to-be stripped changes not on top of the branch\n"
2929 if ($topmost_keep eq $old_head) {
2930 print "unchanged\n";
2932 print "updating to $topmost_keep\n";
2933 update_head_checkout
2934 $old_head, $topmost_keep,
2935 'downstream-rebase-launder-v0';
2939 setlocale(LC_MESSAGES, "");
2940 textdomain("git-debrebase");
2943 (__ "bad options\n",
2944 "D+" => \$debuglevel,
2945 'noop-ok', => \$opt_noop_ok,
2946 'f=s' => \@snag_force_opts,
2947 'anchor=s' => \@opt_anchors,
2948 '--dgit=s' => \($dgit[0]),
2950 'experimental-merge-resolution!', \$opt_merges,
2952 my ($opt,$val) = @_;
2953 badusage f_ "%s: no cuddling to -i for git-rebase", $us
2955 confess if $opt_defaultcmd_interactive; # should not happen
2956 $opt_defaultcmd_interactive = [ qw(-i) ];
2957 # This access to @ARGV is excessive familiarity with
2958 # Getopt::Long, but there isn't another sensible
2959 # approach. '-i=s{0,}' does not work with bundling.
2960 push @$opt_defaultcmd_interactive, @ARGV;
2963 'help' => sub { print __ $usage_message or confess "$!"; finish 0; },
2966 initdebug('git-debrebase ');
2967 enabledebug if $debuglevel;
2969 changedir_git_toplevel();
2971 $rd = fresh_playground "$playprefix/misc";
2973 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2975 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2976 defaultcmd_rebase();
2978 my $cmd = shift @ARGV;
2981 $cmdfn = ${*::}{"cmd_$cmdfn"};
2983 $cmdfn or badusage f_ "unknown git-debrebase sub-operation %s", $cmd;