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 [{..opts...},] $x, $y, sub {... }
229 # calls sub->($name, $ix, $iy) for each difference
230 # $x and $y are as for get_tree
231 # where $name, $ix, $iy are $name and $info from get_tree
232 # opts are all call even for names same in both
233 my $opts = shift @_ if @_>=4;
234 my ($x,$y,$call) = @_;
235 my $all = $opts->{all};
236 return if !$all and $x eq $y;
239 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
242 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
243 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
244 my ($n, $ix, $iy); # all same? $cmp=0, use both
246 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
248 ($n, $ix) = @{ shift @x } if $cmp <= 0;
249 ($n, $iy) = @{ shift @y } if $cmp >= 0;
250 next if !$all and $ix eq $iy;
252 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
253 !!$all,$x,$y, $n,$ix,$iy
255 $call->($n, $ix, $iy);
259 sub get_differs ($$) {
261 # This does a similar job to quiltify_trees_differ, in dgit, a bit.
262 # But we don't care about modes, or dpkg-source-unrepresentable
263 # changes, and we don't need the plethora of different modes.
264 # Conversely we need to distinguish different kinds of changes to
265 # debian/ and debian/patches/.
266 # Also, here we have, and want to use, trees_diff_walk, because
267 # we may be calling this an awful lot and we want it to be fast.
272 no warnings qw(exiting);
274 my $plain = sub { $_[0] =~ m{^(100|0*)644 blob }s; };
276 trees_diff_walk "$x:", "$y:", sub {
277 my ($n,$ix,$iy) = @_;
279 # analyse difference at the toplevel
281 if ($n ne 'debian/') {
285 if ($n eq 'debian') {
286 # one side has a non-tree for ./debian !
287 $differs |= D_DEB_OTH;
291 my $xd = $ix && "$x:debian";
292 my $yd = $iy && "$y:debian";
293 trees_diff_walk $xd, $yd, sub {
294 my ($n,$ix,$iy) = @_;
296 # analyse difference in debian/
298 if ($n eq 'changelog' && (!$ix || $plain->($ix))
300 $differs |= D_DEB_CLOG;
303 if ($n ne 'patches/') {
304 $differs |= D_DEB_OTH;
308 my $xp = $ix && "$xd/patches";
309 my $yp = $iy && "$yd/patches";
310 trees_diff_walk $xp, $yp, sub {
311 my ($n,$ix,$iy) = @_;
313 # analyse difference in debian/patches
316 if ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
318 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
319 my $x_s = (git_cat_file "$xp/series", 'blob');
320 my $y_s = (git_cat_file "$yp/series", 'blob');
321 chomp $x_s; $x_s .= "\n";
322 $ok = $x_s eq substr($y_s, 0, length $x_s);
326 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
331 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
336 sub commit_pr_info ($) {
338 return Data::Dumper->dump([$r], [qw(commit)]);
341 sub calculate_committer_authline () {
342 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
343 'DUMMY COMMIT (git-debrebase)', "HEAD:";
344 my ($h,$m) = get_commit $c;
345 $h =~ m/^committer .*$/m or confess "($h) ?";
349 sub rm_subdir_cached ($) {
351 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
354 sub read_tree_subdir ($$) {
355 my ($subdir, $new_tree_object) = @_;
356 rm_subdir_cached $subdir;
357 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
360 sub read_tree_debian ($) {
362 read_tree_subdir 'debian', "$treeish:debian";
363 rm_subdir_cached 'debian/patches';
366 sub read_tree_upstream ($;$$) {
367 my ($treeish, $keep_patches, $tree_with_debian) = @_;
368 # if $tree_with_debian is supplied, will use that for debian/
369 # otherwise will save and restore it.
371 $tree_with_debian ? "$tree_with_debian:debian"
372 : cmdoutput @git, qw(write-tree --prefix=debian/);
373 runcmd @git, qw(read-tree), $treeish;
374 read_tree_subdir 'debian', $debian;
375 rm_subdir_cached 'debian/patches' unless $keep_patches;
378 sub make_commit ($$) {
379 my ($parents, $message_paras) = @_;
380 my $tree = cmdoutput @git, qw(write-tree);
381 my @cmd = (@git, qw(commit-tree), $tree);
382 push @cmd, qw(-p), $_ foreach @$parents;
383 push @cmd, qw(-m), $_ foreach @$message_paras;
384 return cmdoutput @cmd;
387 our @snag_force_opts;
389 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
390 if (grep { $_ eq $tag } @snag_force_opts) {
392 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
395 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
399 # Important: all mainline code must call snags_maybe_bail after
400 # any point where snag might be called, but before making changes
401 # (eg before any call to run_deferred_updates). snags_maybe_bail
402 # may be called more than once if necessary (but this is not ideal
403 # because then the messages about number of snags may be confusing).
404 sub snags_maybe_bail () {
405 return if all_snags_summarised();
408 "%s: snags: %d overriden by individual -f options\n",
411 if ($snags_tripped) {
414 "%s: snags: %d overriden by global --force\n",
418 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
422 $snags_summarised = $snags_forced + $snags_tripped;
424 sub snags_maybe_bail_early () {
425 # useful to bail out early without doing a lot of work;
426 # not a substitute for snags_maybe_bail.
427 snags_maybe_bail() if $snags_tripped && !$opt_force;
430 return $snags_forced || $snags_tripped;
433 sub ffq_prev_branchinfo () {
434 my $current = git_get_symref();
435 return gdr_ffq_prev_branchinfo($current);
438 sub record_gdrlast ($$;$) {
439 my ($gdrlast, $newvalue, $oldvalue) = @_;
440 $oldvalue ||= $git_null_obj;
441 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
444 sub fail_unprocessable ($) {
447 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
450 Branch/history seems mangled - no longer in gdr format.
451 See ILLEGAL OPERATIONS in git-debrebase(5).
458 Is this meant to be a gdr branch? $ffqm
460 } elsif (git_get_ref $ffq_prev) {
464 Consider git-debrebase scrap, to throw away your recent work.
466 } elsif (!git_get_ref $gdrlast) {
469 Branch does not seem to be meant to be a git-debrebase branch?
470 Wrong branch, or maybe you needed git-debrebase convert-from-*.
472 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
480 Branch/history mangled, and diverged since last git-debrebase.
481 Maybe you reset to, or rebased from, somewhere inappropriate.
486 sub gbp_pq_export ($$$) {
487 my ($bname, $base, $tip) = @_;
488 # must be run in a workarea. $bname and patch-queue/$bname
489 # ought not to exist. Leaves you on patch-queue/$bname with
490 # the patches staged but not committed.
491 printdebug "gbp_pq_export $bname $base $tip\n";
492 runcmd @git, qw(checkout -q -b), $bname, $base;
493 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
494 my @gbp_cmd = (qw(gbp pq export));
495 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
497 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
500 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
504 # MERGE-TODO allow merge resolution separately from laundering, before git merge
507 # use git-format-patch?
508 # our own patch identification algorithm?
509 # this is an alternative strategy
511 sub merge_failed ($$;@) {
512 my ($wrecknotes, $emsg, @xmsgs) = @_;
514 push @m, "Merge resolution failed: $emsg";
520 merge_wreckage_cleaning \@updates;
521 run_ref_updates_now "merge failed", \@updates;
525 while (my ($k,$v) = each %$wrecknotes) {
526 push @updates, "create $wrecknoteprefix/$k $v";
528 run_ref_updates_now "merge failed", \@updates;
529 push @m, "Wreckage left in $wrecknoteprefix/*.";
531 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
533 # use finish rather than fail, in case we are within an eval
534 # (that can happen inside walk!)
536 print STDERR "$us: $_\n" foreach @m;
540 sub mwrecknote ($$$) {
541 my ($wrecknotes, $reftail, $commitish) = @_;
542 confess unless defined $commitish;
543 printdebug "mwrecknote $reftail $commitish\n";
544 $wrecknotes->{$reftail} = $commitish;
547 sub merge_attempt_cmd {
548 my $wrecknotes = shift @_;
552 merge_failed $wrecknotes,
553 failedcmd_waitstatus(),
554 "failed command: @_";
558 sub merge_series_patchqueue_convert ($$$);
560 sub merge_series ($$$;@) {
561 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
562 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
563 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
564 # ^ specifies several patch series (currently we only support exactly 2)
565 # return value is a commit which is the result of
566 # merging the two versions of the same topic branch
567 # $input_q[0] and $input_q[1]
568 # with respect to the old version
572 # Creates, in *_q, a key MR for its private use
574 printdebug "merge_series newbase=$newbase\n";
576 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
577 $base_q->{MR}{S} = 'base';
580 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
581 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
582 # $prereq{<patch filename>} exists or not (even later)
586 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
588 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
591 fresh_workarea "merge";
592 my $seriesfile = "debian/patches/series";
595 foreach my $q ($base_q, reverse @input_qs) {
597 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
599 if (open S, $seriesfile) {
600 while (my $patch = <S>) {
601 chomp $patch or die $!;
602 $prereq{$patch} //= {};
603 foreach my $earlier (@earlier) {
604 $prereq{$patch}{$earlier}{$s}++ and die;
606 push @earlier, $patch;
607 stat "debian/patches/$patch" or die "$patch ?";
609 S->error and die "$seriesfile $!";
612 die "$seriesfile $!" unless $!==ENOENT;
614 read_tree_upstream $newbase, 1;
615 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
616 "Convert $s to patch queue for merging",
617 "[git-debrebase merge-innards patch-queue import:".
620 printdebug "merge_series pec $pec ";
621 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
622 $pec = make_commit [ $pec ], [
623 "Drop series file from $s to avoid merge trouble",
624 "[git-debrebase merge-innards patch-queue prep:".
628 read_tree_debian $newbase;
630 read_tree_subdir 'debian/patches', "$pec:debian/patches";
632 rm_subdir_cached 'debian/patches';
634 $pec = make_commit [ $pec ], [
635 "Update debian/ (excluding patches) to final to avoid re-merging",
636 "debian/ was already merged and we need to just take that.",
637 "[git-debrebase merge-innards patch-queue packaging:".
641 printdebug "pec' $pec\n";
642 runcmd @git, qw(reset -q --hard), $pec;
643 $q->{MR}{PEC} = $pec;
644 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
646 # now, because of reverse, we are on $input_q->{MR}{OQC}
647 runcmd @git, qw(checkout -q -b merge);
648 printdebug "merge_series merging...\n";
649 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
651 $attempt_cmd->(@mergecmd);
653 printdebug "merge_series merge ok, series...\n";
654 # We need to construct a new series file
655 # Firstly, resolve prereq
656 foreach my $f (sort keys %prereq) {
657 printdebug "merge_series patch\t$f\t";
658 if (!stat_exists "debian/patches/$f") {
659 print DEBUG " drop\n" if $debuglevel;
660 # git merge deleted it; that's how we tell it's not wanted
664 print DEBUG " keep\n" if $debuglevel;
665 foreach my $g (sort keys %{ $prereq{$f} }) {
666 my $gfp = $prereq{$f}{$g};
667 printdebug "merge_series prereq\t$f\t-> $g\t";
668 if (!!$gfp->{0} == !!$gfp->{1}
671 print DEBUG "\tkeep\n" if $debuglevel;
673 print DEBUG "\tdrop\n" if $debuglevel;
674 delete $prereq{$f}{$g};
681 return scalar keys %{ $prereq{$f} };
684 my $nodate = time + 1;
686 # $authordate{<patch filename>};
687 my $authordate = sub {
689 $authordate{$f} //= do {
690 open PF, "<", "debian/patches/$f" or die "$f $!";
692 return $nodate if m/^$/;
693 last if s{^Date: }{};
696 return cmdoutput qw(date +%s -d), $_;
700 open NS, '>', $seriesfile or die $!;
702 while (keys %prereq) {
704 foreach my $try (sort keys %prereq) {
707 $unsat->($try) <=> $unsat->($best) or
708 $authordate->($try) <=> $authordate->($best) or
714 printdebug "merge_series series next $best\n";
715 print NS "$best\n" or die $!;
716 delete $prereq{$best};
717 foreach my $gp (values %prereq) {
722 runcmd @git, qw(add), $seriesfile;
723 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
724 $merged_pq = git_rev_parse 'HEAD';
725 $mwrecknote->('merged-patchqueue', $merged_pq);
727 return merge_series_patchqueue_convert
728 $wrecknotes, $newbase, $merged_pq;
731 sub merge_series_patchqueue_convert ($$$) {
732 my ($wrecknotes, $newbase, $merged_pq) = @_;
737 printdebug "merge_series series gbp pq import\n";
738 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
740 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
741 # MERGE-TODO consider git-format-patch etc. instead,
742 # since gbp pq doesn't always round-trip :-/
744 # OK now we are on patch-queue/merge, and we need to rebase
745 # onto the intended parent and drop the patches from each one
747 printdebug "merge_series series ok, building...\n";
748 my $build = $newbase;
749 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
750 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
751 my $commit = git_cat_file $c, 'commit';
752 printdebug "merge_series series ok, building $c\n";
753 read_tree_upstream $c, 0, $newbase;
754 my $tree = cmdoutput @git, qw(write-tree);
755 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
756 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
757 open C, ">", "../mcommit" or die $!;
758 print C $commit or die $!;
760 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
763 mwrecknote($wrecknotes, 'merged-result', $result);
765 runcmd @git, qw(update-ref refs/heads/result), $result;
767 runcmd @git, qw(checkout -q -b debug);
768 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
769 runcmd @git, qw(add .);
770 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
771 my $mdebug = git_rev_parse 'HEAD';
772 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
773 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
775 printdebug "merge_series returns $result\n";
779 # classify returns an info hash like this
781 # Hdr => # commit headers, including 1 final newline
782 # Msg => # commit message (so one newline is dropped)
784 # Type => (see below)
786 # Ix => $index # ie 0, 1, 2, ...
788 # Differs => return value from get_differs
790 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
792 # NewMsg => # commit message, but with any [dgit import ...] edited
793 # # to say "[was: ...]"
803 # has additional entres in classification result
804 # Overwritten = [ subset of Parents ]
805 # Contributor = $the_remaining_Parent
807 # DgitImportUnpatched
808 # has additional entry in classification result
809 # OrigParents = [ subset of Parents ]
812 # has additional entry in classification result
813 # OrigParents = [ subset of Parents ] # singleton list
820 # has additional entry in classification result
823 sub parsecommit ($;$) {
824 my ($objid, $p_ref) = @_;
825 # => hash with CommitId Hdr Msg Tree Parents
826 # Parents entries have only Ix CommitId
827 # $p_ref, if provided, must be [] and is used as a base for Parents
832 my ($h,$m) = get_commit $objid;
834 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
835 my (@ph) = $h =~ m/^parent (\w+)$/mg;
845 foreach my $ph (@ph) {
847 Ix => scalar @$p_ref,
859 my $r = parsecommit($objid, \@p);
863 $p->{Differs} = (get_differs $p->{CommitId}, $t),
866 printdebug "classify $objid \$t=$t \@p",
867 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
871 my ($type, @rest) = @_;
872 $r = { %$r, Type => $type, @rest };
874 printdebug " = $type ".(dd $r)."\n";
880 $r = { %$r, Type => qw(Unknown), Why => $why };
881 printdebug " ** Unknown\n";
885 if (grep { $_ eq $objid } @opt_anchors) {
886 return $classify->('TreatAsAnchor');
889 my @identical = grep { !$_->{Differs} } @p;
890 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
891 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
893 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
894 # multi-orig upstreams are represented with an anchor merge
895 # from a single upstream commit which combines the orig tarballs
897 # Every anchor tagged this way must be a merge.
898 # We are relying on the
899 # [git-debrebase anchor: ...]
900 # commit message annotation in "declare" anchor merges (which
901 # do not have any upstream changes), to distinguish those
902 # anchor merges from ordinary pseudomerges (which we might
903 # just try to strip).
905 # However, the user is going to be doing git-rebase a lot. We
906 # really don't want them to rewrite an anchor commit.
907 # git-rebase trips up on merges, so that is a useful safety
910 # BreakwaterStart commits are also anchors in the terminology
911 # of git-debrebase(5), but they are untagged (and always
912 # manually generated).
914 # We cannot not tolerate any tagged linear commit (ie,
915 # BreakwaterStart commits tagged `[anchor:') because such a
916 # thing could result from an erroneous linearising raw git
917 # rebase of a merge anchor. That would represent a corruption
918 # of the branch. and we want to detect and reject the results
919 # of such corruption before it makes it out anywhere. If we
920 # reject it here then we avoid making the pseudomerge which
921 # would be needed to push it.
923 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
924 @p == 2 or return $badanchor->("has other than two parents");
925 $haspatches and return $badanchor->("contains debian/patches");
927 # How to decide about l/r ordering of anchors ? git
928 # --topo-order prefers to expand 2nd parent first. There's
929 # already an easy rune to look for debian/ history anyway (git log
930 # debian/) so debian breakwater branch should be 1st parent; that
931 # way also there's also an easy rune to look for the upstream
932 # patches (--topo-order).
934 # Also this makes --first-parent be slightly more likely to
935 # be useful - it makes it provide a linearised breakwater history.
937 # Of course one can say somthing like
938 # gitk -- ':/' ':!/debian'
939 # to get _just_ the commits touching upstream files, and by
940 # the TREESAME logic in git-rev-list this will leave the
941 # breakwater into upstream at the first anchor. But that
942 # doesn't report debian/ changes at all.
944 # Other observations about gitk: by default, gitk seems to
945 # produce output in a different order to git-rev-list. I
946 # can't seem to find this documented anywhere. gitk
947 # --date-order DTRT. But, gitk always seems to put the
948 # parents from left to right, in order, so it's easy to see
949 # which way round a pseudomerge is.
951 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
952 $p[1]{Differs} & ~DS_DEB and
953 $badanchor->("upstream files differ from left parent");
954 $p[0]{Differs} & ~D_UPS and
955 $badanchor->("debian/ differs from right parent");
957 return $classify->(qw(Anchor),
958 OrigParents => [ $p[1] ]);
962 my $d = $r->{Parents}[0]{Differs};
963 if ($d == D_PAT_ADD) {
964 return $classify->(qw(AddPatches));
965 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
966 return $unknown->("edits debian/patches");
967 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
968 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
970 if ($d == D_DEB_CLOG) {
971 return $classify->(qw(Changelog));
973 return $classify->(qw(Packaging));
975 } elsif ($ty eq 'missing') {
976 return $classify->(qw(BreakwaterStart));
978 return $unknown->("parent's debian is not a directory");
980 } elsif ($d == D_UPS) {
981 return $classify->(qw(Upstream));
982 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
983 return $classify->(qw(Mixed));
985 return $unknown->("no changes");
987 confess "internal error $objid ?";
991 return $unknown->("origin commit");
994 if (@p == 2 && @identical == 1) {
995 my @overwritten = grep { $_->{Differs} } @p;
996 confess "internal error $objid ?" unless @overwritten==1;
997 return $classify->(qw(Pseudomerge),
998 Overwritten => [ $overwritten[0] ],
999 Contributor => $identical[0]);
1001 if (@p == 2 && @identical == 2) {
1003 my ($ph,$pm) = get_commit $_[0]{CommitId};
1004 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
1008 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
1009 if ($order > 0) { # newer first
1010 } elsif ($order < 0) {
1011 @bytime = reverse @bytime;
1013 # same age, default to order made by -s ours
1014 # that is, commit was made by someone who preferred L
1016 return $classify->(qw(Pseudomerge),
1017 SubType => qw(Ambiguous),
1018 Contributor => $bytime[0],
1019 Overwritten => [ $bytime[1] ]);
1021 foreach my $p (@p) {
1022 my ($p_h, $p_m) = get_commit $p->{CommitId};
1023 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1024 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1026 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1028 if (!(grep { !$_->{IsOrigin} } @p) and
1029 (@orig_ps >= @p - 1) and
1030 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1032 return $classify->(qw(DgitImportUnpatched),
1033 OrigParents => \@orig_ps);
1037 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1038 return $classify->("MergedBreakwaters");
1040 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1041 return $unknown->("unknown kind of merge from $1");
1044 return $unknown->("octopus merge");
1048 return $unknown->("general two-parent merge");
1051 return $classify->("VanillaMerge");
1054 sub keycommits ($;$$$$$);
1056 sub mergedbreakwaters_anchor ($) {
1059 foreach my $p (@{ $cl->{Parents} }) {
1060 my ($panchor, $pbw) = keycommits $p->{CommitId},
1061 undef,undef,undef,undef, 1;
1062 $best_anchor = $panchor
1063 if !defined $best_anchor
1064 or is_fast_fwd $best_anchor, $panchor;
1065 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
1066 unless is_fast_fwd $panchor, $best_anchor;
1068 return $best_anchor;
1071 sub keycommits ($;$$$$$) {
1072 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1073 # => ($anchor, $breakwater)
1075 # $unclean->("unclean-$tagsfx", $msg, $cl)
1076 # $furniture->("unclean-$tagsfx", $msg, $cl)
1077 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
1078 # is callled for each situation or commit that
1079 # wouldn't be found in a laundered branch
1080 # $furniture is for furniture commits such as might be found on an
1081 # interchange branch (pseudomerge, d/patches, changelog)
1082 # $trouble is for things whnich prevent the return of
1083 # anchor and breakwater information; if that is ignored,
1084 # then keycommits returns (undef, undef) instead.
1085 # $fatal is for unprocessable commits, and should normally cause
1086 # a failure. If ignored, agaion, (undef, undef) is returned.
1088 # If $claimed_bw, this is supposed to be a breakwater commit.
1090 # If a callback is undef, fail is called instead.
1091 # If a callback is defined but false, the situation is ignored.
1092 # Callbacks may say:
1093 # no warnings qw(exiting); last;
1094 # if the answer is no longer wanted.
1096 my ($anchor, $breakwater);
1097 $breakwater = $head if $claimed_bw;
1101 $fatal //= sub { fail_unprocessable $_[1]; };
1103 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1104 my $why = $mainwhy.$xwhy;
1105 my $m = "branch needs laundering (run git-debrebase): $why";
1106 fail $m unless defined $cb;
1108 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1110 my $found_anchor = sub {
1112 $breakwater //= $clogonly;
1113 $breakwater //= $head;
1114 no warnings qw(exiting);
1118 $cl = classify $head;
1119 my $ty = $cl->{Type};
1120 if ($ty eq 'Packaging') {
1121 $breakwater //= $clogonly;
1122 $breakwater //= $head;
1123 } elsif ($ty eq 'Changelog') {
1124 # this is going to count as the tip of the breakwater
1125 # only if it has no upstream stuff before it
1126 $clogonly //= $head;
1127 } elsif ($ty eq 'Anchor' or
1128 $ty eq 'TreatAsAnchor' or
1129 $ty eq 'BreakwaterStart') {
1130 $found_anchor->($head);
1131 } elsif ($ty eq 'Upstream') {
1132 $x->($unclean, 'ordering',
1133 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1134 if defined $breakwater;
1136 $breakwater = undef;
1137 } elsif ($ty eq 'Mixed') {
1138 $x->($unclean, 'mixed',
1139 "found mixed upstream/packaging commit"," ($head)");
1141 $breakwater = undef;
1142 } elsif ($ty eq 'Pseudomerge' or
1143 $ty eq 'AddPatches') {
1145 $x->($furniture, (lc $ty),
1146 "found interchange bureaucracy commit ($ty)"," ($head)");
1147 } elsif ($ty eq 'DgitImportUnpatched') {
1149 $x->($trouble, 'dgitimport',
1150 "found dgit dsc import"," ($head)");
1151 return (undef,undef);
1153 $x->($fatal, 'unprocessable',
1154 "found bare dgit dsc import with no prior history",
1156 return (undef,undef);
1158 } elsif ($ty eq 'VanillaMerge') {
1159 $x->($trouble, 'vanillamerge',
1160 "found vanilla merge"," ($head)");
1161 return (undef,undef);
1162 } elsif ($ty eq 'MergedBreakwaters') {
1163 $found_anchor->(mergedbreakwaters_anchor $cl);
1165 $x->($fatal, 'unprocessable',
1166 "found unprocessable commit, cannot cope: $cl->{Why}",
1168 return (undef,undef);
1170 $head = $cl->{Parents}[0]{CommitId};
1172 return ($anchor, $breakwater);
1178 $nogenerate,$report, $report_lprefix) = @_;
1179 # => ($tip, $breakwater_tip, $last_anchor)
1180 # (or nothing, if $nogenerate)
1182 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1183 $report_lprefix //= '';
1185 # go through commits backwards
1186 # we generate two lists of commits to apply:
1187 # breakwater branch and upstream patches
1188 my (@brw_cl, @upp_cl, @processed);
1195 my ($prose, $info) = @_;
1196 my $ms = $cl->{Msg};
1199 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1200 return (Msg => $ms);
1202 my $rewrite_from_here = sub {
1204 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1206 push @processed, $sp_cl;
1211 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1214 return unless $report;
1215 print $report $prdelim, $report_lprefix, @_;
1219 my $bomb = sub { # usage: return $bomb->();
1220 print $report " Unprocessable" if $report;
1221 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1224 return (undef,undef);
1226 fail_unprocessable "found unprocessable commit, cannot cope".
1227 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1228 " (commit $cur) (d.".
1229 (join ' ', map { sprintf "%#x", $_->{Differs} }
1230 @{ $cl->{Parents} }).
1237 my $build_start = sub {
1238 my ($msg, $parent) = @_;
1241 no warnings qw(exiting); last;
1246 merge_failed $cl->{MergeWreckNotes}, $emsg;
1249 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1254 $cl = classify $cur;
1255 $cl->{MergeWreckNotes} //= {};
1256 my $ty = $cl->{Type};
1257 my $st = $cl->{SubType};
1258 $prline->("$cl->{CommitId} $cl->{Type}");
1259 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1260 push @processed, $cl;
1261 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1262 if ($ty eq 'AddPatches') {
1264 $rewrite_from_here->(\@upp_cl);
1266 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1270 } elsif ($ty eq 'BreakwaterStart') {
1271 $last_anchor = $cur;
1272 $build_start->('FirstPackaging', $cur);
1273 } elsif ($ty eq 'Upstream') {
1277 } elsif ($ty eq 'Mixed') {
1280 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1283 $queue->(\@brw_cl, "debian");
1284 $queue->(\@upp_cl, "upstream");
1285 $rewrite_from_here->(\@brw_cl);
1288 } elsif ($ty eq 'Pseudomerge') {
1289 my $contrib = $cl->{Contributor}{CommitId};
1290 print $report " Contributor=$contrib" if $report;
1291 push @pseudomerges, $cl;
1292 $rewrite_from_here->(\@upp_cl);
1295 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1296 $last_anchor = $cur;
1297 $build_start->("Anchor", $cur);
1298 } elsif ($ty eq 'DgitImportUnpatched') {
1299 my $pm = $pseudomerges[-1];
1301 # To an extent, this is heuristic. Imports don't have
1302 # a useful history of the debian/ branch. We assume
1303 # that the first pseudomerge after an import has a
1304 # useful history of debian/, and ignore the histories
1305 # from later pseudomerges. Often the first pseudomerge
1306 # will be the dgit import of the upload to the actual
1307 # suite intended by the non-dgit NMUer, and later
1308 # pseudomerges may represent in-archive copies.
1309 my $ovwrs = $pm->{Overwritten};
1310 printf $report " PM=%s \@Overwr:%d",
1311 $pm->{CommitId}, (scalar @$ovwrs)
1314 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1317 my $ovwr = $ovwrs->[0]{CommitId};
1318 printf $report " Overwr=%s", $ovwr if $report;
1319 # This import has a tree which is just like a
1320 # breakwater tree, but it has the wrong history. It
1321 # ought to have the previous breakwater (which the
1322 # pseudomerge overwrote) as an ancestor. That will
1323 # make the history of the debian/ files correct. As
1324 # for the upstream version: either it's the same as
1325 # was ovewritten (ie, same as the previous
1326 # breakwater), in which case that history is precisely
1327 # right; or, otherwise, it was a non-gitish upload of a
1328 # new upstream version. We can tell these apart by
1329 # looking at the tree of the supposed upstream.
1332 SpecialMethod => 'DgitImportDebianUpdate',
1333 $xmsg->("convert dgit import: debian changes")
1336 SpecialMethod => 'DgitImportUpstreamUpdate',
1337 $xmsg->("convert dgit import: upstream update",
1340 $prline->(" Import");
1341 $rewrite_from_here->(\@brw_cl);
1342 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1346 # Everything is from this import. This kind of import
1347 # is already nearly in valid breakwater format, with the
1348 # patches as commits. Unfortunately it contains
1350 printdebug "*** WALK BOMB bare dgit import\n";
1351 $cl->{Why} = "bare dgit dsc import";
1355 } elsif ($ty eq 'MergedBreakwaters') {
1356 $last_anchor = mergedbreakwaters_anchor $cl;
1357 $build_start->(' MergedBreakwaters', $cur);
1359 } elsif ($ty eq 'VanillaMerge') {
1360 # User may have merged unstitched branch(es). We will
1361 # have now lost what ffq-prev was then (since the later
1362 # pseudomerge may introduce further changes). The effect
1363 # of resolving such a merge is that we may have to go back
1364 # further in history to find a merge base, since the one
1365 # which was reachable via ffq-prev is no longer findable.
1366 # This is suboptimal, but if it all works we'll have done
1368 # MERGE-TODO we should warn the user in the docs about this
1372 # We expect to find a dominating anchor amongst the
1373 # inputs' anchors. That will be the new anchor.
1375 # More complicated is finding a merge base for the
1376 # breakwaters. We need a merge base that is a breakwater
1377 # commit. The ancestors of breakwater commits are more
1378 # breakwater commits and possibly upstream commits and the
1379 # ancestors of those upstream. Upstreams might have
1380 # arbitrary ancestors. But any upstream commit U is
1381 # either included in both anchors, in which case the
1382 # earlier anchor is a better merge base than any of U's
1383 # ancestors; or U is not included in the older anchor, in
1384 # which case U is not an ancestor of the vanilla merge at
1385 # all. So no upstream commit, nor any ancestor thereof,
1386 # is a best merge base. As for non-breakwater Debian
1387 # commits: these are never ancestors of any breakwater.
1389 # So any best merge base as found by git-merge-base
1390 # is a suitable breakwater anchor. Usually there will
1393 printdebug "*** MERGE\n";
1395 my @bwbcmd = (@git, qw(merge-base));
1396 my @ibcmd = (@git, qw(merge-base --all));
1397 my $might_be_in_bw = 1;
1399 my $ps = $cl->{Parents};
1401 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1403 foreach my $p (@$ps) {
1404 $prline->(" VanillaMerge ".$p->{Ix});
1406 my ($ptip, $pbw, $panchor) =
1407 walk $p->{CommitId}, 0, $report,
1408 $report_lprefix.' ';
1409 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1410 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1411 $p->{Anchor} = $panchor;
1413 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1414 $mwrecknote->("$lr-input", $p->{CommitId});
1416 my $mwrecknote_parent = sub {
1418 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1420 $mwrecknote_parent->('Laundered');
1421 $mwrecknote_parent->('Breakwater');
1422 $mwrecknote_parent->('Anchor');
1424 $best_anchor = $panchor if
1425 !defined $best_anchor or
1426 is_fast_fwd $best_anchor, $panchor;
1428 printdebug " MERGE BA best=".($best_anchor//'-').
1432 $mwrecknote->('result-anchor', $best_anchor);
1434 foreach my $p (@$ps) {
1435 $prline->(" VanillaMerge ".$p->{Ix});
1436 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1437 $nomerge->('divergent anchors');
1438 } elsif ($p->{Anchor} eq $best_anchor) {
1439 print $report " SameAnchor" if $report;
1441 print $report " SupersededAnchor" if $report;
1443 if ($p->{Breakwater} eq $p->{CommitId}) {
1444 # this parent commit was its own breakwater,
1445 # ie it is part of the breakwater
1446 print $report " Breakwater" if $report;
1448 $might_be_in_bw = 0;
1450 push @bwbcmd, $p->{Breakwater};
1451 push @ibcmd, $p->{CommitId};
1454 if ($ok && $might_be_in_bw) {
1455 # We could rewrite this to contaion the metadata
1456 # declaring it to be MergedBreakwaters, but
1457 # unnecessarily rewriting a merge seems unhelpful.
1458 $prline->(" VanillaMerge MergedBreakwaters");
1459 $last_anchor = $best_anchor;
1460 $build_start->('MergedBreakwaters', $cur);
1463 my $bwb = cmdoutput @bwbcmd;
1465 # OK, now we have a breakwater base, but we need the merge
1466 # base for the interchange branch because we need the delta
1469 # This a the best merge base of our inputs which has the
1470 # breakwater merge base as an ancestor.
1477 @ibs or confess 'internal error, expected anchor at least ?';
1481 foreach my $tibix (0..$#ibs) {
1482 my $tib = $ibs[$tibix];
1483 my $ff = is_fast_fwd $bwb, $tib;
1484 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1485 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1486 $mwrecknote->($tibleaf, $tib);
1493 $ib or $nomerge->("no suitable interchange merge base");
1495 $prline->(" VanillaMerge Base");
1497 my ($btip, $bbw, $banchor) = eval {
1498 walk $ib, 0, $report, $report_lprefix.' ';
1500 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1504 $mwrecknote->("mergebase-laundered", $btip);
1505 $mwrecknote->("mergebase-breakwater", $bbw);
1506 $mwrecknote->("mergebase-anchor", $banchor);
1508 my $ibinfo = { SeriesTip => $btip,
1511 LeftRight => 'mergebase' };
1514 or $nomerge->("interchange merge-base ($ib)'s".
1515 " breakwater ($bbw)".
1516 " != breakwaters' merge-base ($bwb)");
1518 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1519 or $nomerge->("interchange merge-base ($ib)'s".
1520 " anchor ($ibinfo->{SeriesBase})".
1521 " != any merge input's anchor (".
1522 (join ' ', map { $_->{Anchor} } @$ps).
1525 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1526 $cl->{MergeBestAnchor} = $best_anchor;
1529 SpecialMethod => 'MergeCreateMergedBreakwaters',
1530 $xmsg->('constructed from vanilla merge',
1531 ' merged-breakwater'),
1535 SpecialMethod => 'MergeMergeSeries',
1537 $build_start->('MergeBreakwaters', $cur);
1539 printdebug "*** WALK BOMB unrecognised\n";
1545 printdebug "*** WALK prep done cur=$cur".
1546 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1548 return if $nogenerate;
1550 # Now we build it back up again
1556 $#upp_cl = $upp_limit if defined $upp_limit;
1558 my $committer_authline = calculate_committer_authline();
1560 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1562 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1565 mkdir $rd or $!==EEXIST or die $!;
1567 my $want_debian = $build;
1568 my $want_upstream = $build;
1570 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1571 my $read_tree_debian = sub { ($want_debian) = @_; };
1573 foreach my $cl (qw(Debian), (reverse @brw_cl),
1574 { SpecialMethod => 'RecordBreakwaterTip' },
1575 qw(Upstream), (reverse @upp_cl)) {
1577 $current_method = $cl;
1580 my $method = $cl->{SpecialMethod} // $current_method;
1581 my @parents = ($build);
1582 my $cltree = $cl->{CommitId};
1583 printdebug "WALK BUILD ".($cltree//'undef').
1584 " $method (rewriting=$rewriting)\n";
1585 if ($method eq 'Debian') {
1586 $read_tree_debian->($cltree);
1587 } elsif ($method eq 'Upstream') {
1588 $read_tree_upstream->($cltree);
1589 } elsif ($method eq 'StartRewrite') {
1592 } elsif ($method eq 'RecordBreakwaterTip') {
1593 $breakwater = $build;
1595 } elsif ($method eq 'DgitImportDebianUpdate') {
1596 $read_tree_debian->($cltree);
1597 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1598 confess unless $rewriting;
1599 my $differs = (get_differs $build, $cltree);
1600 next unless $differs & D_UPS;
1601 $read_tree_upstream->($cltree);
1602 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1603 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1604 print "Found a general merge, will try to tidy it up.\n";
1606 $read_tree_upstream->($cl->{MergeBestAnchor});
1607 $read_tree_debian->($cltree);
1608 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1609 } elsif ($method eq 'MergeMergeSeries') {
1610 my $cachehit = reflog_cache_lookup
1611 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1613 print "Using supplied resolution for $cl->{CommitId}...\n";
1615 $mwrecknote->('cached-resolution', $build);
1617 print "Running merge resolution for $cl->{CommitId}...\n";
1618 $mwrecknote->('new-base', $build);
1619 $build = merge_series
1620 $build, $cl->{MergeWreckNotes},
1621 $cl->{MergeInterchangeBaseInfo},
1622 @{ $cl->{Parents} };
1624 $last_anchor = $cl->{MergeBestAnchor};
1626 # Check for mismerges:
1628 my ($against, $allow, $what) = @_;
1629 my $differs = get_differs $build, $against;
1631 "merge misresolved: %s are not the same (%s %s d.%#x)",
1632 $what, $against, $build, $differs)
1633 if $differs & ~($allow | D_PAT_ADD);
1636 # Breakwater changes which were in each side of the
1637 # merge will have been incorporated into the
1638 # MergeCreateMergedBreakwaters output. Because the
1639 # upstream series was rebased onto the new breakwater,
1640 # so should all of the packaging changes which were in
1642 $check->($input, D_UPS, 'debian files');
1644 # Upstream files are merge_series, which ought to
1645 # have been identical to the original merge.
1646 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1648 print "Merge resolution successful.\n";
1651 confess "$method ?";
1654 my $procd = (pop @processed) // 'UNDEF';
1655 if ($cl ne $procd) {
1657 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1661 read_tree_upstream $want_upstream, 0, $want_debian;
1663 my $newtree = cmdoutput @git, qw(write-tree);
1664 my $ch = $cl->{Hdr};
1665 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1666 $ch =~ s{^parent .*\n}{}mg;
1667 $ch =~ s{(?=^author)}{
1668 join '', map { "parent $_\n" } @parents
1669 }me or confess "$ch ?";
1671 $ch =~ s{^committer .*$}{$committer_authline}m
1674 my $cf = "$rd/m$rewriting";
1675 open CD, ">", $cf or die $!;
1676 print CD $ch, "\n", $cl->{Msg} or die $!;
1678 my @cmd = (@git, qw(hash-object));
1679 push @cmd, qw(-w) if $rewriting;
1680 push @cmd, qw(-t commit), $cf;
1681 my $newcommit = cmdoutput @cmd;
1682 confess "$ch ?" unless $rewriting
1683 or $newcommit eq $cl->{CommitId};
1684 $build = $newcommit;
1686 $build = $cl->{CommitId};
1687 trees_diff_walk "$want_upstream:", "$build:", sub {
1689 no warnings qw(exiting);
1690 next if $n eq 'debian/';
1691 confess "mismatch @_ ?";
1693 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1694 confess "mismatch @_ ?";
1696 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1697 confess "mismatch @parents != @old_parents ?"
1698 unless "@parents" eq "@old_parents";
1700 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1701 $last_anchor = $cur;
1706 my $final_check = get_differs $build, $input;
1707 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1708 if $final_check & ~D_PAT_ADD;
1710 my @r = ($build, $breakwater, $last_anchor);
1711 printdebug "*** WALK RETURN @r\n";
1716 git_check_unmodified();
1717 return git_rev_parse qw(HEAD);
1720 sub update_head ($$$) {
1721 my ($old, $new, $mrest) = @_;
1722 push @deferred_updates, "update HEAD $new $old";
1723 run_deferred_updates $mrest;
1726 sub update_head_checkout ($$$) {
1727 my ($old, $new, $mrest) = @_;
1728 update_head $old, $new, $mrest;
1729 runcmd @git, qw(reset --hard);
1732 sub update_head_postlaunder ($$$) {
1733 my ($old, $tip, $reflogmsg) = @_;
1734 return if $tip eq $old && !@deferred_updates;
1735 print "git-debrebase: laundered (head was $old)\n";
1736 update_head $old, $tip, $reflogmsg;
1737 # no tree changes except debian/patches
1738 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1741 sub currently_rebasing() {
1742 foreach (qw(rebase-merge rebase-apply)) {
1743 return 1 if stat_exists "$maindir_gitdir/$_";
1748 sub bail_if_rebasing() {
1749 fail "you are in the middle of a git-rebase already"
1750 if currently_rebasing();
1753 sub do_launder_head ($) {
1754 my ($reflogmsg) = @_;
1755 my $old = get_head();
1757 my ($tip,$breakwater) = walk $old;
1759 update_head_postlaunder $old, $tip, $reflogmsg;
1760 return ($tip,$breakwater);
1763 sub cmd_launder_v0 () {
1764 badusage "no arguments to launder-v0 allowed" if @ARGV;
1765 my $old = get_head();
1766 my ($tip,$breakwater,$last_anchor) = walk $old;
1767 update_head_postlaunder $old, $tip, 'launder';
1768 printf "# breakwater tip\n%s\n", $breakwater;
1769 printf "# working tip\n%s\n", $tip;
1770 printf "# last anchor\n%s\n", $last_anchor;
1773 sub defaultcmd_rebase () {
1774 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1775 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1776 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1779 sub cmd_analyse () {
1780 badusage "analyse does not support any options"
1781 if @ARGV and $ARGV[0] =~ m/^-/;
1782 badusage "too many arguments to analyse" if @ARGV>1;
1785 $old = git_rev_parse $old;
1787 $old = git_rev_parse 'HEAD';
1789 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1790 STDOUT->error and die $!;
1793 sub ffq_check ($;$$) {
1794 # calls $ff and/or $notff zero or more times
1795 # then returns either (status,message) where status is
1800 # or (undef,undef, $ffq_prev,$gdrlast)
1801 # $ff and $notff are called like this:
1802 # $ff->("message for stdout\n");
1803 # $notff->('snag-name', $message);
1804 # normally $currentval should be HEAD
1805 my ($currentval, $ff, $notff) =@_;
1807 $ff //= sub { print $_[0] or die $!; };
1810 my ($status, $message, $current, $ffq_prev, $gdrlast)
1811 = ffq_prev_branchinfo();
1812 return ($status, $message) unless $status eq 'branch';
1814 my $exists = git_get_ref $ffq_prev;
1815 return ('exists',"$ffq_prev already exists") if $exists;
1817 return ('not-branch', 'HEAD symref is not to refs/heads/')
1818 unless $current =~ m{^refs/heads/};
1821 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1824 printdebug "ffq check_specs @check_specs\n";
1827 my ($lrref, $desc) = @_;
1828 printdebug "ffq might check $lrref ($desc)\n";
1830 for my $chk (@check_specs) {
1832 $invert = $glob =~ s{^[!^]}{};
1833 last if fnmatch $glob, $lrref;
1836 my $lrval = git_get_ref $lrref;
1837 return unless length $lrval;
1839 if (is_fast_fwd $lrval, $currentval) {
1840 $ff->("OK, you are ahead of $lrref\n");
1841 $checked{$lrref} = 1;
1842 } elsif (is_fast_fwd $currentval, $lrval) {
1843 $checked{$lrref} = -1;
1844 $notff->('behind', "you are behind $lrref, divergence risk");
1846 $checked{$lrref} = -1;
1847 $notff->('diverged', "you have diverged from $lrref");
1851 my $merge = cfg "branch.$branch.merge",1;
1852 if (defined $merge and $merge =~ m{^refs/heads/}) {
1854 printdebug "ffq merge $rhs\n";
1855 my $check_remote = sub {
1856 my ($remote, $desc) = @_;
1857 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1858 return unless defined $remote;
1859 $check->("refs/remotes/$remote/$rhs", $desc);
1861 $check_remote->((scalar cfg "branch.$branch.remote",1),
1862 'remote fetch/merge branch');
1863 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1864 (scalar cfg "branch.$branch.pushDefault",1),
1865 'remote push branch');
1867 if ($branch =~ m{^dgit/}) {
1868 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1869 } elsif ($branch =~ m{^master$}) {
1870 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1872 return (undef, undef, $ffq_prev, $gdrlast);
1875 sub record_ffq_prev_deferred () {
1876 # => ('status', "message")
1878 # deferred message is undef
1883 # if not ff from some branch we should be ff from, is an snag
1884 # if "deferred", will have added something about that to
1885 # @deferred_update_messages, and also maybe printed (already)
1886 # some messages about ff checks
1888 my $currentval = get_head();
1890 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1891 return ($status,$message) if defined $status;
1895 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1896 push @deferred_updates, "delete $gdrlast";
1897 push @deferred_update_messages, "Recorded previous head for preservation";
1898 return ('deferred', undef);
1901 sub record_ffq_auto () {
1902 my ($status, $message) = record_ffq_prev_deferred();
1903 if ($status eq 'deferred' || $status eq 'exists') {
1905 snag $status, "could not record ffq-prev: $message";
1910 sub ffq_prev_info () {
1912 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1913 my ($status, $message, $current, $ffq_prev, $gdrlast)
1914 = ffq_prev_branchinfo();
1915 if ($status ne 'branch') {
1916 snag $status, "could not check ffq-prev: $message";
1919 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1920 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1923 sub stitch ($$$$$) {
1924 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1926 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1928 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1929 my $differs = get_differs $old_head, $ffq_prev_commitish;
1930 unless ($differs & ~D_PAT_ADD) {
1931 # ffq-prev is ahead of us, and the only tree changes it has
1932 # are possibly addition of things in debian/patches/.
1933 # Just wind forwards rather than making a pointless pseudomerge.
1934 record_gdrlast $gdrlast, $ffq_prev_commitish;
1935 update_head_checkout $old_head, $ffq_prev_commitish,
1936 "stitch (fast forward)";
1941 # We make pseudomerges with L as the contributing parent.
1942 # This makes git rev-list --first-parent work properly.
1943 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1944 'Declare fast forward / record previous work',
1945 "[git-debrebase pseudomerge: $prose]",
1947 record_gdrlast $gdrlast, $new_head;
1948 update_head $old_head, $new_head, "stitch: $prose";
1951 sub do_stitch ($;$) {
1952 my ($prose, $unclean) = @_;
1954 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1955 if (!$ffq_prev_commitish) {
1956 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1959 my $dangling_head = get_head();
1961 keycommits $dangling_head, $unclean,$unclean,$unclean;
1964 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1967 sub upstream_commitish_search ($$) {
1968 my ($upstream_version, $tried) = @_;
1969 # todo: at some point maybe use git-deborig to do this
1970 foreach my $tagpfx ('', 'v', 'upstream/') {
1971 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1972 my $new_upstream = git_get_ref "refs/tags/$tag";
1974 return $new_upstream if length $new_upstream;
1978 sub resolve_upstream_version ($$) {
1979 my ($new_upstream, $upstream_version) = @_;
1981 if (!defined $new_upstream) {
1983 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1984 if (!length $new_upstream) {
1985 fail "Could not determine appropriate upstream commitish.\n".
1986 " (Tried these tags: @tried)\n".
1987 " Check version, and specify upstream commitish explicitly.";
1990 $new_upstream = git_rev_parse $new_upstream;
1992 return $new_upstream;
1995 sub cmd_new_upstream () {
1996 # automatically and unconditionally launders before rebasing
1997 # if rebase --abort is used, laundering has still been done
2001 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
2003 # parse args - low commitment
2004 my $spec_version = shift @ARGV;
2005 my $new_version = (new Dpkg::Version $spec_version, check => 1);
2006 fail "bad version number \`$spec_version'" unless defined $new_version;
2007 if ($new_version->is_native()) {
2008 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
2011 my $new_upstream = shift @ARGV;
2012 my $new_upstream_version = upstreamversion $new_version;
2014 resolve_upstream_version $new_upstream, $new_upstream_version;
2019 my ($n, @x) = @_; # may be ''
2020 my $pc = $pieces{$n} //= {
2022 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
2024 while (my $k = shift @x) { $pc->{$k} = shift @x; }
2029 my $newpiece = sub {
2030 my ($n, @x) = @_; # may be ''
2031 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2032 push @newpieces, $pc;
2037 New => $new_upstream,
2039 while (@ARGV && $ARGV[0] !~ m{^-}) {
2040 my $n = shift @ARGV;
2042 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2043 unless @ARGV && $ARGV[0] !~ m{^-};
2045 my $c = git_rev_parse shift @ARGV;
2046 die unless $n =~ m/^$extra_orig_namepart_re$/;
2047 $newpiece->($n, New => $c);
2050 # now we need to investigate the branch this generates the
2051 # laundered version but we don't switch to it yet
2052 my $old_head = get_head();
2053 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2055 my $old_bw_cl = classify $old_bw;
2056 my $old_anchor_cl = classify $old_anchor;
2058 if (!$old_anchor_cl->{OrigParents}) {
2059 snag 'anchor-treated',
2060 'old anchor is recognised due to --anchor, cannot check upstream';
2062 $old_upstream = parsecommit
2063 $old_anchor_cl->{OrigParents}[0]{CommitId};
2064 $piece->('', Old => $old_upstream->{CommitId});
2067 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2068 if ($old_upstream->{Msg} =~
2069 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2071 my @oldpieces = (split / /, $1);
2072 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2073 if ($old_n_parents != @oldpieces &&
2074 $old_n_parents != @oldpieces + 1) {
2075 snag 'upstream-confusing', sprintf
2076 "previous upstream combine %s".
2077 " mentions %d pieces (each implying one parent)".
2078 " but has %d parents".
2079 " (one per piece plus maybe a previous combine)",
2080 $old_upstream->{CommitId},
2081 (scalar @oldpieces),
2083 } elsif ($oldpieces[0] ne '.') {
2084 snag 'upstream-confusing', sprintf
2085 "previous upstream combine %s".
2086 " first piece is not \`.'",
2090 foreach my $i (0..$#oldpieces) {
2091 my $n = $oldpieces[$i];
2092 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2093 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2097 snag 'upstream-confusing',
2098 "previous upstream $old_upstream->{CommitId} is from".
2099 " git-debrebase but not an \`upstream-combine' commit";
2103 foreach my $pc (values %pieces) {
2104 if (!$old_upstream) {
2105 # we have complained already
2106 } elsif (!$pc->{Old}) {
2107 snag 'upstream-new-piece',
2108 "introducing upstream piece \`$pc->{Name}'";
2109 } elsif (!$pc->{New}) {
2110 snag 'upstream-rm-piece',
2111 "dropping upstream piece \`$pc->{Name}'";
2112 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2113 snag 'upstream-not-ff',
2114 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2118 printdebug "%pieces = ", (dd \%pieces), "\n";
2119 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2127 my @upstream_merge_parents;
2130 push @upstream_merge_parents, $old_upstream->{CommitId};
2133 foreach my $pc (@newpieces) { # always has '' first
2135 read_tree_subdir $pc->{Name}, $pc->{New};
2137 runcmd @git, qw(read-tree), $pc->{New};
2139 push @upstream_merge_parents, $pc->{New};
2142 # index now contains the new upstream
2144 if (@newpieces > 1) {
2145 # need to make the upstream subtree merge commit
2146 $new_upstream = make_commit \@upstream_merge_parents,
2147 [ "Combine upstreams for $new_upstream_version",
2148 ("[git-debrebase upstream-combine . ".
2149 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2154 # $new_upstream is either the single upstream commit, or the
2155 # combined commit we just made. Either way it will be the
2156 # "upstream" parent of the anchor merge.
2158 read_tree_subdir 'debian', "$old_bw:debian";
2160 # index now contains the anchor merge contents
2161 $new_bw = make_commit [ $old_bw, $new_upstream ],
2162 [ "Update to upstream $new_upstream_version",
2163 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2166 my $clogsignoff = cmdoutput qw(git show),
2167 '--pretty=format:%an <%ae> %aD',
2170 # Now we have to add a changelog stanza so the Debian version
2172 die if unlink "debian";
2173 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2174 unlink "debian/changelog" or $!==ENOENT or die $!;
2175 mkdir "debian" or die $!;
2176 open CN, ">", "debian/changelog" or die $!;
2177 my $oldclog = git_cat_file ":debian/changelog";
2178 $oldclog =~ m/^($package_re) \(\S+\) / or
2179 fail "cannot parse old changelog to get package name";
2181 print CN <<END, $oldclog or die $!;
2182 $p ($new_version) UNRELEASED; urgency=medium
2184 * Update to new upstream version $new_upstream_version.
2190 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2192 # Now we have the final new breakwater branch in the index
2193 $new_bw = make_commit [ $new_bw ],
2194 [ "Update changelog for new upstream $new_upstream_version",
2195 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2199 # we have constructed the new breakwater. we now need to commit to
2200 # the laundering output, because git-rebase can't easily be made
2201 # to make a replay list which is based on some other branch
2203 update_head_postlaunder $old_head, $old_laundered_tip,
2204 'launder for new upstream';
2206 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2207 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2208 "debrebase new-upstream $new_version: rebase";
2210 # now it's for the user to sort out
2213 sub cmd_record_ffq_prev () {
2214 badusage "no arguments allowed" if @ARGV;
2215 my ($status, $msg) = record_ffq_prev_deferred();
2216 if ($status eq 'exists' && $opt_noop_ok) {
2217 print "Previous head already recorded\n" or die $!;
2218 } elsif ($status eq 'deferred') {
2219 run_deferred_updates 'record-ffq-prev';
2221 fail "Could not preserve: $msg";
2226 badusage "no arguments allowed" if @ARGV;
2227 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2228 print "$bw\n" or die $!;
2231 sub cmd_breakwater () {
2232 badusage "no arguments allowed" if @ARGV;
2233 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2234 print "$bw\n" or die $!;
2238 badusage "no arguments allowed" if @ARGV;
2240 # todo: gdr status should print divergence info
2241 # todo: gdr status should print upstream component(s) info
2242 # todo: gdr should leave/maintain some refs with this kind of info ?
2244 my $oldest = { Badness => 0 };
2247 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2248 if ($oldest->{Badness} < $badness) {
2249 $oldest = $newest = undef;
2252 Badness => $badness,
2253 CommitId => $cl->{CommitId},
2257 $newest //= $oldest;
2259 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2260 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2261 sub { $note->(2, 'branch is unlaundered', @_); },
2262 sub { $note->(3, 'branch needs laundering', @_); },
2263 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2265 my $prcommitinfo = sub {
2267 flush STDOUT or die $!;
2268 runcmd @git, qw(--no-pager log -n1),
2269 '--pretty=format: %h %s%n',
2273 print "current branch contents, in git-debrebase terms:\n";
2274 if (!$oldest->{Badness}) {
2275 print " branch is laundered\n";
2277 print " $oldest->{OurMsg}\n";
2279 foreach my $info ($oldest, $newest) {
2280 my $cid = $info->{CommitId};
2281 next if $cid eq $printed;
2283 print " $info->{KcMsg}\n";
2284 $prcommitinfo->($cid);
2289 my ($cid, $what) = @_;
2290 if (!defined $cid) {
2291 print " $what is not well-defined\n";
2294 $prcommitinfo->($cid);
2297 print "key git-debrebase commits:\n";
2298 $prab->($anchor, 'anchor');
2299 $prab->($bw, 'breakwater');
2301 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2302 ffq_prev_branchinfo();
2304 print "branch and ref status, in git-debrebase terms:\n";
2306 print " $ffq_msg\n";
2308 $ffq_prev = git_get_ref $ffq_prev;
2309 $gdrlast = git_get_ref $gdrlast;
2311 print " unstitched; previous tip was:\n";
2312 $prcommitinfo->($ffq_prev);
2313 } elsif (!$gdrlast) {
2314 print " stitched? (no record of git-debrebase work)\n";
2315 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2316 print " stitched\n";
2318 print " not git-debrebase (diverged since last stitch)\n"
2321 print "you are currently rebasing\n" if currently_rebasing();
2325 my $prose = 'stitch';
2326 getoptions("stitch",
2327 'prose=s', \$prose);
2328 badusage "no arguments allowed" if @ARGV;
2329 do_stitch $prose, 0;
2331 sub cmd_prepush () {
2337 badusage "no arguments allowed" if @ARGV;
2338 do_launder_head 'launder for git-debrebase quick';
2342 sub cmd_conclude () {
2343 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2344 if (!$ffq_prev_commitish) {
2345 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2348 my $dangling_head = get_head();
2350 badusage "no arguments allowed" if @ARGV;
2351 do_launder_head 'launder for git-debrebase quick';
2356 if (currently_rebasing()) {
2357 runcmd @git, qw(rebase --abort);
2358 push @deferred_updates, 'verify HEAD HEAD';
2359 # noop, but stops us complaining that scrap was a noop
2361 badusage "no arguments allowed" if @ARGV;
2362 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2364 if ($ffq_prev_commitish) {
2365 $scrapping_head = get_head();
2366 push @deferred_updates,
2367 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2368 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2370 if (git_get_ref $merge_cache_ref) {
2371 push @deferred_updates,
2372 "delete $merge_cache_ref";
2374 if (!@deferred_updates) {
2375 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2379 if ($scrapping_head) {
2380 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2382 run_deferred_updates "scrap";
2386 sub make_patches_staged ($) {
2388 # Produces the patches that would result from $head if it were
2390 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2393 gbp_pq_export 'bw', $secret_bw, $secret_head;
2397 sub make_patches ($) {
2399 keycommits $head, 0, \&snag;
2400 make_patches_staged $head;
2403 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2404 runcmd @git, qw(read-tree), $head;
2405 read_tree_subdir 'debian/patches', $ptree;
2406 $out = make_commit [$head], [
2407 'Commit patch queue (exported by git-debrebase)',
2408 '[git-debrebase: export and commit patches]',
2414 sub cmd_make_patches () {
2415 my $opt_quiet_would_amend;
2416 getoptions("make-patches",
2417 'quiet-would-amend!', \$opt_quiet_would_amend);
2418 badusage "no arguments allowed" if @ARGV;
2420 my $old_head = get_head();
2421 my $new = make_patches $old_head;
2422 my $d = get_differs $old_head, $new;
2424 fail "No (more) patches to export." unless $opt_noop_ok;
2426 } elsif ($d == D_PAT_ADD) {
2428 update_head_checkout $old_head, $new, 'make-patches';
2430 print STDERR failmsg
2431 "Patch export produced patch amendments".
2432 " (abandoned output commit $new).".
2433 " Try laundering first."
2434 unless $opt_quiet_would_amend;
2439 sub check_series_has_all_patches ($) {
2441 my $seriesfn = 'debian/patches/series';
2442 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2446 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2447 fail "patch $f repeated in $seriesfn !" if $series{$f}++;
2449 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2450 my ($f,$i) = @$patchfile;
2451 next if $series{$f};
2452 next if $f eq 'series';
2453 snag 'unused-patches', "Unused patch file $f will be discarded";
2457 sub begin_convert_from () {
2458 my $head = get_head();
2459 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2461 fail "ffq-prev exists, this is already managed by git-debrebase!"
2462 if $ffq_prev && git_get_ref $ffq_prev;
2464 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2465 snag 'already-converted',
2466 "ahead of debrebase-last, this is already managed by git-debrebase!"
2467 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2468 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2471 sub complete_convert_from ($$$$) {
2472 my ($old_head, $new_head, $gi, $mrest) = @_;
2473 ffq_check $new_head;
2474 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2477 update_head_checkout $old_head, $new_head, $mrest;
2480 sub cmd_convert_from_gbp () {
2481 badusage "want only 1 optional argument, the upstream git commitish"
2484 my $clogp = parsechangelog();
2485 my $version = $clogp->{'Version'}
2486 // die "missing Version from changelog";
2488 my ($upstream_spec) = @ARGV;
2490 my $upstream_version = upstreamversion $version;
2492 resolve_upstream_version($upstream_spec, $upstream_version);
2494 my ($old_head, $gdrlastinfo) = begin_convert_from();
2496 my $upsdiff = get_differs $upstream, $old_head;
2497 if ($upsdiff & D_UPS) {
2498 runcmd @git, qw(--no-pager diff --stat),
2499 $upstream, $old_head,
2500 qw( -- :!/debian :/);
2502 upstream ($upstream_spec) and HEAD are not
2503 identical in upstream files. See diffstat above, or run
2504 git diff $upstream_spec HEAD -- :!/debian :/
2508 if (!is_fast_fwd $upstream, $old_head) {
2509 snag 'upstream-not-ancestor',
2510 "upstream ($upstream) is not an ancestor of HEAD";
2512 my $wrong = cmdoutput
2513 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2514 qw(-- :/ :!/debian));
2515 if (length $wrong) {
2516 snag 'unexpected-upstream-changes',
2517 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2518 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2522 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2523 snag 'upstream-has-debian',
2524 "upstream ($upstream) contains debian/ directory";
2527 check_series_has_all_patches $old_head;
2529 my $previous_dgit_view = eval {
2530 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2532 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2533 my ($stz, $desc) = @_;
2534 no warnings qw(exiting);
2535 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2536 next unless $stz->{Date};
2537 next unless $stz->{Distribution} ne 'UNRELEASED';
2538 $lvsn = $stz->{Version};
2539 $suite = $stz->{Distribution};
2542 die "neither of the first two changelog entries are released\n"
2543 unless defined $lvsn;
2544 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2545 my $mtag_pat = debiantag_maintview $lvsn, '*';
2546 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2548 die "could not find suitable maintainer view tag $mtag_pat\n"
2549 unless $mtag =~ m{/};
2550 is_fast_fwd $mtag, 'HEAD' or
2551 die "HEAD is not FF from maintainer tag $mtag!";
2552 my $dtag = "archive/$mtag";
2553 git_get_ref "refs/tags/$dtag" or
2554 die "dgit view tag $dtag not found\n";
2555 is_fast_fwd $mtag, $dtag or
2556 die "dgit view tag $dtag is not FF from maintainer tag $mtag\n";
2557 print "will stitch in dgit view, $dtag\n";
2558 git_rev_parse $dtag;
2560 if (!$previous_dgit_view) {
2564 Cannot confirm dgit view: $@
2565 Failed to stitch in dgit view (see messages above).
2566 dgit --overwrite will be needed on the first dgit push after conversion.
2570 snags_maybe_bail_early();
2576 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2577 # make a branch out of the patch queue - we'll want this in a mo
2578 runcmd qw(gbp pq import);
2579 # strip the patches out
2580 runcmd @git, qw(checkout -q gdr-internal~0);
2581 rm_subdir_cached 'debian/patches';
2582 $work = make_commit ['HEAD'], [
2583 'git-debrebase convert-from-gbp: drop patches from tree',
2584 'Delete debian/patches, as part of converting to git-debrebase format.',
2585 '[git-debrebase convert-from-gbp: drop patches from tree]'
2587 # make the anchor merge
2588 # the tree is already exactly right
2589 $work = make_commit [$work, $upstream], [
2590 'git-debrebase import: declare upstream',
2591 'First breakwater merge.',
2592 '[git-debrebase anchor: declare upstream]'
2595 # rebase the patch queue onto the new breakwater
2596 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2597 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2598 $work = git_rev_parse 'HEAD';
2600 if ($previous_dgit_view) {
2601 $work = make_commit [$work, $previous_dgit_view], [
2602 'git-debrebase import: declare ff from dgit archive view',
2603 '[git-debrebase pseudomerge: import-from-gbp]',
2608 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2609 print <<END or die $!;
2610 git-debrebase: converted from patched-unapplied (gbp) branch format, OK
2614 sub cmd_convert_to_gbp () {
2615 badusage "no arguments allowed" if @ARGV;
2616 my $head = get_head();
2617 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2618 keycommits $head, 0;
2620 make_patches_staged $head;
2622 $out = make_commit ['HEAD'], [
2623 'Commit patch queue (converted from git-debrebase format)',
2624 '[git-debrebase convert-to-gbp: commit patches]',
2628 push @deferred_updates, "delete $ffq";
2629 push @deferred_updates, "delete $gdrlast";
2632 update_head_checkout $head, $out, "convert to gbp (v0)";
2633 print <<END or die $!;
2634 git-debrebase: converted to git-buildpackage branch format
2635 git-debrebase: WARNING: do not now run "git-debrebase" any more
2636 git-debrebase: WARNING: doing so would drop all upstream patches!
2640 sub cmd_convert_from_dgit_view () {
2641 my $clogp = parsechangelog();
2643 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2649 getoptions("convert-from-dgit-view",
2650 'diagnose!', \$diagnose,
2651 'build-products-dir:s', \$bpd,
2652 'origs!', \$do_origs,
2654 'always-convert-anyway!', \$always);
2655 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2660 my $spec = shift @ARGV;
2661 my $commit = git_rev_parse "$spec^{commit}";
2662 push @upstreams, { Commit => $commit,
2663 Source => "$ARGV[0], from command line",
2668 my ($head, $gdrlastinfo) = begin_convert_from();
2672 my $trouble = sub { $troubles++; };
2673 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2674 printdebug "troubles=$troubles\n";
2677 $us: Branch already seems to be in git-debrebase format!
2678 $us: --always-convert-anyway would do the conversion operation anyway
2679 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2681 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2686 check_series_has_all_patches $head;
2688 snags_maybe_bail_early();
2690 my $version = upstreamversion $clogp->{Version};
2691 print STDERR "Considering possible commits corresponding to upstream:\n";
2696 my $ups_tag = upstream_commitish_search $version, \@tried;
2698 my $this = "git tag $tried[-1]";
2699 push @upstreams, { Commit => $ups_tag,
2704 " git tag: no suitable tag found (tried %s)\n",
2709 my $p = $clogp->{'Source'};
2710 # we do a quick check to see if there are plausible origs
2712 if (!opendir BPD, $bpd) {
2713 die "$bpd: opendir: $!" unless $!==ENOENT;
2715 while ($!=0, my $f = readdir BPD) {
2716 next unless is_orig_file_of_p_v $f, $p, $version;
2718 " orig: found what looks like a .orig, %s\n",
2723 die "read $bpd: $!" if $!;
2727 my $tree = cmdoutput
2728 @dgit, qw(--build-products-dir), $bpd,
2729 qw(print-unapplied-treeish);
2732 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2733 rm_subdir_cached 'debian';
2734 $tree = cmdoutput @git, qw(write-tree);
2735 my $ups_synth = make_commit [], [ <<END, <<END,
2736 Import effective orig tree for upstream version $version
2738 This includes the contents of the .orig(s), minus any debian/ directory.
2740 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2743 push @upstreams, { Commit => $ups_synth,
2744 Source => "orig(s) imported via dgit",
2749 " orig: no suitable origs found (looked for %s in %s)\n",
2750 "${p}_".(stripeoch $version)."...", $bpd;
2755 my $some_patches = stat_exists 'debian/patches/series';
2757 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2760 foreach my $u (@upstreams) {
2764 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2765 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2766 runcmd @git, qw(clean -xdff);
2767 runcmd @git, qw(checkout), $head, qw(-- debian);
2768 if ($some_patches) {
2769 rm_subdir_cached 'debian/patches';
2770 $work = make_commit [ $work ], [
2771 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2772 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2773 "to git-debrebase format. Upstream changes will appear as commits.",
2774 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2777 $work = make_commit [ $work, $u->{Commit} ], [
2778 'git-debrebase convert-from-dgit-view: declare upstream',
2779 '(Re)constructed breakwater merge.',
2780 '[git-debrebase anchor: declare upstream]'
2782 runcmd @git, qw(checkout --quiet -b mk), $work;
2783 if ($some_patches) {
2784 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2785 runcmd @git, qw(reset --quiet);
2786 my @gbp_cmd = (qw(gbp pq import));
2788 my $gbp_err = "../gbp-pq-err";
2789 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2791 my $r = system @gbp_cmd;
2794 " %s: couldn't apply patches: gbp pq %s",
2795 $u->{Source}, waitstatusmsg();
2799 my $work = git_rev_parse qw(HEAD);
2800 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2801 if (length $diffout) {
2803 " $u->{Source}: applying patches gives different tree\n";
2804 print STDERR $diffout if $diagnose;
2808 $u->{Result} = $work;
2816 Could not find or construct a suitable upstream commit.
2817 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2818 upstream commmit explicitly or provide suitable origs.
2822 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2824 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2825 'convert-from-dgit-view';
2828 sub cmd_record_resolved_merge () {
2829 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2830 # MERGE-TODO needs documentation
2831 my $new = get_head();
2834 print "Checking how you have resolved the merge problem\n";
2835 my $nope = sub { print "Not $method: @_"; 0; };
2837 my $maybe = sub { print "Seems to be $method.\n"; };
2839 my ($key, $ref) = @_;
2840 reflog_cache_insert $merge_cache_ref, $key, $ref;
2841 print "OK. You can switch branches and try git-debrebase again.\n";
2845 fresh_workarea 'merge';
2847 $method = 'vanilla-merge patchqueue';
2848 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2849 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2850 foreach my $lr (qw(left right)) {
2851 my $n = "$wrecknoteprefix/$lr-patchqueue";
2852 my $lrpq = git_get_ref $n;
2853 $lrpq or return $nope->("wreckage did not contain patchqueues");
2854 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2857 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2858 or die "wreckage element $wrecknoteprefix/new-base missing";
2859 my $result = merge_series_patchqueue_convert
2861 $yes->("vanilla-merge $vanilla", $result);
2864 fail "No resolved merge method seems applicable.\n";
2868 sub cmd_downstream_rebase_launder_v0 () {
2869 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2871 $base = git_rev_parse $base;
2872 my $old_head = get_head();
2873 my $current = $old_head;
2876 if ($current eq $base) {
2877 $topmost_keep //= $current;
2878 print " $current BASE stop\n";
2881 my $cl = classify $current;
2882 print " $current $cl->{Type}";
2884 my $p0 = $cl->{Parents}[0]{CommitId};
2886 if ($cl->{Type} eq 'Pseudomerge') {
2887 print " ^".($cl->{Contributor}{Ix}+1);
2888 $next = $cl->{Contributor}{CommitId};
2889 } elsif ($cl->{Type} eq 'AddPatches' or
2890 $cl->{Type} eq 'Changelog') {
2900 $topmost_keep //= $current;
2902 die "to-be stripped changes not on top of the branch\n"
2907 if ($topmost_keep eq $old_head) {
2908 print "unchanged\n";
2910 print "updating to $topmost_keep\n";
2911 update_head_checkout
2912 $old_head, $topmost_keep,
2913 'downstream-rebase-launder-v0';
2919 "D+" => \$debuglevel,
2920 'noop-ok', => \$opt_noop_ok,
2921 'f=s' => \@snag_force_opts,
2922 'anchor=s' => \@opt_anchors,
2923 '--dgit=s' => \($dgit[0]),
2925 'experimental-merge-resolution!', \$opt_merges,
2927 my ($opt,$val) = @_;
2928 badusage "git-debrebase: no cuddling to -i for git-rebase"
2930 die if $opt_defaultcmd_interactive; # should not happen
2931 $opt_defaultcmd_interactive = [ qw(-i) ];
2932 # This access to @ARGV is excessive familiarity with
2933 # Getopt::Long, but there isn't another sensible
2934 # approach. '-i=s{0,}' does not work with bundling.
2935 push @$opt_defaultcmd_interactive, @ARGV;
2938 'help' => sub { print $usage_message or die $!; finish 0; },
2941 initdebug('git-debrebase ');
2942 enabledebug if $debuglevel;
2944 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2945 chdir $toplevel or die "chdir $toplevel: $!";
2947 $rd = fresh_playground "$playprefix/misc";
2949 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2951 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2952 defaultcmd_rebase();
2954 my $cmd = shift @ARGV;
2957 $cmdfn = ${*::}{"cmd_$cmdfn"};
2959 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";