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-* ...
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 make_commit ($$) {
359 my ($parents, $message_paras) = @_;
360 my $tree = cmdoutput @git, qw(write-tree);
361 my @cmd = (@git, qw(commit-tree), $tree);
362 push @cmd, qw(-p), $_ foreach @$parents;
363 push @cmd, qw(-m), $_ foreach @$message_paras;
364 return cmdoutput @cmd;
367 our @snag_force_opts;
369 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
370 if (grep { $_ eq $tag } @snag_force_opts) {
372 print STDERR f_ "%s: snag ignored (-f%s): %s\n", $us, $tag, $msg;
375 print STDERR f_ "%s: snag detected (-f%s): %s\n", $us, $tag, $msg;
379 # Important: all mainline code must call snags_maybe_bail after
380 # any point where snag might be called, but before making changes
381 # (eg before any call to run_deferred_updates). snags_maybe_bail
382 # may be called more than once if necessary (but this is not ideal
383 # because then the messages about number of snags may be confusing).
384 sub snags_maybe_bail () {
385 return if all_snags_summarised();
388 "%s: snags: %d overriden by individual -f options\n",
391 if ($snags_tripped) {
394 "%s: snags: %d overriden by global --force\n",
398 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
402 $snags_summarised = $snags_forced + $snags_tripped;
404 sub snags_maybe_bail_early () {
405 # useful to bail out early without doing a lot of work;
406 # not a substitute for snags_maybe_bail.
407 snags_maybe_bail() if $snags_tripped && !$opt_force;
410 return $snags_forced || $snags_tripped;
413 sub ffq_prev_branchinfo () {
414 my $current = git_get_symref();
415 return gdr_ffq_prev_branchinfo($current);
418 sub record_gdrlast ($$;$) {
419 my ($gdrlast, $newvalue, $oldvalue) = @_;
420 $oldvalue ||= $git_null_obj;
421 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
424 sub fail_unprocessable ($) {
427 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
429 my $mangled = __ <<END;
430 Branch/history seems mangled - no longer in gdr format.
431 See ILLEGAL OPERATIONS in git-debrebase(5).
436 fail f_ <<END, $msg, $ffqm;
438 Is this meant to be a gdr branch? %s
440 } elsif (git_get_ref $ffq_prev) {
441 fail f_ <<END, $msg, $mangled;
444 Consider git-debrebase scrap, to throw away your recent work.
446 } elsif (!git_get_ref $gdrlast) {
449 Branch does not seem to be meant to be a git-debrebase branch?
450 Wrong branch, or maybe you needed git-debrebase convert-from-*.
452 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
460 Branch/history mangled, and diverged since last git-debrebase.
461 Maybe you reset to, or rebased from, somewhere inappropriate.
466 sub gbp_pq_export ($$$) {
467 my ($bname, $base, $tip) = @_;
468 # must be run in a workarea. $bname and patch-queue/$bname
469 # ought not to exist. Leaves you on patch-queue/$bname with
470 # the patches staged but not committed.
471 # returns 1 if there were any patches
472 printdebug "gbp_pq_export $bname $base $tip\n";
473 runcmd @git, qw(checkout -q -b), $bname, $base;
474 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
475 my @gbp_cmd = (qw(gbp pq export));
476 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
478 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
481 return 0 unless stat_exists 'debian/patches';
482 runcmd @git, qw(add -f debian/patches);
487 # MERGE-TODO allow merge resolution separately from laundering, before git merge
490 # use git-format-patch?
491 # our own patch identification algorithm?
492 # this is an alternative strategy
494 sub merge_failed ($$;@) {
495 my ($wrecknotes, $emsg, @xmsgs) = @_;
497 push @m, "Merge resolution failed: $emsg";
503 merge_wreckage_cleaning \@updates;
504 run_ref_updates_now "merge failed", \@updates;
508 while (my ($k,$v) = each %$wrecknotes) {
509 push @updates, "create $wrecknoteprefix/$k $v";
511 run_ref_updates_now "merge failed", \@updates;
512 push @m, "Wreckage left in $wrecknoteprefix/*.";
514 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
516 # use finish rather than fail, in case we are within an eval
517 # (that can happen inside walk!)
519 print STDERR "$us: $_\n" foreach @m;
523 sub mwrecknote ($$$) {
524 my ($wrecknotes, $reftail, $commitish) = @_;
525 confess unless defined $commitish;
526 printdebug "mwrecknote $reftail $commitish\n";
527 $wrecknotes->{$reftail} = $commitish;
530 sub merge_attempt_cmd {
531 my $wrecknotes = shift @_;
535 merge_failed $wrecknotes,
536 failedcmd_waitstatus(),
537 "failed command: @_";
541 sub merge_series_patchqueue_convert ($$$);
543 sub merge_series ($$$;@) {
544 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
545 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
546 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
547 # ^ specifies several patch series (currently we only support exactly 2)
548 # return value is a commit which is the result of
549 # merging the two versions of the same topic branch
550 # $input_q[0] and $input_q[1]
551 # with respect to the old version
555 # Creates, in *_q, a key MR for its private use
557 printdebug "merge_series newbase=$newbase\n";
559 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
560 $base_q->{MR}{S} = 'base';
563 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
564 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
565 # $prereq{<patch filename>} exists or not (even later)
569 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
571 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
574 fresh_workarea "merge";
575 my $seriesfile = "debian/patches/series";
578 foreach my $q ($base_q, reverse @input_qs) {
580 my $any = gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
583 open S, $seriesfile or confess "$seriesfile $!";
584 while (my $patch = <S>) {
585 chomp $patch or confess "$!";
586 $prereq{$patch} //= {};
587 foreach my $earlier (@earlier) {
588 $prereq{$patch}{$earlier}{$s}++ and confess;
590 push @earlier, $patch;
591 stat "debian/patches/$patch" or confess "$patch ?";
593 S->error and confess "$seriesfile $!";
596 read_tree_upstream $newbase, 1;
597 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
598 "Convert $s to patch queue for merging",
599 "[git-debrebase merge-innards patch-queue import:".
602 printdebug "merge_series pec $pec ";
603 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
604 $pec = make_commit [ $pec ], [
605 "Drop series file from $s to avoid merge trouble",
606 "[git-debrebase merge-innards patch-queue prep:".
610 read_tree_debian $newbase;
612 read_tree_subdir 'debian/patches', "$pec:debian/patches";
614 rm_subdir_cached 'debian/patches';
616 $pec = make_commit [ $pec ], [
617 "Update debian/ (excluding patches) to final to avoid re-merging",
618 "debian/ was already merged and we need to just take that.",
619 "[git-debrebase merge-innards patch-queue packaging:".
623 printdebug "pec' $pec\n";
624 runcmd @git, qw(reset -q --hard), $pec;
625 $q->{MR}{PEC} = $pec;
626 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
628 # now, because of reverse, we are on $input_q->{MR}{OQC}
629 runcmd @git, qw(checkout -q -b merge);
630 printdebug "merge_series merging...\n";
631 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
633 $attempt_cmd->(@mergecmd);
635 printdebug "merge_series merge ok, series...\n";
636 # We need to construct a new series file
637 # Firstly, resolve prereq
638 foreach my $f (sort keys %prereq) {
639 printdebug "merge_series patch\t$f\t";
640 if (!stat_exists "debian/patches/$f") {
641 print DEBUG " drop\n" if $debuglevel;
642 # git merge deleted it; that's how we tell it's not wanted
646 print DEBUG " keep\n" if $debuglevel;
647 foreach my $g (sort keys %{ $prereq{$f} }) {
648 my $gfp = $prereq{$f}{$g};
649 printdebug "merge_series prereq\t$f\t-> $g\t";
650 if (!!$gfp->{0} == !!$gfp->{1}
653 print DEBUG "\tkeep\n" if $debuglevel;
655 print DEBUG "\tdrop\n" if $debuglevel;
656 delete $prereq{$f}{$g};
663 return scalar keys %{ $prereq{$f} };
666 my $nodate = time + 1;
668 # $authordate{<patch filename>};
669 my $authordate = sub {
671 $authordate{$f} //= do {
672 open PF, "<", "debian/patches/$f" or confess "$f $!";
674 return $nodate if m/^$/;
675 last if s{^Date: }{};
678 return cmdoutput qw(date +%s -d), $_;
682 open NS, '>', $seriesfile or confess "$!";
684 while (keys %prereq) {
686 foreach my $try (sort keys %prereq) {
689 $unsat->($try) <=> $unsat->($best) or
690 $authordate->($try) <=> $authordate->($best) or
696 printdebug "merge_series series next $best\n";
697 print NS "$best\n" or confess "$!";
698 delete $prereq{$best};
699 foreach my $gp (values %prereq) {
704 runcmd @git, qw(add), $seriesfile;
705 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
706 $merged_pq = git_rev_parse 'HEAD';
707 $mwrecknote->('merged-patchqueue', $merged_pq);
709 return merge_series_patchqueue_convert
710 $wrecknotes, $newbase, $merged_pq;
713 sub merge_series_patchqueue_convert ($$$) {
714 my ($wrecknotes, $newbase, $merged_pq) = @_;
719 printdebug "merge_series series gbp pq import\n";
720 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
722 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
723 # MERGE-TODO consider git-format-patch etc. instead,
724 # since gbp pq doesn't always round-trip :-/
726 # OK now we are on patch-queue/merge, and we need to rebase
727 # onto the intended parent and drop the patches from each one
729 printdebug "merge_series series ok, building...\n";
730 my $build = $newbase;
731 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
732 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
733 my $commit = git_cat_file $c, 'commit';
734 printdebug "merge_series series ok, building $c\n";
735 read_tree_upstream $c, 0, $newbase;
736 my $tree = cmdoutput @git, qw(write-tree);
737 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
738 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
739 open C, ">", "../mcommit" or confess "$!";
740 print C $commit or confess "$!";
741 close C or confess "$!";
742 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
745 mwrecknote($wrecknotes, 'merged-result', $result);
747 runcmd @git, qw(update-ref refs/heads/result), $result;
749 runcmd @git, qw(checkout -q -b debug);
750 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
751 runcmd @git, qw(add .);
752 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
753 my $mdebug = git_rev_parse 'HEAD';
754 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
755 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
757 printdebug "merge_series returns $result\n";
761 # classify returns an info hash like this
763 # Hdr => # commit headers, including 1 final newline
764 # Msg => # commit message (so one newline is dropped)
766 # Type => (see below)
768 # Ix => $index # ie 0, 1, 2, ...
770 # Differs => return value from get_differs
772 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
774 # NewMsg => # commit message, but with any [dgit import ...] edited
775 # # to say "[was: ...]"
785 # has additional entres in classification result
786 # Overwritten = [ subset of Parents ]
787 # Contributor = $the_remaining_Parent
789 # DgitImportUnpatched
790 # has additional entry in classification result
791 # OrigParents = [ subset of Parents ]
794 # has additional entry in classification result
795 # OrigParents = [ subset of Parents ] # singleton list
802 # has additional entry in classification result
805 sub parsecommit ($;$) {
806 my ($objid, $p_ref) = @_;
807 # => hash with CommitId Hdr Msg Tree Parents
808 # Parents entries have only Ix CommitId
809 # $p_ref, if provided, must be [] and is used as a base for Parents
814 my ($h,$m) = get_commit $objid;
816 my ($t) = $h =~ m/^tree (\w+)$/m or confess $objid;
817 my (@ph) = $h =~ m/^parent (\w+)$/mg;
827 foreach my $ph (@ph) {
829 Ix => scalar @$p_ref,
841 my $r = parsecommit($objid, \@p);
845 $p->{Differs} = (get_differs $p->{CommitId}, $t),
848 printdebug "classify $objid \$t=$t \@p",
849 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
853 my ($type, @rest) = @_;
854 $r = { %$r, Type => $type, @rest };
856 printdebug " = $type ".(dd $r)."\n";
862 $r = { %$r, Type => qw(Unknown), Why => $why };
863 printdebug " ** Unknown\n";
867 if (grep { $_ eq $objid } @opt_anchors) {
868 return $classify->('TreatAsAnchor');
871 my @identical = grep { !$_->{Differs} } @p;
872 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
873 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
875 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
876 # multi-orig upstreams are represented with an anchor merge
877 # from a single upstream commit which combines the orig tarballs
879 # Every anchor tagged this way must be a merge.
880 # We are relying on the
881 # [git-debrebase anchor: ...]
882 # commit message annotation in "declare" anchor merges (which
883 # do not have any upstream changes), to distinguish those
884 # anchor merges from ordinary pseudomerges (which we might
885 # just try to strip).
887 # However, the user is going to be doing git-rebase a lot. We
888 # really don't want them to rewrite an anchor commit.
889 # git-rebase trips up on merges, so that is a useful safety
892 # BreakwaterStart commits are also anchors in the terminology
893 # of git-debrebase(5), but they are untagged (and always
894 # manually generated).
896 # We cannot not tolerate any tagged linear commit (ie,
897 # BreakwaterStart commits tagged `[anchor:') because such a
898 # thing could result from an erroneous linearising raw git
899 # rebase of a merge anchor. That would represent a corruption
900 # of the branch. and we want to detect and reject the results
901 # of such corruption before it makes it out anywhere. If we
902 # reject it here then we avoid making the pseudomerge which
903 # would be needed to push it.
905 my $badanchor = sub {
906 $unknown->(f_ "git-debrebase \`anchor' but %s", "@_");
908 @p == 2 or return $badanchor->(__ "has other than two parents");
909 $haspatches and return $badanchor->(__ "contains debian/patches");
911 # How to decide about l/r ordering of anchors ? git
912 # --topo-order prefers to expand 2nd parent first. There's
913 # already an easy rune to look for debian/ history anyway (git log
914 # debian/) so debian breakwater branch should be 1st parent; that
915 # way also there's also an easy rune to look for the upstream
916 # patches (--topo-order).
918 # Also this makes --first-parent be slightly more likely to
919 # be useful - it makes it provide a linearised breakwater history.
921 # Of course one can say somthing like
922 # gitk -- ':/' ':!/debian'
923 # to get _just_ the commits touching upstream files, and by
924 # the TREESAME logic in git-rev-list this will leave the
925 # breakwater into upstream at the first anchor. But that
926 # doesn't report debian/ changes at all.
928 # Other observations about gitk: by default, gitk seems to
929 # produce output in a different order to git-rev-list. I
930 # can't seem to find this documented anywhere. gitk
931 # --date-order DTRT. But, gitk always seems to put the
932 # parents from left to right, in order, so it's easy to see
933 # which way round a pseudomerge is.
935 $p[0]{IsOrigin} and $badanchor->(__ "is an origin commit");
936 $p[1]{Differs} & ~DS_DEB and
937 $badanchor->(__ "upstream files differ from left parent");
938 $p[0]{Differs} & ~D_UPS and
939 $badanchor->(__ "debian/ differs from right parent");
941 return $classify->(qw(Anchor),
942 OrigParents => [ $p[1] ]);
946 my $d = $r->{Parents}[0]{Differs};
947 if ($d == D_PAT_ADD) {
948 return $classify->(qw(AddPatches));
949 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
950 return $unknown->(__ "edits debian/patches");
951 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
952 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
954 if ($d == D_DEB_CLOG) {
955 return $classify->(qw(Changelog));
957 return $classify->(qw(Packaging));
959 } elsif ($ty eq 'missing') {
960 return $classify->(qw(BreakwaterStart));
962 return $unknown->(__ "parent's debian is not a directory");
964 } elsif ($d == D_UPS) {
965 return $classify->(qw(Upstream));
966 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
967 return $classify->(qw(Mixed));
969 return $unknown->(__ "no changes");
971 confess "internal error $objid ?";
975 return $unknown->(__ "origin commit");
978 if (@p == 2 && @identical == 1) {
979 my @overwritten = grep { $_->{Differs} } @p;
980 confess "internal error $objid ?" unless @overwritten==1;
981 return $classify->(qw(Pseudomerge),
982 Overwritten => [ $overwritten[0] ],
983 Contributor => $identical[0]);
985 if (@p == 2 && @identical == 2) {
987 my ($ph,$pm) = get_commit $_[0]{CommitId};
988 $ph =~ m/^committer .* (\d+) [-+]\d+$/m
989 or confess "$_->{CommitId} ?";
993 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
994 if ($order > 0) { # newer first
995 } elsif ($order < 0) {
996 @bytime = reverse @bytime;
998 # same age, default to order made by -s ours
999 # that is, commit was made by someone who preferred L
1001 return $classify->(qw(Pseudomerge),
1002 SubType => qw(Ambiguous),
1003 Contributor => $bytime[0],
1004 Overwritten => [ $bytime[1] ]);
1006 foreach my $p (@p) {
1007 my ($p_h, $p_m) = get_commit $p->{CommitId};
1008 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1009 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1011 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1013 if (!(grep { !$_->{IsOrigin} } @p) and
1014 (@orig_ps >= @p - 1) and
1015 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1017 return $classify->(qw(DgitImportUnpatched),
1018 OrigParents => \@orig_ps);
1022 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1023 return $classify->("MergedBreakwaters");
1025 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1026 return $unknown->(f_ "unknown kind of merge from %s", $1);
1029 return $unknown->(__ "octopus merge");
1033 return $unknown->(__ "general two-parent merge");
1036 return $classify->("VanillaMerge");
1039 sub keycommits ($;$$$$$);
1041 sub mergedbreakwaters_anchor ($) {
1044 foreach my $p (@{ $cl->{Parents} }) {
1045 my ($panchor, $pbw) = keycommits $p->{CommitId},
1046 undef,undef,undef,undef, 1;
1047 $best_anchor = $panchor
1048 if !defined $best_anchor
1049 or is_fast_fwd $best_anchor, $panchor;
1050 fail f_ "inconsistent anchors in merged-breakwaters %s",
1052 unless is_fast_fwd $panchor, $best_anchor;
1054 return $best_anchor;
1057 sub keycommits ($;$$$$$) {
1058 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1059 # => ($anchor, $breakwater)
1061 # $furniture->("unclean-$tagsfx", $msg, $cl)
1062 # $unclean->("unclean-$tagsfx", $msg, $cl)
1063 # is callled for each situation or commit that
1064 # wouldn't be found in a laundered branch
1065 # $furniture is for furniture commits such as might be found on an
1066 # interchange branch (pseudomerge, d/patches, changelog)
1067 # $trouble is for things whnich prevent the return of
1068 # anchor and breakwater information; if that is ignored,
1069 # then keycommits returns (undef, undef) instead.
1070 # $fatal is for unprocessable commits, and should normally cause
1071 # a failure. If ignored, agaion, (undef, undef) is returned.
1073 # If $claimed_bw, this is supposed to be a breakwater commit.
1075 # If a callback is undef, fail is called instead.
1076 # If a callback is defined but false, the situation is ignored.
1077 # Callbacks may say:
1078 # no warnings qw(exiting); last;
1079 # if the answer is no longer wanted.
1081 my ($anchor, $breakwater);
1082 $breakwater = $head if $claimed_bw;
1086 $fatal //= sub { fail_unprocessable $_[1]; };
1088 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1089 my $why = $mainwhy.$xwhy;
1090 my $m = f_ "branch needs laundering (run git-debrebase): %s", $why;
1091 fail $m unless defined $cb;
1093 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1095 my $found_anchor = sub {
1097 $breakwater //= $clogonly;
1098 $breakwater //= $head;
1099 no warnings qw(exiting);
1103 $cl = classify $head;
1104 my $ty = $cl->{Type};
1105 if ($ty eq 'Packaging') {
1106 $breakwater //= $clogonly;
1107 $breakwater //= $head;
1108 } elsif ($ty eq 'Changelog') {
1109 # this is going to count as the tip of the breakwater
1110 # only if it has no upstream stuff before it
1111 $clogonly //= $head;
1112 } elsif ($ty eq 'Anchor' or
1113 $ty eq 'TreatAsAnchor' or
1114 $ty eq 'BreakwaterStart') {
1115 $found_anchor->($head);
1116 } elsif ($ty eq 'Upstream') {
1117 $x->($unclean, 'ordering',
1118 (f_ "packaging change (%s) follows upstream change", $breakwater),
1119 (f_ " (eg %s)", $head))
1120 if defined $breakwater;
1122 $breakwater = undef;
1123 } elsif ($ty eq 'Mixed') {
1124 $x->($unclean, 'mixed',
1125 (__ "found mixed upstream/packaging commit"),
1126 (f_ " (%s)", $head));
1128 $breakwater = undef;
1129 } elsif ($ty eq 'Pseudomerge' or
1130 $ty eq 'AddPatches') {
1132 $x->($furniture, (lc $ty),
1133 (f_ "found interchange bureaucracy commit (%s)", $ty),
1134 (f_ " (%s)", $head));
1135 } elsif ($ty eq 'DgitImportUnpatched') {
1137 $x->($trouble, 'dgitimport',
1138 (__ "found dgit dsc import"),
1139 (f_ " (%s)", $head));
1140 return (undef,undef);
1142 $x->($fatal, 'unprocessable',
1143 (__ "found bare dgit dsc import with no prior history"),
1144 (f_ " (%s)", $head));
1145 return (undef,undef);
1147 } elsif ($ty eq 'VanillaMerge') {
1148 $x->($trouble, 'vanillamerge',
1149 (__ "found vanilla merge"),
1150 (f_ " (%s)", $head));
1151 return (undef,undef);
1152 } elsif ($ty eq 'MergedBreakwaters') {
1153 $found_anchor->(mergedbreakwaters_anchor $cl);
1155 $x->($fatal, 'unprocessable',
1156 (f_ "found unprocessable commit, cannot cope: %s",
1158 (f_ " (%s)", $head));
1159 return (undef,undef);
1161 $head = $cl->{Parents}[0]{CommitId};
1163 return ($anchor, $breakwater);
1169 $nogenerate,$report, $report_lprefix) = @_;
1170 # => ($tip, $breakwater_tip, $last_anchor)
1171 # (or nothing, if $nogenerate)
1173 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1174 $report_lprefix //= '';
1176 # go through commits backwards
1177 # we generate two lists of commits to apply:
1178 # breakwater branch and upstream patches
1179 my (@brw_cl, @upp_cl, @processed);
1186 my ($prose, $info) = @_;
1187 # We deliberately do not translate $prose, since this mostly
1188 # appears in commits in Debian and they should be in English.
1189 my $ms = $cl->{Msg};
1191 confess unless defined $info;
1192 $ms .= "\n\n[git-debrebase $info: $prose]\n";
1193 return (Msg => $ms);
1195 my $rewrite_from_here = sub {
1197 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1199 push @processed, $sp_cl;
1204 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1207 return unless $report;
1208 print $report $prdelim, $report_lprefix, @_;
1212 my $bomb = sub { # usage: return $bomb->();
1213 print $report " Unprocessable" if $report;
1214 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1217 return (undef,undef);
1221 map { sprintf "%#x", $_->{Differs} }
1222 @{ $cl->{Parents} };
1223 fail_unprocessable f_ +(defined $cl->{Why}
1224 ? i_ 'found unprocessable commit, cannot cope; %3$s: (commit %1$s) (d.%2$s)'
1225 : i_ 'found unprocessable commit, cannot cope: (commit %1$s) (d.%2$s)'),
1226 $cur, $d, $cl->{Why};
1232 my $build_start = sub {
1233 my ($msg, $parent) = @_;
1236 no warnings qw(exiting); last;
1241 merge_failed $cl->{MergeWreckNotes}, $emsg;
1244 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1249 $cl = classify $cur;
1250 $cl->{MergeWreckNotes} //= {};
1251 my $ty = $cl->{Type};
1252 my $st = $cl->{SubType};
1253 $prline->("$cl->{CommitId} $cl->{Type}");
1254 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1255 push @processed, $cl;
1256 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1257 if ($ty eq 'AddPatches') {
1259 $rewrite_from_here->(\@upp_cl);
1261 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1265 } elsif ($ty eq 'BreakwaterStart') {
1266 $last_anchor = $cur;
1267 $build_start->('FirstPackaging', $cur);
1268 } elsif ($ty eq 'Upstream') {
1272 } elsif ($ty eq 'Mixed') {
1275 my $cls = { %$cl, $xmsg->("mixed commit: $wh part",'split') };
1278 $queue->(\@brw_cl, "debian");
1279 $queue->(\@upp_cl, "upstream");
1280 $rewrite_from_here->(\@brw_cl);
1283 } elsif ($ty eq 'Pseudomerge') {
1284 my $contrib = $cl->{Contributor}{CommitId};
1285 print $report " Contributor=$contrib" if $report;
1286 push @pseudomerges, $cl;
1287 $rewrite_from_here->(\@upp_cl);
1290 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1291 $last_anchor = $cur;
1292 $build_start->("Anchor", $cur);
1293 } elsif ($ty eq 'DgitImportUnpatched') {
1294 my $pm = $pseudomerges[-1];
1296 # To an extent, this is heuristic. Imports don't have
1297 # a useful history of the debian/ branch. We assume
1298 # that the first pseudomerge after an import has a
1299 # useful history of debian/, and ignore the histories
1300 # from later pseudomerges. Often the first pseudomerge
1301 # will be the dgit import of the upload to the actual
1302 # suite intended by the non-dgit NMUer, and later
1303 # pseudomerges may represent in-archive copies.
1304 my $ovwrs = $pm->{Overwritten};
1305 printf $report " PM=%s \@Overwr:%d",
1306 $pm->{CommitId}, (scalar @$ovwrs)
1309 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1312 my $ovwr = $ovwrs->[0]{CommitId};
1313 printf $report " Overwr=%s", $ovwr if $report;
1314 # This import has a tree which is just like a
1315 # breakwater tree, but it has the wrong history. It
1316 # ought to have the previous breakwater (which the
1317 # pseudomerge overwrote) as an ancestor. That will
1318 # make the history of the debian/ files correct. As
1319 # for the upstream version: either it's the same as
1320 # was ovewritten (ie, same as the previous
1321 # breakwater), in which case that history is precisely
1322 # right; or, otherwise, it was a non-gitish upload of a
1323 # new upstream version. We can tell these apart by
1324 # looking at the tree of the supposed upstream.
1327 SpecialMethod => 'DgitImportDebianUpdate',
1328 $xmsg->("debian changes", 'convert dgit import')
1331 SpecialMethod => 'DgitImportUpstreamUpdate',
1332 $xmsg->("convert dgit import: upstream update",
1335 $prline->(" Import");
1336 $rewrite_from_here->(\@brw_cl);
1337 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1341 # Everything is from this import. This kind of import
1342 # is already nearly in valid breakwater format, with the
1343 # patches as commits. Unfortunately it contains
1345 printdebug "*** WALK BOMB bare dgit import\n";
1346 $cl->{Why} = __ "bare dgit dsc import";
1350 } elsif ($ty eq 'MergedBreakwaters') {
1351 $last_anchor = mergedbreakwaters_anchor $cl;
1352 $build_start->(' MergedBreakwaters', $cur);
1354 } elsif ($ty eq 'VanillaMerge') {
1355 # User may have merged unstitched branch(es). We will
1356 # have now lost what ffq-prev was then (since the later
1357 # pseudomerge may introduce further changes). The effect
1358 # of resolving such a merge is that we may have to go back
1359 # further in history to find a merge base, since the one
1360 # which was reachable via ffq-prev is no longer findable.
1361 # This is suboptimal, but if it all works we'll have done
1363 # MERGE-TODO we should warn the user in the docs about this
1367 # We expect to find a dominating anchor amongst the
1368 # inputs' anchors. That will be the new anchor.
1370 # More complicated is finding a merge base for the
1371 # breakwaters. We need a merge base that is a breakwater
1372 # commit. The ancestors of breakwater commits are more
1373 # breakwater commits and possibly upstream commits and the
1374 # ancestors of those upstream. Upstreams might have
1375 # arbitrary ancestors. But any upstream commit U is
1376 # either included in both anchors, in which case the
1377 # earlier anchor is a better merge base than any of U's
1378 # ancestors; or U is not included in the older anchor, in
1379 # which case U is not an ancestor of the vanilla merge at
1380 # all. So no upstream commit, nor any ancestor thereof,
1381 # is a best merge base. As for non-breakwater Debian
1382 # commits: these are never ancestors of any breakwater.
1384 # So any best merge base as found by git-merge-base
1385 # is a suitable breakwater anchor. Usually there will
1388 printdebug "*** MERGE\n";
1390 my @bwbcmd = (@git, qw(merge-base));
1391 my @ibcmd = (@git, qw(merge-base --all));
1392 my $might_be_in_bw = 1;
1394 my $ps = $cl->{Parents};
1396 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1398 foreach my $p (@$ps) {
1399 $prline->(" VanillaMerge ".$p->{Ix});
1401 my ($ptip, $pbw, $panchor) =
1402 walk $p->{CommitId}, 0, $report,
1403 $report_lprefix.' ';
1404 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1405 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1406 $p->{Anchor} = $panchor;
1408 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1409 $mwrecknote->("$lr-input", $p->{CommitId});
1411 my $mwrecknote_parent = sub {
1413 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1415 $mwrecknote_parent->('Laundered');
1416 $mwrecknote_parent->('Breakwater');
1417 $mwrecknote_parent->('Anchor');
1419 $best_anchor = $panchor if
1420 !defined $best_anchor or
1421 is_fast_fwd $best_anchor, $panchor;
1423 printdebug " MERGE BA best=".($best_anchor//'-').
1427 $mwrecknote->('result-anchor', $best_anchor);
1429 foreach my $p (@$ps) {
1430 $prline->(" VanillaMerge ".$p->{Ix});
1431 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1432 $nomerge->('divergent anchors');
1433 } elsif ($p->{Anchor} eq $best_anchor) {
1434 print $report " SameAnchor" if $report;
1436 print $report " SupersededAnchor" if $report;
1438 if ($p->{Breakwater} eq $p->{CommitId}) {
1439 # this parent commit was its own breakwater,
1440 # ie it is part of the breakwater
1441 print $report " Breakwater" if $report;
1443 $might_be_in_bw = 0;
1445 push @bwbcmd, $p->{Breakwater};
1446 push @ibcmd, $p->{CommitId};
1449 if ($ok && $might_be_in_bw) {
1450 # We could rewrite this to contaion the metadata
1451 # declaring it to be MergedBreakwaters, but
1452 # unnecessarily rewriting a merge seems unhelpful.
1453 $prline->(" VanillaMerge MergedBreakwaters");
1454 $last_anchor = $best_anchor;
1455 $build_start->('MergedBreakwaters', $cur);
1458 my $bwb = cmdoutput @bwbcmd;
1460 # OK, now we have a breakwater base, but we need the merge
1461 # base for the interchange branch because we need the delta
1464 # This a the best merge base of our inputs which has the
1465 # breakwater merge base as an ancestor.
1472 @ibs or confess 'internal error, expected anchor at least ?';
1476 foreach my $tibix (0..$#ibs) {
1477 my $tib = $ibs[$tibix];
1478 my $ff = is_fast_fwd $bwb, $tib;
1479 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1480 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1481 $mwrecknote->($tibleaf, $tib);
1488 $ib or $nomerge->("no suitable interchange merge base");
1490 $prline->(" VanillaMerge Base");
1492 my ($btip, $bbw, $banchor) = eval {
1493 walk $ib, 0, $report, $report_lprefix.' ';
1495 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1499 $mwrecknote->("mergebase-laundered", $btip);
1500 $mwrecknote->("mergebase-breakwater", $bbw);
1501 $mwrecknote->("mergebase-anchor", $banchor);
1503 my $ibinfo = { SeriesTip => $btip,
1506 LeftRight => 'mergebase' };
1509 or $nomerge->("interchange merge-base ($ib)'s".
1510 " breakwater ($bbw)".
1511 " != breakwaters' merge-base ($bwb)");
1513 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1514 or $nomerge->("interchange merge-base ($ib)'s".
1515 " anchor ($ibinfo->{SeriesBase})".
1516 " != any merge input's anchor (".
1517 (join ' ', map { $_->{Anchor} } @$ps).
1520 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1521 $cl->{MergeBestAnchor} = $best_anchor;
1524 SpecialMethod => 'MergeCreateMergedBreakwaters',
1525 $xmsg->('constructed from vanilla merge',
1526 'merged-breakwater'),
1530 SpecialMethod => 'MergeMergeSeries',
1532 $build_start->('MergeBreakwaters', $cur);
1534 printdebug "*** WALK BOMB unrecognised\n";
1540 printdebug "*** WALK prep done cur=$cur".
1541 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1543 return if $nogenerate;
1545 # Now we build it back up again
1551 $#upp_cl = $upp_limit if defined $upp_limit;
1553 my $committer_authline = calculate_committer_authline();
1555 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1557 confess __ "internal error" unless $build eq (pop @processed)->{CommitId};
1560 mkdir $rd or $!==EEXIST or confess "$!";
1562 my $want_debian = $build;
1563 my $want_upstream = $build;
1565 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1566 my $read_tree_debian = sub { ($want_debian) = @_; };
1568 foreach my $cl (qw(Debian), (reverse @brw_cl),
1569 { SpecialMethod => 'RecordBreakwaterTip' },
1570 qw(Upstream), (reverse @upp_cl)) {
1572 $current_method = $cl;
1575 my $method = $cl->{SpecialMethod} // $current_method;
1576 my @parents = ($build);
1577 my $cltree = $cl->{CommitId};
1578 printdebug "WALK BUILD ".($cltree//'undef').
1579 " $method (rewriting=$rewriting)\n";
1580 if ($method eq 'Debian') {
1581 $read_tree_debian->($cltree);
1582 } elsif ($method eq 'Upstream') {
1583 $read_tree_upstream->($cltree);
1584 } elsif ($method eq 'StartRewrite') {
1587 } elsif ($method eq 'RecordBreakwaterTip') {
1588 $breakwater = $build;
1590 } elsif ($method eq 'DgitImportDebianUpdate') {
1591 $read_tree_debian->($cltree);
1592 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1593 confess unless $rewriting;
1594 my $differs = (get_differs $build, $cltree);
1595 next unless $differs & D_UPS;
1596 $read_tree_upstream->($cltree);
1597 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1598 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1599 print "Found a general merge, will try to tidy it up.\n";
1601 $read_tree_upstream->($cl->{MergeBestAnchor});
1602 $read_tree_debian->($cltree);
1603 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1604 } elsif ($method eq 'MergeMergeSeries') {
1605 my $cachehit = reflog_cache_lookup
1606 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1608 print "Using supplied resolution for $cl->{CommitId}...\n";
1610 $mwrecknote->('cached-resolution', $build);
1612 print "Running merge resolution for $cl->{CommitId}...\n";
1613 $mwrecknote->('new-base', $build);
1614 $build = merge_series
1615 $build, $cl->{MergeWreckNotes},
1616 $cl->{MergeInterchangeBaseInfo},
1617 @{ $cl->{Parents} };
1619 $last_anchor = $cl->{MergeBestAnchor};
1621 # Check for mismerges:
1623 my ($against, $allow, $what) = @_;
1624 my $differs = get_differs $build, $against;
1626 "merge misresolved: %s are not the same (%s %s d.%#x)",
1627 $what, $against, $build, $differs)
1628 if $differs & ~($allow | D_PAT_ADD);
1631 # Breakwater changes which were in each side of the
1632 # merge will have been incorporated into the
1633 # MergeCreateMergedBreakwaters output. Because the
1634 # upstream series was rebased onto the new breakwater,
1635 # so should all of the packaging changes which were in
1637 $check->($input, D_UPS, 'debian files');
1639 # Upstream files are merge_series, which ought to
1640 # have been identical to the original merge.
1641 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1643 print "Merge resolution successful.\n";
1646 confess "$method ?";
1649 my $procd = (pop @processed) // 'UNDEF';
1650 if ($cl ne $procd) {
1652 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1656 read_tree_upstream $want_upstream, 0, $want_debian;
1658 my $newtree = cmdoutput @git, qw(write-tree);
1659 my $ch = $cl->{Hdr};
1660 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1661 $ch =~ s{^parent .*\n}{}mg;
1662 $ch =~ s{(?=^author)}{
1663 join '', map { "parent $_\n" } @parents
1664 }me or confess "$ch ?";
1666 $ch =~ s{^committer .*$}{$committer_authline}m
1669 my $cf = "$rd/m$rewriting";
1670 open CD, ">", $cf or confess "$!";
1671 print CD $ch, "\n", $cl->{Msg} or confess "$!";
1672 close CD or confess "$!";
1673 my @cmd = (@git, qw(hash-object));
1674 push @cmd, qw(-w) if $rewriting;
1675 push @cmd, qw(-t commit), $cf;
1676 my $newcommit = cmdoutput @cmd;
1677 confess "$ch ?" unless $rewriting
1678 or $newcommit eq $cl->{CommitId};
1679 $build = $newcommit;
1681 $build = $cl->{CommitId};
1682 trees_diff_walk "$want_upstream:", "$build:", sub {
1684 no warnings qw(exiting);
1685 next if $n eq 'debian/';
1686 confess f_ "mismatch %s ?", "@_";
1688 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1689 confess f_ "mismatch %s ?", "@_";
1691 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1692 confess f_ "mismatch %s != %s ?", "@parents", "@old_parents"
1693 unless "@parents" eq "@old_parents";
1695 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1696 $last_anchor = $cur;
1701 my $final_check = get_differs $build, $input;
1702 confess f_ "internal error %#x %s %s", $final_check, $input, $build
1703 if $final_check & ~D_PAT_ADD;
1705 my @r = ($build, $breakwater, $last_anchor);
1706 printdebug "*** WALK RETURN @r\n";
1711 git_check_unmodified();
1712 return git_rev_parse qw(HEAD);
1715 sub update_head ($$$) {
1716 my ($old, $new, $mrest) = @_;
1717 push @deferred_updates, "update HEAD $new $old";
1718 run_deferred_updates $mrest;
1721 sub update_head_checkout ($$$) {
1722 my ($old, $new, $mrest) = @_;
1723 update_head $old, $new, $mrest;
1724 runcmd @git, qw(reset --hard);
1727 sub update_head_postlaunder ($$$) {
1728 my ($old, $tip, $reflogmsg) = @_;
1729 return if $tip eq $old && !@deferred_updates;
1730 print f_ "%s: laundered (head was %s)\n", $us, $old;
1731 update_head $old, $tip, $reflogmsg;
1732 # no tree changes except debian/patches
1733 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1736 sub currently_rebasing() {
1737 foreach (qw(rebase-merge rebase-apply)) {
1738 return 1 if stat_exists "$maindir_gitdir/$_";
1743 sub bail_if_rebasing() {
1744 fail __ "you are in the middle of a git-rebase already"
1745 if currently_rebasing();
1748 sub do_launder_head ($) {
1749 my ($reflogmsg) = @_;
1750 my $old = get_head();
1752 my ($tip,$breakwater) = walk $old;
1754 update_head_postlaunder $old, $tip, $reflogmsg;
1755 return ($tip,$breakwater);
1758 sub cmd_launder_v0 () {
1759 badusage "no arguments to launder-v0 allowed" if @ARGV;
1760 my $old = get_head();
1761 my ($tip,$breakwater,$last_anchor) = walk $old;
1762 update_head_postlaunder $old, $tip, 'launder';
1763 printf "# breakwater tip\n%s\n", $breakwater;
1764 printf "# working tip\n%s\n", $tip;
1765 printf "# last anchor\n%s\n", $last_anchor;
1768 sub defaultcmd_rebase () {
1769 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1770 my ($tip,$breakwater) = do_launder_head __ 'launder for rebase';
1771 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1774 sub cmd_analyse () {
1775 badusage __ "analyse does not support any options"
1776 if @ARGV and $ARGV[0] =~ m/^-/;
1777 badusage __ "too many arguments to analyse" if @ARGV>1;
1780 $old = git_rev_parse $old;
1782 $old = git_rev_parse 'HEAD';
1784 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1785 STDOUT->error and confess "$!";
1788 sub ffq_check ($;$$) {
1789 # calls $ff and/or $notff zero or more times
1790 # then returns either (status,message) where status is
1795 # or (undef,undef, $ffq_prev,$gdrlast)
1796 # $ff and $notff are called like this:
1797 # $ff->("message for stdout\n");
1798 # $notff->('snag-name', $message);
1799 # normally $currentval should be HEAD
1800 my ($currentval, $ff, $notff) =@_;
1802 $ff //= sub { print $_[0] or confess "$!"; };
1805 my ($status, $message, $current, $ffq_prev, $gdrlast)
1806 = ffq_prev_branchinfo();
1807 return ($status, $message) unless $status eq 'branch';
1809 my $exists = git_get_ref $ffq_prev;
1810 return ('exists', f_ "%s already exists", $ffq_prev) if $exists;
1812 return ('not-branch', __ 'HEAD symref is not to refs/heads/')
1813 unless $current =~ m{^refs/heads/};
1816 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1819 printdebug "ffq check_specs @check_specs\n";
1822 my ($lrref, $desc) = @_;
1823 printdebug "ffq might check $lrref ($desc)\n";
1825 for my $chk (@check_specs) {
1827 $invert = $glob =~ s{^[!^]}{};
1828 last if fnmatch $glob, $lrref;
1831 my $lrval = git_get_ref $lrref;
1832 return unless length $lrval;
1834 if (is_fast_fwd $lrval, $currentval) {
1835 $ff->(f_ "OK, you are ahead of %s\n", $lrref);
1836 $checked{$lrref} = 1;
1837 } elsif (is_fast_fwd $currentval, $lrval) {
1838 $checked{$lrref} = -1;
1839 $notff->('behind', f_ "you are behind %s, divergence risk",
1842 $checked{$lrref} = -1;
1843 $notff->('diverged', f_ "you have diverged from %s", $lrref);
1847 my $merge = cfg "branch.$branch.merge",1;
1848 if (defined $merge and $merge =~ m{^refs/heads/}) {
1850 printdebug "ffq merge $rhs\n";
1851 my $check_remote = sub {
1852 my ($remote, $desc) = @_;
1853 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1854 return unless defined $remote;
1855 $check->("refs/remotes/$remote/$rhs", $desc);
1857 $check_remote->((scalar cfg "branch.$branch.remote",1),
1858 'remote fetch/merge branch');
1859 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1860 (scalar cfg "branch.$branch.pushDefault",1),
1861 'remote push branch');
1863 if ($branch =~ m{^dgit/}) {
1864 $check->("refs/remotes/dgit/$branch",
1865 __ 'remote dgit branch');
1866 } elsif ($branch =~ m{^master$}) {
1867 $check->("refs/remotes/dgit/dgit/sid",
1868 __ 'remote dgit branch for sid');
1870 return (undef, undef, $ffq_prev, $gdrlast);
1873 sub record_ffq_prev_deferred () {
1874 # => ('status', "message")
1876 # deferred message is undef
1881 # if not ff from some branch we should be ff from, is an snag
1882 # if "deferred", will have added something about that to
1883 # @deferred_update_messages, and also maybe printed (already)
1884 # some messages about ff checks
1886 my $currentval = get_head();
1888 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1889 return ($status,$message) if defined $status;
1893 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1894 push @deferred_updates, "delete $gdrlast";
1895 push @deferred_update_messages,
1896 __ "Recorded previous head for preservation";
1897 return ('deferred', undef);
1900 sub record_ffq_auto () {
1901 my ($status, $message) = record_ffq_prev_deferred();
1902 if ($status eq 'deferred' || $status eq 'exists') {
1904 snag $status, f_ "could not record ffq-prev: %s", $message;
1909 sub ffq_prev_info () {
1911 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1912 my ($status, $message, $current, $ffq_prev, $gdrlast)
1913 = ffq_prev_branchinfo();
1914 if ($status ne 'branch') {
1915 snag $status, f_ "could not check ffq-prev: %s", $message;
1918 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1919 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1922 sub stitch ($$$$$) {
1923 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1925 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1927 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1928 my $differs = get_differs $old_head, $ffq_prev_commitish;
1929 unless ($differs & ~D_PAT_ADD) {
1930 # ffq-prev is ahead of us, and the only tree changes it has
1931 # are possibly addition of things in debian/patches/.
1932 # Just wind forwards rather than making a pointless pseudomerge.
1933 record_gdrlast $gdrlast, $ffq_prev_commitish;
1934 update_head_checkout $old_head, $ffq_prev_commitish,
1935 sprintf "stitch (%s)", __ 'fast forward';
1940 # We make pseudomerges with L as the contributing parent.
1941 # This makes git rev-list --first-parent work properly.
1942 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1943 # we translate this against the time when this same code is
1944 # used outside Debian, for downstreams and users
1945 (__ 'Declare fast forward / record previous work'),
1946 "[git-debrebase pseudomerge: $prose]",
1948 record_gdrlast $gdrlast, $new_head;
1949 update_head $old_head, $new_head, "stitch: $prose";
1952 sub do_stitch ($;$) {
1953 my ($prose, $unclean) = @_;
1955 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1956 if (!$ffq_prev_commitish) {
1957 fail __ "No ffq-prev to stitch." unless $opt_noop_ok;
1960 my $dangling_head = get_head();
1962 keycommits $dangling_head, $unclean,$unclean,$unclean;
1965 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1968 sub cmd_new_upstream () {
1969 # automatically and unconditionally launders before rebasing
1970 # if rebase --abort is used, laundering has still been done
1974 badusage __ "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1976 # parse args - low commitment
1977 my $spec_version = shift @ARGV;
1978 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1979 fail f_ "bad version number \`%s'", $spec_version
1980 unless defined $new_version;
1981 if ($new_version->is_native()) {
1982 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1985 my $new_upstream = shift @ARGV;
1986 my $new_upstream_version = upstreamversion $new_version;
1987 my $new_upstream_used;
1988 ($new_upstream, $new_upstream_used) =
1989 resolve_upstream_version $new_upstream, $new_upstream_version;
1994 my ($n, @x) = @_; # may be ''
1995 my $pc = $pieces{$n} //= {
1997 Desc => ($n ? (f_ "upstream piece \`%s'", $n)
1998 : (__ "upstream (main piece")),
2000 while (my $k = shift @x) { $pc->{$k} = shift @x; }
2005 my $newpiece = sub {
2006 my ($n, @x) = @_; # may be ''
2007 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2008 push @newpieces, $pc;
2013 New => $new_upstream,
2015 while (@ARGV && $ARGV[0] !~ m{^-}) {
2016 my $n = shift @ARGV;
2018 badusage __ "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2019 unless @ARGV && $ARGV[0] !~ m{^-};
2021 my $c = git_rev_parse shift @ARGV;
2022 confess unless $n =~ m/^$extra_orig_namepart_re$/;
2023 $newpiece->($n, New => $c);
2026 # now we need to investigate the branch this generates the
2027 # laundered version but we don't switch to it yet
2028 my $old_head = get_head();
2029 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2031 my $old_bw_cl = classify $old_bw;
2032 my $old_anchor_cl = classify $old_anchor;
2034 if (!$old_anchor_cl->{OrigParents}) {
2035 snag 'anchor-treated',
2036 __ 'old anchor is recognised due to --anchor, cannot check upstream';
2038 $old_upstream = parsecommit
2039 $old_anchor_cl->{OrigParents}[0]{CommitId};
2040 $piece->('', Old => $old_upstream->{CommitId});
2043 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2044 if ($old_upstream->{Msg} =~
2045 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2047 my @oldpieces = (split / /, $1);
2048 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2049 if ($old_n_parents != @oldpieces &&
2050 $old_n_parents != @oldpieces + 1) {
2051 snag 'upstream-confusing', f_
2052 "previous upstream combine %s".
2053 " mentions %d pieces (each implying one parent)".
2054 " but has %d parents".
2055 " (one per piece plus maybe a previous combine)",
2056 $old_upstream->{CommitId},
2057 (scalar @oldpieces),
2059 } elsif ($oldpieces[0] ne '.') {
2060 snag 'upstream-confusing', f_
2061 "previous upstream combine %s".
2062 " first piece is not \`.'",
2066 foreach my $i (0..$#oldpieces) {
2067 my $n = $oldpieces[$i];
2068 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2069 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2073 snag 'upstream-confusing', f_
2074 "previous upstream %s is from".
2075 " git-debrebase but not an \`upstream-combine' commit",
2076 $old_upstream->{CommitId};
2080 foreach my $pc (values %pieces) {
2081 if (!$old_upstream) {
2082 # we have complained already
2083 } elsif (!$pc->{Old}) {
2084 snag 'upstream-new-piece',
2085 f_ "introducing upstream piece \`%s'", $pc->{Name};
2086 } elsif (!$pc->{New}) {
2087 snag 'upstream-rm-piece',
2088 f_ "dropping upstream piece \`%s'", $pc->{Name};
2089 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2090 snag 'upstream-not-ff',
2091 f_ "not fast forward: %s %s",
2092 $pc->{Name}, "$pc->{Old}..$pc->{New}";
2096 printdebug "%pieces = ", (dd \%pieces), "\n";
2097 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2105 my @upstream_merge_parents;
2108 push @upstream_merge_parents, $old_upstream->{CommitId};
2111 foreach my $pc (@newpieces) { # always has '' first
2113 read_tree_subdir $pc->{Name}, $pc->{New};
2115 runcmd @git, qw(read-tree), $pc->{New};
2117 push @upstream_merge_parents, $pc->{New};
2120 # index now contains the new upstream
2122 if (@newpieces > 1) {
2123 # need to make the upstream subtree merge commit
2124 $new_upstream = make_commit \@upstream_merge_parents,
2125 [ "Combine upstreams for $new_upstream_version",
2126 ("[git-debrebase upstream-combine . ".
2127 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2132 # $new_upstream is either the single upstream commit, or the
2133 # combined commit we just made. Either way it will be the
2134 # "upstream" parent of the anchor merge.
2136 read_tree_subdir 'debian', "$old_bw:debian";
2138 # index now contains the anchor merge contents
2139 $new_bw = make_commit [ $old_bw, $new_upstream ],
2140 [ "Update to upstream $new_upstream_version",
2141 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2144 # Now we have to add a changelog stanza so the Debian version
2145 # is right. We use debchange to do this. Invoking debchange
2146 # here is a bit fiddly because it has a lot of optional
2147 # exciting behaviours, some of which will break stuff, and
2148 # some of which won't work in a playtree.
2150 # Make debchange use git's idea of the user's identity.
2151 # That way, if the user never uses debchange et al, configuring
2156 defined $v or return;
2159 $usetup->('DEBEMAIL', 'user.email');
2160 $usetup->('DEBFULLNAME', 'user.name');
2162 my @dch = (qw(debchange
2163 --allow-lower-version .*
2166 --vendor=Unknown-Vendor
2167 --changelog debian/changelog
2168 --check-dirname-level 0
2169 --release-heuristic=changelog
2171 "Update to new upstream version $new_upstream_version.");
2173 runcmd @git, qw(checkout -q debian/changelog);
2175 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2177 # Now we have the final new breakwater branch in the index
2178 $new_bw = make_commit [ $new_bw ],
2179 [ "Update changelog for new upstream $new_upstream_version",
2180 "[git-debrebase changelog: new upstream $new_upstream_version]",
2184 # we have constructed the new breakwater. we now need to commit to
2185 # the laundering output, because git-rebase can't easily be made
2186 # to make a replay list which is based on some other branch
2188 update_head_postlaunder $old_head, $old_laundered_tip,
2189 'launder for new upstream';
2191 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2192 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2193 "debrebase new-upstream $new_version: rebase";
2195 # now it's for the user to sort out
2198 sub cmd_record_ffq_prev () {
2199 badusage "no arguments allowed" if @ARGV;
2200 my ($status, $msg) = record_ffq_prev_deferred();
2201 if ($status eq 'exists' && $opt_noop_ok) {
2202 print __ "Previous head already recorded\n" or confess "$!";
2203 } elsif ($status eq 'deferred') {
2204 run_deferred_updates 'record-ffq-prev';
2206 fail f_ "Could not preserve: %s", $msg;
2211 badusage __ "no arguments allowed" if @ARGV;
2212 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2213 print "$anchor\n" or confess "$!";
2216 sub cmd_breakwater () {
2217 badusage __ "no arguments allowed" if @ARGV;
2218 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2219 print "$bw\n" or confess "$!";
2223 badusage __ "no arguments allowed" if @ARGV;
2225 # todo: gdr status should print divergence info
2226 # todo: gdr status should print upstream component(s) info
2227 # todo: gdr should leave/maintain some refs with this kind of info ?
2229 my $oldest = { Badness => 0 };
2232 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2233 if ($oldest->{Badness} < $badness) {
2234 $oldest = $newest = undef;
2237 Badness => $badness,
2238 CommitId => $cl->{CommitId},
2242 $newest //= $oldest;
2244 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2245 sub { $note->(1, __ 'branch contains furniture (not laundered)',@_); },
2246 sub { $note->(2, __ 'branch is unlaundered', @_); },
2247 sub { $note->(3, __ 'branch needs laundering', @_); },
2248 sub { $note->(4, __ 'branch not in git-debrebase form', @_); };
2250 my $prcommitinfo = sub {
2252 flush STDOUT or confess "$!";
2253 runcmd @git, qw(--no-pager log -n1),
2254 '--pretty=format: %h %s%n',
2258 print __ "current branch contents, in git-debrebase terms:\n";
2259 if (!$oldest->{Badness}) {
2260 print __ " branch is laundered\n";
2262 print " $oldest->{OurMsg}\n";
2264 foreach my $info ($oldest, $newest) {
2265 my $cid = $info->{CommitId};
2266 next if $cid eq $printed;
2268 print " $info->{KcMsg}\n";
2269 $prcommitinfo->($cid);
2274 my ($cid, $what) = @_;
2275 if (!defined $cid) {
2276 print f_ " %s is not well-defined\n", $what;
2279 $prcommitinfo->($cid);
2282 print __ "key git-debrebase commits:\n";
2283 $prab->($anchor, __ 'anchor');
2284 $prab->($bw, __ 'breakwater');
2286 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2287 ffq_prev_branchinfo();
2289 print __ "branch and ref status, in git-debrebase terms:\n";
2291 print " $ffq_msg\n";
2293 $ffq_prev = git_get_ref $ffq_prev;
2294 $gdrlast = git_get_ref $gdrlast;
2296 print __ " unstitched; previous tip was:\n";
2297 $prcommitinfo->($ffq_prev);
2298 } elsif (!$gdrlast) {
2299 print __ " stitched? (no record of git-debrebase work)\n";
2300 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2301 print __ " stitched\n";
2303 print __ " not git-debrebase (diverged since last stitch)\n"
2306 print __ "you are currently rebasing\n" if currently_rebasing();
2310 my $prose = 'stitch';
2311 getoptions("stitch",
2312 'prose=s', \$prose);
2313 badusage __ "no arguments allowed" if @ARGV;
2314 do_stitch $prose, 0;
2316 sub cmd_prepush () {
2322 badusage __ "no arguments allowed" if @ARGV;
2323 do_launder_head __ 'launder for git-debrebase quick';
2327 sub cmd_conclude () {
2328 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2329 if (!$ffq_prev_commitish) {
2330 fail __ "No ongoing git-debrebase session." unless $opt_noop_ok;
2333 my $dangling_head = get_head();
2335 badusage "no arguments allowed" if @ARGV;
2336 do_launder_head __ 'launder for git-debrebase quick';
2341 if (currently_rebasing()) {
2342 runcmd @git, qw(rebase --abort);
2343 push @deferred_updates, 'verify HEAD HEAD';
2344 # noop, but stops us complaining that scrap was a noop
2346 badusage __ "no arguments allowed" if @ARGV;
2347 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2349 if ($ffq_prev_commitish) {
2350 $scrapping_head = get_head();
2351 push @deferred_updates,
2352 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2353 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2355 if (git_get_ref $merge_cache_ref) {
2356 push @deferred_updates,
2357 "delete $merge_cache_ref";
2359 if (!@deferred_updates) {
2360 fail __ "No ongoing git-debrebase session." unless $opt_noop_ok;
2364 if ($scrapping_head) {
2365 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2367 run_deferred_updates "scrap";
2371 sub make_patches_staged ($) {
2373 # Produces the patches that would result from $head if it were
2375 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2379 $any = gbp_pq_export 'bw', $secret_bw, $secret_head;
2384 sub make_patches ($) {
2386 keycommits $head, 0, \&snag;
2387 my $any = make_patches_staged $head;
2390 my $ptree = !$any ? undef :
2391 cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2392 runcmd @git, qw(read-tree), $head;
2394 read_tree_subdir 'debian/patches', $ptree;
2396 rm_subdir_cached 'debian/patches';
2398 $out = make_commit [$head], [
2399 (__ 'Commit patch queue (exported by git-debrebase)'),
2400 '[git-debrebase make-patches: export and commit patches]',
2406 sub cmd_make_patches () {
2407 my $opt_quiet_would_amend;
2408 getoptions("make-patches",
2409 'quiet-would-amend!', \$opt_quiet_would_amend);
2410 badusage __ "no arguments allowed" if @ARGV;
2412 my $old_head = get_head();
2413 my $new = make_patches $old_head;
2414 my $d = get_differs $old_head, $new;
2416 fail __ "No (more) patches to export." unless $opt_noop_ok;
2418 } elsif ($d == D_PAT_ADD) {
2420 update_head_checkout $old_head, $new, 'make-patches';
2422 print STDERR failmsg f_
2423 "Patch export produced patch amendments".
2424 " (abandoned output commit %s).".
2425 " Try laundering first.",
2427 unless $opt_quiet_would_amend;
2432 sub check_series_has_all_patches ($) {
2434 my $seriesfn = 'debian/patches/series';
2435 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2439 our $comments_snagged;
2440 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2441 if ($f =~ m/^\s*\#/) {
2442 snag 'series-comments', f_
2443 "%s contains comments, which will be discarded",
2445 unless $comments_snagged++;
2448 fail f_ "patch %s repeated in %s !", $f, $seriesfn if $series{$f}++;
2450 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2451 my ($f,$i) = @$patchfile;
2452 next if $series{$f};
2453 next if $f eq 'series';
2454 snag 'unused-patches', f_
2455 "Unused patch file %s will be discarded", $f;
2459 sub begin_convert_from () {
2460 my $head = get_head();
2461 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2463 fail __ "ffq-prev exists, this is already managed by git-debrebase!"
2464 if $ffq_prev && git_get_ref $ffq_prev;
2466 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2467 snag 'already-converted', __
2468 "ahead of debrebase-last, this is already managed by git-debrebase!"
2469 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2470 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2473 sub complete_convert_from ($$$$) {
2474 my ($old_head, $new_head, $gi, $mrest) = @_;
2475 ffq_check $new_head;
2476 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2479 update_head_checkout $old_head, $new_head, $mrest;
2482 sub cmd_convert_from_unapplied () { cmd_convert_from_gbp(); }
2483 sub cmd_convert_from_gbp () {
2484 badusage __ "want only 1 optional argument, the upstream git commitish"
2487 my $clogp = parsechangelog();
2488 my $version = $clogp->{'Version'}
2489 // fail __ "missing Version from changelog\n";
2491 my ($upstream_spec) = @ARGV;
2493 my $upstream_version = upstreamversion $version;
2494 my ($upstream, $upstream_used) =
2495 resolve_upstream_version($upstream_spec, $upstream_version);
2497 my ($old_head, $gdrlastinfo) = begin_convert_from();
2499 my $upsdiff = get_differs $upstream, $old_head;
2500 if ($upsdiff & D_UPS) {
2501 runcmd @git, qw(--no-pager diff --stat),
2502 $upstream, $old_head,
2503 qw( -- :!/debian :/);
2504 fail f_ <<END, $upstream_used, $upstream;
2505 upstream (%s) and HEAD are not
2506 identical in upstream files. See diffstat above, or run
2507 git diff %s HEAD -- :!/debian :/
2511 if (!is_fast_fwd $upstream, $old_head) {
2512 snag 'upstream-not-ancestor',
2513 f_ "upstream (%s) is not an ancestor of HEAD", $upstream;
2515 my $wrong = cmdoutput
2516 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2517 qw(-- :/ :!/debian));
2518 if (length $wrong) {
2519 snag 'unexpected-upstream-changes', f_
2520 "history between upstream (%s) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?",
2522 print STDERR f_ "list expected changes with: %s\n",
2523 "git log --stat --ancestry-path $upstream..HEAD -- :/ ':!/debian'";
2527 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2528 snag 'upstream-has-debian',
2529 f_ "upstream (%s) contains debian/ directory", $upstream;
2532 check_series_has_all_patches $old_head;
2534 my $previous_dgit_view = eval {
2535 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2537 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2538 my ($stz, $desc) = @_;
2539 no warnings qw(exiting);
2540 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2541 next unless $stz->{Date};
2542 next unless $stz->{Distribution} ne 'UNRELEASED';
2543 $lvsn = $stz->{Version};
2544 $suite = $stz->{Distribution};
2547 die __ "neither of the first two changelog entries are released\n"
2548 unless defined $lvsn;
2549 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2550 my $mtag_pat = debiantag_maintview $lvsn, '*';
2551 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2553 die f_ "could not find suitable maintainer view tag %s\n", $mtag_pat
2554 unless $mtag =~ m{/};
2555 is_fast_fwd $mtag, 'HEAD' or
2556 die f_ "HEAD is not FF from maintainer tag %s!", $mtag;
2557 my $dtag = "archive/$mtag";
2558 git_get_ref "refs/tags/$dtag" or
2559 die f_ "dgit view tag %s not found\n", $dtag;
2560 is_fast_fwd $mtag, $dtag or
2561 die f_ "dgit view tag %s is not FF from maintainer tag %s\n",
2563 print f_ "will stitch in dgit view, %s\n", $dtag;
2564 git_rev_parse $dtag;
2566 if (!$previous_dgit_view) {
2569 print STDERR f_ <<END, "$@";
2570 Cannot confirm dgit view: %s
2571 Failed to stitch in dgit view (see messages above).
2572 dgit --overwrite will be needed on the first dgit push after conversion.
2576 snags_maybe_bail_early();
2582 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2583 # make a branch out of the patch queue - we'll want this in a mo
2584 runcmd qw(gbp pq import);
2585 # strip the patches out
2586 runcmd @git, qw(checkout -q gdr-internal~0);
2587 rm_subdir_cached 'debian/patches';
2588 $work = make_commit ['HEAD'], [
2589 'git-debrebase convert-from-gbp: drop patches from tree',
2590 'Delete debian/patches, as part of converting to git-debrebase format.',
2591 '[git-debrebase convert-from-gbp: drop patches from tree]'
2593 # make the anchor merge
2594 # the tree is already exactly right
2595 $work = make_commit [$work, $upstream], [
2596 'git-debrebase import: declare upstream',
2597 'First breakwater merge.',
2598 '[git-debrebase anchor: declare upstream]'
2601 # rebase the patch queue onto the new breakwater
2602 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2603 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2604 $work = git_rev_parse 'HEAD';
2606 if ($previous_dgit_view) {
2607 $work = make_commit [$work, $previous_dgit_view], [
2608 'git-debrebase import: declare ff from dgit archive view',
2609 '[git-debrebase pseudomerge: import-from-gbp]',
2614 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2615 print f_ <<END, $us or confess "$!";
2616 %s: converted from patched-unapplied (gbp) branch format, OK
2620 sub cmd_convert_to_gbp () {
2621 badusage "no arguments allowed" if @ARGV;
2622 my $head = get_head();
2623 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2624 my ($anchor, $breakwater) = keycommits $head, 0;
2625 my $out = $breakwater;
2626 my $any = make_patches_staged $head;
2629 $out = make_commit [$out], [
2630 'Commit patch queue (converted from git-debrebase format)',
2631 '[git-debrebase convert-to-gbp: commit patches]',
2635 # in this case, it can be fast forward
2639 push @deferred_updates, "delete $ffq";
2640 push @deferred_updates, "delete $gdrlast";
2643 update_head_checkout $head, $out, "convert to gbp (v0)";
2644 print f_ <<END, $us,$us,$us or confess "$!";
2645 %s: converted to git-buildpackage branch format
2646 %s: WARNING: do not now run "git-debrebase" any more
2647 %s: WARNING: doing so would drop all upstream patches!
2651 sub cmd_convert_from_dgit_view () {
2652 my $clogp = parsechangelog();
2654 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2660 getoptions("convert-from-dgit-view",
2661 'diagnose!', \$diagnose,
2662 'build-products-dir:s', \$bpd,
2663 'origs!', \$do_origs,
2665 'always-convert-anyway!', \$always);
2666 fail __ "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2671 my $spec = shift @ARGV;
2672 my $commit = git_rev_parse "$spec^{commit}";
2673 push @upstreams, { Commit => $commit,
2674 Source => (f_ "%s, from command line", $ARGV[0]),
2679 my ($head, $gdrlastinfo) = begin_convert_from();
2683 my $trouble = sub { $troubles++; };
2684 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2685 printdebug "troubles=$troubles\n";
2687 print STDERR f_ <<END, $us,$us,$us;
2688 %s: Branch already seems to be in git-debrebase format!
2689 %s: --always-convert-anyway would do the conversion operation anyway
2690 %s: but is probably a bad idea. Probably, you wanted to do nothing.
2692 fail __ "Branch already in git-debrebase format."
2693 unless $opt_noop_ok;
2698 check_series_has_all_patches $head;
2700 snags_maybe_bail_early();
2702 my $version = upstreamversion $clogp->{Version};
2704 "Considering possible commits corresponding to upstream:\n";
2709 my $ups_tag = upstream_commitish_search $version, \@tried;
2711 my $this = f_ "git tag %s", $tried[-1];
2712 push @upstreams, { Commit => $ups_tag,
2717 " git tag: no suitable tag found (tried %s)\n",
2722 my $p = $clogp->{'Source'};
2723 # we do a quick check to see if there are plausible origs
2725 if (!opendir BPD, $bpd) {
2726 die f_ "opendir build-products-dir %s: %s", $bpd, $!
2729 while ($!=0, my $f = readdir BPD) {
2730 next unless is_orig_file_of_p_v $f, $p, $version;
2732 " orig: found what looks like a .orig, %s\n",
2737 confess "read $bpd: $!" if $!;
2741 my $tree = cmdoutput
2742 @dgit, qw(--build-products-dir), $bpd,
2743 qw(print-unapplied-treeish);
2746 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2747 rm_subdir_cached 'debian';
2748 $tree = cmdoutput @git, qw(write-tree);
2749 my $ups_synth = make_commit [], [ <<END, <<END,
2750 Import effective orig tree for upstream version $version
2752 This includes the contents of the .orig(s), minus any debian/ directory.
2754 [git-debrebase convert-from-dgit-view upstream-import-convert: $version]
2757 push @upstreams, { Commit => $ups_synth,
2758 Source => "orig(s) imported via dgit",
2763 " orig: no suitable origs found (looked for %s in %s)\n",
2764 "${p}_".(stripeoch $version)."...", $bpd;
2769 my $some_patches = stat_exists 'debian/patches/series';
2772 "Evaluating possible commits corresponding to upstream:\n";
2775 foreach my $u (@upstreams) {
2779 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2780 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2781 runcmd @git, qw(clean -xdff);
2782 runcmd @git, qw(checkout), $head, qw(-- debian);
2783 if ($some_patches) {
2784 rm_subdir_cached 'debian/patches';
2785 $work = make_commit [ $work ], [
2786 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2787 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2788 "to git-debrebase format. Upstream changes will appear as commits.",
2789 '[git-debrebase convert-from-dgit-view drop-patches]'
2792 $work = make_commit [ $work, $u->{Commit} ], [
2793 'git-debrebase convert-from-dgit-view: declare upstream',
2794 '(Re)constructed breakwater merge.',
2795 '[git-debrebase anchor: declare upstream]'
2797 runcmd @git, qw(checkout --quiet -b mk), $work;
2798 if ($some_patches) {
2799 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2800 runcmd @git, qw(reset --quiet);
2801 my @gbp_cmd = (qw(gbp pq import));
2803 my $gbp_err = "../gbp-pq-err";
2804 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2806 my $r = system @gbp_cmd;
2809 " %s: couldn't apply patches: gbp pq %s",
2810 $u->{Source}, waitstatusmsg();
2814 my $work = git_rev_parse qw(HEAD);
2815 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2816 if (length $diffout) {
2818 " %s: applying patches gives different tree\n",
2820 print STDERR $diffout if $diagnose;
2824 $u->{Result} = $work;
2832 Could not find or construct a suitable upstream commit.
2833 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2834 upstream commmit explicitly or provide suitable origs.
2838 print STDERR f_ "Yes, will base new branch on %s\n", $result->{Source};
2840 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2841 'convert-from-dgit-view';
2844 sub cmd_forget_was_ever_debrebase () {
2845 badusage __ "forget-was-ever-debrebase takes no further arguments"
2847 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2848 ffq_prev_branchinfo();
2849 fail f_ "Not suitable for recording git-debrebaseness anyway: %s",
2851 if defined $ffq_msg;
2852 push @deferred_updates, "delete $ffq_prev";
2853 push @deferred_updates, "delete $gdrlast";
2855 run_deferred_updates "forget-was-ever-debrebase";
2858 sub cmd_record_resolved_merge () {
2859 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2860 # MERGE-TODO needs documentation
2861 my $new = get_head();
2864 print "Checking how you have resolved the merge problem\n";
2865 my $nope = sub { print "Not $method: @_"; 0; };
2867 my $maybe = sub { print "Seems to be $method.\n"; };
2869 my ($key, $ref) = @_;
2870 reflog_cache_insert $merge_cache_ref, $key, $ref;
2871 print "OK. You can switch branches and try git-debrebase again.\n";
2875 fresh_workarea 'merge';
2877 $method = 'vanilla-merge patchqueue';
2878 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2879 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2880 foreach my $lr (qw(left right)) {
2881 my $n = "$wrecknoteprefix/$lr-patchqueue";
2882 my $lrpq = git_get_ref $n;
2883 $lrpq or return $nope->("wreckage did not contain patchqueues");
2884 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2887 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2888 or die "wreckage element $wrecknoteprefix/new-base missing";
2889 my $result = merge_series_patchqueue_convert
2891 $yes->("vanilla-merge $vanilla", $result);
2894 fail "No resolved merge method seems applicable.\n";
2898 sub cmd_downstream_rebase_launder_v0 () {
2899 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2901 $base = git_rev_parse $base;
2902 my $old_head = get_head();
2903 my $current = $old_head;
2906 if ($current eq $base) {
2907 $topmost_keep //= $current;
2908 print " $current BASE stop\n";
2911 my $cl = classify $current;
2912 print " $current $cl->{Type}";
2914 my $p0 = $cl->{Parents}[0]{CommitId};
2916 if ($cl->{Type} eq 'Pseudomerge') {
2917 print " ^".($cl->{Contributor}{Ix}+1);
2918 $next = $cl->{Contributor}{CommitId};
2919 } elsif ($cl->{Type} eq 'AddPatches' or
2920 $cl->{Type} eq 'Changelog') {
2930 $topmost_keep //= $current;
2932 die "to-be stripped changes not on top of the branch\n"
2937 if ($topmost_keep eq $old_head) {
2938 print "unchanged\n";
2940 print "updating to $topmost_keep\n";
2941 update_head_checkout
2942 $old_head, $topmost_keep,
2943 'downstream-rebase-launder-v0';
2947 setlocale(LC_MESSAGES, "");
2948 textdomain("git-debrebase");
2951 (__ "bad options\n",
2952 "D+" => \$debuglevel,
2953 'noop-ok', => \$opt_noop_ok,
2954 'f=s' => \@snag_force_opts,
2955 'anchor=s' => \@opt_anchors,
2956 '--dgit=s' => \($dgit[0]),
2958 'experimental-merge-resolution!', \$opt_merges,
2960 my ($opt,$val) = @_;
2961 badusage f_ "%s: no cuddling to -i for git-rebase", $us
2963 confess if $opt_defaultcmd_interactive; # should not happen
2964 $opt_defaultcmd_interactive = [ qw(-i) ];
2965 # This access to @ARGV is excessive familiarity with
2966 # Getopt::Long, but there isn't another sensible
2967 # approach. '-i=s{0,}' does not work with bundling.
2968 push @$opt_defaultcmd_interactive, @ARGV;
2971 'help' => sub { print __ $usage_message or confess "$!"; finish 0; },
2974 initdebug('git-debrebase ');
2975 enabledebug if $debuglevel;
2977 changedir_git_toplevel();
2979 $rd = fresh_playground "$playprefix/misc";
2981 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2983 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2984 defaultcmd_rebase();
2986 my $cmd = shift @ARGV;
2989 $cmdfn = ${*::}{"cmd_$cmdfn"};
2991 $cmdfn or badusage f_ "unknown git-debrebase sub-operation %s", $cmd;