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 ffq_prev_branchinfo () {
432 my $current = git_get_symref();
433 return gdr_ffq_prev_branchinfo($current);
436 sub record_gdrlast ($$;$) {
437 my ($gdrlast, $newvalue, $oldvalue) = @_;
438 $oldvalue ||= $git_null_obj;
439 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
442 sub fail_unprocessable ($) {
445 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
448 Branch/history seems mangled - no longer in gdr format.
449 See ILLEGAL OPERATIONS in git-debrebase(5).
456 Is this meant to be a gdr branch? $ffqm
458 } elsif (git_get_ref $ffq_prev) {
462 Consider git-debrebase scrap, to throw away your recent work.
464 } elsif (!git_get_ref $gdrlast) {
467 Branch does not seem to be meant to be a git-debrebase branch?
468 Wrong branch, or maybe you needed git-debrebase convert-from-*.
470 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
478 Branch/history mangled, and diverged since last git-debrebase.
479 Maybe you reset to, or rebased from, somewhere inappropriate.
484 sub gbp_pq_export ($$$) {
485 my ($bname, $base, $tip) = @_;
486 # must be run in a workarea. $bname and patch-queue/$bname
487 # ought not to exist. Leaves you on patch-queue/$bname with
488 # the patches staged but not committed.
489 printdebug "gbp_pq_export $bname $base $tip\n";
490 runcmd @git, qw(checkout -q -b), $bname, $base;
491 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
492 my @gbp_cmd = (qw(gbp pq export));
493 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
495 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
498 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
502 # MERGE-TODO allow merge resolution separately from laundering, before git merge
505 # use git-format-patch?
506 # our own patch identification algorithm?
507 # this is an alternative strategy
509 sub merge_failed ($$;@) {
510 my ($wrecknotes, $emsg, @xmsgs) = @_;
512 push @m, "Merge resolution failed: $emsg";
518 merge_wreckage_cleaning \@updates;
519 run_ref_updates_now "merge failed", \@updates;
523 while (my ($k,$v) = each %$wrecknotes) {
524 push @updates, "create $wrecknoteprefix/$k $v";
526 run_ref_updates_now "merge failed", \@updates;
527 push @m, "Wreckage left in $wrecknoteprefix/*.";
529 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
531 # use finish rather than fail, in case we are within an eval
532 # (that can happen inside walk!)
534 print STDERR "$us: $_\n" foreach @m;
538 sub mwrecknote ($$$) {
539 my ($wrecknotes, $reftail, $commitish) = @_;
540 confess unless defined $commitish;
541 printdebug "mwrecknote $reftail $commitish\n";
542 $wrecknotes->{$reftail} = $commitish;
545 sub merge_attempt_cmd {
546 my $wrecknotes = shift @_;
550 merge_failed $wrecknotes,
551 failedcmd_waitstatus(),
552 "failed command: @_";
556 sub merge_series_patchqueue_convert ($$$);
558 sub merge_series ($$$;@) {
559 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
560 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
561 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
562 # ^ specifies several patch series (currently we only support exactly 2)
563 # return value is a commit which is the result of
564 # merging the two versions of the same topic branch
565 # $input_q[0] and $input_q[1]
566 # with respect to the old version
570 # Creates, in *_q, a key MR for its private use
572 printdebug "merge_series newbase=$newbase\n";
574 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
575 $base_q->{MR}{S} = 'base';
578 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
579 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
580 # $prereq{<patch filename>} exists or not (even later)
584 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
586 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
589 fresh_workarea "merge";
590 my $seriesfile = "debian/patches/series";
593 foreach my $q ($base_q, reverse @input_qs) {
595 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
597 if (open S, $seriesfile) {
598 while (my $patch = <S>) {
599 chomp $patch or die $!;
600 $prereq{$patch} //= {};
601 foreach my $earlier (@earlier) {
602 $prereq{$patch}{$earlier}{$s}++ and die;
604 push @earlier, $patch;
605 stat "debian/patches/$patch" or die "$patch ?";
607 S->error and die "$seriesfile $!";
610 die "$seriesfile $!" unless $!==ENOENT;
612 read_tree_upstream $newbase, 1;
613 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
614 "Convert $s to patch queue for merging",
615 "[git-debrebase merge-innards patch-queue import:".
618 printdebug "merge_series pec $pec ";
619 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
620 $pec = make_commit [ $pec ], [
621 "Drop series file from $s to avoid merge trouble",
622 "[git-debrebase merge-innards patch-queue prep:".
626 read_tree_debian $newbase;
628 read_tree_subdir 'debian/patches', "$pec:debian/patches";
630 rm_subdir_cached 'debian/patches';
632 $pec = make_commit [ $pec ], [
633 "Update debian/ (excluding patches) to final to avoid re-merging",
634 "debian/ was already merged and we need to just take that.",
635 "[git-debrebase merge-innards patch-queue packaging:".
639 printdebug "pec' $pec\n";
640 runcmd @git, qw(reset -q --hard), $pec;
641 $q->{MR}{PEC} = $pec;
642 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
644 # now, because of reverse, we are on $input_q->{MR}{OQC}
645 runcmd @git, qw(checkout -q -b merge);
646 printdebug "merge_series merging...\n";
647 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
649 $attempt_cmd->(@mergecmd);
651 printdebug "merge_series merge ok, series...\n";
652 # We need to construct a new series file
653 # Firstly, resolve prereq
654 foreach my $f (sort keys %prereq) {
655 printdebug "merge_series patch\t$f\t";
656 if (!stat_exists "debian/patches/$f") {
657 print DEBUG " drop\n" if $debuglevel;
658 # git merge deleted it; that's how we tell it's not wanted
662 print DEBUG " keep\n" if $debuglevel;
663 foreach my $g (sort keys %{ $prereq{$f} }) {
664 my $gfp = $prereq{$f}{$g};
665 printdebug "merge_series prereq\t$f\t-> $g\t";
666 if (!!$gfp->{0} == !!$gfp->{1}
669 print DEBUG "\tkeep\n" if $debuglevel;
671 print DEBUG "\tdrop\n" if $debuglevel;
672 delete $prereq{$f}{$g};
679 return scalar keys %{ $prereq{$f} };
682 my $nodate = time + 1;
684 # $authordate{<patch filename>};
685 my $authordate = sub {
687 $authordate{$f} //= do {
688 open PF, "<", "debian/patches/$f" or die "$f $!";
690 return $nodate if m/^$/;
691 last if s{^Date: }{};
694 return cmdoutput qw(date +%s -d), $_;
698 open NS, '>', $seriesfile or die $!;
700 while (keys %prereq) {
702 foreach my $try (sort keys %prereq) {
705 $unsat->($try) <=> $unsat->($best) or
706 $authordate->($try) <=> $authordate->($best) or
712 printdebug "merge_series series next $best\n";
713 print NS "$best\n" or die $!;
714 delete $prereq{$best};
715 foreach my $gp (values %prereq) {
720 runcmd @git, qw(add), $seriesfile;
721 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
722 $merged_pq = git_rev_parse 'HEAD';
723 $mwrecknote->('merged-patchqueue', $merged_pq);
725 return merge_series_patchqueue_convert
726 $wrecknotes, $newbase, $merged_pq;
729 sub merge_series_patchqueue_convert ($$$) {
730 my ($wrecknotes, $newbase, $merged_pq) = @_;
735 printdebug "merge_series series gbp pq import\n";
736 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
738 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
739 # MERGE-TODO consider git-format-patch etc. instead,
740 # since gbp pq doesn't always round-trip :-/
742 # OK now we are on patch-queue/merge, and we need to rebase
743 # onto the intended parent and drop the patches from each one
745 printdebug "merge_series series ok, building...\n";
746 my $build = $newbase;
747 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
748 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
749 my $commit = git_cat_file $c, 'commit';
750 printdebug "merge_series series ok, building $c\n";
751 read_tree_upstream $c, 0, $newbase;
752 my $tree = cmdoutput @git, qw(write-tree);
753 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
754 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
755 open C, ">", "../mcommit" or die $!;
756 print C $commit or die $!;
758 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
761 mwrecknote($wrecknotes, 'merged-result', $result);
763 runcmd @git, qw(update-ref refs/heads/result), $result;
765 runcmd @git, qw(checkout -q -b debug);
766 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
767 runcmd @git, qw(add .);
768 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
769 my $mdebug = git_rev_parse 'HEAD';
770 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
771 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
773 printdebug "merge_series returns $result\n";
777 # classify returns an info hash like this
779 # Hdr => # commit headers, including 1 final newline
780 # Msg => # commit message (so one newline is dropped)
782 # Type => (see below)
784 # Ix => $index # ie 0, 1, 2, ...
786 # Differs => return value from get_differs
788 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
790 # NewMsg => # commit message, but with any [dgit import ...] edited
791 # # to say "[was: ...]"
801 # has additional entres in classification result
802 # Overwritten = [ subset of Parents ]
803 # Contributor = $the_remaining_Parent
805 # DgitImportUnpatched
806 # has additional entry in classification result
807 # OrigParents = [ subset of Parents ]
810 # has additional entry in classification result
811 # OrigParents = [ subset of Parents ] # singleton list
818 # has additional entry in classification result
821 sub parsecommit ($;$) {
822 my ($objid, $p_ref) = @_;
823 # => hash with CommitId Hdr Msg Tree Parents
824 # Parents entries have only Ix CommitId
825 # $p_ref, if provided, must be [] and is used as a base for Parents
830 my ($h,$m) = get_commit $objid;
832 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
833 my (@ph) = $h =~ m/^parent (\w+)$/mg;
843 foreach my $ph (@ph) {
845 Ix => scalar @$p_ref,
857 my $r = parsecommit($objid, \@p);
861 $p->{Differs} = (get_differs $p->{CommitId}, $t),
864 printdebug "classify $objid \$t=$t \@p",
865 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
869 my ($type, @rest) = @_;
870 $r = { %$r, Type => $type, @rest };
872 printdebug " = $type ".(dd $r)."\n";
878 $r = { %$r, Type => qw(Unknown), Why => $why };
879 printdebug " ** Unknown\n";
883 if (grep { $_ eq $objid } @opt_anchors) {
884 return $classify->('TreatAsAnchor');
887 my @identical = grep { !$_->{Differs} } @p;
888 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
889 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
891 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
892 # multi-orig upstreams are represented with an anchor merge
893 # from a single upstream commit which combines the orig tarballs
895 # Every anchor tagged this way must be a merge.
896 # We are relying on the
897 # [git-debrebase anchor: ...]
898 # commit message annotation in "declare" anchor merges (which
899 # do not have any upstream changes), to distinguish those
900 # anchor merges from ordinary pseudomerges (which we might
901 # just try to strip).
903 # However, the user is going to be doing git-rebase a lot. We
904 # really don't want them to rewrite an anchor commit.
905 # git-rebase trips up on merges, so that is a useful safety
908 # BreakwaterStart commits are also anchors in the terminology
909 # of git-debrebase(5), but they are untagged (and always
910 # manually generated).
912 # We cannot not tolerate any tagged linear commit (ie,
913 # BreakwaterStart commits tagged `[anchor:') because such a
914 # thing could result from an erroneous linearising raw git
915 # rebase of a merge anchor. That would represent a corruption
916 # of the branch. and we want to detect and reject the results
917 # of such corruption before it makes it out anywhere. If we
918 # reject it here then we avoid making the pseudomerge which
919 # would be needed to push it.
921 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
922 @p == 2 or return $badanchor->("has other than two parents");
923 $haspatches and return $badanchor->("contains debian/patches");
925 # How to decide about l/r ordering of anchors ? git
926 # --topo-order prefers to expand 2nd parent first. There's
927 # already an easy rune to look for debian/ history anyway (git log
928 # debian/) so debian breakwater branch should be 1st parent; that
929 # way also there's also an easy rune to look for the upstream
930 # patches (--topo-order).
932 # Also this makes --first-parent be slightly more likely to
933 # be useful - it makes it provide a linearised breakwater history.
935 # Of course one can say somthing like
936 # gitk -- ':/' ':!/debian'
937 # to get _just_ the commits touching upstream files, and by
938 # the TREESAME logic in git-rev-list this will leave the
939 # breakwater into upstream at the first anchor. But that
940 # doesn't report debian/ changes at all.
942 # Other observations about gitk: by default, gitk seems to
943 # produce output in a different order to git-rev-list. I
944 # can't seem to find this documented anywhere. gitk
945 # --date-order DTRT. But, gitk always seems to put the
946 # parents from left to right, in order, so it's easy to see
947 # which way round a pseudomerge is.
949 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
950 $p[1]{Differs} & ~DS_DEB and
951 $badanchor->("upstream files differ from left parent");
952 $p[0]{Differs} & ~D_UPS and
953 $badanchor->("debian/ differs from right parent");
955 return $classify->(qw(Anchor),
956 OrigParents => [ $p[1] ]);
960 my $d = $r->{Parents}[0]{Differs};
961 if ($d == D_PAT_ADD) {
962 return $classify->(qw(AddPatches));
963 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
964 return $unknown->("edits debian/patches");
965 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
966 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
968 if ($d == D_DEB_CLOG) {
969 return $classify->(qw(Changelog));
971 return $classify->(qw(Packaging));
973 } elsif ($ty eq 'missing') {
974 return $classify->(qw(BreakwaterStart));
976 return $unknown->("parent's debian is not a directory");
978 } elsif ($d == D_UPS) {
979 return $classify->(qw(Upstream));
980 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
981 return $classify->(qw(Mixed));
983 return $unknown->("no changes");
985 confess "internal error $objid ?";
989 return $unknown->("origin commit");
992 if (@p == 2 && @identical == 1) {
993 my @overwritten = grep { $_->{Differs} } @p;
994 confess "internal error $objid ?" unless @overwritten==1;
995 return $classify->(qw(Pseudomerge),
996 Overwritten => [ $overwritten[0] ],
997 Contributor => $identical[0]);
999 if (@p == 2 && @identical == 2) {
1001 my ($ph,$pm) = get_commit $_[0]{CommitId};
1002 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
1006 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
1007 if ($order > 0) { # newer first
1008 } elsif ($order < 0) {
1009 @bytime = reverse @bytime;
1011 # same age, default to order made by -s ours
1012 # that is, commit was made by someone who preferred L
1014 return $classify->(qw(Pseudomerge),
1015 SubType => qw(Ambiguous),
1016 Contributor => $bytime[0],
1017 Overwritten => [ $bytime[1] ]);
1019 foreach my $p (@p) {
1020 my ($p_h, $p_m) = get_commit $p->{CommitId};
1021 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1022 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1024 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1026 if (!(grep { !$_->{IsOrigin} } @p) and
1027 (@orig_ps >= @p - 1) and
1028 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1030 return $classify->(qw(DgitImportUnpatched),
1031 OrigParents => \@orig_ps);
1035 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1036 return $classify->("MergedBreakwaters");
1038 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1039 return $unknown->("unknown kind of merge from $1");
1042 return $unknown->("octopus merge");
1046 return $unknown->("general two-parent merge");
1049 return $classify->("VanillaMerge");
1052 sub keycommits ($;$$$$$);
1054 sub mergedbreakwaters_anchor ($) {
1057 foreach my $p (@{ $cl->{Parents} }) {
1058 my ($panchor, $pbw) = keycommits $p->{CommitId},
1059 undef,undef,undef,undef, 1;
1060 $best_anchor = $panchor
1061 if !defined $best_anchor
1062 or is_fast_fwd $best_anchor, $panchor;
1063 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
1064 unless is_fast_fwd $panchor, $best_anchor;
1066 return $best_anchor;
1069 sub keycommits ($;$$$$$) {
1070 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1071 # => ($anchor, $breakwater)
1073 # $unclean->("unclean-$tagsfx", $msg, $cl)
1074 # $furniture->("unclean-$tagsfx", $msg, $cl)
1075 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
1076 # is callled for each situation or commit that
1077 # wouldn't be found in a laundered branch
1078 # $furniture is for furniture commits such as might be found on an
1079 # interchange branch (pseudomerge, d/patches, changelog)
1080 # $trouble is for things whnich prevent the return of
1081 # anchor and breakwater information; if that is ignored,
1082 # then keycommits returns (undef, undef) instead.
1083 # $fatal is for unprocessable commits, and should normally cause
1084 # a failure. If ignored, agaion, (undef, undef) is returned.
1086 # If $claimed_bw, this is supposed to be a breakwater commit.
1088 # If a callback is undef, fail is called instead.
1089 # If a callback is defined but false, the situation is ignored.
1090 # Callbacks may say:
1091 # no warnings qw(exiting); last;
1092 # if the answer is no longer wanted.
1094 my ($anchor, $breakwater);
1095 $breakwater = $head if $claimed_bw;
1099 $fatal //= sub { fail_unprocessable $_[1]; };
1101 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1102 my $why = $mainwhy.$xwhy;
1103 my $m = "branch needs laundering (run git-debrebase): $why";
1104 fail $m unless defined $cb;
1106 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1108 my $found_anchor = sub {
1110 $breakwater //= $clogonly;
1111 $breakwater //= $head;
1112 no warnings qw(exiting);
1116 $cl = classify $head;
1117 my $ty = $cl->{Type};
1118 if ($ty eq 'Packaging') {
1119 $breakwater //= $clogonly;
1120 $breakwater //= $head;
1121 } elsif ($ty eq 'Changelog') {
1122 # this is going to count as the tip of the breakwater
1123 # only if it has no upstream stuff before it
1124 $clogonly //= $head;
1125 } elsif ($ty eq 'Anchor' or
1126 $ty eq 'TreatAsAnchor' or
1127 $ty eq 'BreakwaterStart') {
1128 $found_anchor->($head);
1129 } elsif ($ty eq 'Upstream') {
1130 $x->($unclean, 'ordering',
1131 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1132 if defined $breakwater;
1134 $breakwater = undef;
1135 } elsif ($ty eq 'Mixed') {
1136 $x->($unclean, 'mixed',
1137 "found mixed upstream/packaging commit"," ($head)");
1139 $breakwater = undef;
1140 } elsif ($ty eq 'Pseudomerge' or
1141 $ty eq 'AddPatches') {
1143 $x->($furniture, (lc $ty),
1144 "found interchange bureaucracy commit ($ty)"," ($head)");
1145 } elsif ($ty eq 'DgitImportUnpatched') {
1147 $x->($trouble, 'dgitimport',
1148 "found dgit dsc import"," ($head)");
1149 return (undef,undef);
1151 $x->($fatal, 'unprocessable',
1152 "found bare dgit dsc import with no prior history",
1154 return (undef,undef);
1156 } elsif ($ty eq 'VanillaMerge') {
1157 $x->($trouble, 'vanillamerge',
1158 "found vanilla merge"," ($head)");
1159 return (undef,undef);
1160 } elsif ($ty eq 'MergedBreakwaters') {
1161 $found_anchor->(mergedbreakwaters_anchor $cl);
1163 $x->($fatal, 'unprocessable',
1164 "found unprocessable commit, cannot cope: $cl->{Why}",
1166 return (undef,undef);
1168 $head = $cl->{Parents}[0]{CommitId};
1170 return ($anchor, $breakwater);
1176 $nogenerate,$report, $report_lprefix) = @_;
1177 # => ($tip, $breakwater_tip, $last_anchor)
1178 # (or nothing, if $nogenerate)
1180 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1181 $report_lprefix //= '';
1183 # go through commits backwards
1184 # we generate two lists of commits to apply:
1185 # breakwater branch and upstream patches
1186 my (@brw_cl, @upp_cl, @processed);
1193 my ($prose, $info) = @_;
1194 my $ms = $cl->{Msg};
1197 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1198 return (Msg => $ms);
1200 my $rewrite_from_here = sub {
1202 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1204 push @processed, $sp_cl;
1209 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1212 return unless $report;
1213 print $report $prdelim, $report_lprefix, @_;
1217 my $bomb = sub { # usage: return $bomb->();
1218 print $report " Unprocessable" if $report;
1219 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1222 return (undef,undef);
1224 fail_unprocessable "found unprocessable commit, cannot cope".
1225 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1226 " (commit $cur) (d.".
1227 (join ' ', map { sprintf "%#x", $_->{Differs} }
1228 @{ $cl->{Parents} }).
1235 my $build_start = sub {
1236 my ($msg, $parent) = @_;
1239 no warnings qw(exiting); last;
1244 merge_failed $cl->{MergeWreckNotes}, $emsg;
1247 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1252 $cl = classify $cur;
1253 $cl->{MergeWreckNotes} //= {};
1254 my $ty = $cl->{Type};
1255 my $st = $cl->{SubType};
1256 $prline->("$cl->{CommitId} $cl->{Type}");
1257 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1258 push @processed, $cl;
1259 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1260 if ($ty eq 'AddPatches') {
1262 $rewrite_from_here->(\@upp_cl);
1264 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1268 } elsif ($ty eq 'BreakwaterStart') {
1269 $last_anchor = $cur;
1270 $build_start->('FirstPackaging', $cur);
1271 } elsif ($ty eq 'Upstream') {
1275 } elsif ($ty eq 'Mixed') {
1278 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1281 $queue->(\@brw_cl, "debian");
1282 $queue->(\@upp_cl, "upstream");
1283 $rewrite_from_here->(\@brw_cl);
1286 } elsif ($ty eq 'Pseudomerge') {
1287 my $contrib = $cl->{Contributor}{CommitId};
1288 print $report " Contributor=$contrib" if $report;
1289 push @pseudomerges, $cl;
1290 $rewrite_from_here->(\@upp_cl);
1293 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1294 $last_anchor = $cur;
1295 $build_start->("Anchor", $cur);
1296 } elsif ($ty eq 'DgitImportUnpatched') {
1297 my $pm = $pseudomerges[-1];
1299 # To an extent, this is heuristic. Imports don't have
1300 # a useful history of the debian/ branch. We assume
1301 # that the first pseudomerge after an import has a
1302 # useful history of debian/, and ignore the histories
1303 # from later pseudomerges. Often the first pseudomerge
1304 # will be the dgit import of the upload to the actual
1305 # suite intended by the non-dgit NMUer, and later
1306 # pseudomerges may represent in-archive copies.
1307 my $ovwrs = $pm->{Overwritten};
1308 printf $report " PM=%s \@Overwr:%d",
1309 $pm->{CommitId}, (scalar @$ovwrs)
1312 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1315 my $ovwr = $ovwrs->[0]{CommitId};
1316 printf $report " Overwr=%s", $ovwr if $report;
1317 # This import has a tree which is just like a
1318 # breakwater tree, but it has the wrong history. It
1319 # ought to have the previous breakwater (which the
1320 # pseudomerge overwrote) as an ancestor. That will
1321 # make the history of the debian/ files correct. As
1322 # for the upstream version: either it's the same as
1323 # was ovewritten (ie, same as the previous
1324 # breakwater), in which case that history is precisely
1325 # right; or, otherwise, it was a non-gitish upload of a
1326 # new upstream version. We can tell these apart by
1327 # looking at the tree of the supposed upstream.
1330 SpecialMethod => 'DgitImportDebianUpdate',
1331 $xmsg->("convert dgit import: debian changes")
1334 SpecialMethod => 'DgitImportUpstreamUpdate',
1335 $xmsg->("convert dgit import: upstream update",
1338 $prline->(" Import");
1339 $rewrite_from_here->(\@brw_cl);
1340 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1344 # Everything is from this import. This kind of import
1345 # is already nearly in valid breakwater format, with the
1346 # patches as commits. Unfortunately it contains
1348 printdebug "*** WALK BOMB bare dgit import\n";
1349 $cl->{Why} = "bare dgit dsc import";
1353 } elsif ($ty eq 'MergedBreakwaters') {
1354 $last_anchor = mergedbreakwaters_anchor $cl;
1355 $build_start->(' MergedBreakwaters', $cur);
1357 } elsif ($ty eq 'VanillaMerge') {
1358 # User may have merged unstitched branch(es). We will
1359 # have now lost what ffq-prev was then (since the later
1360 # pseudomerge may introduce further changes). The effect
1361 # of resolving such a merge is that we may have to go back
1362 # further in history to find a merge base, since the one
1363 # which was reachable via ffq-prev is no longer findable.
1364 # This is suboptimal, but if it all works we'll have done
1366 # MERGE-TODO we should warn the user in the docs about this
1370 # We expect to find a dominating anchor amongst the
1371 # inputs' anchors. That will be the new anchor.
1373 # More complicated is finding a merge base for the
1374 # breakwaters. We need a merge base that is a breakwater
1375 # commit. The ancestors of breakwater commits are more
1376 # breakwater commits and possibly upstream commits and the
1377 # ancestors of those upstream. Upstreams might have
1378 # arbitrary ancestors. But any upstream commit U is
1379 # either included in both anchors, in which case the
1380 # earlier anchor is a better merge base than any of U's
1381 # ancestors; or U is not included in the older anchor, in
1382 # which case U is not an ancestor of the vanilla merge at
1383 # all. So no upstream commit, nor any ancestor thereof,
1384 # is a best merge base. As for non-breakwater Debian
1385 # commits: these are never ancestors of any breakwater.
1387 # So any best merge base as found by git-merge-base
1388 # is a suitable breakwater anchor. Usually there will
1391 printdebug "*** MERGE\n";
1393 my @bwbcmd = (@git, qw(merge-base));
1394 my @ibcmd = (@git, qw(merge-base --all));
1395 my $might_be_in_bw = 1;
1397 my $ps = $cl->{Parents};
1399 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1401 foreach my $p (@$ps) {
1402 $prline->(" VanillaMerge ".$p->{Ix});
1404 my ($ptip, $pbw, $panchor) =
1405 walk $p->{CommitId}, 0, $report,
1406 $report_lprefix.' ';
1407 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1408 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1409 $p->{Anchor} = $panchor;
1411 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1412 $mwrecknote->("$lr-input", $p->{CommitId});
1414 my $mwrecknote_parent = sub {
1416 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1418 $mwrecknote_parent->('Laundered');
1419 $mwrecknote_parent->('Breakwater');
1420 $mwrecknote_parent->('Anchor');
1422 $best_anchor = $panchor if
1423 !defined $best_anchor or
1424 is_fast_fwd $best_anchor, $panchor;
1426 printdebug " MERGE BA best=".($best_anchor//'-').
1430 $mwrecknote->('result-anchor', $best_anchor);
1432 foreach my $p (@$ps) {
1433 $prline->(" VanillaMerge ".$p->{Ix});
1434 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1435 $nomerge->('divergent anchors');
1436 } elsif ($p->{Anchor} eq $best_anchor) {
1437 print $report " SameAnchor" if $report;
1439 print $report " SupersededAnchor" if $report;
1441 if ($p->{Breakwater} eq $p->{CommitId}) {
1442 # this parent commit was its own breakwater,
1443 # ie it is part of the breakwater
1444 print $report " Breakwater" if $report;
1446 $might_be_in_bw = 0;
1448 push @bwbcmd, $p->{Breakwater};
1449 push @ibcmd, $p->{CommitId};
1452 if ($ok && $might_be_in_bw) {
1453 # We could rewrite this to contaion the metadata
1454 # declaring it to be MergedBreakwaters, but
1455 # unnecessarily rewriting a merge seems unhelpful.
1456 $prline->(" VanillaMerge MergedBreakwaters");
1457 $last_anchor = $best_anchor;
1458 $build_start->('MergedBreakwaters', $cur);
1461 my $bwb = cmdoutput @bwbcmd;
1463 # OK, now we have a breakwater base, but we need the merge
1464 # base for the interchange branch because we need the delta
1467 # This a the best merge base of our inputs which has the
1468 # breakwater merge base as an ancestor.
1475 @ibs or confess 'internal error, expected anchor at least ?';
1479 foreach my $tibix (0..$#ibs) {
1480 my $tib = $ibs[$tibix];
1481 my $ff = is_fast_fwd $bwb, $tib;
1482 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1483 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1484 $mwrecknote->($tibleaf, $tib);
1491 $ib or $nomerge->("no suitable interchange merge base");
1493 $prline->(" VanillaMerge Base");
1495 my ($btip, $bbw, $banchor) = eval {
1496 walk $ib, 0, $report, $report_lprefix.' ';
1498 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1502 $mwrecknote->("mergebase-laundered", $btip);
1503 $mwrecknote->("mergebase-breakwater", $bbw);
1504 $mwrecknote->("mergebase-anchor", $banchor);
1506 my $ibinfo = { SeriesTip => $btip,
1509 LeftRight => 'mergebase' };
1512 or $nomerge->("interchange merge-base ($ib)'s".
1513 " breakwater ($bbw)".
1514 " != breakwaters' merge-base ($bwb)");
1516 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1517 or $nomerge->("interchange merge-base ($ib)'s".
1518 " anchor ($ibinfo->{SeriesBase})".
1519 " != any merge input's anchor (".
1520 (join ' ', map { $_->{Anchor} } @$ps).
1523 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1524 $cl->{MergeBestAnchor} = $best_anchor;
1527 SpecialMethod => 'MergeCreateMergedBreakwaters',
1528 $xmsg->('constructed from vanilla merge',
1529 ' merged-breakwater'),
1533 SpecialMethod => 'MergeMergeSeries',
1535 $build_start->('MergeBreakwaters', $cur);
1537 printdebug "*** WALK BOMB unrecognised\n";
1543 printdebug "*** WALK prep done cur=$cur".
1544 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1546 return if $nogenerate;
1548 # Now we build it back up again
1554 $#upp_cl = $upp_limit if defined $upp_limit;
1556 my $committer_authline = calculate_committer_authline();
1558 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1560 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1563 mkdir $rd or $!==EEXIST or die $!;
1565 my $want_debian = $build;
1566 my $want_upstream = $build;
1568 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1569 my $read_tree_debian = sub { ($want_debian) = @_; };
1571 foreach my $cl (qw(Debian), (reverse @brw_cl),
1572 { SpecialMethod => 'RecordBreakwaterTip' },
1573 qw(Upstream), (reverse @upp_cl)) {
1575 $current_method = $cl;
1578 my $method = $cl->{SpecialMethod} // $current_method;
1579 my @parents = ($build);
1580 my $cltree = $cl->{CommitId};
1581 printdebug "WALK BUILD ".($cltree//'undef').
1582 " $method (rewriting=$rewriting)\n";
1583 if ($method eq 'Debian') {
1584 $read_tree_debian->($cltree);
1585 } elsif ($method eq 'Upstream') {
1586 $read_tree_upstream->($cltree);
1587 } elsif ($method eq 'StartRewrite') {
1590 } elsif ($method eq 'RecordBreakwaterTip') {
1591 $breakwater = $build;
1593 } elsif ($method eq 'DgitImportDebianUpdate') {
1594 $read_tree_debian->($cltree);
1595 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1596 confess unless $rewriting;
1597 my $differs = (get_differs $build, $cltree);
1598 next unless $differs & D_UPS;
1599 $read_tree_upstream->($cltree);
1600 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1601 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1602 print "Found a general merge, will try to tidy it up.\n";
1604 $read_tree_upstream->($cl->{MergeBestAnchor});
1605 $read_tree_debian->($cltree);
1606 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1607 } elsif ($method eq 'MergeMergeSeries') {
1608 my $cachehit = reflog_cache_lookup
1609 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1611 print "Using supplied resolution for $cl->{CommitId}...\n";
1613 $mwrecknote->('cached-resolution', $build);
1615 print "Running merge resolution for $cl->{CommitId}...\n";
1616 $mwrecknote->('new-base', $build);
1617 $build = merge_series
1618 $build, $cl->{MergeWreckNotes},
1619 $cl->{MergeInterchangeBaseInfo},
1620 @{ $cl->{Parents} };
1622 $last_anchor = $cl->{MergeBestAnchor};
1624 # Check for mismerges:
1626 my ($against, $allow, $what) = @_;
1627 my $differs = get_differs $build, $against;
1629 "merge misresolved: %s are not the same (%s %s d.%#x)",
1630 $what, $against, $build, $differs)
1631 if $differs & ~($allow | D_PAT_ADD);
1634 # Breakwater changes which were in each side of the
1635 # merge will have been incorporated into the
1636 # MergeCreateMergedBreakwaters output. Because the
1637 # upstream series was rebased onto the new breakwater,
1638 # so should all of the packaging changes which were in
1640 $check->($input, D_UPS, 'debian files');
1642 # Upstream files are merge_series, which ought to
1643 # have been identical to the original merge.
1644 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1646 print "Merge resolution successful.\n";
1649 confess "$method ?";
1652 my $procd = (pop @processed) // 'UNDEF';
1653 if ($cl ne $procd) {
1655 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1659 read_tree_upstream $want_upstream, 0, $want_debian;
1661 my $newtree = cmdoutput @git, qw(write-tree);
1662 my $ch = $cl->{Hdr};
1663 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1664 $ch =~ s{^parent .*\n}{}mg;
1665 $ch =~ s{(?=^author)}{
1666 join '', map { "parent $_\n" } @parents
1667 }me or confess "$ch ?";
1669 $ch =~ s{^committer .*$}{$committer_authline}m
1672 my $cf = "$rd/m$rewriting";
1673 open CD, ">", $cf or die $!;
1674 print CD $ch, "\n", $cl->{Msg} or die $!;
1676 my @cmd = (@git, qw(hash-object));
1677 push @cmd, qw(-w) if $rewriting;
1678 push @cmd, qw(-t commit), $cf;
1679 my $newcommit = cmdoutput @cmd;
1680 confess "$ch ?" unless $rewriting
1681 or $newcommit eq $cl->{CommitId};
1682 $build = $newcommit;
1684 $build = $cl->{CommitId};
1685 trees_diff_walk "$want_upstream:", "$build:", sub {
1687 no warnings qw(exiting);
1688 next if $n eq 'debian/';
1689 confess "mismatch @_ ?";
1691 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1692 confess "mismatch @_ ?";
1694 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1695 confess "mismatch @parents != @old_parents ?"
1696 unless "@parents" eq "@old_parents";
1698 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1699 $last_anchor = $cur;
1704 my $final_check = get_differs $build, $input;
1705 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1706 if $final_check & ~D_PAT_ADD;
1708 my @r = ($build, $breakwater, $last_anchor);
1709 printdebug "*** WALK RETURN @r\n";
1714 git_check_unmodified();
1715 return git_rev_parse qw(HEAD);
1718 sub update_head ($$$) {
1719 my ($old, $new, $mrest) = @_;
1720 push @deferred_updates, "update HEAD $new $old";
1721 run_deferred_updates $mrest;
1724 sub update_head_checkout ($$$) {
1725 my ($old, $new, $mrest) = @_;
1726 update_head $old, $new, $mrest;
1727 runcmd @git, qw(reset --hard);
1730 sub update_head_postlaunder ($$$) {
1731 my ($old, $tip, $reflogmsg) = @_;
1732 return if $tip eq $old && !@deferred_updates;
1733 print "git-debrebase: laundered (head was $old)\n";
1734 update_head $old, $tip, $reflogmsg;
1735 # no tree changes except debian/patches
1736 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1739 sub currently_rebasing() {
1740 foreach (qw(rebase-merge rebase-apply)) {
1741 return 1 if stat_exists "$maindir_gitdir/$_";
1746 sub bail_if_rebasing() {
1747 fail "you are in the middle of a git-rebase already"
1748 if currently_rebasing();
1751 sub do_launder_head ($) {
1752 my ($reflogmsg) = @_;
1753 my $old = get_head();
1755 my ($tip,$breakwater) = walk $old;
1757 update_head_postlaunder $old, $tip, $reflogmsg;
1758 return ($tip,$breakwater);
1761 sub cmd_launder_v0 () {
1762 badusage "no arguments to launder-v0 allowed" if @ARGV;
1763 my $old = get_head();
1764 my ($tip,$breakwater,$last_anchor) = walk $old;
1765 update_head_postlaunder $old, $tip, 'launder';
1766 printf "# breakwater tip\n%s\n", $breakwater;
1767 printf "# working tip\n%s\n", $tip;
1768 printf "# last anchor\n%s\n", $last_anchor;
1771 sub defaultcmd_rebase () {
1772 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1773 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1774 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1777 sub cmd_analyse () {
1778 badusage "analyse does not support any options"
1779 if @ARGV and $ARGV[0] =~ m/^-/;
1780 badusage "too many arguments to analyse" if @ARGV>1;
1783 $old = git_rev_parse $old;
1785 $old = git_rev_parse 'HEAD';
1787 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1788 STDOUT->error and die $!;
1791 sub ffq_check ($;$$) {
1792 # calls $ff and/or $notff zero or more times
1793 # then returns either (status,message) where status is
1798 # or (undef,undef, $ffq_prev,$gdrlast)
1799 # $ff and $notff are called like this:
1800 # $ff->("message for stdout\n");
1801 # $notff->('snag-name', $message);
1802 # normally $currentval should be HEAD
1803 my ($currentval, $ff, $notff) =@_;
1805 $ff //= sub { print $_[0] or die $!; };
1808 my ($status, $message, $current, $ffq_prev, $gdrlast)
1809 = ffq_prev_branchinfo();
1810 return ($status, $message) unless $status eq 'branch';
1812 my $exists = git_get_ref $ffq_prev;
1813 return ('exists',"$ffq_prev already exists") if $exists;
1815 return ('not-branch', 'HEAD symref is not to refs/heads/')
1816 unless $current =~ m{^refs/heads/};
1819 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1822 printdebug "ffq check_specs @check_specs\n";
1825 my ($lrref, $desc) = @_;
1826 printdebug "ffq might check $lrref ($desc)\n";
1828 for my $chk (@check_specs) {
1830 $invert = $glob =~ s{^[!^]}{};
1831 last if fnmatch $glob, $lrref;
1834 my $lrval = git_get_ref $lrref;
1835 return unless length $lrval;
1837 if (is_fast_fwd $lrval, $currentval) {
1838 $ff->("OK, you are ahead of $lrref\n");
1839 $checked{$lrref} = 1;
1840 } elsif (is_fast_fwd $currentval, $lrval) {
1841 $checked{$lrref} = -1;
1842 $notff->('behind', "you are behind $lrref, divergence risk");
1844 $checked{$lrref} = -1;
1845 $notff->('diverged', "you have diverged from $lrref");
1849 my $merge = cfg "branch.$branch.merge",1;
1850 if (defined $merge and $merge =~ m{^refs/heads/}) {
1852 printdebug "ffq merge $rhs\n";
1853 my $check_remote = sub {
1854 my ($remote, $desc) = @_;
1855 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1856 return unless defined $remote;
1857 $check->("refs/remotes/$remote/$rhs", $desc);
1859 $check_remote->((scalar cfg "branch.$branch.remote",1),
1860 'remote fetch/merge branch');
1861 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1862 (scalar cfg "branch.$branch.pushDefault",1),
1863 'remote push branch');
1865 if ($branch =~ m{^dgit/}) {
1866 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1867 } elsif ($branch =~ m{^master$}) {
1868 $check->("refs/remotes/dgit/dgit/sid", '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, "Recorded previous head for preservation";
1896 return ('deferred', undef);
1899 sub record_ffq_auto () {
1900 my ($status, $message) = record_ffq_prev_deferred();
1901 if ($status eq 'deferred' || $status eq 'exists') {
1903 snag $status, "could not record ffq-prev: $message";
1908 sub ffq_prev_info () {
1910 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1911 my ($status, $message, $current, $ffq_prev, $gdrlast)
1912 = ffq_prev_branchinfo();
1913 if ($status ne 'branch') {
1914 snag $status, "could not check ffq-prev: $message";
1917 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1918 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1921 sub stitch ($$$$$) {
1922 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1924 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1926 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1927 my $differs = get_differs $old_head, $ffq_prev_commitish;
1928 unless ($differs & ~D_PAT_ADD) {
1929 # ffq-prev is ahead of us, and the only tree changes it has
1930 # are possibly addition of things in debian/patches/.
1931 # Just wind forwards rather than making a pointless pseudomerge.
1932 record_gdrlast $gdrlast, $ffq_prev_commitish;
1933 update_head_checkout $old_head, $ffq_prev_commitish,
1934 "stitch (fast forward)";
1939 # We make pseudomerges with L as the contributing parent.
1940 # This makes git rev-list --first-parent work properly.
1941 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1942 'Declare fast forward / record previous work',
1943 "[git-debrebase pseudomerge: $prose]",
1945 record_gdrlast $gdrlast, $new_head;
1946 update_head $old_head, $new_head, "stitch: $prose";
1949 sub do_stitch ($;$) {
1950 my ($prose, $unclean) = @_;
1952 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1953 if (!$ffq_prev_commitish) {
1954 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1957 my $dangling_head = get_head();
1959 keycommits $dangling_head, $unclean,$unclean,$unclean;
1962 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1965 sub upstream_commitish_search ($$) {
1966 my ($upstream_version, $tried) = @_;
1967 # todo: at some point maybe use git-deborig to do this
1968 foreach my $tagpfx ('', 'v', 'upstream/') {
1969 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1970 my $new_upstream = git_get_ref "refs/tags/$tag";
1972 return $new_upstream if length $new_upstream;
1976 sub resolve_upstream_version ($$) {
1977 my ($new_upstream, $upstream_version) = @_;
1979 if (!defined $new_upstream) {
1981 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1982 if (!length $new_upstream) {
1983 fail "Could not determine appropriate upstream commitish.\n".
1984 " (Tried these tags: @tried)\n".
1985 " Check version, and specify upstream commitish explicitly.";
1988 $new_upstream = git_rev_parse $new_upstream;
1990 return $new_upstream;
1993 sub cmd_new_upstream () {
1994 # automatically and unconditionally launders before rebasing
1995 # if rebase --abort is used, laundering has still been done
1999 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
2001 # parse args - low commitment
2002 my $spec_version = shift @ARGV;
2003 my $new_version = (new Dpkg::Version $spec_version, check => 1);
2004 fail "bad version number \`$spec_version'" unless defined $new_version;
2005 if ($new_version->is_native()) {
2006 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
2009 my $new_upstream = shift @ARGV;
2010 my $new_upstream_version = upstreamversion $new_version;
2012 resolve_upstream_version $new_upstream, $new_upstream_version;
2017 my ($n, @x) = @_; # may be ''
2018 my $pc = $pieces{$n} //= {
2020 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
2022 while (my $k = shift @x) { $pc->{$k} = shift @x; }
2027 my $newpiece = sub {
2028 my ($n, @x) = @_; # may be ''
2029 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2030 push @newpieces, $pc;
2035 New => $new_upstream,
2037 while (@ARGV && $ARGV[0] !~ m{^-}) {
2038 my $n = shift @ARGV;
2040 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2041 unless @ARGV && $ARGV[0] !~ m{^-};
2043 my $c = git_rev_parse shift @ARGV;
2044 die unless $n =~ m/^$extra_orig_namepart_re$/;
2045 $newpiece->($n, New => $c);
2048 # now we need to investigate the branch this generates the
2049 # laundered version but we don't switch to it yet
2050 my $old_head = get_head();
2051 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2053 my $old_bw_cl = classify $old_bw;
2054 my $old_anchor_cl = classify $old_anchor;
2056 if (!$old_anchor_cl->{OrigParents}) {
2057 snag 'anchor-treated',
2058 'old anchor is recognised due to --anchor, cannot check upstream';
2060 $old_upstream = parsecommit
2061 $old_anchor_cl->{OrigParents}[0]{CommitId};
2062 $piece->('', Old => $old_upstream->{CommitId});
2065 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2066 if ($old_upstream->{Msg} =~
2067 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2069 my @oldpieces = (split / /, $1);
2070 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2071 if ($old_n_parents != @oldpieces &&
2072 $old_n_parents != @oldpieces + 1) {
2073 snag 'upstream-confusing', sprintf
2074 "previous upstream combine %s".
2075 " mentions %d pieces (each implying one parent)".
2076 " but has %d parents".
2077 " (one per piece plus maybe a previous combine)",
2078 $old_upstream->{CommitId},
2079 (scalar @oldpieces),
2081 } elsif ($oldpieces[0] ne '.') {
2082 snag 'upstream-confusing', sprintf
2083 "previous upstream combine %s".
2084 " first piece is not \`.'",
2088 foreach my $i (0..$#oldpieces) {
2089 my $n = $oldpieces[$i];
2090 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2091 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2095 snag 'upstream-confusing',
2096 "previous upstream $old_upstream->{CommitId} is from".
2097 " git-debrebase but not an \`upstream-combine' commit";
2101 foreach my $pc (values %pieces) {
2102 if (!$old_upstream) {
2103 # we have complained already
2104 } elsif (!$pc->{Old}) {
2105 snag 'upstream-new-piece',
2106 "introducing upstream piece \`$pc->{Name}'";
2107 } elsif (!$pc->{New}) {
2108 snag 'upstream-rm-piece',
2109 "dropping upstream piece \`$pc->{Name}'";
2110 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2111 snag 'upstream-not-ff',
2112 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2116 printdebug "%pieces = ", (dd \%pieces), "\n";
2117 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2125 my @upstream_merge_parents;
2128 push @upstream_merge_parents, $old_upstream->{CommitId};
2131 foreach my $pc (@newpieces) { # always has '' first
2133 read_tree_subdir $pc->{Name}, $pc->{New};
2135 runcmd @git, qw(read-tree), $pc->{New};
2137 push @upstream_merge_parents, $pc->{New};
2140 # index now contains the new upstream
2142 if (@newpieces > 1) {
2143 # need to make the upstream subtree merge commit
2144 $new_upstream = make_commit \@upstream_merge_parents,
2145 [ "Combine upstreams for $new_upstream_version",
2146 ("[git-debrebase upstream-combine . ".
2147 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2152 # $new_upstream is either the single upstream commit, or the
2153 # combined commit we just made. Either way it will be the
2154 # "upstream" parent of the anchor merge.
2156 read_tree_subdir 'debian', "$old_bw:debian";
2158 # index now contains the anchor merge contents
2159 $new_bw = make_commit [ $old_bw, $new_upstream ],
2160 [ "Update to upstream $new_upstream_version",
2161 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2164 my $clogsignoff = cmdoutput qw(git show),
2165 '--pretty=format:%an <%ae> %aD',
2168 # Now we have to add a changelog stanza so the Debian version
2170 die if unlink "debian";
2171 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2172 unlink "debian/changelog" or $!==ENOENT or die $!;
2173 mkdir "debian" or die $!;
2174 open CN, ">", "debian/changelog" or die $!;
2175 my $oldclog = git_cat_file ":debian/changelog";
2176 $oldclog =~ m/^($package_re) \(\S+\) / or
2177 fail "cannot parse old changelog to get package name";
2179 print CN <<END, $oldclog or die $!;
2180 $p ($new_version) UNRELEASED; urgency=medium
2182 * Update to new upstream version $new_upstream_version.
2188 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2190 # Now we have the final new breakwater branch in the index
2191 $new_bw = make_commit [ $new_bw ],
2192 [ "Update changelog for new upstream $new_upstream_version",
2193 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2197 # we have constructed the new breakwater. we now need to commit to
2198 # the laundering output, because git-rebase can't easily be made
2199 # to make a replay list which is based on some other branch
2201 update_head_postlaunder $old_head, $old_laundered_tip,
2202 'launder for new upstream';
2204 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2205 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2206 "debrebase new-upstream $new_version: rebase";
2208 # now it's for the user to sort out
2211 sub cmd_record_ffq_prev () {
2212 badusage "no arguments allowed" if @ARGV;
2213 my ($status, $msg) = record_ffq_prev_deferred();
2214 if ($status eq 'exists' && $opt_noop_ok) {
2215 print "Previous head already recorded\n" or die $!;
2216 } elsif ($status eq 'deferred') {
2217 run_deferred_updates 'record-ffq-prev';
2219 fail "Could not preserve: $msg";
2224 badusage "no arguments allowed" if @ARGV;
2225 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2226 print "$bw\n" or die $!;
2229 sub cmd_breakwater () {
2230 badusage "no arguments allowed" if @ARGV;
2231 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2232 print "$bw\n" or die $!;
2236 badusage "no arguments allowed" if @ARGV;
2238 # todo: gdr status should print divergence info
2239 # todo: gdr status should print upstream component(s) info
2240 # todo: gdr should leave/maintain some refs with this kind of info ?
2242 my $oldest = { Badness => 0 };
2245 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2246 if ($oldest->{Badness} < $badness) {
2247 $oldest = $newest = undef;
2250 Badness => $badness,
2251 CommitId => $cl->{CommitId},
2255 $newest //= $oldest;
2257 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2258 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2259 sub { $note->(2, 'branch is unlaundered', @_); },
2260 sub { $note->(3, 'branch needs laundering', @_); },
2261 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2263 my $prcommitinfo = sub {
2265 flush STDOUT or die $!;
2266 runcmd @git, qw(--no-pager log -n1),
2267 '--pretty=format: %h %s%n',
2271 print "current branch contents, in git-debrebase terms:\n";
2272 if (!$oldest->{Badness}) {
2273 print " branch is laundered\n";
2275 print " $oldest->{OurMsg}\n";
2277 foreach my $info ($oldest, $newest) {
2278 my $cid = $info->{CommitId};
2279 next if $cid eq $printed;
2281 print " $info->{KcMsg}\n";
2282 $prcommitinfo->($cid);
2287 my ($cid, $what) = @_;
2288 if (!defined $cid) {
2289 print " $what is not well-defined\n";
2292 $prcommitinfo->($cid);
2295 print "key git-debrebase commits:\n";
2296 $prab->($anchor, 'anchor');
2297 $prab->($bw, 'breakwater');
2299 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2300 ffq_prev_branchinfo();
2302 print "branch and ref status, in git-debrebase terms:\n";
2304 print " $ffq_msg\n";
2306 $ffq_prev = git_get_ref $ffq_prev;
2307 $gdrlast = git_get_ref $gdrlast;
2309 print " unstitched; previous tip was:\n";
2310 $prcommitinfo->($ffq_prev);
2311 } elsif (!$gdrlast) {
2312 print " stitched? (no record of git-debrebase work)\n";
2313 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2314 print " stitched\n";
2316 print " not git-debrebase (diverged since last stitch)\n"
2319 print "you are currently rebasing\n" if currently_rebasing();
2323 my $prose = 'stitch';
2324 getoptions("stitch",
2325 'prose=s', \$prose);
2326 badusage "no arguments allowed" if @ARGV;
2327 do_stitch $prose, 0;
2329 sub cmd_prepush () {
2335 badusage "no arguments allowed" if @ARGV;
2336 do_launder_head 'launder for git-debrebase quick';
2340 sub cmd_conclude () {
2341 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2342 if (!$ffq_prev_commitish) {
2343 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2346 my $dangling_head = get_head();
2348 badusage "no arguments allowed" if @ARGV;
2349 do_launder_head 'launder for git-debrebase quick';
2354 if (currently_rebasing()) {
2355 runcmd @git, qw(rebase --abort);
2356 push @deferred_updates, 'verify HEAD HEAD';
2357 # noop, but stops us complaining that scrap was a noop
2359 badusage "no arguments allowed" if @ARGV;
2360 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2362 if ($ffq_prev_commitish) {
2363 $scrapping_head = get_head();
2364 push @deferred_updates,
2365 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2366 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2368 if (git_get_ref $merge_cache_ref) {
2369 push @deferred_updates,
2370 "delete $merge_cache_ref";
2372 if (!@deferred_updates) {
2373 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2377 if ($scrapping_head) {
2378 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2380 run_deferred_updates "scrap";
2384 sub make_patches_staged ($) {
2386 # Produces the patches that would result from $head if it were
2388 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2391 gbp_pq_export 'bw', $secret_bw, $secret_head;
2395 sub make_patches ($) {
2397 keycommits $head, 0, \&snag;
2398 make_patches_staged $head;
2401 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2402 runcmd @git, qw(read-tree), $head;
2403 read_tree_subdir 'debian/patches', $ptree;
2404 $out = make_commit [$head], [
2405 'Commit patch queue (exported by git-debrebase)',
2406 '[git-debrebase: export and commit patches]',
2412 sub cmd_make_patches () {
2413 my $opt_quiet_would_amend;
2414 getoptions("make-patches",
2415 'quiet-would-amend!', \$opt_quiet_would_amend);
2416 badusage "no arguments allowed" if @ARGV;
2418 my $old_head = get_head();
2419 my $new = make_patches $old_head;
2420 my $d = get_differs $old_head, $new;
2422 fail "No (more) patches to export." unless $opt_noop_ok;
2424 } elsif ($d == D_PAT_ADD) {
2426 update_head_checkout $old_head, $new, 'make-patches';
2428 print STDERR failmsg
2429 "Patch export produced patch amendments".
2430 " (abandoned output commit $new).".
2431 " Try laundering first."
2432 unless $opt_quiet_would_amend;
2437 sub check_series_has_all_patches ($) {
2439 my $seriesfn = 'debian/patches/series';
2440 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2444 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2445 fail "patch $f repeated in $seriesfn !" if $series{$f}++;
2447 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2448 my ($f,$i) = @$patchfile;
2449 next if $series{$f};
2450 next if $f eq 'series';
2451 snag 'unused-patches', "Unused patch file $f will be discarded";
2455 sub begin_convert_from () {
2456 my $head = get_head();
2457 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2459 fail "ffq-prev exists, this is already managed by git-debrebase!"
2460 if $ffq_prev && git_get_ref $ffq_prev;
2462 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2463 snag 'already-converted',
2464 "ahead of debrebase-last, this is already managed by git-debrebase!"
2465 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2466 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2469 sub complete_convert_from ($$$$) {
2470 my ($old_head, $new_head, $gi, $mrest) = @_;
2471 ffq_check $new_head;
2472 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2475 update_head_checkout $old_head, $new_head, $mrest;
2478 sub cmd_convert_from_gbp () {
2479 badusage "want only 1 optional argument, the upstream git commitish"
2482 my $clogp = parsechangelog();
2483 my $version = $clogp->{'Version'}
2484 // die "missing Version from changelog";
2486 my ($upstream_spec) = @ARGV;
2488 my $upstream_version = upstreamversion $version;
2490 resolve_upstream_version($upstream_spec, $upstream_version);
2492 my ($old_head, $gdrlastinfo) = begin_convert_from();
2494 my $upsdiff = get_differs $upstream, $old_head;
2495 if ($upsdiff & D_UPS) {
2496 runcmd @git, qw(--no-pager diff --stat),
2497 $upstream, $old_head,
2498 qw( -- :!/debian :/);
2500 upstream ($upstream_spec) and HEAD are not
2501 identical in upstream files. See diffstat above, or run
2502 git diff $upstream_spec HEAD -- :!/debian :/
2506 if (!is_fast_fwd $upstream, $old_head) {
2507 snag 'upstream-not-ancestor',
2508 "upstream ($upstream) is not an ancestor of HEAD";
2510 my $wrong = cmdoutput
2511 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2512 qw(-- :/ :!/debian));
2513 if (length $wrong) {
2514 snag 'unexpected-upstream-changes',
2515 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2516 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2520 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2521 snag 'upstream-has-debian',
2522 "upstream ($upstream) contains debian/ directory";
2525 check_series_has_all_patches $old_head;
2527 my $previous_dgit_view = eval {
2528 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2530 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2531 my ($stz, $desc) = @_;
2532 no warnings qw(exiting);
2533 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2534 next unless $stz->{Date};
2535 next unless $stz->{Distribution} ne 'UNRELEASED';
2536 $lvsn = $stz->{Version};
2537 $suite = $stz->{Distribution};
2540 die "neither of the first two changelog entries are released\n"
2541 unless defined $lvsn;
2542 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2543 my $mtag_pat = debiantag_maintview $lvsn, '*';
2544 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2546 die "could not find suitable maintainer view tag $mtag_pat\n"
2547 unless $mtag =~ m{/};
2548 is_fast_fwd $mtag, 'HEAD' or
2549 die "HEAD is not FF from maintainer tag $mtag!";
2550 my $dtag = "archive/$mtag";
2551 git_get_ref "refs/tags/$dtag" or
2552 die "dgit view tag $dtag not found\n";
2553 is_fast_fwd $mtag, $dtag or
2554 die "dgit view tag $dtag is not FF from maintainer tag $mtag\n";
2555 print "will stitch in dgit view, $dtag\n";
2556 git_rev_parse $dtag;
2558 if (!$previous_dgit_view) {
2562 Cannot confirm dgit view: $@
2563 Failed to stitch in dgit view (see messages above).
2564 dgit --overwrite will be needed on the first dgit push after conversion.
2568 snags_maybe_bail_early();
2574 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2575 # make a branch out of the patch queue - we'll want this in a mo
2576 runcmd qw(gbp pq import);
2577 # strip the patches out
2578 runcmd @git, qw(checkout -q gdr-internal~0);
2579 rm_subdir_cached 'debian/patches';
2580 $work = make_commit ['HEAD'], [
2581 'git-debrebase convert-from-gbp: drop patches from tree',
2582 'Delete debian/patches, as part of converting to git-debrebase format.',
2583 '[git-debrebase convert-from-gbp: drop patches from tree]'
2585 # make the anchor merge
2586 # the tree is already exactly right
2587 $work = make_commit [$work, $upstream], [
2588 'git-debrebase import: declare upstream',
2589 'First breakwater merge.',
2590 '[git-debrebase anchor: declare upstream]'
2593 # rebase the patch queue onto the new breakwater
2594 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2595 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2596 $work = git_rev_parse 'HEAD';
2598 if ($previous_dgit_view) {
2599 $work = make_commit [$work, $previous_dgit_view], [
2600 'git-debrebase import: declare ff from dgit archive view',
2601 '[git-debrebase pseudomerge: import-from-gbp]',
2606 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2607 print <<END or die $!;
2608 git-debrebase: converted from patched-unapplied (gbp) branch format, OK
2612 sub cmd_convert_to_gbp () {
2613 badusage "no arguments allowed" if @ARGV;
2614 my $head = get_head();
2615 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2616 keycommits $head, 0;
2618 make_patches_staged $head;
2620 $out = make_commit ['HEAD'], [
2621 'Commit patch queue (converted from git-debrebase format)',
2622 '[git-debrebase convert-to-gbp: commit patches]',
2626 push @deferred_updates, "delete $ffq";
2627 push @deferred_updates, "delete $gdrlast";
2630 update_head_checkout $head, $out, "convert to gbp (v0)";
2631 print <<END or die $!;
2632 git-debrebase: converted to git-buildpackage branch format
2633 git-debrebase: WARNING: do not now run "git-debrebase" any more
2634 git-debrebase: WARNING: doing so would drop all upstream patches!
2638 sub cmd_convert_from_dgit_view () {
2639 my $clogp = parsechangelog();
2641 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2647 getoptions("convert-from-dgit-view",
2648 'diagnose!', \$diagnose,
2649 'build-products-dir:s', \$bpd,
2650 'origs!', \$do_origs,
2652 'always-convert-anyway!', \$always);
2653 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2658 my $spec = shift @ARGV;
2659 my $commit = git_rev_parse "$spec^{commit}";
2660 push @upstreams, { Commit => $commit,
2661 Source => "$ARGV[0], from command line",
2666 my ($head, $gdrlastinfo) = begin_convert_from();
2670 my $trouble = sub { $troubles++; };
2671 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2672 printdebug "troubles=$troubles\n";
2675 $us: Branch already seems to be in git-debrebase format!
2676 $us: --always-convert-anyway would do the conversion operation anyway
2677 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2679 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2684 check_series_has_all_patches $head;
2686 snags_maybe_bail_early();
2688 my $version = upstreamversion $clogp->{Version};
2689 print STDERR "Considering possible commits corresponding to upstream:\n";
2694 my $ups_tag = upstream_commitish_search $version, \@tried;
2696 my $this = "git tag $tried[-1]";
2697 push @upstreams, { Commit => $ups_tag,
2702 " git tag: no suitable tag found (tried %s)\n",
2707 my $p = $clogp->{'Source'};
2708 # we do a quick check to see if there are plausible origs
2710 if (!opendir BPD, $bpd) {
2711 die "$bpd: opendir: $!" unless $!==ENOENT;
2713 while ($!=0, my $f = readdir BPD) {
2714 next unless is_orig_file_of_p_v $f, $p, $version;
2716 " orig: found what looks like a .orig, %s\n",
2721 die "read $bpd: $!" if $!;
2725 my $tree = cmdoutput
2726 @dgit, qw(--build-products-dir), $bpd,
2727 qw(print-unapplied-treeish);
2730 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2731 rm_subdir_cached 'debian';
2732 $tree = cmdoutput @git, qw(write-tree);
2733 my $ups_synth = make_commit [], [ <<END, <<END,
2734 Import effective orig tree for upstream version $version
2736 This includes the contents of the .orig(s), minus any debian/ directory.
2738 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2741 push @upstreams, { Commit => $ups_synth,
2742 Source => "orig(s) imported via dgit",
2747 " orig: no suitable origs found (looked for %s in %s)\n",
2748 "${p}_".(stripeoch $version)."...", $bpd;
2753 my $some_patches = stat_exists 'debian/patches/series';
2755 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2758 foreach my $u (@upstreams) {
2762 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2763 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2764 runcmd @git, qw(clean -xdff);
2765 runcmd @git, qw(checkout), $head, qw(-- debian);
2766 if ($some_patches) {
2767 rm_subdir_cached 'debian/patches';
2768 $work = make_commit [ $work ], [
2769 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2770 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2771 "to git-debrebase format. Upstream changes will appear as commits.",
2772 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2775 $work = make_commit [ $work, $u->{Commit} ], [
2776 'git-debrebase convert-from-dgit-view: declare upstream',
2777 '(Re)constructed breakwater merge.',
2778 '[git-debrebase anchor: declare upstream]'
2780 runcmd @git, qw(checkout --quiet -b mk), $work;
2781 if ($some_patches) {
2782 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2783 runcmd @git, qw(reset --quiet);
2784 my @gbp_cmd = (qw(gbp pq import));
2786 my $gbp_err = "../gbp-pq-err";
2787 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2789 my $r = system @gbp_cmd;
2792 " %s: couldn't apply patches: gbp pq %s",
2793 $u->{Source}, waitstatusmsg();
2797 my $work = git_rev_parse qw(HEAD);
2798 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2799 if (length $diffout) {
2801 " $u->{Source}: applying patches gives different tree\n";
2802 print STDERR $diffout if $diagnose;
2806 $u->{Result} = $work;
2814 Could not find or construct a suitable upstream commit.
2815 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2816 upstream commmit explicitly or provide suitable origs.
2820 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2822 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2823 'convert-from-dgit-view';
2826 sub cmd_record_resolved_merge () {
2827 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2828 # MERGE-TODO needs documentation
2829 my $new = get_head();
2832 print "Checking how you have resolved the merge problem\n";
2833 my $nope = sub { print "Not $method: @_"; 0; };
2835 my $maybe = sub { print "Seems to be $method.\n"; };
2837 my ($key, $ref) = @_;
2838 reflog_cache_insert $merge_cache_ref, $key, $ref;
2839 print "OK. You can switch branches and try git-debrebase again.\n";
2843 fresh_workarea 'merge';
2845 $method = 'vanilla-merge patchqueue';
2846 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2847 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2848 foreach my $lr (qw(left right)) {
2849 my $n = "$wrecknoteprefix/$lr-patchqueue";
2850 my $lrpq = git_get_ref $n;
2851 $lrpq or return $nope->("wreckage did not contain patchqueues");
2852 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2855 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2856 or die "wreckage element $wrecknoteprefix/new-base missing";
2857 my $result = merge_series_patchqueue_convert
2859 $yes->("vanilla-merge $vanilla", $result);
2862 fail "No resolved merge method seems applicable.\n";
2866 sub cmd_downstream_rebase_launder_v0 () {
2867 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2869 $base = git_rev_parse $base;
2870 my $old_head = get_head();
2871 my $current = $old_head;
2874 if ($current eq $base) {
2875 $topmost_keep //= $current;
2876 print " $current BASE stop\n";
2879 my $cl = classify $current;
2880 print " $current $cl->{Type}";
2882 my $p0 = $cl->{Parents}[0]{CommitId};
2884 if ($cl->{Type} eq 'Pseudomerge') {
2885 print " ^".($cl->{Contributor}{Ix}+1);
2886 $next = $cl->{Contributor}{CommitId};
2887 } elsif ($cl->{Type} eq 'AddPatches' or
2888 $cl->{Type} eq 'Changelog') {
2898 $topmost_keep //= $current;
2900 die "to-be stripped changes not on top of the branch\n"
2905 if ($topmost_keep eq $old_head) {
2906 print "unchanged\n";
2908 print "updating to $topmost_keep\n";
2909 update_head_checkout
2910 $old_head, $topmost_keep,
2911 'downstream-rebase-launder-v0';
2917 "D+" => \$debuglevel,
2918 'noop-ok', => \$opt_noop_ok,
2919 'f=s' => \@snag_force_opts,
2920 'anchor=s' => \@opt_anchors,
2921 '--dgit=s' => \($dgit[0]),
2923 'experimental-merge-resolution!', \$opt_merges,
2925 my ($opt,$val) = @_;
2926 badusage "git-debrebase: no cuddling to -i for git-rebase"
2928 die if $opt_defaultcmd_interactive; # should not happen
2929 $opt_defaultcmd_interactive = [ qw(-i) ];
2930 # This access to @ARGV is excessive familiarity with
2931 # Getopt::Long, but there isn't another sensible
2932 # approach. '-i=s{0,}' does not work with bundling.
2933 push @$opt_defaultcmd_interactive, @ARGV;
2936 'help' => sub { print $usage_message or die $!; finish 0; },
2939 initdebug('git-debrebase ');
2940 enabledebug if $debuglevel;
2942 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2943 chdir $toplevel or die "chdir $toplevel: $!";
2945 $rd = fresh_playground "$playprefix/misc";
2947 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2949 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2950 defaultcmd_rebase();
2952 my $cmd = shift @ARGV;
2955 $cmdfn = ${*::}{"cmd_$cmdfn"};
2957 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";