3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
6 # Copyright (C)2017,2018 Ian Jackson
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::GDR;
23 use Debian::Dgit::ExitStatus;
27 use Debian::Dgit qw(:DEFAULT :playground);
34 use Getopt::Long qw(:config posix_default gnu_compat bundling);
36 use File::FnMatch qw(:fnmatch);
39 $debugcmd_when_debuglevel = 2;
41 our ($usage_message) = <<'END';
43 git-debrebase [<options>] [--|-i <git rebase options...>]
44 git-debrebase [<options>] status
45 git-debrebase [<options>] prepush [--prose=...]
46 git-debrebase [<options>] quick|conclude
47 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
48 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
50 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
53 our ($opt_force, $opt_noop_ok, $opt_merges, @opt_anchors);
54 our ($opt_defaultcmd_interactive);
56 our $us = qw(git-debrebase);
58 our $wrecknoteprefix = 'refs/debrebase/wreckage';
59 our $merge_cache_ref = 'refs/debrebase/merge-resolutions';
65 print STDERR "$us: bad usage: $m\n";
71 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
72 GetOptions @_ or badusage $m;
76 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
80 my ($k, $optional) = @_;
82 my @cmd = qw(git config -z);
83 push @cmd, qw(--get-all) if wantarray;
85 my $out = cmdoutput_errok @cmd;
87 fail "missing required git config $k" unless $optional;
90 my @l = split /\0/, $out;
91 return wantarray ? @l : $l[0];
98 my $dd = new Data::Dumper [ $v ];
99 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
105 my $data = (git_cat_file $objid, 'commit');
106 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
110 sub D_UPS () { 0x02; } # upstream files
111 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
112 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
113 sub D_DEB_CLOG () { 0x10; } # debian/changelog
114 sub D_DEB_OTH () { 0x20; } # debian/ (not patches/ or changelog)
115 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
117 our $playprefix = 'debrebase';
122 our @dgit = qw(dgit);
124 sub in_workarea ($) {
127 my $r = eval { $sub->(); };
128 { local $@; changedir $maindir; }
132 sub fresh_workarea (;$) {
135 $workarea = fresh_playground "$playprefix/$subdir";
136 in_workarea sub { playtree_setup };
139 sub run_ref_updates_now ($$) {
140 my ($mrest, $updates) = @_;
141 # @$updates is a list of lines for git-update-ref, without \ns
143 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
144 debugcmd '>|', @upd_cmd;
145 open U, "|-", @upd_cmd or die $!;
146 foreach (@$updates) {
147 printdebug ">= ", $_, "\n";
148 print U $_, "\n" or die $!;
151 close U or failedcmd @upd_cmd;
154 our $snags_forced = 0;
155 our $snags_tripped = 0;
156 our $snags_summarised = 0;
157 our @deferred_updates;
158 our @deferred_update_messages;
160 sub merge_wreckage_cleaning ($) {
162 git_for_each_ref("$wrecknoteprefix/*", sub {
163 my ($objid,$objtype,$fullrefname,$reftail) = @_;
164 push @$updates, "delete $fullrefname";
168 sub all_snags_summarised () {
169 $snags_forced + $snags_tripped == $snags_summarised;
171 sub run_deferred_updates ($) {
174 confess 'dangerous internal error' unless all_snags_summarised();
176 merge_wreckage_cleaning \@deferred_updates;
177 run_ref_updates_now $mrest, \@deferred_updates;
178 print $_, "\n" foreach @deferred_update_messages;
180 @deferred_updates = ();
181 @deferred_update_messages = ();
184 sub get_tree ($;$$) {
185 # tree object name => ([ $name, $info ], ...)
186 # where $name is the sort key, ie has / at end for subtrees
187 # $info is the LHS from git-ls-tree (<mode> <type> <hash>)
188 # without $precheck, will crash if $x does not exist, so don't do that;
189 # instead pass '' to get ().
190 my ($x, $precheck, $recurse) = @_;
192 return () if !length $x;
195 my ($type, $dummy) = git_cat_file $x, [qw(tree missing)];
196 return () if $type eq 'missing';
199 confess "get_tree needs object not $x ?" unless $x =~ m{^[0-9a-f]+\:};
201 our (@get_tree_memo, %get_tree_memo);
202 my $memo = $get_tree_memo{$x};
203 return @$memo if $memo;
205 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
207 my @cmd = (qw(git ls-tree -z --full-tree));
208 push @cmd, qw(-r) if $recurse;
209 push @cmd, qw(--), $x;
210 my $o = cmdoutput @cmd;
213 foreach my $l (split /\0/, $o) {
214 my ($i, $n) = split /\t/, $l, 2;
215 $n .= '/' if $i =~ m/^\d+ tree /;
217 confess "$x need $last < $n ?" unless $last lt $n;
219 $get_tree_memo{$x} = \@l;
220 push @get_tree_memo, $x;
221 if (@get_tree_memo > 10) {
222 delete $get_tree_memo{ shift @get_tree_memo };
227 sub trees_diff_walk ($$$;$) {
228 # trees_diff_walk [$all,] $x, $y, sub {... }
229 # calls sub->($name, $ix, $iy) for each difference (with $all, each name)
230 # $x and $y are as for get_tree
231 # where $name, $ix, $iy are $name and $info from get_tree
232 my $all = shift @_ if @_>=4;
233 my ($x,$y,$call) = @_;
234 return if !$all and $x eq $y;
237 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
240 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
241 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
242 my ($n, $ix, $iy); # all same? $cmp=0, use both
244 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
246 ($n, $ix) = @{ shift @x } if $cmp <= 0;
247 ($n, $iy) = @{ shift @y } if $cmp >= 0;
248 next if !$all and $ix eq $iy;
250 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
251 !!$all,$x,$y, $n,$ix,$iy
253 $call->($n, $ix, $iy);
257 sub get_differs ($$) {
259 # This does a similar job to quiltify_trees_differ, in dgit, a bit.
260 # But we don't care about modes, or dpkg-source-unrepresentable
261 # changes, and we don't need the plethora of different modes.
262 # Conversely we need to distinguish different kinds of changes to
263 # debian/ and debian/patches/.
264 # Also, here we have, and want to use, trees_diff_walk, because
265 # we may be calling this an awful lot and we want it to be fast.
270 no warnings qw(exiting);
272 my $plain = sub { $_[0] =~ m{^(100|0*)644 blob }s; };
274 trees_diff_walk "$x:", "$y:", sub {
275 my ($n,$ix,$iy) = @_;
277 # analyse difference at the toplevel
279 if ($n ne 'debian/') {
283 if ($n eq 'debian') {
284 # one side has a non-tree for ./debian !
285 $differs |= D_DEB_OTH;
289 my $xd = $ix && "$x:debian";
290 my $yd = $iy && "$y:debian";
291 trees_diff_walk $xd, $yd, sub {
292 my ($n,$ix,$iy) = @_;
294 # analyse difference in debian/
296 if ($n eq 'changelog' && (!$ix || $plain->($ix))
298 $differs |= D_DEB_CLOG;
301 if ($n ne 'patches/') {
302 $differs |= D_DEB_OTH;
306 my $xp = $ix && "$xd/patches";
307 my $yp = $iy && "$yd/patches";
308 trees_diff_walk $xp, $yp, sub {
309 my ($n,$ix,$iy) = @_;
311 # analyse difference in debian/patches
314 if ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
316 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
317 my $x_s = (git_cat_file "$xp/series", 'blob');
318 my $y_s = (git_cat_file "$yp/series", 'blob');
319 chomp $x_s; $x_s .= "\n";
320 $ok = $x_s eq substr($y_s, 0, length $x_s);
324 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
329 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
334 sub commit_pr_info ($) {
336 return Data::Dumper->dump([$r], [qw(commit)]);
339 sub calculate_committer_authline () {
340 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
341 'DUMMY COMMIT (git-debrebase)', "HEAD:";
342 my ($h,$m) = get_commit $c;
343 $h =~ m/^committer .*$/m or confess "($h) ?";
347 sub rm_subdir_cached ($) {
349 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
352 sub read_tree_subdir ($$) {
353 my ($subdir, $new_tree_object) = @_;
354 rm_subdir_cached $subdir;
355 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
358 sub read_tree_debian ($) {
360 read_tree_subdir 'debian', "$treeish:debian";
361 rm_subdir_cached 'debian/patches';
364 sub read_tree_upstream ($;$$) {
365 my ($treeish, $keep_patches, $tree_with_debian) = @_;
366 # if $tree_with_debian is supplied, will use that for debian/
367 # otherwise will save and restore it.
369 $tree_with_debian ? "$tree_with_debian:debian"
370 : cmdoutput @git, qw(write-tree --prefix=debian/);
371 runcmd @git, qw(read-tree), $treeish;
372 read_tree_subdir 'debian', $debian;
373 rm_subdir_cached 'debian/patches' unless $keep_patches;
376 sub make_commit ($$) {
377 my ($parents, $message_paras) = @_;
378 my $tree = cmdoutput @git, qw(write-tree);
379 my @cmd = (@git, qw(commit-tree), $tree);
380 push @cmd, qw(-p), $_ foreach @$parents;
381 push @cmd, qw(-m), $_ foreach @$message_paras;
382 return cmdoutput @cmd;
385 our @snag_force_opts;
387 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
388 if (grep { $_ eq $tag } @snag_force_opts) {
390 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
393 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
397 # Important: all mainline code must call snags_maybe_bail after
398 # any point where snag might be called, but before making changes
399 # (eg before any call to run_deferred_updates). snags_maybe_bail
400 # may be called more than once if necessary (but this is not ideal
401 # because then the messages about number of snags may be confusing).
402 sub snags_maybe_bail () {
403 return if all_snags_summarised();
406 "%s: snags: %d overriden by individual -f options\n",
409 if ($snags_tripped) {
412 "%s: snags: %d overriden by global --force\n",
416 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
420 $snags_summarised = $snags_forced + $snags_tripped;
422 sub snags_maybe_bail_early () {
423 # useful to bail out early without doing a lot of work;
424 # not a substitute for snags_maybe_bail.
425 snags_maybe_bail() if $snags_tripped && !$opt_force;
428 return $snags_forced || $snags_tripped;
431 sub gbp_pq_export ($$$) {
432 my ($bname, $base, $tip) = @_;
433 # must be run in a workarea. $bname and patch-queue/$bname
434 # ought not to exist. Leaves you on patch-queue/$bname with
435 # the patches staged but not committed.
436 printdebug "gbp_pq_export $bname $base $tip\n";
437 runcmd @git, qw(checkout -q -b), $bname, $base;
438 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
439 my @gbp_cmd = (qw(gbp pq export));
440 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
442 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
445 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
449 # MERGE-TODO allow merge resolution separately from laundering, before git merge
452 # use git-format-patch?
453 # our own patch identification algorithm?
454 # this is an alternative strategy
456 sub merge_failed ($$;@) {
457 my ($wrecknotes, $emsg, @xmsgs) = @_;
459 push @m, "Merge resolution failed: $emsg";
465 merge_wreckage_cleaning \@updates;
466 run_ref_updates_now "merge failed", \@updates;
470 while (my ($k,$v) = each %$wrecknotes) {
471 push @updates, "create $wrecknoteprefix/$k $v";
473 run_ref_updates_now "merge failed", \@updates;
474 push @m, "Wreckage left in $wrecknoteprefix/*.";
476 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
478 # use finish rather than fail, in case we are within an eval
479 # (that can happen inside walk!)
481 print STDERR "$us: $_\n" foreach @m;
485 sub mwrecknote ($$$) {
486 my ($wrecknotes, $reftail, $commitish) = @_;
487 confess unless defined $commitish;
488 printdebug "mwrecknote $reftail $commitish\n";
489 $wrecknotes->{$reftail} = $commitish;
492 sub merge_attempt_cmd {
493 my $wrecknotes = shift @_;
497 merge_failed $wrecknotes,
498 failedcmd_waitstatus(),
499 "failed command: @_";
503 sub merge_series_patchqueue_convert ($$$);
505 sub merge_series ($$$;@) {
506 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
507 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
508 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
509 # ^ specifies several patch series (currently we only support exactly 2)
510 # return value is a commit which is the result of
511 # merging the two versions of the same topic branch
512 # $input_q[0] and $input_q[1]
513 # with respect to the old version
517 # Creates, in *_q, a key MR for its private use
519 printdebug "merge_series newbase=$newbase\n";
521 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
522 $base_q->{MR}{S} = 'base';
525 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
526 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
527 # $prereq{<patch filename>} exists or not (even later)
531 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
533 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
536 fresh_workarea "merge";
537 my $seriesfile = "debian/patches/series";
540 foreach my $q ($base_q, reverse @input_qs) {
542 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
544 if (open S, $seriesfile) {
545 while (my $patch = <S>) {
546 chomp $patch or die $!;
547 $prereq{$patch} //= {};
548 foreach my $earlier (@earlier) {
549 $prereq{$patch}{$earlier}{$s}++ and die;
551 push @earlier, $patch;
552 stat "debian/patches/$patch" or die "$patch ?";
554 S->error and die "$seriesfile $!";
557 die "$seriesfile $!" unless $!==ENOENT;
559 read_tree_upstream $newbase, 1;
560 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
561 "Convert $s to patch queue for merging",
562 "[git-debrebase merge-innards patch-queue import:".
565 printdebug "merge_series pec $pec ";
566 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
567 $pec = make_commit [ $pec ], [
568 "Drop series file from $s to avoid merge trouble",
569 "[git-debrebase merge-innards patch-queue prep:".
573 read_tree_debian $newbase;
575 read_tree_subdir 'debian/patches', "$pec:debian/patches";
577 rm_subdir_cached 'debian/patches';
579 $pec = make_commit [ $pec ], [
580 "Update debian/ (excluding patches) to final to avoid re-merging",
581 "debian/ was already merged and we need to just take that.",
582 "[git-debrebase merge-innards patch-queue packaging:".
586 printdebug "pec' $pec\n";
587 runcmd @git, qw(reset -q --hard), $pec;
588 $q->{MR}{PEC} = $pec;
589 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
591 # now, because of reverse, we are on $input_q->{MR}{OQC}
592 runcmd @git, qw(checkout -q -b merge);
593 printdebug "merge_series merging...\n";
594 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
596 $attempt_cmd->(@mergecmd);
598 printdebug "merge_series merge ok, series...\n";
599 # We need to construct a new series file
600 # Firstly, resolve prereq
601 foreach my $f (sort keys %prereq) {
602 printdebug "merge_series patch\t$f\t";
603 if (!stat_exists "debian/patches/$f") {
604 print DEBUG " drop\n" if $debuglevel;
605 # git merge deleted it; that's how we tell it's not wanted
609 print DEBUG " keep\n" if $debuglevel;
610 foreach my $g (sort keys %{ $prereq{$f} }) {
611 my $gfp = $prereq{$f}{$g};
612 printdebug "merge_series prereq\t$f\t-> $g\t";
613 if (!!$gfp->{0} == !!$gfp->{1}
616 print DEBUG "\tkeep\n" if $debuglevel;
618 print DEBUG "\tdrop\n" if $debuglevel;
619 delete $prereq{$f}{$g};
626 return scalar keys %{ $prereq{$f} };
629 my $nodate = time + 1;
631 # $authordate{<patch filename>};
632 my $authordate = sub {
634 $authordate{$f} //= do {
635 open PF, "<", "debian/patches/$f" or die "$f $!";
637 return $nodate if m/^$/;
638 last if s{^Date: }{};
641 return cmdoutput qw(date +%s -d), $_;
645 open NS, '>', $seriesfile or die $!;
647 while (keys %prereq) {
649 foreach my $try (sort keys %prereq) {
652 $unsat->($try) <=> $unsat->($best) or
653 $authordate->($try) <=> $authordate->($best) or
659 printdebug "merge_series series next $best\n";
660 print NS "$best\n" or die $!;
661 delete $prereq{$best};
662 foreach my $gp (values %prereq) {
667 runcmd @git, qw(add), $seriesfile;
668 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
669 $merged_pq = git_rev_parse 'HEAD';
670 $mwrecknote->('merged-patchqueue', $merged_pq);
672 return merge_series_patchqueue_convert
673 $wrecknotes, $newbase, $merged_pq;
676 sub merge_series_patchqueue_convert ($$$) {
677 my ($wrecknotes, $newbase, $merged_pq) = @_;
682 printdebug "merge_series series gbp pq import\n";
683 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
685 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
686 # MERGE-TODO consider git-format-patch etc. instead,
687 # since gbp pq doesn't always round-trip :-/
689 # OK now we are on patch-queue/merge, and we need to rebase
690 # onto the intended parent and drop the patches from each one
692 printdebug "merge_series series ok, building...\n";
693 my $build = $newbase;
694 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
695 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
696 my $commit = git_cat_file $c, 'commit';
697 printdebug "merge_series series ok, building $c\n";
698 read_tree_upstream $c, 0, $newbase;
699 my $tree = cmdoutput @git, qw(write-tree);
700 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
701 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
702 open C, ">", "../mcommit" or die $!;
703 print C $commit or die $!;
705 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
708 mwrecknote($wrecknotes, 'merged-result', $result);
710 runcmd @git, qw(update-ref refs/heads/result), $result;
712 runcmd @git, qw(checkout -q -b debug);
713 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
714 runcmd @git, qw(add .);
715 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
716 my $mdebug = git_rev_parse 'HEAD';
717 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
718 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
720 printdebug "merge_series returns $result\n";
724 # classify returns an info hash like this
726 # Hdr => # commit headers, including 1 final newline
727 # Msg => # commit message (so one newline is dropped)
729 # Type => (see below)
731 # Ix => $index # ie 0, 1, 2, ...
733 # Differs => return value from get_differs
735 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
737 # NewMsg => # commit message, but with any [dgit import ...] edited
738 # # to say "[was: ...]"
748 # has additional entres in classification result
749 # Overwritten = [ subset of Parents ]
750 # Contributor = $the_remaining_Parent
752 # DgitImportUnpatched
753 # has additional entry in classification result
754 # OrigParents = [ subset of Parents ]
757 # has additional entry in classification result
758 # OrigParents = [ subset of Parents ] # singleton list
765 # has additional entry in classification result
768 sub parsecommit ($;$) {
769 my ($objid, $p_ref) = @_;
770 # => hash with CommitId Hdr Msg Tree Parents
771 # Parents entries have only Ix CommitId
772 # $p_ref, if provided, must be [] and is used as a base for Parents
777 my ($h,$m) = get_commit $objid;
779 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
780 my (@ph) = $h =~ m/^parent (\w+)$/mg;
790 foreach my $ph (@ph) {
792 Ix => scalar @$p_ref,
804 my $r = parsecommit($objid, \@p);
808 $p->{Differs} = (get_differs $p->{CommitId}, $t),
811 printdebug "classify $objid \$t=$t \@p",
812 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
816 my ($type, @rest) = @_;
817 $r = { %$r, Type => $type, @rest };
819 printdebug " = $type ".(dd $r)."\n";
825 $r = { %$r, Type => qw(Unknown), Why => $why };
826 printdebug " ** Unknown\n";
830 if (grep { $_ eq $objid } @opt_anchors) {
831 return $classify->('TreatAsAnchor');
834 my @identical = grep { !$_->{Differs} } @p;
835 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
836 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
838 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
839 # multi-orig upstreams are represented with an anchor merge
840 # from a single upstream commit which combines the orig tarballs
842 # Every anchor tagged this way must be a merge.
843 # We are relying on the
844 # [git-debrebase anchor: ...]
845 # commit message annotation in "declare" anchor merges (which
846 # do not have any upstream changes), to distinguish those
847 # anchor merges from ordinary pseudomerges (which we might
848 # just try to strip).
850 # However, the user is going to be doing git-rebase a lot. We
851 # really don't want them to rewrite an anchor commit.
852 # git-rebase trips up on merges, so that is a useful safety
855 # BreakwaterStart commits are also anchors in the terminology
856 # of git-debrebase(5), but they are untagged (and always
857 # manually generated).
859 # We cannot not tolerate any tagged linear commit (ie,
860 # BreakwaterStart commits tagged `[anchor:') because such a
861 # thing could result from an erroneous linearising raw git
862 # rebase of a merge anchor. That would represent a corruption
863 # of the branch. and we want to detect and reject the results
864 # of such corruption before it makes it out anywhere. If we
865 # reject it here then we avoid making the pseudomerge which
866 # would be needed to push it.
868 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
869 @p == 2 or return $badanchor->("has other than two parents");
870 $haspatches and return $badanchor->("contains debian/patches");
872 # How to decide about l/r ordering of anchors ? git
873 # --topo-order prefers to expand 2nd parent first. There's
874 # already an easy rune to look for debian/ history anyway (git log
875 # debian/) so debian breakwater branch should be 1st parent; that
876 # way also there's also an easy rune to look for the upstream
877 # patches (--topo-order).
879 # Also this makes --first-parent be slightly more likely to
880 # be useful - it makes it provide a linearised breakwater history.
882 # Of course one can say somthing like
883 # gitk -- ':/' ':!/debian'
884 # to get _just_ the commits touching upstream files, and by
885 # the TREESAME logic in git-rev-list this will leave the
886 # breakwater into upstream at the first anchor. But that
887 # doesn't report debian/ changes at all.
889 # Other observations about gitk: by default, gitk seems to
890 # produce output in a different order to git-rev-list. I
891 # can't seem to find this documented anywhere. gitk
892 # --date-order DTRT. But, gitk always seems to put the
893 # parents from left to right, in order, so it's easy to see
894 # which way round a pseudomerge is.
896 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
897 $p[1]{Differs} & ~DS_DEB and
898 $badanchor->("upstream files differ from left parent");
899 $p[0]{Differs} & ~D_UPS and
900 $badanchor->("debian/ differs from right parent");
902 return $classify->(qw(Anchor),
903 OrigParents => [ $p[1] ]);
907 my $d = $r->{Parents}[0]{Differs};
908 if ($d == D_PAT_ADD) {
909 return $classify->(qw(AddPatches));
910 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
911 return $unknown->("edits debian/patches");
912 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
913 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
915 if ($d == D_DEB_CLOG) {
916 return $classify->(qw(Changelog));
918 return $classify->(qw(Packaging));
920 } elsif ($ty eq 'missing') {
921 return $classify->(qw(BreakwaterStart));
923 return $unknown->("parent's debian is not a directory");
925 } elsif ($d == D_UPS) {
926 return $classify->(qw(Upstream));
927 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
928 return $classify->(qw(Mixed));
930 return $unknown->("no changes");
932 confess "internal error $objid ?";
936 return $unknown->("origin commit");
939 if (@p == 2 && @identical == 1) {
940 my @overwritten = grep { $_->{Differs} } @p;
941 confess "internal error $objid ?" unless @overwritten==1;
942 return $classify->(qw(Pseudomerge),
943 Overwritten => [ $overwritten[0] ],
944 Contributor => $identical[0]);
946 if (@p == 2 && @identical == 2) {
948 my ($ph,$pm) = get_commit $_[0]{CommitId};
949 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
953 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
954 if ($order > 0) { # newer first
955 } elsif ($order < 0) {
956 @bytime = reverse @bytime;
958 # same age, default to order made by -s ours
959 # that is, commit was made by someone who preferred L
961 return $classify->(qw(Pseudomerge),
962 SubType => qw(Ambiguous),
963 Contributor => $bytime[0],
964 Overwritten => [ $bytime[1] ]);
967 my ($p_h, $p_m) = get_commit $p->{CommitId};
968 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
969 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
971 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
973 if (!(grep { !$_->{IsOrigin} } @p) and
974 (@orig_ps >= @p - 1) and
975 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
977 return $classify->(qw(DgitImportUnpatched),
978 OrigParents => \@orig_ps);
982 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
983 return $classify->("MergedBreakwaters");
985 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
986 return $unknown->("unknown kind of merge from $1");
989 return $unknown->("octopus merge");
993 return $unknown->("general two-parent merge");
996 return $classify->("VanillaMerge");
999 sub keycommits ($;$$$$$);
1001 sub mergedbreakwaters_anchor ($) {
1004 foreach my $p (@{ $cl->{Parents} }) {
1005 my ($panchor, $pbw) = keycommits $p->{CommitId},
1006 undef,undef,undef,undef, 1;
1007 $best_anchor = $panchor
1008 if !defined $best_anchor
1009 or is_fast_fwd $best_anchor, $panchor;
1010 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
1011 unless is_fast_fwd $panchor, $best_anchor;
1013 return $best_anchor;
1016 sub keycommits ($;$$$$$) {
1017 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1018 # => ($anchor, $breakwater)
1020 # $unclean->("unclean-$tagsfx", $msg, $cl)
1021 # $furniture->("unclean-$tagsfx", $msg, $cl)
1022 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
1023 # is callled for each situation or commit that
1024 # wouldn't be found in a laundered branch
1025 # $furniture is for furniture commits such as might be found on an
1026 # interchange branch (pseudomerge, d/patches, changelog)
1027 # $trouble is for things whnich prevent the return of
1028 # anchor and breakwater information; if that is ignored,
1029 # then keycommits returns (undef, undef) instead.
1030 # $fatal is for unprocessable commits, and should normally cause
1031 # a failure. If ignored, agaion, (undef, undef) is returned.
1033 # If $claimed_bw, this is supposed to be a breakwater commit.
1035 # If a callback is undef, fail is called instead.
1036 # If a callback is defined but false, the situation is ignored.
1037 # Callbacks may say:
1038 # no warnings qw(exiting); last;
1039 # if the answer is no longer wanted.
1041 my ($anchor, $breakwater);
1042 $breakwater = $head if $claimed_bw;
1046 $fatal //= sub { fail $_[1]; };
1048 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1049 my $why = $mainwhy.$xwhy;
1050 my $m = "branch needs laundering (run git-debrebase): $why";
1051 fail $m unless defined $cb;
1053 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1055 my $found_anchor = sub {
1057 $breakwater //= $clogonly;
1058 $breakwater //= $head;
1059 no warnings qw(exiting);
1063 $cl = classify $head;
1064 my $ty = $cl->{Type};
1065 if ($ty eq 'Packaging') {
1066 $breakwater //= $clogonly;
1067 $breakwater //= $head;
1068 } elsif ($ty eq 'Changelog') {
1069 # this is going to count as the tip of the breakwater
1070 # only if it has no upstream stuff before it
1071 $clogonly //= $head;
1072 } elsif ($ty eq 'Anchor' or
1073 $ty eq 'TreatAsAnchor' or
1074 $ty eq 'BreakwaterStart') {
1075 $found_anchor->($head);
1076 } elsif ($ty eq 'Upstream') {
1077 $x->($unclean, 'ordering',
1078 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1079 if defined $breakwater;
1081 $breakwater = undef;
1082 } elsif ($ty eq 'Mixed') {
1083 $x->($unclean, 'mixed',
1084 "found mixed upstream/packaging commit"," ($head)");
1086 $breakwater = undef;
1087 } elsif ($ty eq 'Pseudomerge' or
1088 $ty eq 'AddPatches') {
1090 $x->($furniture, (lc $ty),
1091 "found interchange bureaucracy commit ($ty)"," ($head)");
1092 } elsif ($ty eq 'DgitImportUnpatched') {
1094 $x->($trouble, 'dgitimport',
1095 "found dgit dsc import"," ($head)");
1096 return (undef,undef);
1098 $x->($fatal, 'unprocessable',
1099 "found bare dgit dsc import with no prior history",
1101 return (undef,undef);
1103 } elsif ($ty eq 'VanillaMerge') {
1104 $x->($trouble, 'vanillamerge',
1105 "found vanilla merge"," ($head)");
1106 return (undef,undef);
1107 } elsif ($ty eq 'MergedBreakwaters') {
1108 $found_anchor->(mergedbreakwaters_anchor $cl);
1110 $x->($fatal, 'unprocessable',
1111 "found unprocessable commit, cannot cope: $cl->{Why}",
1113 return (undef,undef);
1115 $head = $cl->{Parents}[0]{CommitId};
1117 return ($anchor, $breakwater);
1123 $nogenerate,$report, $report_lprefix) = @_;
1124 # => ($tip, $breakwater_tip, $last_anchor)
1125 # (or nothing, if $nogenerate)
1127 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1128 $report_lprefix //= '';
1130 # go through commits backwards
1131 # we generate two lists of commits to apply:
1132 # breakwater branch and upstream patches
1133 my (@brw_cl, @upp_cl, @processed);
1140 my ($prose, $info) = @_;
1141 my $ms = $cl->{Msg};
1144 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1145 return (Msg => $ms);
1147 my $rewrite_from_here = sub {
1149 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1151 push @processed, $sp_cl;
1156 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1159 return unless $report;
1160 print $report $prdelim, $report_lprefix, @_;
1164 my $bomb = sub { # usage: return $bomb->();
1165 print $report " Unprocessable" if $report;
1166 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1169 return (undef,undef);
1171 fail "found unprocessable commit, cannot cope".
1172 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1173 " (commit $cur) (d.".
1174 (join ' ', map { sprintf "%#x", $_->{Differs} }
1175 @{ $cl->{Parents} }).
1182 my $build_start = sub {
1183 my ($msg, $parent) = @_;
1186 no warnings qw(exiting); last;
1191 merge_failed $cl->{MergeWreckNotes}, $emsg;
1194 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1199 $cl = classify $cur;
1200 $cl->{MergeWreckNotes} //= {};
1201 my $ty = $cl->{Type};
1202 my $st = $cl->{SubType};
1203 $prline->("$cl->{CommitId} $cl->{Type}");
1204 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1205 push @processed, $cl;
1206 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1207 if ($ty eq 'AddPatches') {
1209 $rewrite_from_here->(\@upp_cl);
1211 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1215 } elsif ($ty eq 'BreakwaterStart') {
1216 $last_anchor = $cur;
1217 $build_start->('FirstPackaging', $cur);
1218 } elsif ($ty eq 'Upstream') {
1222 } elsif ($ty eq 'Mixed') {
1225 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1228 $queue->(\@brw_cl, "debian");
1229 $queue->(\@upp_cl, "upstream");
1230 $rewrite_from_here->(\@brw_cl);
1233 } elsif ($ty eq 'Pseudomerge') {
1234 my $contrib = $cl->{Contributor}{CommitId};
1235 print $report " Contributor=$contrib" if $report;
1236 push @pseudomerges, $cl;
1237 $rewrite_from_here->(\@upp_cl);
1240 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1241 $last_anchor = $cur;
1242 $build_start->("Anchor", $cur);
1243 } elsif ($ty eq 'DgitImportUnpatched') {
1244 my $pm = $pseudomerges[-1];
1246 # To an extent, this is heuristic. Imports don't have
1247 # a useful history of the debian/ branch. We assume
1248 # that the first pseudomerge after an import has a
1249 # useful history of debian/, and ignore the histories
1250 # from later pseudomerges. Often the first pseudomerge
1251 # will be the dgit import of the upload to the actual
1252 # suite intended by the non-dgit NMUer, and later
1253 # pseudomerges may represent in-archive copies.
1254 my $ovwrs = $pm->{Overwritten};
1255 printf $report " PM=%s \@Overwr:%d",
1256 $pm->{CommitId}, (scalar @$ovwrs)
1259 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1262 my $ovwr = $ovwrs->[0]{CommitId};
1263 printf $report " Overwr=%s", $ovwr if $report;
1264 # This import has a tree which is just like a
1265 # breakwater tree, but it has the wrong history. It
1266 # ought to have the previous breakwater (which the
1267 # pseudomerge overwrote) as an ancestor. That will
1268 # make the history of the debian/ files correct. As
1269 # for the upstream version: either it's the same as
1270 # was ovewritten (ie, same as the previous
1271 # breakwater), in which case that history is precisely
1272 # right; or, otherwise, it was a non-gitish upload of a
1273 # new upstream version. We can tell these apart by
1274 # looking at the tree of the supposed upstream.
1277 SpecialMethod => 'DgitImportDebianUpdate',
1278 $xmsg->("convert dgit import: debian changes")
1281 SpecialMethod => 'DgitImportUpstreamUpdate',
1282 $xmsg->("convert dgit import: upstream update",
1285 $prline->(" Import");
1286 $rewrite_from_here->(\@brw_cl);
1287 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1291 # Everything is from this import. This kind of import
1292 # is already nearly in valid breakwater format, with the
1293 # patches as commits. Unfortunately it contains
1295 printdebug "*** WALK BOMB bare dgit import\n";
1296 $cl->{Why} = "bare dgit dsc import";
1300 } elsif ($ty eq 'MergedBreakwaters') {
1301 $last_anchor = mergedbreakwaters_anchor $cl;
1302 $build_start->(' MergedBreakwaters', $cur);
1304 } elsif ($ty eq 'VanillaMerge') {
1305 # User may have merged unstitched branch(es). We will
1306 # have now lost what ffq-prev was then (since the later
1307 # pseudomerge may introduce further changes). The effect
1308 # of resolving such a merge is that we may have to go back
1309 # further in history to find a merge base, since the one
1310 # which was reachable via ffq-prev is no longer findable.
1311 # This is suboptimal, but if it all works we'll have done
1313 # MERGE-TODO we should warn the user in the docs about this
1317 # We expect to find a dominating anchor amongst the
1318 # inputs' anchors. That will be the new anchor.
1320 # More complicated is finding a merge base for the
1321 # breakwaters. We need a merge base that is a breakwater
1322 # commit. The ancestors of breakwater commits are more
1323 # breakwater commits and possibly upstream commits and the
1324 # ancestors of those upstream. Upstreams might have
1325 # arbitrary ancestors. But any upstream commit U is
1326 # either included in both anchors, in which case the
1327 # earlier anchor is a better merge base than any of U's
1328 # ancestors; or U is not included in the older anchor, in
1329 # which case U is not an ancestor of the vanilla merge at
1330 # all. So no upstream commit, nor any ancestor thereof,
1331 # is a best merge base. As for non-breakwater Debian
1332 # commits: these are never ancestors of any breakwater.
1334 # So any best merge base as found by git-merge-base
1335 # is a suitable breakwater anchor. Usually there will
1338 printdebug "*** MERGE\n";
1340 my @bwbcmd = (@git, qw(merge-base));
1341 my @ibcmd = (@git, qw(merge-base --all));
1342 my $might_be_in_bw = 1;
1344 my $ps = $cl->{Parents};
1346 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1348 foreach my $p (@$ps) {
1349 $prline->(" VanillaMerge ".$p->{Ix});
1351 my ($ptip, $pbw, $panchor) =
1352 walk $p->{CommitId}, 0, $report,
1353 $report_lprefix.' ';
1354 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1355 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1356 $p->{Anchor} = $panchor;
1358 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1359 $mwrecknote->("$lr-input", $p->{CommitId});
1361 my $mwrecknote_parent = sub {
1363 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1365 $mwrecknote_parent->('Laundered');
1366 $mwrecknote_parent->('Breakwater');
1367 $mwrecknote_parent->('Anchor');
1369 $best_anchor = $panchor if
1370 !defined $best_anchor or
1371 is_fast_fwd $best_anchor, $panchor;
1373 printdebug " MERGE BA best=".($best_anchor//'-').
1377 $mwrecknote->('result-anchor', $best_anchor);
1379 foreach my $p (@$ps) {
1380 $prline->(" VanillaMerge ".$p->{Ix});
1381 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1382 $nomerge->('divergent anchors');
1383 } elsif ($p->{Anchor} eq $best_anchor) {
1384 print $report " SameAnchor" if $report;
1386 print $report " SupersededAnchor" if $report;
1388 if ($p->{Breakwater} eq $p->{CommitId}) {
1389 # this parent commit was its own breakwater,
1390 # ie it is part of the breakwater
1391 print $report " Breakwater" if $report;
1393 $might_be_in_bw = 0;
1395 push @bwbcmd, $p->{Breakwater};
1396 push @ibcmd, $p->{CommitId};
1399 if ($ok && $might_be_in_bw) {
1400 # We could rewrite this to contaion the metadata
1401 # declaring it to be MergedBreakwaters, but
1402 # unnecessarily rewriting a merge seems unhelpful.
1403 $prline->(" VanillaMerge MergedBreakwaters");
1404 $last_anchor = $best_anchor;
1405 $build_start->('MergedBreakwaters', $cur);
1408 my $bwb = cmdoutput @bwbcmd;
1410 # OK, now we have a breakwater base, but we need the merge
1411 # base for the interchange branch because we need the delta
1414 # This a the best merge base of our inputs which has the
1415 # breakwater merge base as an ancestor.
1422 @ibs or confess 'internal error, expected anchor at least ?';
1426 foreach my $tibix (0..$#ibs) {
1427 my $tib = $ibs[$tibix];
1428 my $ff = is_fast_fwd $bwb, $tib;
1429 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1430 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1431 $mwrecknote->($tibleaf, $tib);
1438 $ib or $nomerge->("no suitable interchange merge base");
1440 $prline->(" VanillaMerge Base");
1442 my ($btip, $bbw, $banchor) = eval {
1443 walk $ib, 0, $report, $report_lprefix.' ';
1445 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1449 $mwrecknote->("mergebase-laundered", $btip);
1450 $mwrecknote->("mergebase-breakwater", $bbw);
1451 $mwrecknote->("mergebase-anchor", $banchor);
1453 my $ibinfo = { SeriesTip => $btip,
1456 LeftRight => 'mergebase' };
1459 or $nomerge->("interchange merge-base ($ib)'s".
1460 " breakwater ($bbw)".
1461 " != breakwaters' merge-base ($bwb)");
1463 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1464 or $nomerge->("interchange merge-base ($ib)'s".
1465 " anchor ($ibinfo->{SeriesBase})".
1466 " != any merge input's anchor (".
1467 (join ' ', map { $_->{Anchor} } @$ps).
1470 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1471 $cl->{MergeBestAnchor} = $best_anchor;
1474 SpecialMethod => 'MergeCreateMergedBreakwaters',
1475 $xmsg->('constructed from vanilla merge',
1476 ' merged-breakwater'),
1480 SpecialMethod => 'MergeMergeSeries',
1482 $build_start->('MergeBreakwaters', $cur);
1484 printdebug "*** WALK BOMB unrecognised\n";
1490 printdebug "*** WALK prep done cur=$cur".
1491 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1493 return if $nogenerate;
1495 # Now we build it back up again
1501 $#upp_cl = $upp_limit if defined $upp_limit;
1503 my $committer_authline = calculate_committer_authline();
1505 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1507 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1510 mkdir $rd or $!==EEXIST or die $!;
1512 my $want_debian = $build;
1513 my $want_upstream = $build;
1515 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1516 my $read_tree_debian = sub { ($want_debian) = @_; };
1518 foreach my $cl (qw(Debian), (reverse @brw_cl),
1519 { SpecialMethod => 'RecordBreakwaterTip' },
1520 qw(Upstream), (reverse @upp_cl)) {
1522 $current_method = $cl;
1525 my $method = $cl->{SpecialMethod} // $current_method;
1526 my @parents = ($build);
1527 my $cltree = $cl->{CommitId};
1528 printdebug "WALK BUILD ".($cltree//'undef').
1529 " $method (rewriting=$rewriting)\n";
1530 if ($method eq 'Debian') {
1531 $read_tree_debian->($cltree);
1532 } elsif ($method eq 'Upstream') {
1533 $read_tree_upstream->($cltree);
1534 } elsif ($method eq 'StartRewrite') {
1537 } elsif ($method eq 'RecordBreakwaterTip') {
1538 $breakwater = $build;
1540 } elsif ($method eq 'DgitImportDebianUpdate') {
1541 $read_tree_debian->($cltree);
1542 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1543 confess unless $rewriting;
1544 my $differs = (get_differs $build, $cltree);
1545 next unless $differs & D_UPS;
1546 $read_tree_upstream->($cltree);
1547 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1548 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1549 print "Found a general merge, will try to tidy it up.\n";
1551 $read_tree_upstream->($cl->{MergeBestAnchor});
1552 $read_tree_debian->($cltree);
1553 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1554 } elsif ($method eq 'MergeMergeSeries') {
1555 my $cachehit = reflog_cache_lookup
1556 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1558 print "Using supplied resolution for $cl->{CommitId}...\n";
1560 $mwrecknote->('cached-resolution', $build);
1562 print "Running merge resolution for $cl->{CommitId}...\n";
1563 $mwrecknote->('new-base', $build);
1564 $build = merge_series
1565 $build, $cl->{MergeWreckNotes},
1566 $cl->{MergeInterchangeBaseInfo},
1567 @{ $cl->{Parents} };
1569 $last_anchor = $cl->{MergeBestAnchor};
1571 # Check for mismerges:
1573 my ($against, $allow, $what) = @_;
1574 my $differs = get_differs $build, $against;
1576 "merge misresolved: %s are not the same (%s %s d.%#x)",
1577 $what, $against, $build, $differs)
1578 if $differs & ~($allow | D_PAT_ADD);
1581 # Breakwater changes which were in each side of the
1582 # merge will have been incorporated into the
1583 # MergeCreateMergedBreakwaters output. Because the
1584 # upstream series was rebased onto the new breakwater,
1585 # so should all of the packaging changes which were in
1587 $check->($input, D_UPS, 'debian files');
1589 # Upstream files are merge_series, which ought to
1590 # have been identical to the original merge.
1591 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1593 print "Merge resolution successful.\n";
1596 confess "$method ?";
1599 my $procd = (pop @processed) // 'UNDEF';
1600 if ($cl ne $procd) {
1602 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1606 read_tree_upstream $want_upstream, 0, $want_debian;
1608 my $newtree = cmdoutput @git, qw(write-tree);
1609 my $ch = $cl->{Hdr};
1610 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1611 $ch =~ s{^parent .*\n}{}mg;
1612 $ch =~ s{(?=^author)}{
1613 join '', map { "parent $_\n" } @parents
1614 }me or confess "$ch ?";
1616 $ch =~ s{^committer .*$}{$committer_authline}m
1619 my $cf = "$rd/m$rewriting";
1620 open CD, ">", $cf or die $!;
1621 print CD $ch, "\n", $cl->{Msg} or die $!;
1623 my @cmd = (@git, qw(hash-object));
1624 push @cmd, qw(-w) if $rewriting;
1625 push @cmd, qw(-t commit), $cf;
1626 my $newcommit = cmdoutput @cmd;
1627 confess "$ch ?" unless $rewriting
1628 or $newcommit eq $cl->{CommitId};
1629 $build = $newcommit;
1631 $build = $cl->{CommitId};
1632 trees_diff_walk "$want_upstream:", "$build:", sub {
1634 no warnings qw(exiting);
1635 next if $n eq 'debian/';
1636 confess "mismatch @_ ?";
1638 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1639 confess "mismatch @_ ?";
1641 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1642 confess "mismatch @parents != @old_parents ?"
1643 unless "@parents" eq "@old_parents";
1645 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1646 $last_anchor = $cur;
1651 my $final_check = get_differs $build, $input;
1652 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1653 if $final_check & ~D_PAT_ADD;
1655 my @r = ($build, $breakwater, $last_anchor);
1656 printdebug "*** WALK RETURN @r\n";
1661 git_check_unmodified();
1662 return git_rev_parse qw(HEAD);
1665 sub update_head ($$$) {
1666 my ($old, $new, $mrest) = @_;
1667 push @deferred_updates, "update HEAD $new $old";
1668 run_deferred_updates $mrest;
1671 sub update_head_checkout ($$$) {
1672 my ($old, $new, $mrest) = @_;
1673 update_head $old, $new, $mrest;
1674 runcmd @git, qw(reset --hard);
1677 sub update_head_postlaunder ($$$) {
1678 my ($old, $tip, $reflogmsg) = @_;
1679 return if $tip eq $old && !@deferred_updates;
1680 print "git-debrebase: laundered (head was $old)\n";
1681 update_head $old, $tip, $reflogmsg;
1682 # no tree changes except debian/patches
1683 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1686 sub currently_rebasing() {
1687 foreach (qw(rebase-merge rebase-apply)) {
1688 return 1 if stat_exists "$maindir_gitdir/$_";
1693 sub bail_if_rebasing() {
1694 fail "you are in the middle of a git-rebase already"
1695 if currently_rebasing();
1698 sub do_launder_head ($) {
1699 my ($reflogmsg) = @_;
1700 my $old = get_head();
1702 my ($tip,$breakwater) = walk $old;
1704 update_head_postlaunder $old, $tip, $reflogmsg;
1705 return ($tip,$breakwater);
1708 sub cmd_launder_v0 () {
1709 badusage "no arguments to launder-v0 allowed" if @ARGV;
1710 my $old = get_head();
1711 my ($tip,$breakwater,$last_anchor) = walk $old;
1712 update_head_postlaunder $old, $tip, 'launder';
1713 printf "# breakwater tip\n%s\n", $breakwater;
1714 printf "# working tip\n%s\n", $tip;
1715 printf "# last anchor\n%s\n", $last_anchor;
1718 sub defaultcmd_rebase () {
1719 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1720 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1721 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1724 sub cmd_analyse () {
1725 badusage "analyse does not support any options"
1726 if @ARGV and $ARGV[0] =~ m/^-/;
1727 badusage "too many arguments to analyse" if @ARGV>1;
1730 $old = git_rev_parse $old;
1732 $old = git_rev_parse 'HEAD';
1734 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1735 STDOUT->error and die $!;
1738 sub ffq_prev_branchinfo () {
1739 my $current = git_get_symref();
1740 return gdr_ffq_prev_branchinfo($current);
1743 sub ffq_check ($;$$) {
1744 # calls $ff and/or $notff zero or more times
1745 # then returns either (status,message) where status is
1750 # or (undef,undef, $ffq_prev,$gdrlast)
1751 # $ff and $notff are called like this:
1752 # $ff->("message for stdout\n");
1753 # $notff->('snag-name', $message);
1754 # normally $currentval should be HEAD
1755 my ($currentval, $ff, $notff) =@_;
1757 $ff //= sub { print $_[0] or die $!; };
1760 my ($status, $message, $current, $ffq_prev, $gdrlast)
1761 = ffq_prev_branchinfo();
1762 return ($status, $message) unless $status eq 'branch';
1764 my $exists = git_get_ref $ffq_prev;
1765 return ('exists',"$ffq_prev already exists") if $exists;
1767 return ('not-branch', 'HEAD symref is not to refs/heads/')
1768 unless $current =~ m{^refs/heads/};
1771 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1774 printdebug "ffq check_specs @check_specs\n";
1777 my ($lrref, $desc) = @_;
1778 printdebug "ffq might check $lrref ($desc)\n";
1780 for my $chk (@check_specs) {
1782 $invert = $glob =~ s{^[!^]}{};
1783 last if fnmatch $glob, $lrref;
1786 my $lrval = git_get_ref $lrref;
1787 return unless length $lrval;
1789 if (is_fast_fwd $lrval, $currentval) {
1790 $ff->("OK, you are ahead of $lrref\n");
1791 $checked{$lrref} = 1;
1792 } elsif (is_fast_fwd $currentval, $lrval) {
1793 $checked{$lrref} = -1;
1794 $notff->('behind', "you are behind $lrref, divergence risk");
1796 $checked{$lrref} = -1;
1797 $notff->('diverged', "you have diverged from $lrref");
1801 my $merge = cfg "branch.$branch.merge",1;
1802 if (defined $merge and $merge =~ m{^refs/heads/}) {
1804 printdebug "ffq merge $rhs\n";
1805 my $check_remote = sub {
1806 my ($remote, $desc) = @_;
1807 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1808 return unless defined $remote;
1809 $check->("refs/remotes/$remote/$rhs", $desc);
1811 $check_remote->((scalar cfg "branch.$branch.remote",1),
1812 'remote fetch/merge branch');
1813 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1814 (scalar cfg "branch.$branch.pushDefault",1),
1815 'remote push branch');
1817 if ($branch =~ m{^dgit/}) {
1818 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1819 } elsif ($branch =~ m{^master$}) {
1820 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1822 return (undef, undef, $ffq_prev, $gdrlast);
1825 sub record_ffq_prev_deferred () {
1826 # => ('status', "message")
1828 # deferred message is undef
1833 # if not ff from some branch we should be ff from, is an snag
1834 # if "deferred", will have added something about that to
1835 # @deferred_update_messages, and also maybe printed (already)
1836 # some messages about ff checks
1838 my $currentval = get_head();
1840 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1841 return ($status,$message) if defined $status;
1845 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1846 push @deferred_updates, "delete $gdrlast";
1847 push @deferred_update_messages, "Recorded previous head for preservation";
1848 return ('deferred', undef);
1851 sub record_ffq_auto () {
1852 my ($status, $message) = record_ffq_prev_deferred();
1853 if ($status eq 'deferred' || $status eq 'exists') {
1855 snag $status, "could not record ffq-prev: $message";
1860 sub ffq_prev_info () {
1862 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1863 my ($status, $message, $current, $ffq_prev, $gdrlast)
1864 = ffq_prev_branchinfo();
1865 if ($status ne 'branch') {
1866 snag $status, "could not check ffq-prev: $message";
1869 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1870 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1873 sub stitch ($$$$$) {
1874 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1876 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1878 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1879 my $differs = get_differs $old_head, $ffq_prev_commitish;
1880 unless ($differs & ~D_PAT_ADD) {
1881 # ffq-prev is ahead of us, and the only tree changes it has
1882 # are possibly addition of things in debian/patches/.
1883 # Just wind forwards rather than making a pointless pseudomerge.
1884 push @deferred_updates,
1885 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1886 update_head_checkout $old_head, $ffq_prev_commitish,
1887 "stitch (fast forward)";
1892 # We make pseudomerges with L as the contributing parent.
1893 # This makes git rev-list --first-parent work properly.
1894 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1895 'Declare fast forward / record previous work',
1896 "[git-debrebase pseudomerge: $prose]",
1898 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1899 update_head $old_head, $new_head, "stitch: $prose";
1902 sub do_stitch ($;$) {
1903 my ($prose, $unclean) = @_;
1905 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1906 if (!$ffq_prev_commitish) {
1907 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1910 my $dangling_head = get_head();
1912 keycommits $dangling_head, $unclean,$unclean,$unclean;
1915 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1918 sub upstream_commitish_search ($$) {
1919 my ($upstream_version, $tried) = @_;
1920 # todo: at some point maybe use git-deborig to do this
1921 foreach my $tagpfx ('', 'v', 'upstream/') {
1922 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1923 my $new_upstream = git_get_ref "refs/tags/$tag";
1925 return $new_upstream if length $new_upstream;
1929 sub resolve_upstream_version ($$) {
1930 my ($new_upstream, $upstream_version) = @_;
1932 if (!defined $new_upstream) {
1934 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1935 if (!length $new_upstream) {
1936 fail "Could not determine appropriate upstream commitish.\n".
1937 " (Tried these tags: @tried)\n".
1938 " Check version, and specify upstream commitish explicitly.";
1941 $new_upstream = git_rev_parse $new_upstream;
1943 return $new_upstream;
1946 sub cmd_new_upstream () {
1947 # automatically and unconditionally launders before rebasing
1948 # if rebase --abort is used, laundering has still been done
1952 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1954 # parse args - low commitment
1955 my $spec_version = shift @ARGV;
1956 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1957 fail "bad version number \`$spec_version'" unless defined $new_version;
1958 if ($new_version->is_native()) {
1959 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1962 my $new_upstream = shift @ARGV;
1963 my $new_upstream_version = upstreamversion $new_version;
1965 resolve_upstream_version $new_upstream, $new_upstream_version;
1970 my ($n, @x) = @_; # may be ''
1971 my $pc = $pieces{$n} //= {
1973 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1975 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1980 my $newpiece = sub {
1981 my ($n, @x) = @_; # may be ''
1982 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1983 push @newpieces, $pc;
1988 New => $new_upstream,
1990 while (@ARGV && $ARGV[0] !~ m{^-}) {
1991 my $n = shift @ARGV;
1993 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1994 unless @ARGV && $ARGV[0] !~ m{^-};
1996 my $c = git_rev_parse shift @ARGV;
1997 die unless $n =~ m/^$extra_orig_namepart_re$/;
1998 $newpiece->($n, New => $c);
2001 # now we need to investigate the branch this generates the
2002 # laundered version but we don't switch to it yet
2003 my $old_head = get_head();
2004 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2006 my $old_bw_cl = classify $old_bw;
2007 my $old_anchor_cl = classify $old_anchor;
2009 if (!$old_anchor_cl->{OrigParents}) {
2010 snag 'anchor-treated',
2011 'old anchor is recognised due to --anchor, cannot check upstream';
2013 $old_upstream = parsecommit
2014 $old_anchor_cl->{OrigParents}[0]{CommitId};
2015 $piece->('', Old => $old_upstream->{CommitId});
2018 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2019 if ($old_upstream->{Msg} =~
2020 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2022 my @oldpieces = (split / /, $1);
2023 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2024 if ($old_n_parents != @oldpieces &&
2025 $old_n_parents != @oldpieces + 1) {
2026 snag 'upstream-confusing', sprintf
2027 "previous upstream combine %s".
2028 " mentions %d pieces (each implying one parent)".
2029 " but has %d parents".
2030 " (one per piece plus maybe a previous combine)",
2031 $old_upstream->{CommitId},
2032 (scalar @oldpieces),
2034 } elsif ($oldpieces[0] ne '.') {
2035 snag 'upstream-confusing', sprintf
2036 "previous upstream combine %s".
2037 " first piece is not \`.'",
2041 foreach my $i (0..$#oldpieces) {
2042 my $n = $oldpieces[$i];
2043 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2044 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2048 snag 'upstream-confusing',
2049 "previous upstream $old_upstream->{CommitId} is from".
2050 " git-debrebase but not an \`upstream-combine' commit";
2054 foreach my $pc (values %pieces) {
2055 if (!$old_upstream) {
2056 # we have complained already
2057 } elsif (!$pc->{Old}) {
2058 snag 'upstream-new-piece',
2059 "introducing upstream piece \`$pc->{Name}'";
2060 } elsif (!$pc->{New}) {
2061 snag 'upstream-rm-piece',
2062 "dropping upstream piece \`$pc->{Name}'";
2063 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2064 snag 'upstream-not-ff',
2065 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2069 printdebug "%pieces = ", (dd \%pieces), "\n";
2070 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2078 my @upstream_merge_parents;
2081 push @upstream_merge_parents, $old_upstream->{CommitId};
2084 foreach my $pc (@newpieces) { # always has '' first
2086 read_tree_subdir $pc->{Name}, $pc->{New};
2088 runcmd @git, qw(read-tree), $pc->{New};
2090 push @upstream_merge_parents, $pc->{New};
2093 # index now contains the new upstream
2095 if (@newpieces > 1) {
2096 # need to make the upstream subtree merge commit
2097 $new_upstream = make_commit \@upstream_merge_parents,
2098 [ "Combine upstreams for $new_upstream_version",
2099 ("[git-debrebase upstream-combine . ".
2100 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2105 # $new_upstream is either the single upstream commit, or the
2106 # combined commit we just made. Either way it will be the
2107 # "upstream" parent of the anchor merge.
2109 read_tree_subdir 'debian', "$old_bw:debian";
2111 # index now contains the anchor merge contents
2112 $new_bw = make_commit [ $old_bw, $new_upstream ],
2113 [ "Update to upstream $new_upstream_version",
2114 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2117 my $clogsignoff = cmdoutput qw(git show),
2118 '--pretty=format:%an <%ae> %aD',
2121 # Now we have to add a changelog stanza so the Debian version
2123 die if unlink "debian";
2124 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2125 unlink "debian/changelog" or $!==ENOENT or die $!;
2126 mkdir "debian" or die $!;
2127 open CN, ">", "debian/changelog" or die $!;
2128 my $oldclog = git_cat_file ":debian/changelog";
2129 $oldclog =~ m/^($package_re) \(\S+\) / or
2130 fail "cannot parse old changelog to get package name";
2132 print CN <<END, $oldclog or die $!;
2133 $p ($new_version) UNRELEASED; urgency=medium
2135 * Update to new upstream version $new_upstream_version.
2141 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2143 # Now we have the final new breakwater branch in the index
2144 $new_bw = make_commit [ $new_bw ],
2145 [ "Update changelog for new upstream $new_upstream_version",
2146 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2150 # we have constructed the new breakwater. we now need to commit to
2151 # the laundering output, because git-rebase can't easily be made
2152 # to make a replay list which is based on some other branch
2154 update_head_postlaunder $old_head, $old_laundered_tip,
2155 'launder for new upstream';
2157 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2158 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2159 "debrebase new-upstream $new_version: rebase";
2161 # now it's for the user to sort out
2164 sub cmd_record_ffq_prev () {
2165 badusage "no arguments allowed" if @ARGV;
2166 my ($status, $msg) = record_ffq_prev_deferred();
2167 if ($status eq 'exists' && $opt_noop_ok) {
2168 print "Previous head already recorded\n" or die $!;
2169 } elsif ($status eq 'deferred') {
2170 run_deferred_updates 'record-ffq-prev';
2172 fail "Could not preserve: $msg";
2177 badusage "no arguments allowed" if @ARGV;
2178 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2179 print "$bw\n" or die $!;
2182 sub cmd_breakwater () {
2183 badusage "no arguments allowed" if @ARGV;
2184 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2185 print "$bw\n" or die $!;
2189 badusage "no arguments allowed" if @ARGV;
2191 # todo: gdr status should print divergence info
2192 # todo: gdr status should print upstream component(s) info
2193 # todo: gdr should leave/maintain some refs with this kind of info ?
2195 my $oldest = { Badness => 0 };
2198 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2199 if ($oldest->{Badness} < $badness) {
2200 $oldest = $newest = undef;
2203 Badness => $badness,
2204 CommitId => $cl->{CommitId},
2208 $newest //= $oldest;
2210 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2211 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2212 sub { $note->(2, 'branch is unlaundered', @_); },
2213 sub { $note->(3, 'branch needs laundering', @_); },
2214 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2216 my $prcommitinfo = sub {
2218 flush STDOUT or die $!;
2219 runcmd @git, qw(--no-pager log -n1),
2220 '--pretty=format: %h %s%n',
2224 print "current branch contents, in git-debrebase terms:\n";
2225 if (!$oldest->{Badness}) {
2226 print " branch is laundered\n";
2228 print " $oldest->{OurMsg}\n";
2230 foreach my $info ($oldest, $newest) {
2231 my $cid = $info->{CommitId};
2232 next if $cid eq $printed;
2234 print " $info->{KcMsg}\n";
2235 $prcommitinfo->($cid);
2240 my ($cid, $what) = @_;
2241 if (!defined $cid) {
2242 print " $what is not well-defined\n";
2245 $prcommitinfo->($cid);
2248 print "key git-debrebase commits:\n";
2249 $prab->($anchor, 'anchor');
2250 $prab->($bw, 'breakwater');
2252 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2253 ffq_prev_branchinfo();
2255 print "branch and ref status, in git-debrebase terms:\n";
2257 print " $ffq_msg\n";
2259 $ffq_prev = git_get_ref $ffq_prev;
2260 $gdrlast = git_get_ref $gdrlast;
2262 print " unstitched; previous tip was:\n";
2263 $prcommitinfo->($ffq_prev);
2264 } elsif (!$gdrlast) {
2265 print " stitched? (no record of git-debrebase work)\n";
2266 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2267 print " stitched\n";
2269 print " not git-debrebase (diverged since last stitch)\n"
2272 print "you are currently rebasing\n" if currently_rebasing();
2276 my $prose = 'stitch';
2277 getoptions("stitch",
2278 'prose=s', \$prose);
2279 badusage "no arguments allowed" if @ARGV;
2280 do_stitch $prose, 0;
2282 sub cmd_prepush () {
2288 badusage "no arguments allowed" if @ARGV;
2289 do_launder_head 'launder for git-debrebase quick';
2293 sub cmd_conclude () {
2294 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2295 if (!$ffq_prev_commitish) {
2296 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2299 my $dangling_head = get_head();
2301 badusage "no arguments allowed" if @ARGV;
2302 do_launder_head 'launder for git-debrebase quick';
2307 if (currently_rebasing()) {
2308 runcmd @git, qw(rebase --abort);
2309 push @deferred_updates, 'verify HEAD HEAD';
2310 # noop, but stops us complaining that scrap was a noop
2312 badusage "no arguments allowed" if @ARGV;
2313 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2315 if ($ffq_prev_commitish) {
2316 $scrapping_head = get_head();
2317 push @deferred_updates,
2318 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2319 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2321 if (git_get_ref $merge_cache_ref) {
2322 push @deferred_updates,
2323 "delete $merge_cache_ref";
2325 if (!@deferred_updates) {
2326 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2330 if ($scrapping_head) {
2331 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2333 run_deferred_updates "scrap";
2337 sub make_patches_staged ($) {
2339 # Produces the patches that would result from $head if it were
2341 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2344 gbp_pq_export 'bw', $secret_bw, $secret_head;
2348 sub make_patches ($) {
2350 keycommits $head, 0, \&snag;
2351 make_patches_staged $head;
2354 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2355 runcmd @git, qw(read-tree), $head;
2356 read_tree_subdir 'debian/patches', $ptree;
2357 $out = make_commit [$head], [
2358 'Commit patch queue (exported by git-debrebase)',
2359 '[git-debrebase: export and commit patches]',
2365 sub cmd_make_patches () {
2366 my $opt_quiet_would_amend;
2367 getoptions("make-patches",
2368 'quiet-would-amend!', \$opt_quiet_would_amend);
2369 badusage "no arguments allowed" if @ARGV;
2371 my $old_head = get_head();
2372 my $new = make_patches $old_head;
2373 my $d = get_differs $old_head, $new;
2375 fail "No (more) patches to export." unless $opt_noop_ok;
2377 } elsif ($d == D_PAT_ADD) {
2379 update_head_checkout $old_head, $new, 'make-patches';
2381 print STDERR failmsg
2382 "Patch export produced patch amendments".
2383 " (abandoned output commit $new).".
2384 " Try laundering first."
2385 unless $opt_quiet_would_amend;
2390 sub check_series_has_all_patches ($) {
2392 my $seriesfn = 'debian/patches/series';
2393 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2397 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2398 fail "patch $f repeated in $seriesfn !" if $series{$f}++;
2400 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2401 my ($f,$i) = @$patchfile;
2402 next if $series{$f};
2403 next if $f eq 'series';
2404 snag 'unused-patches', "Unused patch file $f will be discarded";
2408 sub cmd_convert_from_gbp () {
2409 badusage "want only 1 optional argument, the upstream git commitish"
2412 my $clogp = parsechangelog();
2413 my $version = $clogp->{'Version'}
2414 // die "missing Version from changelog";
2416 my ($upstream_spec) = @ARGV;
2418 my $upstream_version = upstreamversion $version;
2420 resolve_upstream_version($upstream_spec, $upstream_version);
2422 my $old_head = get_head();
2424 my $upsdiff = get_differs $upstream, $old_head;
2425 if ($upsdiff & D_UPS) {
2426 runcmd @git, qw(--no-pager diff --stat),
2427 $upstream, $old_head,
2428 qw( -- :!/debian :/);
2430 upstream ($upstream_spec) and HEAD are not
2431 identical in upstream files. See diffstat above, or run
2432 git diff $upstream_spec HEAD -- :!/debian :/
2436 if (!is_fast_fwd $upstream, $old_head) {
2437 snag 'upstream-not-ancestor',
2438 "upstream ($upstream) is not an ancestor of HEAD";
2440 my $wrong = cmdoutput
2441 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2442 qw(-- :/ :!/debian));
2443 if (length $wrong) {
2444 snag 'unexpected-upstream-changes',
2445 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2446 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2450 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2451 snag 'upstream-has-debian',
2452 "upstream ($upstream) contains debian/ directory";
2455 check_series_has_all_patches $old_head;
2457 my $previous_dgit_view = eval {
2458 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2460 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2461 my ($stz, $desc) = @_;
2462 no warnings qw(exiting);
2463 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2464 next unless $stz->{Date};
2465 next unless $stz->{Distribution} ne 'UNRELEASED';
2466 $lvsn = $stz->{Version};
2467 $suite = $stz->{Distribution};
2470 die "neither of the first two changelog entries are released\n"
2471 unless defined $lvsn;
2472 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2473 my $mtag_pat = debiantag_maintview $lvsn, '*';
2474 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2476 die "could not find suitable maintainer view tag $mtag_pat\n"
2477 unless $mtag =~ m{/};
2478 is_fast_fwd $mtag, 'HEAD' or
2479 die "HEAD is not FF from maintainer tag $mtag!";
2480 my $dtag = "archive/$mtag";
2481 git_get_ref "refs/tags/$dtag" or
2482 die "dgit view tag $dtag not found\n";
2483 is_fast_fwd $mtag, $dtag or
2484 die "dgit view tag $dtag is not FF from maintainer tag $mtag\n";
2485 print "will stitch in dgit view, $dtag\n";
2486 git_rev_parse $dtag;
2488 if (!$previous_dgit_view) {
2492 Cannot confirm dgit view: $@
2493 Failed to stitch in dgit view (see messages above).
2494 dgit --overwrite will be needed on the first dgit push after conversion.
2498 snags_maybe_bail_early();
2504 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2505 # make a branch out of the patch queue - we'll want this in a mo
2506 runcmd qw(gbp pq import);
2507 # strip the patches out
2508 runcmd @git, qw(checkout -q gdr-internal~0);
2509 rm_subdir_cached 'debian/patches';
2510 $work = make_commit ['HEAD'], [
2511 'git-debrebase convert-from-gbp: drop patches from tree',
2512 'Delete debian/patches, as part of converting to git-debrebase format.',
2513 '[git-debrebase convert-from-gbp: drop patches from tree]'
2515 # make the anchor merge
2516 # the tree is already exactly right
2517 $work = make_commit [$work, $upstream], [
2518 'git-debrebase import: declare upstream',
2519 'First breakwater merge.',
2520 '[git-debrebase anchor: declare upstream]'
2523 # rebase the patch queue onto the new breakwater
2524 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2525 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2526 $work = git_rev_parse 'HEAD';
2528 if ($previous_dgit_view) {
2529 $work = make_commit [$work, $previous_dgit_view], [
2530 'git-debrebase import: declare ff from dgit archive view',
2531 '[git-debrebase pseudomerge: import-from-gbp]',
2538 update_head_checkout $old_head, $work, 'convert-from-gbp';
2539 print <<END or die $!;
2540 git-debrebase: converted from patched-unapplied (gbp) branch format, OK
2544 sub cmd_convert_to_gbp () {
2545 badusage "no arguments allowed" if @ARGV;
2546 my $head = get_head();
2547 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2548 keycommits $head, 0;
2550 make_patches_staged $head;
2552 $out = make_commit ['HEAD'], [
2553 'Commit patch queue (converted from git-debrebase format)',
2554 '[git-debrebase convert-to-gbp: commit patches]',
2558 push @deferred_updates, "delete $ffq";
2559 push @deferred_updates, "delete $gdrlast";
2562 update_head_checkout $head, $out, "convert to gbp (v0)";
2563 print <<END or die $!;
2564 git-debrebase: converted to git-buildpackage branch format
2565 git-debrebase: WARNING: do not now run "git-debrebase" any more
2566 git-debrebase: WARNING: doing so would drop all upstream patches!
2570 sub cmd_convert_from_dgit_view () {
2571 my $clogp = parsechangelog();
2573 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2579 getoptions("convert-from-dgit-view",
2580 'diagnose!', \$diagnose,
2581 'build-products-dir:s', \$bpd,
2582 'origs!', \$do_origs,
2584 'always-convert-anyway!', \$always);
2585 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2590 my $spec = shift @ARGV;
2591 my $commit = git_rev_parse "$spec^{commit}";
2592 push @upstreams, { Commit => $commit,
2593 Source => "$ARGV[0], from command line",
2598 my $head = get_head();
2602 my $trouble = sub { $troubles++; };
2603 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2604 printdebug "troubles=$troubles\n";
2607 $us: Branch already seems to be in git-debrebase format!
2608 $us: --always-convert-anyway would do the conversion operation anyway
2609 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2611 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2616 check_series_has_all_patches $head;
2618 snags_maybe_bail_early();
2620 my $version = upstreamversion $clogp->{Version};
2621 print STDERR "Considering possible commits corresponding to upstream:\n";
2626 my $ups_tag = upstream_commitish_search $version, \@tried;
2628 my $this = "git tag $tried[-1]";
2629 push @upstreams, { Commit => $ups_tag,
2634 " git tag: no suitable tag found (tried %s)\n",
2639 my $p = $clogp->{'Source'};
2640 # we do a quick check to see if there are plausible origs
2642 if (!opendir BPD, $bpd) {
2643 die "$bpd: opendir: $!" unless $!==ENOENT;
2645 while ($!=0, my $f = readdir BPD) {
2646 next unless is_orig_file_of_p_v $f, $p, $version;
2648 " orig: found what looks like a .orig, %s\n",
2653 die "read $bpd: $!" if $!;
2657 my $tree = cmdoutput
2658 @dgit, qw(--build-products-dir), $bpd,
2659 qw(print-unapplied-treeish);
2662 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2663 rm_subdir_cached 'debian';
2664 $tree = cmdoutput @git, qw(write-tree);
2665 my $ups_synth = make_commit [], [ <<END, <<END,
2666 Import effective orig tree for upstream version $version
2668 This includes the contents of the .orig(s), minus any debian/ directory.
2670 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2673 push @upstreams, { Commit => $ups_synth,
2674 Source => "orig(s) imported via dgit",
2679 " orig: no suitable origs found (looked for %s in %s)\n",
2680 "${p}_".(stripeoch $version)."...", $bpd;
2685 my $some_patches = stat_exists 'debian/patches/series';
2687 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2690 foreach my $u (@upstreams) {
2694 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2695 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2696 runcmd @git, qw(clean -xdff);
2697 runcmd @git, qw(checkout), $head, qw(-- debian);
2698 if ($some_patches) {
2699 rm_subdir_cached 'debian/patches';
2700 $work = make_commit [ $work ], [
2701 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2702 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2703 "to git-debrebase format. Upstream changes will appear as commits.",
2704 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2707 $work = make_commit [ $work, $u->{Commit} ], [
2708 'git-debrebase convert-from-dgit-view: declare upstream',
2709 '(Re)constructed breakwater merge.',
2710 '[git-debrebase anchor: declare upstream]'
2712 runcmd @git, qw(checkout --quiet -b mk), $work;
2713 if ($some_patches) {
2714 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2715 runcmd @git, qw(reset --quiet);
2716 my @gbp_cmd = (qw(gbp pq import));
2718 my $gbp_err = "../gbp-pq-err";
2719 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2721 my $r = system @gbp_cmd;
2724 " %s: couldn't apply patches: gbp pq %s",
2725 $u->{Source}, waitstatusmsg();
2729 my $work = git_rev_parse qw(HEAD);
2730 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2731 if (length $diffout) {
2733 " $u->{Source}: applying patches gives different tree\n";
2734 print STDERR $diffout if $diagnose;
2738 $u->{Result} = $work;
2746 Could not find or construct a suitable upstream commit.
2747 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2748 upstream commmit explicitly or provide suitable origs.
2752 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2754 ffq_check $result->{Result};
2756 update_head_checkout $head, $result->{Result},
2757 'convert-from-dgit-view';
2760 sub cmd_record_resolved_merge () {
2761 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2762 # MERGE-TODO needs documentation
2763 my $new = get_head();
2766 print "Checking how you have resolved the merge problem\n";
2767 my $nope = sub { print "Not $method: @_"; 0; };
2769 my $maybe = sub { print "Seems to be $method.\n"; };
2771 my ($key, $ref) = @_;
2772 reflog_cache_insert $merge_cache_ref, $key, $ref;
2773 print "OK. You can switch branches and try git-debrebase again.\n";
2777 fresh_workarea 'merge';
2779 $method = 'vanilla-merge patchqueue';
2780 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2781 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2782 foreach my $lr (qw(left right)) {
2783 my $n = "$wrecknoteprefix/$lr-patchqueue";
2784 my $lrpq = git_get_ref $n;
2785 $lrpq or return $nope->("wreckage did not contain patchqueues");
2786 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2789 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2790 or die "wreckage element $wrecknoteprefix/new-base missing";
2791 my $result = merge_series_patchqueue_convert
2793 $yes->("vanilla-merge $vanilla", $result);
2796 fail "No resolved merge method seems applicable.\n";
2800 sub cmd_downstream_rebase_launder_v0 () {
2801 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2803 $base = git_rev_parse $base;
2804 my $old_head = get_head();
2805 my $current = $old_head;
2808 if ($current eq $base) {
2809 $topmost_keep //= $current;
2810 print " $current BASE stop\n";
2813 my $cl = classify $current;
2814 print " $current $cl->{Type}";
2816 my $p0 = $cl->{Parents}[0]{CommitId};
2818 if ($cl->{Type} eq 'Pseudomerge') {
2819 print " ^".($cl->{Contributor}{Ix}+1);
2820 $next = $cl->{Contributor}{CommitId};
2821 } elsif ($cl->{Type} eq 'AddPatches' or
2822 $cl->{Type} eq 'Changelog') {
2832 $topmost_keep //= $current;
2834 die "to-be stripped changes not on top of the branch\n"
2839 if ($topmost_keep eq $old_head) {
2840 print "unchanged\n";
2842 print "updating to $topmost_keep\n";
2843 update_head_checkout
2844 $old_head, $topmost_keep,
2845 'downstream-rebase-launder-v0';
2851 "D+" => \$debuglevel,
2852 'noop-ok', => \$opt_noop_ok,
2853 'f=s' => \@snag_force_opts,
2854 'anchor=s' => \@opt_anchors,
2855 '--dgit=s' => \($dgit[0]),
2857 'experimental-merge-resolution!', \$opt_merges,
2859 my ($opt,$val) = @_;
2860 badusage "git-debrebase: no cuddling to -i for git-rebase"
2862 die if $opt_defaultcmd_interactive; # should not happen
2863 $opt_defaultcmd_interactive = [ qw(-i) ];
2864 # This access to @ARGV is excessive familiarity with
2865 # Getopt::Long, but there isn't another sensible
2866 # approach. '-i=s{0,}' does not work with bundling.
2867 push @$opt_defaultcmd_interactive, @ARGV;
2870 'help' => sub { print $usage_message or die $!; finish 0; },
2873 initdebug('git-debrebase ');
2874 enabledebug if $debuglevel;
2876 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2877 chdir $toplevel or die "chdir $toplevel: $!";
2879 $rd = fresh_playground "$playprefix/misc";
2881 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2883 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2884 defaultcmd_rebase();
2886 my $cmd = shift @ARGV;
2889 $cmdfn = ${*::}{"cmd_$cmdfn"};
2891 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";