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 $recurse = !!$recurse;
201 confess "get_tree needs object not $x ?" unless $x =~ m{^[0-9a-f]+\:};
203 our (@get_tree_memo, %get_tree_memo);
204 my $memo = $get_tree_memo{$recurse,$x};
205 return @$memo if $memo;
207 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
209 my @cmd = (qw(git ls-tree -z --full-tree));
210 push @cmd, qw(-r) if $recurse;
211 push @cmd, qw(--), $x;
212 my $o = cmdoutput @cmd;
215 foreach my $l (split /\0/, $o) {
216 my ($i, $n) = split /\t/, $l, 2;
217 $n .= '/' if $i =~ m/^\d+ tree /;
219 confess "$x need $last < $n ?" unless $last lt $n;
221 $get_tree_memo{$recurse,$x} = \@l;
222 push @get_tree_memo, $x;
223 if (@get_tree_memo > 10) {
224 delete $get_tree_memo{ shift @get_tree_memo };
229 sub trees_diff_walk ($$$;$) {
230 # trees_diff_walk [{..opts...},] $x, $y, sub {... }
231 # calls sub->($name, $ix, $iy) for each difference
232 # $x and $y are as for get_tree
233 # where $name, $ix, $iy are $name and $info from get_tree
234 # opts are all call even for names same in both
235 my $opts = shift @_ if @_>=4;
236 my ($x,$y,$call) = @_;
237 my $all = $opts->{all};
238 return if !$all and $x eq $y;
241 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
244 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
245 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
246 my ($n, $ix, $iy); # all same? $cmp=0, use both
248 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
250 ($n, $ix) = @{ shift @x } if $cmp <= 0;
251 ($n, $iy) = @{ shift @y } if $cmp >= 0;
252 next if !$all and $ix eq $iy;
254 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
255 !!$all,$x,$y, $n,$ix,$iy
257 $call->($n, $ix, $iy);
261 sub get_differs ($$) {
263 # This does a similar job to quiltify_trees_differ, in dgit, a bit.
264 # But we don't care about modes, or dpkg-source-unrepresentable
265 # changes, and we don't need the plethora of different modes.
266 # Conversely we need to distinguish different kinds of changes to
267 # debian/ and debian/patches/.
268 # Also, here we have, and want to use, trees_diff_walk, because
269 # we may be calling this an awful lot and we want it to be fast.
274 no warnings qw(exiting);
276 my $plain = sub { $_[0] =~ m{^(100|0*)644 blob }s; };
278 trees_diff_walk "$x:", "$y:", sub {
279 my ($n,$ix,$iy) = @_;
281 # analyse difference at the toplevel
283 if ($n ne 'debian/') {
287 if ($n eq 'debian') {
288 # one side has a non-tree for ./debian !
289 $differs |= D_DEB_OTH;
293 my $xd = $ix && "$x:debian";
294 my $yd = $iy && "$y:debian";
295 trees_diff_walk $xd, $yd, sub {
296 my ($n,$ix,$iy) = @_;
298 # analyse difference in debian/
300 if ($n eq 'changelog' && (!$ix || $plain->($ix))
302 $differs |= D_DEB_CLOG;
305 if ($n ne 'patches/') {
306 $differs |= D_DEB_OTH;
310 my $xp = $ix && "$xd/patches";
311 my $yp = $iy && "$yd/patches";
312 trees_diff_walk $xp, $yp, sub {
313 my ($n,$ix,$iy) = @_;
315 # analyse difference in debian/patches
318 if ($n !~ m/\.series$/s && !$ix && $plain->($iy)) {
320 } elsif ($n eq 'series' && $plain->($ix) && $plain->($iy)) {
321 my $x_s = (git_cat_file "$xp/series", 'blob');
322 my $y_s = (git_cat_file "$yp/series", 'blob');
323 chomp $x_s; $x_s .= "\n";
324 $ok = $x_s eq substr($y_s, 0, length $x_s);
328 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
333 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
338 sub commit_pr_info ($) {
340 return Data::Dumper->dump([$r], [qw(commit)]);
343 sub calculate_committer_authline () {
344 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
345 'DUMMY COMMIT (git-debrebase)', "HEAD:";
346 my ($h,$m) = get_commit $c;
347 $h =~ m/^committer .*$/m or confess "($h) ?";
351 sub rm_subdir_cached ($) {
353 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
356 sub read_tree_subdir ($$) {
357 my ($subdir, $new_tree_object) = @_;
358 rm_subdir_cached $subdir;
359 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
362 sub read_tree_debian ($) {
364 read_tree_subdir 'debian', "$treeish:debian";
365 rm_subdir_cached 'debian/patches';
368 sub read_tree_upstream ($;$$) {
369 my ($treeish, $keep_patches, $tree_with_debian) = @_;
370 # if $tree_with_debian is supplied, will use that for debian/
371 # otherwise will save and restore it.
373 $tree_with_debian ? "$tree_with_debian:debian"
374 : cmdoutput @git, qw(write-tree --prefix=debian/);
375 runcmd @git, qw(read-tree), $treeish;
376 read_tree_subdir 'debian', $debian;
377 rm_subdir_cached 'debian/patches' unless $keep_patches;
380 sub make_commit ($$) {
381 my ($parents, $message_paras) = @_;
382 my $tree = cmdoutput @git, qw(write-tree);
383 my @cmd = (@git, qw(commit-tree), $tree);
384 push @cmd, qw(-p), $_ foreach @$parents;
385 push @cmd, qw(-m), $_ foreach @$message_paras;
386 return cmdoutput @cmd;
389 our @snag_force_opts;
391 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
392 if (grep { $_ eq $tag } @snag_force_opts) {
394 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
397 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
401 # Important: all mainline code must call snags_maybe_bail after
402 # any point where snag might be called, but before making changes
403 # (eg before any call to run_deferred_updates). snags_maybe_bail
404 # may be called more than once if necessary (but this is not ideal
405 # because then the messages about number of snags may be confusing).
406 sub snags_maybe_bail () {
407 return if all_snags_summarised();
410 "%s: snags: %d overriden by individual -f options\n",
413 if ($snags_tripped) {
416 "%s: snags: %d overriden by global --force\n",
420 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
424 $snags_summarised = $snags_forced + $snags_tripped;
426 sub snags_maybe_bail_early () {
427 # useful to bail out early without doing a lot of work;
428 # not a substitute for snags_maybe_bail.
429 snags_maybe_bail() if $snags_tripped && !$opt_force;
432 return $snags_forced || $snags_tripped;
435 sub ffq_prev_branchinfo () {
436 my $current = git_get_symref();
437 return gdr_ffq_prev_branchinfo($current);
440 sub record_gdrlast ($$;$) {
441 my ($gdrlast, $newvalue, $oldvalue) = @_;
442 $oldvalue ||= $git_null_obj;
443 push @deferred_updates, "update $gdrlast $newvalue $oldvalue";
446 sub fail_unprocessable ($) {
449 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
452 Branch/history seems mangled - no longer in gdr format.
453 See ILLEGAL OPERATIONS in git-debrebase(5).
460 Is this meant to be a gdr branch? $ffqm
462 } elsif (git_get_ref $ffq_prev) {
466 Consider git-debrebase scrap, to throw away your recent work.
468 } elsif (!git_get_ref $gdrlast) {
471 Branch does not seem to be meant to be a git-debrebase branch?
472 Wrong branch, or maybe you needed git-debrebase convert-from-*.
474 } elsif (is_fast_fwd $gdrlast, git_rev_parse 'HEAD') {
482 Branch/history mangled, and diverged since last git-debrebase.
483 Maybe you reset to, or rebased from, somewhere inappropriate.
488 sub gbp_pq_export ($$$) {
489 my ($bname, $base, $tip) = @_;
490 # must be run in a workarea. $bname and patch-queue/$bname
491 # ought not to exist. Leaves you on patch-queue/$bname with
492 # the patches staged but not committed.
493 printdebug "gbp_pq_export $bname $base $tip\n";
494 runcmd @git, qw(checkout -q -b), $bname, $base;
495 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
496 my @gbp_cmd = (qw(gbp pq export));
497 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
499 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
502 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
506 # MERGE-TODO allow merge resolution separately from laundering, before git merge
509 # use git-format-patch?
510 # our own patch identification algorithm?
511 # this is an alternative strategy
513 sub merge_failed ($$;@) {
514 my ($wrecknotes, $emsg, @xmsgs) = @_;
516 push @m, "Merge resolution failed: $emsg";
522 merge_wreckage_cleaning \@updates;
523 run_ref_updates_now "merge failed", \@updates;
527 while (my ($k,$v) = each %$wrecknotes) {
528 push @updates, "create $wrecknoteprefix/$k $v";
530 run_ref_updates_now "merge failed", \@updates;
531 push @m, "Wreckage left in $wrecknoteprefix/*.";
533 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
535 # use finish rather than fail, in case we are within an eval
536 # (that can happen inside walk!)
538 print STDERR "$us: $_\n" foreach @m;
542 sub mwrecknote ($$$) {
543 my ($wrecknotes, $reftail, $commitish) = @_;
544 confess unless defined $commitish;
545 printdebug "mwrecknote $reftail $commitish\n";
546 $wrecknotes->{$reftail} = $commitish;
549 sub merge_attempt_cmd {
550 my $wrecknotes = shift @_;
554 merge_failed $wrecknotes,
555 failedcmd_waitstatus(),
556 "failed command: @_";
560 sub merge_series_patchqueue_convert ($$$);
562 sub merge_series ($$$;@) {
563 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
564 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
565 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
566 # ^ specifies several patch series (currently we only support exactly 2)
567 # return value is a commit which is the result of
568 # merging the two versions of the same topic branch
569 # $input_q[0] and $input_q[1]
570 # with respect to the old version
574 # Creates, in *_q, a key MR for its private use
576 printdebug "merge_series newbase=$newbase\n";
578 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
579 $base_q->{MR}{S} = 'base';
582 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
583 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
584 # $prereq{<patch filename>} exists or not (even later)
588 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
590 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
593 fresh_workarea "merge";
594 my $seriesfile = "debian/patches/series";
597 foreach my $q ($base_q, reverse @input_qs) {
599 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
601 if (open S, $seriesfile) {
602 while (my $patch = <S>) {
603 chomp $patch or die $!;
604 $prereq{$patch} //= {};
605 foreach my $earlier (@earlier) {
606 $prereq{$patch}{$earlier}{$s}++ and die;
608 push @earlier, $patch;
609 stat "debian/patches/$patch" or die "$patch ?";
611 S->error and die "$seriesfile $!";
614 die "$seriesfile $!" unless $!==ENOENT;
616 read_tree_upstream $newbase, 1;
617 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
618 "Convert $s to patch queue for merging",
619 "[git-debrebase merge-innards patch-queue import:".
622 printdebug "merge_series pec $pec ";
623 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
624 $pec = make_commit [ $pec ], [
625 "Drop series file from $s to avoid merge trouble",
626 "[git-debrebase merge-innards patch-queue prep:".
630 read_tree_debian $newbase;
632 read_tree_subdir 'debian/patches', "$pec:debian/patches";
634 rm_subdir_cached 'debian/patches';
636 $pec = make_commit [ $pec ], [
637 "Update debian/ (excluding patches) to final to avoid re-merging",
638 "debian/ was already merged and we need to just take that.",
639 "[git-debrebase merge-innards patch-queue packaging:".
643 printdebug "pec' $pec\n";
644 runcmd @git, qw(reset -q --hard), $pec;
645 $q->{MR}{PEC} = $pec;
646 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
648 # now, because of reverse, we are on $input_q->{MR}{OQC}
649 runcmd @git, qw(checkout -q -b merge);
650 printdebug "merge_series merging...\n";
651 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
653 $attempt_cmd->(@mergecmd);
655 printdebug "merge_series merge ok, series...\n";
656 # We need to construct a new series file
657 # Firstly, resolve prereq
658 foreach my $f (sort keys %prereq) {
659 printdebug "merge_series patch\t$f\t";
660 if (!stat_exists "debian/patches/$f") {
661 print DEBUG " drop\n" if $debuglevel;
662 # git merge deleted it; that's how we tell it's not wanted
666 print DEBUG " keep\n" if $debuglevel;
667 foreach my $g (sort keys %{ $prereq{$f} }) {
668 my $gfp = $prereq{$f}{$g};
669 printdebug "merge_series prereq\t$f\t-> $g\t";
670 if (!!$gfp->{0} == !!$gfp->{1}
673 print DEBUG "\tkeep\n" if $debuglevel;
675 print DEBUG "\tdrop\n" if $debuglevel;
676 delete $prereq{$f}{$g};
683 return scalar keys %{ $prereq{$f} };
686 my $nodate = time + 1;
688 # $authordate{<patch filename>};
689 my $authordate = sub {
691 $authordate{$f} //= do {
692 open PF, "<", "debian/patches/$f" or die "$f $!";
694 return $nodate if m/^$/;
695 last if s{^Date: }{};
698 return cmdoutput qw(date +%s -d), $_;
702 open NS, '>', $seriesfile or die $!;
704 while (keys %prereq) {
706 foreach my $try (sort keys %prereq) {
709 $unsat->($try) <=> $unsat->($best) or
710 $authordate->($try) <=> $authordate->($best) or
716 printdebug "merge_series series next $best\n";
717 print NS "$best\n" or die $!;
718 delete $prereq{$best};
719 foreach my $gp (values %prereq) {
724 runcmd @git, qw(add), $seriesfile;
725 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
726 $merged_pq = git_rev_parse 'HEAD';
727 $mwrecknote->('merged-patchqueue', $merged_pq);
729 return merge_series_patchqueue_convert
730 $wrecknotes, $newbase, $merged_pq;
733 sub merge_series_patchqueue_convert ($$$) {
734 my ($wrecknotes, $newbase, $merged_pq) = @_;
739 printdebug "merge_series series gbp pq import\n";
740 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
742 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
743 # MERGE-TODO consider git-format-patch etc. instead,
744 # since gbp pq doesn't always round-trip :-/
746 # OK now we are on patch-queue/merge, and we need to rebase
747 # onto the intended parent and drop the patches from each one
749 printdebug "merge_series series ok, building...\n";
750 my $build = $newbase;
751 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
752 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
753 my $commit = git_cat_file $c, 'commit';
754 printdebug "merge_series series ok, building $c\n";
755 read_tree_upstream $c, 0, $newbase;
756 my $tree = cmdoutput @git, qw(write-tree);
757 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
758 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
759 open C, ">", "../mcommit" or die $!;
760 print C $commit or die $!;
762 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
765 mwrecknote($wrecknotes, 'merged-result', $result);
767 runcmd @git, qw(update-ref refs/heads/result), $result;
769 runcmd @git, qw(checkout -q -b debug);
770 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
771 runcmd @git, qw(add .);
772 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
773 my $mdebug = git_rev_parse 'HEAD';
774 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
775 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
777 printdebug "merge_series returns $result\n";
781 # classify returns an info hash like this
783 # Hdr => # commit headers, including 1 final newline
784 # Msg => # commit message (so one newline is dropped)
786 # Type => (see below)
788 # Ix => $index # ie 0, 1, 2, ...
790 # Differs => return value from get_differs
792 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
794 # NewMsg => # commit message, but with any [dgit import ...] edited
795 # # to say "[was: ...]"
805 # has additional entres in classification result
806 # Overwritten = [ subset of Parents ]
807 # Contributor = $the_remaining_Parent
809 # DgitImportUnpatched
810 # has additional entry in classification result
811 # OrigParents = [ subset of Parents ]
814 # has additional entry in classification result
815 # OrigParents = [ subset of Parents ] # singleton list
822 # has additional entry in classification result
825 sub parsecommit ($;$) {
826 my ($objid, $p_ref) = @_;
827 # => hash with CommitId Hdr Msg Tree Parents
828 # Parents entries have only Ix CommitId
829 # $p_ref, if provided, must be [] and is used as a base for Parents
834 my ($h,$m) = get_commit $objid;
836 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
837 my (@ph) = $h =~ m/^parent (\w+)$/mg;
847 foreach my $ph (@ph) {
849 Ix => scalar @$p_ref,
861 my $r = parsecommit($objid, \@p);
865 $p->{Differs} = (get_differs $p->{CommitId}, $t),
868 printdebug "classify $objid \$t=$t \@p",
869 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
873 my ($type, @rest) = @_;
874 $r = { %$r, Type => $type, @rest };
876 printdebug " = $type ".(dd $r)."\n";
882 $r = { %$r, Type => qw(Unknown), Why => $why };
883 printdebug " ** Unknown\n";
887 if (grep { $_ eq $objid } @opt_anchors) {
888 return $classify->('TreatAsAnchor');
891 my @identical = grep { !$_->{Differs} } @p;
892 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
893 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
895 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
896 # multi-orig upstreams are represented with an anchor merge
897 # from a single upstream commit which combines the orig tarballs
899 # Every anchor tagged this way must be a merge.
900 # We are relying on the
901 # [git-debrebase anchor: ...]
902 # commit message annotation in "declare" anchor merges (which
903 # do not have any upstream changes), to distinguish those
904 # anchor merges from ordinary pseudomerges (which we might
905 # just try to strip).
907 # However, the user is going to be doing git-rebase a lot. We
908 # really don't want them to rewrite an anchor commit.
909 # git-rebase trips up on merges, so that is a useful safety
912 # BreakwaterStart commits are also anchors in the terminology
913 # of git-debrebase(5), but they are untagged (and always
914 # manually generated).
916 # We cannot not tolerate any tagged linear commit (ie,
917 # BreakwaterStart commits tagged `[anchor:') because such a
918 # thing could result from an erroneous linearising raw git
919 # rebase of a merge anchor. That would represent a corruption
920 # of the branch. and we want to detect and reject the results
921 # of such corruption before it makes it out anywhere. If we
922 # reject it here then we avoid making the pseudomerge which
923 # would be needed to push it.
925 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
926 @p == 2 or return $badanchor->("has other than two parents");
927 $haspatches and return $badanchor->("contains debian/patches");
929 # How to decide about l/r ordering of anchors ? git
930 # --topo-order prefers to expand 2nd parent first. There's
931 # already an easy rune to look for debian/ history anyway (git log
932 # debian/) so debian breakwater branch should be 1st parent; that
933 # way also there's also an easy rune to look for the upstream
934 # patches (--topo-order).
936 # Also this makes --first-parent be slightly more likely to
937 # be useful - it makes it provide a linearised breakwater history.
939 # Of course one can say somthing like
940 # gitk -- ':/' ':!/debian'
941 # to get _just_ the commits touching upstream files, and by
942 # the TREESAME logic in git-rev-list this will leave the
943 # breakwater into upstream at the first anchor. But that
944 # doesn't report debian/ changes at all.
946 # Other observations about gitk: by default, gitk seems to
947 # produce output in a different order to git-rev-list. I
948 # can't seem to find this documented anywhere. gitk
949 # --date-order DTRT. But, gitk always seems to put the
950 # parents from left to right, in order, so it's easy to see
951 # which way round a pseudomerge is.
953 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
954 $p[1]{Differs} & ~DS_DEB and
955 $badanchor->("upstream files differ from left parent");
956 $p[0]{Differs} & ~D_UPS and
957 $badanchor->("debian/ differs from right parent");
959 return $classify->(qw(Anchor),
960 OrigParents => [ $p[1] ]);
964 my $d = $r->{Parents}[0]{Differs};
965 if ($d == D_PAT_ADD) {
966 return $classify->(qw(AddPatches));
967 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
968 return $unknown->("edits debian/patches");
969 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
970 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
972 if ($d == D_DEB_CLOG) {
973 return $classify->(qw(Changelog));
975 return $classify->(qw(Packaging));
977 } elsif ($ty eq 'missing') {
978 return $classify->(qw(BreakwaterStart));
980 return $unknown->("parent's debian is not a directory");
982 } elsif ($d == D_UPS) {
983 return $classify->(qw(Upstream));
984 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
985 return $classify->(qw(Mixed));
987 return $unknown->("no changes");
989 confess "internal error $objid ?";
993 return $unknown->("origin commit");
996 if (@p == 2 && @identical == 1) {
997 my @overwritten = grep { $_->{Differs} } @p;
998 confess "internal error $objid ?" unless @overwritten==1;
999 return $classify->(qw(Pseudomerge),
1000 Overwritten => [ $overwritten[0] ],
1001 Contributor => $identical[0]);
1003 if (@p == 2 && @identical == 2) {
1005 my ($ph,$pm) = get_commit $_[0]{CommitId};
1006 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
1010 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
1011 if ($order > 0) { # newer first
1012 } elsif ($order < 0) {
1013 @bytime = reverse @bytime;
1015 # same age, default to order made by -s ours
1016 # that is, commit was made by someone who preferred L
1018 return $classify->(qw(Pseudomerge),
1019 SubType => qw(Ambiguous),
1020 Contributor => $bytime[0],
1021 Overwritten => [ $bytime[1] ]);
1023 foreach my $p (@p) {
1024 my ($p_h, $p_m) = get_commit $p->{CommitId};
1025 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
1026 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
1028 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
1030 if (!(grep { !$_->{IsOrigin} } @p) and
1031 (@orig_ps >= @p - 1) and
1032 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
1034 return $classify->(qw(DgitImportUnpatched),
1035 OrigParents => \@orig_ps);
1039 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
1040 return $classify->("MergedBreakwaters");
1042 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
1043 return $unknown->("unknown kind of merge from $1");
1046 return $unknown->("octopus merge");
1050 return $unknown->("general two-parent merge");
1053 return $classify->("VanillaMerge");
1056 sub keycommits ($;$$$$$);
1058 sub mergedbreakwaters_anchor ($) {
1061 foreach my $p (@{ $cl->{Parents} }) {
1062 my ($panchor, $pbw) = keycommits $p->{CommitId},
1063 undef,undef,undef,undef, 1;
1064 $best_anchor = $panchor
1065 if !defined $best_anchor
1066 or is_fast_fwd $best_anchor, $panchor;
1067 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
1068 unless is_fast_fwd $panchor, $best_anchor;
1070 return $best_anchor;
1073 sub keycommits ($;$$$$$) {
1074 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1075 # => ($anchor, $breakwater)
1077 # $unclean->("unclean-$tagsfx", $msg, $cl)
1078 # $furniture->("unclean-$tagsfx", $msg, $cl)
1079 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
1080 # is callled for each situation or commit that
1081 # wouldn't be found in a laundered branch
1082 # $furniture is for furniture commits such as might be found on an
1083 # interchange branch (pseudomerge, d/patches, changelog)
1084 # $trouble is for things whnich prevent the return of
1085 # anchor and breakwater information; if that is ignored,
1086 # then keycommits returns (undef, undef) instead.
1087 # $fatal is for unprocessable commits, and should normally cause
1088 # a failure. If ignored, agaion, (undef, undef) is returned.
1090 # If $claimed_bw, this is supposed to be a breakwater commit.
1092 # If a callback is undef, fail is called instead.
1093 # If a callback is defined but false, the situation is ignored.
1094 # Callbacks may say:
1095 # no warnings qw(exiting); last;
1096 # if the answer is no longer wanted.
1098 my ($anchor, $breakwater);
1099 $breakwater = $head if $claimed_bw;
1103 $fatal //= sub { fail_unprocessable $_[1]; };
1105 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1106 my $why = $mainwhy.$xwhy;
1107 my $m = "branch needs laundering (run git-debrebase): $why";
1108 fail $m unless defined $cb;
1110 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1112 my $found_anchor = sub {
1114 $breakwater //= $clogonly;
1115 $breakwater //= $head;
1116 no warnings qw(exiting);
1120 $cl = classify $head;
1121 my $ty = $cl->{Type};
1122 if ($ty eq 'Packaging') {
1123 $breakwater //= $clogonly;
1124 $breakwater //= $head;
1125 } elsif ($ty eq 'Changelog') {
1126 # this is going to count as the tip of the breakwater
1127 # only if it has no upstream stuff before it
1128 $clogonly //= $head;
1129 } elsif ($ty eq 'Anchor' or
1130 $ty eq 'TreatAsAnchor' or
1131 $ty eq 'BreakwaterStart') {
1132 $found_anchor->($head);
1133 } elsif ($ty eq 'Upstream') {
1134 $x->($unclean, 'ordering',
1135 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1136 if defined $breakwater;
1138 $breakwater = undef;
1139 } elsif ($ty eq 'Mixed') {
1140 $x->($unclean, 'mixed',
1141 "found mixed upstream/packaging commit"," ($head)");
1143 $breakwater = undef;
1144 } elsif ($ty eq 'Pseudomerge' or
1145 $ty eq 'AddPatches') {
1147 $x->($furniture, (lc $ty),
1148 "found interchange bureaucracy commit ($ty)"," ($head)");
1149 } elsif ($ty eq 'DgitImportUnpatched') {
1151 $x->($trouble, 'dgitimport',
1152 "found dgit dsc import"," ($head)");
1153 return (undef,undef);
1155 $x->($fatal, 'unprocessable',
1156 "found bare dgit dsc import with no prior history",
1158 return (undef,undef);
1160 } elsif ($ty eq 'VanillaMerge') {
1161 $x->($trouble, 'vanillamerge',
1162 "found vanilla merge"," ($head)");
1163 return (undef,undef);
1164 } elsif ($ty eq 'MergedBreakwaters') {
1165 $found_anchor->(mergedbreakwaters_anchor $cl);
1167 $x->($fatal, 'unprocessable',
1168 "found unprocessable commit, cannot cope: $cl->{Why}",
1170 return (undef,undef);
1172 $head = $cl->{Parents}[0]{CommitId};
1174 return ($anchor, $breakwater);
1180 $nogenerate,$report, $report_lprefix) = @_;
1181 # => ($tip, $breakwater_tip, $last_anchor)
1182 # (or nothing, if $nogenerate)
1184 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1185 $report_lprefix //= '';
1187 # go through commits backwards
1188 # we generate two lists of commits to apply:
1189 # breakwater branch and upstream patches
1190 my (@brw_cl, @upp_cl, @processed);
1197 my ($prose, $info) = @_;
1198 my $ms = $cl->{Msg};
1201 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1202 return (Msg => $ms);
1204 my $rewrite_from_here = sub {
1206 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1208 push @processed, $sp_cl;
1213 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1216 return unless $report;
1217 print $report $prdelim, $report_lprefix, @_;
1221 my $bomb = sub { # usage: return $bomb->();
1222 print $report " Unprocessable" if $report;
1223 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1226 return (undef,undef);
1228 fail_unprocessable "found unprocessable commit, cannot cope".
1229 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1230 " (commit $cur) (d.".
1231 (join ' ', map { sprintf "%#x", $_->{Differs} }
1232 @{ $cl->{Parents} }).
1239 my $build_start = sub {
1240 my ($msg, $parent) = @_;
1243 no warnings qw(exiting); last;
1248 merge_failed $cl->{MergeWreckNotes}, $emsg;
1251 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1256 $cl = classify $cur;
1257 $cl->{MergeWreckNotes} //= {};
1258 my $ty = $cl->{Type};
1259 my $st = $cl->{SubType};
1260 $prline->("$cl->{CommitId} $cl->{Type}");
1261 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1262 push @processed, $cl;
1263 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1264 if ($ty eq 'AddPatches') {
1266 $rewrite_from_here->(\@upp_cl);
1268 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1272 } elsif ($ty eq 'BreakwaterStart') {
1273 $last_anchor = $cur;
1274 $build_start->('FirstPackaging', $cur);
1275 } elsif ($ty eq 'Upstream') {
1279 } elsif ($ty eq 'Mixed') {
1282 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1285 $queue->(\@brw_cl, "debian");
1286 $queue->(\@upp_cl, "upstream");
1287 $rewrite_from_here->(\@brw_cl);
1290 } elsif ($ty eq 'Pseudomerge') {
1291 my $contrib = $cl->{Contributor}{CommitId};
1292 print $report " Contributor=$contrib" if $report;
1293 push @pseudomerges, $cl;
1294 $rewrite_from_here->(\@upp_cl);
1297 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1298 $last_anchor = $cur;
1299 $build_start->("Anchor", $cur);
1300 } elsif ($ty eq 'DgitImportUnpatched') {
1301 my $pm = $pseudomerges[-1];
1303 # To an extent, this is heuristic. Imports don't have
1304 # a useful history of the debian/ branch. We assume
1305 # that the first pseudomerge after an import has a
1306 # useful history of debian/, and ignore the histories
1307 # from later pseudomerges. Often the first pseudomerge
1308 # will be the dgit import of the upload to the actual
1309 # suite intended by the non-dgit NMUer, and later
1310 # pseudomerges may represent in-archive copies.
1311 my $ovwrs = $pm->{Overwritten};
1312 printf $report " PM=%s \@Overwr:%d",
1313 $pm->{CommitId}, (scalar @$ovwrs)
1316 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1319 my $ovwr = $ovwrs->[0]{CommitId};
1320 printf $report " Overwr=%s", $ovwr if $report;
1321 # This import has a tree which is just like a
1322 # breakwater tree, but it has the wrong history. It
1323 # ought to have the previous breakwater (which the
1324 # pseudomerge overwrote) as an ancestor. That will
1325 # make the history of the debian/ files correct. As
1326 # for the upstream version: either it's the same as
1327 # was ovewritten (ie, same as the previous
1328 # breakwater), in which case that history is precisely
1329 # right; or, otherwise, it was a non-gitish upload of a
1330 # new upstream version. We can tell these apart by
1331 # looking at the tree of the supposed upstream.
1334 SpecialMethod => 'DgitImportDebianUpdate',
1335 $xmsg->("convert dgit import: debian changes")
1338 SpecialMethod => 'DgitImportUpstreamUpdate',
1339 $xmsg->("convert dgit import: upstream update",
1342 $prline->(" Import");
1343 $rewrite_from_here->(\@brw_cl);
1344 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1348 # Everything is from this import. This kind of import
1349 # is already nearly in valid breakwater format, with the
1350 # patches as commits. Unfortunately it contains
1352 printdebug "*** WALK BOMB bare dgit import\n";
1353 $cl->{Why} = "bare dgit dsc import";
1357 } elsif ($ty eq 'MergedBreakwaters') {
1358 $last_anchor = mergedbreakwaters_anchor $cl;
1359 $build_start->(' MergedBreakwaters', $cur);
1361 } elsif ($ty eq 'VanillaMerge') {
1362 # User may have merged unstitched branch(es). We will
1363 # have now lost what ffq-prev was then (since the later
1364 # pseudomerge may introduce further changes). The effect
1365 # of resolving such a merge is that we may have to go back
1366 # further in history to find a merge base, since the one
1367 # which was reachable via ffq-prev is no longer findable.
1368 # This is suboptimal, but if it all works we'll have done
1370 # MERGE-TODO we should warn the user in the docs about this
1374 # We expect to find a dominating anchor amongst the
1375 # inputs' anchors. That will be the new anchor.
1377 # More complicated is finding a merge base for the
1378 # breakwaters. We need a merge base that is a breakwater
1379 # commit. The ancestors of breakwater commits are more
1380 # breakwater commits and possibly upstream commits and the
1381 # ancestors of those upstream. Upstreams might have
1382 # arbitrary ancestors. But any upstream commit U is
1383 # either included in both anchors, in which case the
1384 # earlier anchor is a better merge base than any of U's
1385 # ancestors; or U is not included in the older anchor, in
1386 # which case U is not an ancestor of the vanilla merge at
1387 # all. So no upstream commit, nor any ancestor thereof,
1388 # is a best merge base. As for non-breakwater Debian
1389 # commits: these are never ancestors of any breakwater.
1391 # So any best merge base as found by git-merge-base
1392 # is a suitable breakwater anchor. Usually there will
1395 printdebug "*** MERGE\n";
1397 my @bwbcmd = (@git, qw(merge-base));
1398 my @ibcmd = (@git, qw(merge-base --all));
1399 my $might_be_in_bw = 1;
1401 my $ps = $cl->{Parents};
1403 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1405 foreach my $p (@$ps) {
1406 $prline->(" VanillaMerge ".$p->{Ix});
1408 my ($ptip, $pbw, $panchor) =
1409 walk $p->{CommitId}, 0, $report,
1410 $report_lprefix.' ';
1411 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1412 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1413 $p->{Anchor} = $panchor;
1415 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1416 $mwrecknote->("$lr-input", $p->{CommitId});
1418 my $mwrecknote_parent = sub {
1420 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1422 $mwrecknote_parent->('Laundered');
1423 $mwrecknote_parent->('Breakwater');
1424 $mwrecknote_parent->('Anchor');
1426 $best_anchor = $panchor if
1427 !defined $best_anchor or
1428 is_fast_fwd $best_anchor, $panchor;
1430 printdebug " MERGE BA best=".($best_anchor//'-').
1434 $mwrecknote->('result-anchor', $best_anchor);
1436 foreach my $p (@$ps) {
1437 $prline->(" VanillaMerge ".$p->{Ix});
1438 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1439 $nomerge->('divergent anchors');
1440 } elsif ($p->{Anchor} eq $best_anchor) {
1441 print $report " SameAnchor" if $report;
1443 print $report " SupersededAnchor" if $report;
1445 if ($p->{Breakwater} eq $p->{CommitId}) {
1446 # this parent commit was its own breakwater,
1447 # ie it is part of the breakwater
1448 print $report " Breakwater" if $report;
1450 $might_be_in_bw = 0;
1452 push @bwbcmd, $p->{Breakwater};
1453 push @ibcmd, $p->{CommitId};
1456 if ($ok && $might_be_in_bw) {
1457 # We could rewrite this to contaion the metadata
1458 # declaring it to be MergedBreakwaters, but
1459 # unnecessarily rewriting a merge seems unhelpful.
1460 $prline->(" VanillaMerge MergedBreakwaters");
1461 $last_anchor = $best_anchor;
1462 $build_start->('MergedBreakwaters', $cur);
1465 my $bwb = cmdoutput @bwbcmd;
1467 # OK, now we have a breakwater base, but we need the merge
1468 # base for the interchange branch because we need the delta
1471 # This a the best merge base of our inputs which has the
1472 # breakwater merge base as an ancestor.
1479 @ibs or confess 'internal error, expected anchor at least ?';
1483 foreach my $tibix (0..$#ibs) {
1484 my $tib = $ibs[$tibix];
1485 my $ff = is_fast_fwd $bwb, $tib;
1486 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1487 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1488 $mwrecknote->($tibleaf, $tib);
1495 $ib or $nomerge->("no suitable interchange merge base");
1497 $prline->(" VanillaMerge Base");
1499 my ($btip, $bbw, $banchor) = eval {
1500 walk $ib, 0, $report, $report_lprefix.' ';
1502 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1506 $mwrecknote->("mergebase-laundered", $btip);
1507 $mwrecknote->("mergebase-breakwater", $bbw);
1508 $mwrecknote->("mergebase-anchor", $banchor);
1510 my $ibinfo = { SeriesTip => $btip,
1513 LeftRight => 'mergebase' };
1516 or $nomerge->("interchange merge-base ($ib)'s".
1517 " breakwater ($bbw)".
1518 " != breakwaters' merge-base ($bwb)");
1520 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1521 or $nomerge->("interchange merge-base ($ib)'s".
1522 " anchor ($ibinfo->{SeriesBase})".
1523 " != any merge input's anchor (".
1524 (join ' ', map { $_->{Anchor} } @$ps).
1527 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1528 $cl->{MergeBestAnchor} = $best_anchor;
1531 SpecialMethod => 'MergeCreateMergedBreakwaters',
1532 $xmsg->('constructed from vanilla merge',
1533 ' merged-breakwater'),
1537 SpecialMethod => 'MergeMergeSeries',
1539 $build_start->('MergeBreakwaters', $cur);
1541 printdebug "*** WALK BOMB unrecognised\n";
1547 printdebug "*** WALK prep done cur=$cur".
1548 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1550 return if $nogenerate;
1552 # Now we build it back up again
1558 $#upp_cl = $upp_limit if defined $upp_limit;
1560 my $committer_authline = calculate_committer_authline();
1562 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1564 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1567 mkdir $rd or $!==EEXIST or die $!;
1569 my $want_debian = $build;
1570 my $want_upstream = $build;
1572 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1573 my $read_tree_debian = sub { ($want_debian) = @_; };
1575 foreach my $cl (qw(Debian), (reverse @brw_cl),
1576 { SpecialMethod => 'RecordBreakwaterTip' },
1577 qw(Upstream), (reverse @upp_cl)) {
1579 $current_method = $cl;
1582 my $method = $cl->{SpecialMethod} // $current_method;
1583 my @parents = ($build);
1584 my $cltree = $cl->{CommitId};
1585 printdebug "WALK BUILD ".($cltree//'undef').
1586 " $method (rewriting=$rewriting)\n";
1587 if ($method eq 'Debian') {
1588 $read_tree_debian->($cltree);
1589 } elsif ($method eq 'Upstream') {
1590 $read_tree_upstream->($cltree);
1591 } elsif ($method eq 'StartRewrite') {
1594 } elsif ($method eq 'RecordBreakwaterTip') {
1595 $breakwater = $build;
1597 } elsif ($method eq 'DgitImportDebianUpdate') {
1598 $read_tree_debian->($cltree);
1599 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1600 confess unless $rewriting;
1601 my $differs = (get_differs $build, $cltree);
1602 next unless $differs & D_UPS;
1603 $read_tree_upstream->($cltree);
1604 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1605 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1606 print "Found a general merge, will try to tidy it up.\n";
1608 $read_tree_upstream->($cl->{MergeBestAnchor});
1609 $read_tree_debian->($cltree);
1610 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1611 } elsif ($method eq 'MergeMergeSeries') {
1612 my $cachehit = reflog_cache_lookup
1613 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1615 print "Using supplied resolution for $cl->{CommitId}...\n";
1617 $mwrecknote->('cached-resolution', $build);
1619 print "Running merge resolution for $cl->{CommitId}...\n";
1620 $mwrecknote->('new-base', $build);
1621 $build = merge_series
1622 $build, $cl->{MergeWreckNotes},
1623 $cl->{MergeInterchangeBaseInfo},
1624 @{ $cl->{Parents} };
1626 $last_anchor = $cl->{MergeBestAnchor};
1628 # Check for mismerges:
1630 my ($against, $allow, $what) = @_;
1631 my $differs = get_differs $build, $against;
1633 "merge misresolved: %s are not the same (%s %s d.%#x)",
1634 $what, $against, $build, $differs)
1635 if $differs & ~($allow | D_PAT_ADD);
1638 # Breakwater changes which were in each side of the
1639 # merge will have been incorporated into the
1640 # MergeCreateMergedBreakwaters output. Because the
1641 # upstream series was rebased onto the new breakwater,
1642 # so should all of the packaging changes which were in
1644 $check->($input, D_UPS, 'debian files');
1646 # Upstream files are merge_series, which ought to
1647 # have been identical to the original merge.
1648 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1650 print "Merge resolution successful.\n";
1653 confess "$method ?";
1656 my $procd = (pop @processed) // 'UNDEF';
1657 if ($cl ne $procd) {
1659 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1663 read_tree_upstream $want_upstream, 0, $want_debian;
1665 my $newtree = cmdoutput @git, qw(write-tree);
1666 my $ch = $cl->{Hdr};
1667 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1668 $ch =~ s{^parent .*\n}{}mg;
1669 $ch =~ s{(?=^author)}{
1670 join '', map { "parent $_\n" } @parents
1671 }me or confess "$ch ?";
1673 $ch =~ s{^committer .*$}{$committer_authline}m
1676 my $cf = "$rd/m$rewriting";
1677 open CD, ">", $cf or die $!;
1678 print CD $ch, "\n", $cl->{Msg} or die $!;
1680 my @cmd = (@git, qw(hash-object));
1681 push @cmd, qw(-w) if $rewriting;
1682 push @cmd, qw(-t commit), $cf;
1683 my $newcommit = cmdoutput @cmd;
1684 confess "$ch ?" unless $rewriting
1685 or $newcommit eq $cl->{CommitId};
1686 $build = $newcommit;
1688 $build = $cl->{CommitId};
1689 trees_diff_walk "$want_upstream:", "$build:", sub {
1691 no warnings qw(exiting);
1692 next if $n eq 'debian/';
1693 confess "mismatch @_ ?";
1695 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1696 confess "mismatch @_ ?";
1698 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1699 confess "mismatch @parents != @old_parents ?"
1700 unless "@parents" eq "@old_parents";
1702 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1703 $last_anchor = $cur;
1708 my $final_check = get_differs $build, $input;
1709 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1710 if $final_check & ~D_PAT_ADD;
1712 my @r = ($build, $breakwater, $last_anchor);
1713 printdebug "*** WALK RETURN @r\n";
1718 git_check_unmodified();
1719 return git_rev_parse qw(HEAD);
1722 sub update_head ($$$) {
1723 my ($old, $new, $mrest) = @_;
1724 push @deferred_updates, "update HEAD $new $old";
1725 run_deferred_updates $mrest;
1728 sub update_head_checkout ($$$) {
1729 my ($old, $new, $mrest) = @_;
1730 update_head $old, $new, $mrest;
1731 runcmd @git, qw(reset --hard);
1734 sub update_head_postlaunder ($$$) {
1735 my ($old, $tip, $reflogmsg) = @_;
1736 return if $tip eq $old && !@deferred_updates;
1737 print "git-debrebase: laundered (head was $old)\n";
1738 update_head $old, $tip, $reflogmsg;
1739 # no tree changes except debian/patches
1740 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1743 sub currently_rebasing() {
1744 foreach (qw(rebase-merge rebase-apply)) {
1745 return 1 if stat_exists "$maindir_gitdir/$_";
1750 sub bail_if_rebasing() {
1751 fail "you are in the middle of a git-rebase already"
1752 if currently_rebasing();
1755 sub do_launder_head ($) {
1756 my ($reflogmsg) = @_;
1757 my $old = get_head();
1759 my ($tip,$breakwater) = walk $old;
1761 update_head_postlaunder $old, $tip, $reflogmsg;
1762 return ($tip,$breakwater);
1765 sub cmd_launder_v0 () {
1766 badusage "no arguments to launder-v0 allowed" if @ARGV;
1767 my $old = get_head();
1768 my ($tip,$breakwater,$last_anchor) = walk $old;
1769 update_head_postlaunder $old, $tip, 'launder';
1770 printf "# breakwater tip\n%s\n", $breakwater;
1771 printf "# working tip\n%s\n", $tip;
1772 printf "# last anchor\n%s\n", $last_anchor;
1775 sub defaultcmd_rebase () {
1776 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1777 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1778 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1781 sub cmd_analyse () {
1782 badusage "analyse does not support any options"
1783 if @ARGV and $ARGV[0] =~ m/^-/;
1784 badusage "too many arguments to analyse" if @ARGV>1;
1787 $old = git_rev_parse $old;
1789 $old = git_rev_parse 'HEAD';
1791 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1792 STDOUT->error and die $!;
1795 sub ffq_check ($;$$) {
1796 # calls $ff and/or $notff zero or more times
1797 # then returns either (status,message) where status is
1802 # or (undef,undef, $ffq_prev,$gdrlast)
1803 # $ff and $notff are called like this:
1804 # $ff->("message for stdout\n");
1805 # $notff->('snag-name', $message);
1806 # normally $currentval should be HEAD
1807 my ($currentval, $ff, $notff) =@_;
1809 $ff //= sub { print $_[0] or die $!; };
1812 my ($status, $message, $current, $ffq_prev, $gdrlast)
1813 = ffq_prev_branchinfo();
1814 return ($status, $message) unless $status eq 'branch';
1816 my $exists = git_get_ref $ffq_prev;
1817 return ('exists',"$ffq_prev already exists") if $exists;
1819 return ('not-branch', 'HEAD symref is not to refs/heads/')
1820 unless $current =~ m{^refs/heads/};
1823 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1826 printdebug "ffq check_specs @check_specs\n";
1829 my ($lrref, $desc) = @_;
1830 printdebug "ffq might check $lrref ($desc)\n";
1832 for my $chk (@check_specs) {
1834 $invert = $glob =~ s{^[!^]}{};
1835 last if fnmatch $glob, $lrref;
1838 my $lrval = git_get_ref $lrref;
1839 return unless length $lrval;
1841 if (is_fast_fwd $lrval, $currentval) {
1842 $ff->("OK, you are ahead of $lrref\n");
1843 $checked{$lrref} = 1;
1844 } elsif (is_fast_fwd $currentval, $lrval) {
1845 $checked{$lrref} = -1;
1846 $notff->('behind', "you are behind $lrref, divergence risk");
1848 $checked{$lrref} = -1;
1849 $notff->('diverged', "you have diverged from $lrref");
1853 my $merge = cfg "branch.$branch.merge",1;
1854 if (defined $merge and $merge =~ m{^refs/heads/}) {
1856 printdebug "ffq merge $rhs\n";
1857 my $check_remote = sub {
1858 my ($remote, $desc) = @_;
1859 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1860 return unless defined $remote;
1861 $check->("refs/remotes/$remote/$rhs", $desc);
1863 $check_remote->((scalar cfg "branch.$branch.remote",1),
1864 'remote fetch/merge branch');
1865 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1866 (scalar cfg "branch.$branch.pushDefault",1),
1867 'remote push branch');
1869 if ($branch =~ m{^dgit/}) {
1870 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1871 } elsif ($branch =~ m{^master$}) {
1872 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1874 return (undef, undef, $ffq_prev, $gdrlast);
1877 sub record_ffq_prev_deferred () {
1878 # => ('status', "message")
1880 # deferred message is undef
1885 # if not ff from some branch we should be ff from, is an snag
1886 # if "deferred", will have added something about that to
1887 # @deferred_update_messages, and also maybe printed (already)
1888 # some messages about ff checks
1890 my $currentval = get_head();
1892 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1893 return ($status,$message) if defined $status;
1897 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1898 push @deferred_updates, "delete $gdrlast";
1899 push @deferred_update_messages, "Recorded previous head for preservation";
1900 return ('deferred', undef);
1903 sub record_ffq_auto () {
1904 my ($status, $message) = record_ffq_prev_deferred();
1905 if ($status eq 'deferred' || $status eq 'exists') {
1907 snag $status, "could not record ffq-prev: $message";
1912 sub ffq_prev_info () {
1914 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1915 my ($status, $message, $current, $ffq_prev, $gdrlast)
1916 = ffq_prev_branchinfo();
1917 if ($status ne 'branch') {
1918 snag $status, "could not check ffq-prev: $message";
1921 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1922 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1925 sub stitch ($$$$$) {
1926 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1928 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1930 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1931 my $differs = get_differs $old_head, $ffq_prev_commitish;
1932 unless ($differs & ~D_PAT_ADD) {
1933 # ffq-prev is ahead of us, and the only tree changes it has
1934 # are possibly addition of things in debian/patches/.
1935 # Just wind forwards rather than making a pointless pseudomerge.
1936 record_gdrlast $gdrlast, $ffq_prev_commitish;
1937 update_head_checkout $old_head, $ffq_prev_commitish,
1938 "stitch (fast forward)";
1943 # We make pseudomerges with L as the contributing parent.
1944 # This makes git rev-list --first-parent work properly.
1945 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1946 'Declare fast forward / record previous work',
1947 "[git-debrebase pseudomerge: $prose]",
1949 record_gdrlast $gdrlast, $new_head;
1950 update_head $old_head, $new_head, "stitch: $prose";
1953 sub do_stitch ($;$) {
1954 my ($prose, $unclean) = @_;
1956 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1957 if (!$ffq_prev_commitish) {
1958 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1961 my $dangling_head = get_head();
1963 keycommits $dangling_head, $unclean,$unclean,$unclean;
1966 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1969 sub upstream_commitish_search ($$) {
1970 my ($upstream_version, $tried) = @_;
1971 # todo: at some point maybe use git-deborig to do this
1972 foreach my $tagpfx ('', 'v', 'upstream/') {
1973 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1974 my $new_upstream = git_get_ref "refs/tags/$tag";
1976 return $new_upstream if length $new_upstream;
1980 sub resolve_upstream_version ($$) {
1981 my ($new_upstream, $upstream_version) = @_;
1983 if (!defined $new_upstream) {
1985 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1986 if (!length $new_upstream) {
1987 fail "Could not determine appropriate upstream commitish.\n".
1988 " (Tried these tags: @tried)\n".
1989 " Check version, and specify upstream commitish explicitly.";
1992 $new_upstream = git_rev_parse $new_upstream;
1994 return $new_upstream;
1997 sub cmd_new_upstream () {
1998 # automatically and unconditionally launders before rebasing
1999 # if rebase --abort is used, laundering has still been done
2003 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
2005 # parse args - low commitment
2006 my $spec_version = shift @ARGV;
2007 my $new_version = (new Dpkg::Version $spec_version, check => 1);
2008 fail "bad version number \`$spec_version'" unless defined $new_version;
2009 if ($new_version->is_native()) {
2010 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
2013 my $new_upstream = shift @ARGV;
2014 my $new_upstream_version = upstreamversion $new_version;
2016 resolve_upstream_version $new_upstream, $new_upstream_version;
2021 my ($n, @x) = @_; # may be ''
2022 my $pc = $pieces{$n} //= {
2024 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
2026 while (my $k = shift @x) { $pc->{$k} = shift @x; }
2031 my $newpiece = sub {
2032 my ($n, @x) = @_; # may be ''
2033 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
2034 push @newpieces, $pc;
2039 New => $new_upstream,
2041 while (@ARGV && $ARGV[0] !~ m{^-}) {
2042 my $n = shift @ARGV;
2044 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
2045 unless @ARGV && $ARGV[0] !~ m{^-};
2047 my $c = git_rev_parse shift @ARGV;
2048 die unless $n =~ m/^$extra_orig_namepart_re$/;
2049 $newpiece->($n, New => $c);
2052 # now we need to investigate the branch this generates the
2053 # laundered version but we don't switch to it yet
2054 my $old_head = get_head();
2055 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
2057 my $old_bw_cl = classify $old_bw;
2058 my $old_anchor_cl = classify $old_anchor;
2060 if (!$old_anchor_cl->{OrigParents}) {
2061 snag 'anchor-treated',
2062 'old anchor is recognised due to --anchor, cannot check upstream';
2064 $old_upstream = parsecommit
2065 $old_anchor_cl->{OrigParents}[0]{CommitId};
2066 $piece->('', Old => $old_upstream->{CommitId});
2069 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2070 if ($old_upstream->{Msg} =~
2071 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2073 my @oldpieces = (split / /, $1);
2074 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2075 if ($old_n_parents != @oldpieces &&
2076 $old_n_parents != @oldpieces + 1) {
2077 snag 'upstream-confusing', sprintf
2078 "previous upstream combine %s".
2079 " mentions %d pieces (each implying one parent)".
2080 " but has %d parents".
2081 " (one per piece plus maybe a previous combine)",
2082 $old_upstream->{CommitId},
2083 (scalar @oldpieces),
2085 } elsif ($oldpieces[0] ne '.') {
2086 snag 'upstream-confusing', sprintf
2087 "previous upstream combine %s".
2088 " first piece is not \`.'",
2092 foreach my $i (0..$#oldpieces) {
2093 my $n = $oldpieces[$i];
2094 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2095 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2099 snag 'upstream-confusing',
2100 "previous upstream $old_upstream->{CommitId} is from".
2101 " git-debrebase but not an \`upstream-combine' commit";
2105 foreach my $pc (values %pieces) {
2106 if (!$old_upstream) {
2107 # we have complained already
2108 } elsif (!$pc->{Old}) {
2109 snag 'upstream-new-piece',
2110 "introducing upstream piece \`$pc->{Name}'";
2111 } elsif (!$pc->{New}) {
2112 snag 'upstream-rm-piece',
2113 "dropping upstream piece \`$pc->{Name}'";
2114 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2115 snag 'upstream-not-ff',
2116 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2120 printdebug "%pieces = ", (dd \%pieces), "\n";
2121 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2129 my @upstream_merge_parents;
2132 push @upstream_merge_parents, $old_upstream->{CommitId};
2135 foreach my $pc (@newpieces) { # always has '' first
2137 read_tree_subdir $pc->{Name}, $pc->{New};
2139 runcmd @git, qw(read-tree), $pc->{New};
2141 push @upstream_merge_parents, $pc->{New};
2144 # index now contains the new upstream
2146 if (@newpieces > 1) {
2147 # need to make the upstream subtree merge commit
2148 $new_upstream = make_commit \@upstream_merge_parents,
2149 [ "Combine upstreams for $new_upstream_version",
2150 ("[git-debrebase upstream-combine . ".
2151 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2156 # $new_upstream is either the single upstream commit, or the
2157 # combined commit we just made. Either way it will be the
2158 # "upstream" parent of the anchor merge.
2160 read_tree_subdir 'debian', "$old_bw:debian";
2162 # index now contains the anchor merge contents
2163 $new_bw = make_commit [ $old_bw, $new_upstream ],
2164 [ "Update to upstream $new_upstream_version",
2165 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2168 my $clogsignoff = cmdoutput qw(git show),
2169 '--pretty=format:%an <%ae> %aD',
2172 # Now we have to add a changelog stanza so the Debian version
2174 die if unlink "debian";
2175 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2176 unlink "debian/changelog" or $!==ENOENT or die $!;
2177 mkdir "debian" or die $!;
2178 open CN, ">", "debian/changelog" or die $!;
2179 my $oldclog = git_cat_file ":debian/changelog";
2180 $oldclog =~ m/^($package_re) \(\S+\) / or
2181 fail "cannot parse old changelog to get package name";
2183 print CN <<END, $oldclog or die $!;
2184 $p ($new_version) UNRELEASED; urgency=medium
2186 * Update to new upstream version $new_upstream_version.
2192 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2194 # Now we have the final new breakwater branch in the index
2195 $new_bw = make_commit [ $new_bw ],
2196 [ "Update changelog for new upstream $new_upstream_version",
2197 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2201 # we have constructed the new breakwater. we now need to commit to
2202 # the laundering output, because git-rebase can't easily be made
2203 # to make a replay list which is based on some other branch
2205 update_head_postlaunder $old_head, $old_laundered_tip,
2206 'launder for new upstream';
2208 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2209 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2210 "debrebase new-upstream $new_version: rebase";
2212 # now it's for the user to sort out
2215 sub cmd_record_ffq_prev () {
2216 badusage "no arguments allowed" if @ARGV;
2217 my ($status, $msg) = record_ffq_prev_deferred();
2218 if ($status eq 'exists' && $opt_noop_ok) {
2219 print "Previous head already recorded\n" or die $!;
2220 } elsif ($status eq 'deferred') {
2221 run_deferred_updates 'record-ffq-prev';
2223 fail "Could not preserve: $msg";
2228 badusage "no arguments allowed" if @ARGV;
2229 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2230 print "$bw\n" or die $!;
2233 sub cmd_breakwater () {
2234 badusage "no arguments allowed" if @ARGV;
2235 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2236 print "$bw\n" or die $!;
2240 badusage "no arguments allowed" if @ARGV;
2242 # todo: gdr status should print divergence info
2243 # todo: gdr status should print upstream component(s) info
2244 # todo: gdr should leave/maintain some refs with this kind of info ?
2246 my $oldest = { Badness => 0 };
2249 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2250 if ($oldest->{Badness} < $badness) {
2251 $oldest = $newest = undef;
2254 Badness => $badness,
2255 CommitId => $cl->{CommitId},
2259 $newest //= $oldest;
2261 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2262 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2263 sub { $note->(2, 'branch is unlaundered', @_); },
2264 sub { $note->(3, 'branch needs laundering', @_); },
2265 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2267 my $prcommitinfo = sub {
2269 flush STDOUT or die $!;
2270 runcmd @git, qw(--no-pager log -n1),
2271 '--pretty=format: %h %s%n',
2275 print "current branch contents, in git-debrebase terms:\n";
2276 if (!$oldest->{Badness}) {
2277 print " branch is laundered\n";
2279 print " $oldest->{OurMsg}\n";
2281 foreach my $info ($oldest, $newest) {
2282 my $cid = $info->{CommitId};
2283 next if $cid eq $printed;
2285 print " $info->{KcMsg}\n";
2286 $prcommitinfo->($cid);
2291 my ($cid, $what) = @_;
2292 if (!defined $cid) {
2293 print " $what is not well-defined\n";
2296 $prcommitinfo->($cid);
2299 print "key git-debrebase commits:\n";
2300 $prab->($anchor, 'anchor');
2301 $prab->($bw, 'breakwater');
2303 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2304 ffq_prev_branchinfo();
2306 print "branch and ref status, in git-debrebase terms:\n";
2308 print " $ffq_msg\n";
2310 $ffq_prev = git_get_ref $ffq_prev;
2311 $gdrlast = git_get_ref $gdrlast;
2313 print " unstitched; previous tip was:\n";
2314 $prcommitinfo->($ffq_prev);
2315 } elsif (!$gdrlast) {
2316 print " stitched? (no record of git-debrebase work)\n";
2317 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2318 print " stitched\n";
2320 print " not git-debrebase (diverged since last stitch)\n"
2323 print "you are currently rebasing\n" if currently_rebasing();
2327 my $prose = 'stitch';
2328 getoptions("stitch",
2329 'prose=s', \$prose);
2330 badusage "no arguments allowed" if @ARGV;
2331 do_stitch $prose, 0;
2333 sub cmd_prepush () {
2339 badusage "no arguments allowed" if @ARGV;
2340 do_launder_head 'launder for git-debrebase quick';
2344 sub cmd_conclude () {
2345 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2346 if (!$ffq_prev_commitish) {
2347 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2350 my $dangling_head = get_head();
2352 badusage "no arguments allowed" if @ARGV;
2353 do_launder_head 'launder for git-debrebase quick';
2358 if (currently_rebasing()) {
2359 runcmd @git, qw(rebase --abort);
2360 push @deferred_updates, 'verify HEAD HEAD';
2361 # noop, but stops us complaining that scrap was a noop
2363 badusage "no arguments allowed" if @ARGV;
2364 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2366 if ($ffq_prev_commitish) {
2367 $scrapping_head = get_head();
2368 push @deferred_updates,
2369 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2370 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2372 if (git_get_ref $merge_cache_ref) {
2373 push @deferred_updates,
2374 "delete $merge_cache_ref";
2376 if (!@deferred_updates) {
2377 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2381 if ($scrapping_head) {
2382 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2384 run_deferred_updates "scrap";
2388 sub make_patches_staged ($) {
2390 # Produces the patches that would result from $head if it were
2392 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2395 gbp_pq_export 'bw', $secret_bw, $secret_head;
2399 sub make_patches ($) {
2401 keycommits $head, 0, \&snag;
2402 make_patches_staged $head;
2405 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2406 runcmd @git, qw(read-tree), $head;
2407 read_tree_subdir 'debian/patches', $ptree;
2408 $out = make_commit [$head], [
2409 'Commit patch queue (exported by git-debrebase)',
2410 '[git-debrebase: export and commit patches]',
2416 sub cmd_make_patches () {
2417 my $opt_quiet_would_amend;
2418 getoptions("make-patches",
2419 'quiet-would-amend!', \$opt_quiet_would_amend);
2420 badusage "no arguments allowed" if @ARGV;
2422 my $old_head = get_head();
2423 my $new = make_patches $old_head;
2424 my $d = get_differs $old_head, $new;
2426 fail "No (more) patches to export." unless $opt_noop_ok;
2428 } elsif ($d == D_PAT_ADD) {
2430 update_head_checkout $old_head, $new, 'make-patches';
2432 print STDERR failmsg
2433 "Patch export produced patch amendments".
2434 " (abandoned output commit $new).".
2435 " Try laundering first."
2436 unless $opt_quiet_would_amend;
2441 sub check_series_has_all_patches ($) {
2443 my $seriesfn = 'debian/patches/series';
2444 my ($dummy, $series) = git_cat_file "$head:$seriesfn",
2448 foreach my $f (grep /\S/, grep {!m/^\s\#/} split /\n/, $series) {
2449 fail "patch $f repeated in $seriesfn !" if $series{$f}++;
2451 foreach my $patchfile (get_tree "$head:debian/patches", 1,1) {
2452 my ($f,$i) = @$patchfile;
2453 next if $series{$f};
2454 next if $f eq 'series';
2455 snag 'unused-patches', "Unused patch file $f will be discarded";
2459 sub begin_convert_from () {
2460 my $head = get_head();
2461 my ($ffqs, $ffqm, $symref, $ffq_prev, $gdrlast) = ffq_prev_branchinfo();
2463 fail "ffq-prev exists, this is already managed by git-debrebase!"
2464 if $ffq_prev && git_get_ref $ffq_prev;
2466 my $gdrlast_obj = $gdrlast && git_get_ref $gdrlast;
2467 snag 'already-converted',
2468 "ahead of debrebase-last, this is already managed by git-debrebase!"
2469 if $gdrlast_obj && is_fast_fwd $gdrlast_obj, $head;
2470 return ($head, { LastRef => $gdrlast, LastObj => $gdrlast_obj });
2473 sub complete_convert_from ($$$$) {
2474 my ($old_head, $new_head, $gi, $mrest) = @_;
2475 ffq_check $new_head;
2476 record_gdrlast $gi->{LastRef}, $new_head, $gi->{LastObj}
2479 update_head_checkout $old_head, $new_head, $mrest;
2482 sub cmd_convert_from_gbp () {
2483 badusage "want only 1 optional argument, the upstream git commitish"
2486 my $clogp = parsechangelog();
2487 my $version = $clogp->{'Version'}
2488 // die "missing Version from changelog";
2490 my ($upstream_spec) = @ARGV;
2492 my $upstream_version = upstreamversion $version;
2494 resolve_upstream_version($upstream_spec, $upstream_version);
2496 my ($old_head, $gdrlastinfo) = begin_convert_from();
2498 my $upsdiff = get_differs $upstream, $old_head;
2499 if ($upsdiff & D_UPS) {
2500 runcmd @git, qw(--no-pager diff --stat),
2501 $upstream, $old_head,
2502 qw( -- :!/debian :/);
2504 upstream ($upstream_spec) and HEAD are not
2505 identical in upstream files. See diffstat above, or run
2506 git diff $upstream_spec HEAD -- :!/debian :/
2510 if (!is_fast_fwd $upstream, $old_head) {
2511 snag 'upstream-not-ancestor',
2512 "upstream ($upstream) is not an ancestor of HEAD";
2514 my $wrong = cmdoutput
2515 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2516 qw(-- :/ :!/debian));
2517 if (length $wrong) {
2518 snag 'unexpected-upstream-changes',
2519 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2520 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2524 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2525 snag 'upstream-has-debian',
2526 "upstream ($upstream) contains debian/ directory";
2529 check_series_has_all_patches $old_head;
2531 my $previous_dgit_view = eval {
2532 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2534 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2535 my ($stz, $desc) = @_;
2536 no warnings qw(exiting);
2537 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2538 next unless $stz->{Date};
2539 next unless $stz->{Distribution} ne 'UNRELEASED';
2540 $lvsn = $stz->{Version};
2541 $suite = $stz->{Distribution};
2544 die "neither of the first two changelog entries are released\n"
2545 unless defined $lvsn;
2546 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2547 my $mtag_pat = debiantag_maintview $lvsn, '*';
2548 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2550 die "could not find suitable maintainer view tag $mtag_pat\n"
2551 unless $mtag =~ m{/};
2552 is_fast_fwd $mtag, 'HEAD' or
2553 die "HEAD is not FF from maintainer tag $mtag!";
2554 my $dtag = "archive/$mtag";
2555 git_get_ref "refs/tags/$dtag" or
2556 die "dgit view tag $dtag not found\n";
2557 is_fast_fwd $mtag, $dtag or
2558 die "dgit view tag $dtag is not FF from maintainer tag $mtag\n";
2559 print "will stitch in dgit view, $dtag\n";
2560 git_rev_parse $dtag;
2562 if (!$previous_dgit_view) {
2566 Cannot confirm dgit view: $@
2567 Failed to stitch in dgit view (see messages above).
2568 dgit --overwrite will be needed on the first dgit push after conversion.
2572 snags_maybe_bail_early();
2578 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2579 # make a branch out of the patch queue - we'll want this in a mo
2580 runcmd qw(gbp pq import);
2581 # strip the patches out
2582 runcmd @git, qw(checkout -q gdr-internal~0);
2583 rm_subdir_cached 'debian/patches';
2584 $work = make_commit ['HEAD'], [
2585 'git-debrebase convert-from-gbp: drop patches from tree',
2586 'Delete debian/patches, as part of converting to git-debrebase format.',
2587 '[git-debrebase convert-from-gbp: drop patches from tree]'
2589 # make the anchor merge
2590 # the tree is already exactly right
2591 $work = make_commit [$work, $upstream], [
2592 'git-debrebase import: declare upstream',
2593 'First breakwater merge.',
2594 '[git-debrebase anchor: declare upstream]'
2597 # rebase the patch queue onto the new breakwater
2598 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2599 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2600 $work = git_rev_parse 'HEAD';
2602 if ($previous_dgit_view) {
2603 $work = make_commit [$work, $previous_dgit_view], [
2604 'git-debrebase import: declare ff from dgit archive view',
2605 '[git-debrebase pseudomerge: import-from-gbp]',
2610 complete_convert_from $old_head, $work, $gdrlastinfo, 'convert-from-gbp';
2611 print <<END or die $!;
2612 git-debrebase: converted from patched-unapplied (gbp) branch format, OK
2616 sub cmd_convert_to_gbp () {
2617 badusage "no arguments allowed" if @ARGV;
2618 my $head = get_head();
2619 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2620 keycommits $head, 0;
2622 make_patches_staged $head;
2624 $out = make_commit ['HEAD'], [
2625 'Commit patch queue (converted from git-debrebase format)',
2626 '[git-debrebase convert-to-gbp: commit patches]',
2630 push @deferred_updates, "delete $ffq";
2631 push @deferred_updates, "delete $gdrlast";
2634 update_head_checkout $head, $out, "convert to gbp (v0)";
2635 print <<END or die $!;
2636 git-debrebase: converted to git-buildpackage branch format
2637 git-debrebase: WARNING: do not now run "git-debrebase" any more
2638 git-debrebase: WARNING: doing so would drop all upstream patches!
2642 sub cmd_convert_from_dgit_view () {
2643 my $clogp = parsechangelog();
2645 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2651 getoptions("convert-from-dgit-view",
2652 'diagnose!', \$diagnose,
2653 'build-products-dir:s', \$bpd,
2654 'origs!', \$do_origs,
2656 'always-convert-anyway!', \$always);
2657 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2662 my $spec = shift @ARGV;
2663 my $commit = git_rev_parse "$spec^{commit}";
2664 push @upstreams, { Commit => $commit,
2665 Source => "$ARGV[0], from command line",
2670 my ($head, $gdrlastinfo) = begin_convert_from();
2674 my $trouble = sub { $troubles++; };
2675 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2676 printdebug "troubles=$troubles\n";
2679 $us: Branch already seems to be in git-debrebase format!
2680 $us: --always-convert-anyway would do the conversion operation anyway
2681 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2683 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2688 check_series_has_all_patches $head;
2690 snags_maybe_bail_early();
2692 my $version = upstreamversion $clogp->{Version};
2693 print STDERR "Considering possible commits corresponding to upstream:\n";
2698 my $ups_tag = upstream_commitish_search $version, \@tried;
2700 my $this = "git tag $tried[-1]";
2701 push @upstreams, { Commit => $ups_tag,
2706 " git tag: no suitable tag found (tried %s)\n",
2711 my $p = $clogp->{'Source'};
2712 # we do a quick check to see if there are plausible origs
2714 if (!opendir BPD, $bpd) {
2715 die "$bpd: opendir: $!" unless $!==ENOENT;
2717 while ($!=0, my $f = readdir BPD) {
2718 next unless is_orig_file_of_p_v $f, $p, $version;
2720 " orig: found what looks like a .orig, %s\n",
2725 die "read $bpd: $!" if $!;
2729 my $tree = cmdoutput
2730 @dgit, qw(--build-products-dir), $bpd,
2731 qw(print-unapplied-treeish);
2734 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2735 rm_subdir_cached 'debian';
2736 $tree = cmdoutput @git, qw(write-tree);
2737 my $ups_synth = make_commit [], [ <<END, <<END,
2738 Import effective orig tree for upstream version $version
2740 This includes the contents of the .orig(s), minus any debian/ directory.
2742 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2745 push @upstreams, { Commit => $ups_synth,
2746 Source => "orig(s) imported via dgit",
2751 " orig: no suitable origs found (looked for %s in %s)\n",
2752 "${p}_".(stripeoch $version)."...", $bpd;
2757 my $some_patches = stat_exists 'debian/patches/series';
2759 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2762 foreach my $u (@upstreams) {
2766 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2767 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2768 runcmd @git, qw(clean -xdff);
2769 runcmd @git, qw(checkout), $head, qw(-- debian);
2770 if ($some_patches) {
2771 rm_subdir_cached 'debian/patches';
2772 $work = make_commit [ $work ], [
2773 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2774 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2775 "to git-debrebase format. Upstream changes will appear as commits.",
2776 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2779 $work = make_commit [ $work, $u->{Commit} ], [
2780 'git-debrebase convert-from-dgit-view: declare upstream',
2781 '(Re)constructed breakwater merge.',
2782 '[git-debrebase anchor: declare upstream]'
2784 runcmd @git, qw(checkout --quiet -b mk), $work;
2785 if ($some_patches) {
2786 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2787 runcmd @git, qw(reset --quiet);
2788 my @gbp_cmd = (qw(gbp pq import));
2790 my $gbp_err = "../gbp-pq-err";
2791 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2793 my $r = system @gbp_cmd;
2796 " %s: couldn't apply patches: gbp pq %s",
2797 $u->{Source}, waitstatusmsg();
2801 my $work = git_rev_parse qw(HEAD);
2802 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2803 if (length $diffout) {
2805 " $u->{Source}: applying patches gives different tree\n";
2806 print STDERR $diffout if $diagnose;
2810 $u->{Result} = $work;
2818 Could not find or construct a suitable upstream commit.
2819 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2820 upstream commmit explicitly or provide suitable origs.
2824 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2826 complete_convert_from $head, $result->{Result}, $gdrlastinfo,
2827 'convert-from-dgit-view';
2830 sub cmd_record_resolved_merge () {
2831 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2832 # MERGE-TODO needs documentation
2833 my $new = get_head();
2836 print "Checking how you have resolved the merge problem\n";
2837 my $nope = sub { print "Not $method: @_"; 0; };
2839 my $maybe = sub { print "Seems to be $method.\n"; };
2841 my ($key, $ref) = @_;
2842 reflog_cache_insert $merge_cache_ref, $key, $ref;
2843 print "OK. You can switch branches and try git-debrebase again.\n";
2847 fresh_workarea 'merge';
2849 $method = 'vanilla-merge patchqueue';
2850 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2851 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2852 foreach my $lr (qw(left right)) {
2853 my $n = "$wrecknoteprefix/$lr-patchqueue";
2854 my $lrpq = git_get_ref $n;
2855 $lrpq or return $nope->("wreckage did not contain patchqueues");
2856 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2859 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2860 or die "wreckage element $wrecknoteprefix/new-base missing";
2861 my $result = merge_series_patchqueue_convert
2863 $yes->("vanilla-merge $vanilla", $result);
2866 fail "No resolved merge method seems applicable.\n";
2870 sub cmd_downstream_rebase_launder_v0 () {
2871 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2873 $base = git_rev_parse $base;
2874 my $old_head = get_head();
2875 my $current = $old_head;
2878 if ($current eq $base) {
2879 $topmost_keep //= $current;
2880 print " $current BASE stop\n";
2883 my $cl = classify $current;
2884 print " $current $cl->{Type}";
2886 my $p0 = $cl->{Parents}[0]{CommitId};
2888 if ($cl->{Type} eq 'Pseudomerge') {
2889 print " ^".($cl->{Contributor}{Ix}+1);
2890 $next = $cl->{Contributor}{CommitId};
2891 } elsif ($cl->{Type} eq 'AddPatches' or
2892 $cl->{Type} eq 'Changelog') {
2902 $topmost_keep //= $current;
2904 die "to-be stripped changes not on top of the branch\n"
2909 if ($topmost_keep eq $old_head) {
2910 print "unchanged\n";
2912 print "updating to $topmost_keep\n";
2913 update_head_checkout
2914 $old_head, $topmost_keep,
2915 'downstream-rebase-launder-v0';
2921 "D+" => \$debuglevel,
2922 'noop-ok', => \$opt_noop_ok,
2923 'f=s' => \@snag_force_opts,
2924 'anchor=s' => \@opt_anchors,
2925 '--dgit=s' => \($dgit[0]),
2927 'experimental-merge-resolution!', \$opt_merges,
2929 my ($opt,$val) = @_;
2930 badusage "git-debrebase: no cuddling to -i for git-rebase"
2932 die if $opt_defaultcmd_interactive; # should not happen
2933 $opt_defaultcmd_interactive = [ qw(-i) ];
2934 # This access to @ARGV is excessive familiarity with
2935 # Getopt::Long, but there isn't another sensible
2936 # approach. '-i=s{0,}' does not work with bundling.
2937 push @$opt_defaultcmd_interactive, @ARGV;
2940 'help' => sub { print $usage_message or die $!; finish 0; },
2943 initdebug('git-debrebase ');
2944 enabledebug if $debuglevel;
2946 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2947 chdir $toplevel or die "chdir $toplevel: $!";
2949 $rd = fresh_playground "$playprefix/misc";
2951 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2953 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2954 defaultcmd_rebase();
2956 my $cmd = shift @ARGV;
2959 $cmdfn = ${*::}{"cmd_$cmdfn"};
2961 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";