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_careful, $opt_noop_ok, @opt_anchors);
54 our ($opt_defaultcmd_interactive);
58 our $us = qw(git-debrebase);
60 our $wrecknoteprefix = 'refs/debrebase/wreckage';
61 our $merge_cache_ref = 'refs/debrebase/merge-resolutions';
67 print STDERR "$us: bad usage: $m\n";
73 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
74 GetOptions @_ or badusage $m;
78 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
82 my ($k, $optional) = @_;
84 my @cmd = qw(git config -z);
85 push @cmd, qw(--get-all) if wantarray;
87 my $out = cmdoutput_errok @cmd;
89 fail "missing required git config $k" unless $optional;
92 my @l = split /\0/, $out;
93 return wantarray ? @l : $l[0];
100 my $dd = new Data::Dumper [ $v ];
101 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
107 my $data = (git_cat_file $objid, 'commit');
108 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
112 sub D_UPS () { 0x02; } # upstream files
113 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
114 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
115 sub D_DEB_CLOG () { 0x10; } # debian/changelog
116 sub D_DEB_OTH () { 0x20; } # debian/ (not patches/ or changelog)
117 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
119 our $playprefix = 'debrebase';
124 our @dgit = qw(dgit);
126 sub in_workarea ($) {
129 my $r = eval { $sub->(); };
130 { local $@; changedir $maindir; }
134 sub fresh_workarea (;$) {
137 $workarea = fresh_playground "$playprefix/$subdir";
138 in_workarea sub { playtree_setup };
141 sub run_ref_updates_now ($$) {
142 my ($mrest, $updates) = @_;
143 # @$updates is a list of lines for git-update-ref, without \ns
145 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
146 debugcmd '>|', @upd_cmd;
147 open U, "|-", @upd_cmd or die $!;
148 foreach (@$updates) {
149 printdebug ">= ", $_, "\n";
150 print U $_, "\n" or die $!;
153 close U or failedcmd @upd_cmd;
156 our $snags_forced = 0;
157 our $snags_tripped = 0;
158 our $snags_summarised = 0;
159 our @deferred_updates;
160 our @deferred_update_messages;
162 sub merge_wreckage_cleaning ($) {
164 git_for_each_ref("$wrecknoteprefix/*", sub {
165 my ($objid,$objtype,$fullrefname,$reftail) = @_;
166 push @$updates, "delete $fullrefname";
170 sub all_snags_summarised () {
171 $snags_forced + $snags_tripped == $snags_summarised;
173 sub run_deferred_updates ($) {
176 confess 'dangerous internal error' unless all_snags_summarised();
178 merge_wreckage_cleaning \@deferred_updates;
179 run_ref_updates_now $mrest, \@deferred_updates;
180 print $_, "\n" foreach @deferred_update_messages;
182 @deferred_updates = ();
183 @deferred_update_messages = ();
187 # tree object name => ([ $name, $info ], ...)
188 # where $name is the sort key, ie has / at end for subtrees
189 # $info is the LHS from git-ls-tree (<mode> <type> <hash>)
190 # will crash if $x does not exist, so don't do that;
191 # instead pass '' to get ().
194 return () if !length $x;
196 our (@get_tree_memo, %get_tree_memo);
197 my $memo = $get_tree_memo{$x};
198 return @$memo if $memo;
200 local $Debian::Dgit::debugcmd_when_debuglevel = 3;
202 my @cmd = (qw(git ls-tree -z --full-tree --), $x);
203 my $o = cmdoutput @cmd;
206 foreach my $l (split /\0/, $o) {
207 my ($i, $n) = split /\t/, $l, 2;
208 $n .= '/' if $i =~ m/^\d+ tree /;
210 confess "$x need $last < $n ?" unless $last lt $n;
212 $get_tree_memo{$x} = \@l;
213 push @get_tree_memo, $x;
214 if (@get_tree_memo > 10) {
215 delete $get_tree_memo{ shift @get_tree_memo };
220 sub trees_diff_walk ($$$;$) {
221 # trees_diff_walk [$all,] $x, $y, sub {... }
222 # calls sub->($name, $ix, $iy) for each difference (with $all, each name)
223 # $x and $y are as for get_tree
224 # where $name, $ix, $iy are $name and $info from get_tree
225 my $all = shift @_ if @_>=4;
226 my ($x,$y,$call) = @_;
227 return if !$all and $x eq $y;
230 printdebug "trees_diff_walk(..$x,$y..) ".Dumper(\@x,\@y)
233 my $cmp = !@x <=> !@y # eg @y empty? $cmp=-1, use x
234 || $x[0][0] cmp $y[0][0]; # eg, x lt y ? $cmp=-1, use x
235 my ($n, $ix, $iy); # all same? $cmp=0, use both
237 printdebug "trees_diff_walk $cmp : @{ $x[0]//[] } | @{ $y[0]//[] }\n"
239 ($n, $ix) = @{ shift @x } if $cmp <= 0;
240 ($n, $iy) = @{ shift @y } if $cmp >= 0;
241 next if !$all and $ix eq $iy;
243 "trees_diff_walk(%d,'%s','%s') call('%s','%s','%s')\n",
244 !!$all,$x,$y, $n,$ix,$iy
246 $call->($n, $ix, $iy);
250 sub get_differs ($$) {
252 # This resembles quiltify_trees_differ, in dgit, a bit.
253 # But we don't care about modes, or dpkg-source-unrepresentable
254 # changes, and we don't need the plethora of different modes.
255 # Conversely we need to distinguish different kinds of changes to
256 # debian/ and debian/patches/.
261 my ($opts, $limits, $fn) = @_;
262 my @cmd = (@git, qw(diff-tree -z --no-renames));
264 push @cmd, "$_:" foreach $x, $y;
265 push @cmd, '--', @$limits;
266 my $diffs = cmdoutput @cmd;
267 foreach (split /\0/, $diffs) { $fn->(); }
270 $rundiff->([qw(--name-only)], [], sub {
271 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
274 if ($differs & DS_DEB) {
276 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
278 m{^debian/patches/} ? D_PAT_OTH :
279 $_ eq 'debian/changelog' ? D_DEB_CLOG :
282 die "mysterious debian changes $x..$y"
283 unless $differs & (D_PAT_OTH|DS_DEB);
286 if ($differs & D_PAT_OTH) {
288 $differs &= ~D_PAT_OTH;
290 $differs |= D_PAT_OTH;
291 no warnings qw(exiting); last;
293 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
294 no warnings qw(exiting);
295 if (!defined $mode) {
298 die unless s{^debian/patches/}{};
300 if ($mode eq 'A' && !m/\.series$/s) {
302 } elsif ($mode eq 'M' && $_ eq 'series') {
303 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
304 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
305 chomp $x_s; $x_s .= "\n";
306 $ok = $x_s eq substr($y_s, 0, length $x_s);
311 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
313 die "mysterious debian/patches changes $x..$y"
314 unless $differs & (D_PAT_ADD|D_PAT_OTH);
317 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
322 sub commit_pr_info ($) {
324 return Data::Dumper->dump([$r], [qw(commit)]);
327 sub calculate_committer_authline () {
328 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
329 'DUMMY COMMIT (git-debrebase)', "HEAD:";
330 my ($h,$m) = get_commit $c;
331 $h =~ m/^committer .*$/m or confess "($h) ?";
335 sub rm_subdir_cached ($) {
337 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
340 sub read_tree_subdir ($$) {
341 my ($subdir, $new_tree_object) = @_;
342 rm_subdir_cached $subdir;
343 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
346 sub read_tree_debian ($) {
348 read_tree_subdir 'debian', "$treeish:debian";
349 rm_subdir_cached 'debian/patches';
352 sub read_tree_upstream ($;$$) {
353 my ($treeish, $keep_patches, $tree_with_debian) = @_;
354 # if $tree_with_debian is supplied, will use that for debian/
355 # otherwise will save and restore it.
357 $tree_with_debian ? "$tree_with_debian:debian"
358 : cmdoutput @git, qw(write-tree --prefix=debian/);
359 runcmd @git, qw(read-tree), $treeish;
360 read_tree_subdir 'debian', $debian;
361 rm_subdir_cached 'debian/patches' unless $keep_patches;
364 sub make_commit ($$) {
365 my ($parents, $message_paras) = @_;
366 my $tree = cmdoutput @git, qw(write-tree);
367 my @cmd = (@git, qw(commit-tree), $tree);
368 push @cmd, qw(-p), $_ foreach @$parents;
369 push @cmd, qw(-m), $_ foreach @$message_paras;
370 return cmdoutput @cmd;
373 our @snag_force_opts;
375 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
376 if (grep { $_ eq $tag } @snag_force_opts) {
378 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
381 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
385 # Important: all mainline code must call snags_maybe_bail after
386 # any point where snag might be called, but before making changes
387 # (eg before any call to run_deferred_updates). snags_maybe_bail
388 # may be called more than once if necessary (but this is not ideal
389 # because then the messages about number of snags may be confusing).
390 sub snags_maybe_bail () {
391 return if all_snags_summarised();
394 "%s: snags: %d overriden by individual -f options\n",
397 if ($snags_tripped) {
400 "%s: snags: %d overriden by global --force\n",
404 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
408 $snags_summarised = $snags_forced + $snags_tripped;
410 sub snags_maybe_bail_early () {
411 # useful to bail out early without doing a lot of work;
412 # not a substitute for snags_maybe_bail.
413 snags_maybe_bail() if $snags_tripped && !$opt_force;
416 return $snags_forced || $snags_tripped;
419 sub gbp_pq_export ($$$) {
420 my ($bname, $base, $tip) = @_;
421 # must be run in a workarea. $bname and patch-queue/$bname
422 # ought not to exist. Leaves you on patch-queue/$bname with
423 # the patches staged but not committed.
424 printdebug "gbp_pq_export $bname $base $tip\n";
425 runcmd @git, qw(checkout -q -b), $bname, $base;
426 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
427 my @gbp_cmd = (qw(gbp pq export));
428 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
430 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
433 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
437 # xxx allow merge resolution separately from laundering, before git merge
439 # xxx general gdr docs highlight forbidden things
440 # xxx general gdr docs list allowable things ?
441 # xxx general gdr docs explicitly forbid some rebase
444 # use git-format-patch?
445 # our own patch identification algorithm?
446 # this is an alternative strategy
448 sub merge_failed ($$;@) {
449 my ($wrecknotes, $emsg, @xmsgs) = @_;
451 push @m, "Merge resolution failed: $emsg";
457 merge_wreckage_cleaning \@updates;
458 run_ref_updates_now "merge failed", \@updates;
462 while (my ($k,$v) = each %$wrecknotes) {
463 push @updates, "create $wrecknoteprefix/$k $v";
465 run_ref_updates_now "merge failed", \@updates;
466 push @m, "Wreckage left in $wrecknoteprefix/*.";
468 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
470 # use finish rather than fail, in case we are within an eval
471 # (that can happen inside walk!)
473 print STDERR "$us: $_\n" foreach @m;
477 sub mwrecknote ($$$) {
478 my ($wrecknotes, $reftail, $commitish) = @_;
479 confess unless defined $commitish;
480 printdebug "mwrecknote $reftail $commitish\n";
481 $wrecknotes->{$reftail} = $commitish;
484 sub merge_attempt_cmd {
485 my $wrecknotes = shift @_;
489 merge_failed $wrecknotes,
490 failedcmd_waitstatus(),
491 "failed command: @_";
495 sub merge_series_patchqueue_convert ($$$);
497 sub merge_series ($$$;@) {
498 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
499 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
500 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
501 # ^ specifies several patch series (currently we only support exactly 2)
502 # return value is a commit which is the result of
503 # merging the two versions of the same topic branch
504 # $input_q[0] and $input_q[1]
505 # with respect to the old version
509 # Creates, in *_q, a key MR for its private use
511 printdebug "merge_series newbase=$newbase\n";
513 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
514 $base_q->{MR}{S} = 'base';
517 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
518 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
519 # $prereq{<patch filename>} exists or not (even later)
523 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
525 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
528 fresh_workarea "merge";
529 my $seriesfile = "debian/patches/series";
532 foreach my $q ($base_q, reverse @input_qs) {
534 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
536 if (open S, $seriesfile) {
537 while (my $patch = <S>) {
538 chomp $patch or die $!;
539 $prereq{$patch} //= {};
540 foreach my $earlier (@earlier) {
541 $prereq{$patch}{$earlier}{$s}++ and die;
543 push @earlier, $patch;
544 stat "debian/patches/$patch" or die "$patch ?";
546 S->error and die "$seriesfile $!";
549 die "$seriesfile $!" unless $!==ENOENT;
551 read_tree_upstream $newbase, 1;
552 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
553 "Convert $s to patch queue for merging",
554 "[git-debrebase merge-innards patch-queue import:".
557 printdebug "merge_series pec $pec ";
558 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
559 $pec = make_commit [ $pec ], [
560 "Drop series file from $s to avoid merge trouble",
561 "[git-debrebase merge-innards patch-queue prep:".
565 read_tree_debian $newbase;
567 read_tree_subdir 'debian/patches', "$pec:debian/patches";
569 rm_subdir_cached 'debian/patches';
571 $pec = make_commit [ $pec ], [
572 "Update debian/ (excluding patches) to final to avoid re-merging",
573 "debian/ was already merged and we need to just take that.",
574 "[git-debrebase merge-innards patch-queue packaging:".
578 printdebug "pec' $pec\n";
579 runcmd @git, qw(reset -q --hard), $pec;
580 $q->{MR}{PEC} = $pec;
581 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
583 # now, because of reverse, we are on $input_q->{MR}{OQC}
584 runcmd @git, qw(checkout -q -b merge);
585 printdebug "merge_series merging...\n";
586 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
588 $attempt_cmd->(@mergecmd);
590 printdebug "merge_series merge ok, series...\n";
591 # We need to construct a new series file
592 # Firstly, resolve prereq
593 foreach my $f (sort keys %prereq) {
594 printdebug "merge_series patch\t$f\t";
595 if (!stat_exists "debian/patches/$f") {
596 print DEBUG " drop\n" if $debuglevel;
597 # git merge deleted it; that's how we tell it's not wanted
601 print DEBUG " keep\n" if $debuglevel;
602 foreach my $g (sort keys %{ $prereq{$f} }) {
603 my $gfp = $prereq{$f}{$g};
604 printdebug "merge_series prereq\t$f\t-> $g\t";
605 if (!!$gfp->{0} == !!$gfp->{1}
608 print DEBUG "\tkeep\n" if $debuglevel;
610 print DEBUG "\tdrop\n" if $debuglevel;
611 delete $prereq{$f}{$g};
618 return scalar keys %{ $prereq{$f} };
621 my $nodate = time + 1;
623 # $authordate{<patch filename>};
624 my $authordate = sub {
626 $authordate{$f} //= do {
627 open PF, "<", "debian/patches/$f" or die "$f $!";
629 return $nodate if m/^$/;
630 last if s{^Date: }{};
633 return cmdoutput qw(date +%s -d), $_;
637 open NS, '>', $seriesfile or die $!;
639 while (keys %prereq) {
641 foreach my $try (sort keys %prereq) {
644 $unsat->($try) <=> $unsat->($best) or
645 $authordate->($try) <=> $authordate->($best) or
651 printdebug "merge_series series next $best\n";
652 print NS "$best\n" or die $!;
653 delete $prereq{$best};
654 foreach my $gp (values %prereq) {
659 runcmd @git, qw(add), $seriesfile;
660 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
661 $merged_pq = git_rev_parse 'HEAD';
662 $mwrecknote->('merged-patchqueue', $merged_pq);
664 return merge_series_patchqueue_convert
665 $wrecknotes, $newbase, $merged_pq;
668 sub merge_series_patchqueue_convert ($$$) {
669 my ($wrecknotes, $newbase, $merged_pq) = @_;
674 printdebug "merge_series series gbp pq import\n";
675 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
677 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
679 # OK now we are on patch-queue/merge, and we need to rebase
680 # onto the intended parent and drop the patches from each one
682 printdebug "merge_series series ok, building...\n";
683 my $build = $newbase;
684 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
685 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
686 my $commit = git_cat_file $c, 'commit';
687 printdebug "merge_series series ok, building $c\n";
688 read_tree_upstream $c, 0, $newbase;
689 my $tree = cmdoutput @git, qw(write-tree);
690 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
691 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
692 open C, ">", "../mcommit" or die $!;
693 print C $commit or die $!;
695 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
698 mwrecknote($wrecknotes, 'merged-result', $result);
700 runcmd @git, qw(update-ref refs/heads/result), $result;
702 runcmd @git, qw(checkout -q -b debug);
703 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
704 runcmd @git, qw(add .);
705 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
706 my $mdebug = git_rev_parse 'HEAD';
707 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
708 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
710 printdebug "merge_series returns $result\n";
714 # classify returns an info hash like this
716 # Hdr => # commit headers, including 1 final newline
717 # Msg => # commit message (so one newline is dropped)
719 # Type => (see below)
721 # Ix => $index # ie 0, 1, 2, ...
723 # Differs => return value from get_differs
725 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
727 # NewMsg => # commit message, but with any [dgit import ...] edited
728 # # to say "[was: ...]"
738 # has additional entres in classification result
739 # Overwritten = [ subset of Parents ]
740 # Contributor = $the_remaining_Parent
742 # DgitImportUnpatched
743 # has additional entry in classification result
744 # OrigParents = [ subset of Parents ]
747 # has additional entry in classification result
748 # OrigParents = [ subset of Parents ] # singleton list
755 # has additional entry in classification result
758 sub parsecommit ($;$) {
759 my ($objid, $p_ref) = @_;
760 # => hash with CommitId Hdr Msg Tree Parents
761 # Parents entries have only Ix CommitId
762 # $p_ref, if provided, must be [] and is used as a base for Parents
767 my ($h,$m) = get_commit $objid;
769 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
770 my (@ph) = $h =~ m/^parent (\w+)$/mg;
780 foreach my $ph (@ph) {
782 Ix => scalar @$p_ref,
794 my $r = parsecommit($objid, \@p);
798 $p->{Differs} = (get_differs $p->{CommitId}, $t),
801 printdebug "classify $objid \$t=$t \@p",
802 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
806 my ($type, @rest) = @_;
807 $r = { %$r, Type => $type, @rest };
809 printdebug " = $type ".(dd $r)."\n";
815 $r = { %$r, Type => qw(Unknown), Why => $why };
816 printdebug " ** Unknown\n";
820 if (grep { $_ eq $objid } @opt_anchors) {
821 return $classify->('TreatAsAnchor');
824 my @identical = grep { !$_->{Differs} } @p;
825 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
826 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
828 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
829 # multi-orig upstreams are represented with an anchor merge
830 # from a single upstream commit which combines the orig tarballs
832 # Every anchor tagged this way must be a merge.
833 # We are relying on the
834 # [git-debrebase anchor: ...]
835 # commit message annotation in "declare" anchor merges (which
836 # do not have any upstream changes), to distinguish those
837 # anchor merges from ordinary pseudomerges (which we might
838 # just try to strip).
840 # However, the user is going to be doing git-rebase a lot. We
841 # really don't want them to rewrite an anchor commit.
842 # git-rebase trips up on merges, so that is a useful safety
845 # BreakwaterStart commits are also anchors in the terminology
846 # of git-debrebase(5), but they are untagged (and always
847 # manually generated).
849 # We cannot not tolerate any tagged linear commit (ie,
850 # BreakwaterStart commits tagged `[anchor:') because such a
851 # thing could result from an erroneous linearising raw git
852 # rebase of a merge anchor. That would represent a corruption
853 # of the branch. and we want to detect and reject the results
854 # of such corruption before it makes it out anywhere. If we
855 # reject it here then we avoid making the pseudomerge which
856 # would be needed to push it.
858 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
859 @p == 2 or return $badanchor->("has other than two parents");
860 $haspatches and return $badanchor->("contains debian/patches");
862 # How to decide about l/r ordering of anchors ? git
863 # --topo-order prefers to expand 2nd parent first. There's
864 # already an easy rune to look for debian/ history anyway (git log
865 # debian/) so debian breakwater branch should be 1st parent; that
866 # way also there's also an easy rune to look for the upstream
867 # patches (--topo-order).
869 # Also this makes --first-parent be slightly more likely to
870 # be useful - it makes it provide a linearised breakwater history.
872 # Of course one can say somthing like
873 # gitk -- ':/' ':!/debian'
874 # to get _just_ the commits touching upstream files, and by
875 # the TREESAME logic in git-rev-list this will leave the
876 # breakwater into upstream at the first anchor. But that
877 # doesn't report debian/ changes at all.
879 # Other observations about gitk: by default, gitk seems to
880 # produce output in a different order to git-rev-list. I
881 # can't seem to find this documented anywhere. gitk
882 # --date-order DTRT. But, gitk always seems to put the
883 # parents from left to right, in order, so it's easy to see
884 # which way round a pseudomerge is.
886 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
887 $p[1]{Differs} & ~DS_DEB and
888 $badanchor->("upstream files differ from left parent");
889 $p[0]{Differs} & ~D_UPS and
890 $badanchor->("debian/ differs from right parent");
892 return $classify->(qw(Anchor),
893 OrigParents => [ $p[1] ]);
897 my $d = $r->{Parents}[0]{Differs};
898 if ($d == D_PAT_ADD) {
899 return $classify->(qw(AddPatches));
900 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
901 return $unknown->("edits debian/patches");
902 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
903 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
905 if ($d == D_DEB_CLOG) {
906 return $classify->(qw(Changelog));
908 return $classify->(qw(Packaging));
910 } elsif ($ty eq 'missing') {
911 return $classify->(qw(BreakwaterStart));
913 return $unknown->("parent's debian is not a directory");
915 } elsif ($d == D_UPS) {
916 return $classify->(qw(Upstream));
917 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
918 return $classify->(qw(Mixed));
920 return $unknown->("no changes");
922 confess "internal error $objid ?";
926 return $unknown->("origin commit");
929 if (@p == 2 && @identical == 1) {
930 my @overwritten = grep { $_->{Differs} } @p;
931 confess "internal error $objid ?" unless @overwritten==1;
932 return $classify->(qw(Pseudomerge),
933 Overwritten => [ $overwritten[0] ],
934 Contributor => $identical[0]);
936 if (@p == 2 && @identical == 2) {
938 my ($ph,$pm) = get_commit $_[0]{CommitId};
939 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
943 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
944 if ($order > 0) { # newer first
945 } elsif ($order < 0) {
946 @bytime = reverse @bytime;
948 # same age, default to order made by -s ours
949 # that is, commit was made by someone who preferred L
951 return $classify->(qw(Pseudomerge),
952 SubType => qw(Ambiguous),
953 Contributor => $bytime[0],
954 Overwritten => [ $bytime[1] ]);
957 my ($p_h, $p_m) = get_commit $p->{CommitId};
958 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
959 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
961 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
963 if (!(grep { !$_->{IsOrigin} } @p) and
964 (@orig_ps >= @p - 1) and
965 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
967 return $classify->(qw(DgitImportUnpatched),
968 OrigParents => \@orig_ps);
972 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
973 # xxx ^ metadata tag needs adding to (5)
974 return $classify->("MergedBreakwaters");
976 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
977 return $unknown->("unknown kind of merge from $1");
980 return $unknown->("octopus merge");
983 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
984 return $unknown->("general two-parent merge");
987 return $classify->("VanillaMerge");
990 sub keycommits ($;$$$$$);
992 sub mergedbreakwaters_anchor ($) {
995 foreach my $p (@{ $cl->{Parents} }) {
996 my ($panchor, $pbw) = keycommits $p->{CommitId},
997 undef,undef,undef,undef, 1;
998 $best_anchor = $panchor
999 if !defined $best_anchor
1000 or is_fast_fwd $best_anchor, $panchor;
1001 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
1002 unless is_fast_fwd $panchor, $best_anchor;
1004 return $best_anchor;
1007 sub keycommits ($;$$$$$) {
1008 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
1009 # => ($anchor, $breakwater)
1011 # $unclean->("unclean-$tagsfx", $msg, $cl)
1012 # $furniture->("unclean-$tagsfx", $msg, $cl)
1013 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
1014 # is callled for each situation or commit that
1015 # wouldn't be found in a laundered branch
1016 # $furniture is for furniture commits such as might be found on an
1017 # interchange branch (pseudomerge, d/patches, changelog)
1018 # $trouble is for things whnich prevent the return of
1019 # anchor and breakwater information; if that is ignored,
1020 # then keycommits returns (undef, undef) instead.
1021 # $fatal is for unprocessable commits, and should normally cause
1022 # a failure. If ignored, agaion, (undef, undef) is returned.
1024 # If $claimed_bw, this is supposed to be a breakwater commit.
1026 # If a callback is undef, fail is called instead.
1027 # If a callback is defined but false, the situation is ignored.
1028 # Callbacks may say:
1029 # no warnings qw(exiting); last;
1030 # if the answer is no longer wanted.
1032 my ($anchor, $breakwater);
1033 $breakwater = $head if $claimed_bw;
1037 $fatal //= sub { fail $_[1]; };
1039 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
1040 my $why = $mainwhy.$xwhy;
1041 my $m = "branch needs laundering (run git-debrebase): $why";
1042 fail $m unless defined $cb;
1044 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
1046 my $found_anchor = sub {
1048 $breakwater //= $clogonly;
1049 $breakwater //= $head;
1050 no warnings qw(exiting);
1054 $cl = classify $head;
1055 my $ty = $cl->{Type};
1056 if ($ty eq 'Packaging') {
1057 $breakwater //= $clogonly;
1058 $breakwater //= $head;
1059 } elsif ($ty eq 'Changelog') {
1060 # this is going to count as the tip of the breakwater
1061 # only if it has no upstream stuff before it
1062 $clogonly //= $head;
1063 } elsif ($ty eq 'Anchor' or
1064 $ty eq 'TreatAsAnchor' or
1065 $ty eq 'BreakwaterStart') {
1066 $found_anchor->($head);
1067 } elsif ($ty eq 'Upstream') {
1068 $x->($unclean, 'ordering',
1069 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1070 if defined $breakwater;
1072 $breakwater = undef;
1073 } elsif ($ty eq 'Mixed') {
1074 $x->($unclean, 'mixed',
1075 "found mixed upstream/packaging commit"," ($head)");
1077 $breakwater = undef;
1078 } elsif ($ty eq 'Pseudomerge' or
1079 $ty eq 'AddPatches') {
1081 $x->($furniture, (lc $ty),
1082 "found interchange bureaucracy commit ($ty)"," ($head)");
1083 } elsif ($ty eq 'DgitImportUnpatched') {
1085 $x->($trouble, 'dgitimport',
1086 "found dgit dsc import"," ($head)");
1087 return (undef,undef);
1089 $x->($fatal, 'unprocessable',
1090 "found bare dgit dsc import with no prior history",
1092 return (undef,undef);
1094 } elsif ($ty eq 'VanillaMerge') {
1095 $x->($trouble, 'vanillamerge',
1096 "found vanilla merge"," ($head)");
1097 return (undef,undef);
1098 } elsif ($ty eq 'MergedBreakwaters') {
1099 $found_anchor->(mergedbreakwaters_anchor $cl);
1101 $x->($fatal, 'unprocessable',
1102 "found unprocessable commit, cannot cope: $cl->{Why}",
1104 return (undef,undef);
1106 $head = $cl->{Parents}[0]{CommitId};
1108 return ($anchor, $breakwater);
1114 $nogenerate,$report, $report_lprefix) = @_;
1115 # => ($tip, $breakwater_tip, $last_anchor)
1116 # (or nothing, if $nogenerate)
1118 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1119 $report_lprefix //= '';
1121 # go through commits backwards
1122 # we generate two lists of commits to apply:
1123 # breakwater branch and upstream patches
1124 my (@brw_cl, @upp_cl, @processed);
1131 my ($prose, $info) = @_;
1132 my $ms = $cl->{Msg};
1135 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1136 return (Msg => $ms);
1138 my $rewrite_from_here = sub {
1140 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1142 push @processed, $sp_cl;
1147 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1150 return unless $report;
1151 print $report $prdelim, $report_lprefix, @_;
1155 my $bomb = sub { # usage: return $bomb->();
1156 print $report " Unprocessable" if $report;
1157 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1160 return (undef,undef);
1162 fail "found unprocessable commit, cannot cope".
1163 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1164 " (commit $cur) (d.".
1165 (join ' ', map { sprintf "%#x", $_->{Differs} }
1166 @{ $cl->{Parents} }).
1173 my $build_start = sub {
1174 my ($msg, $parent) = @_;
1177 no warnings qw(exiting); last;
1182 merge_failed $cl->{MergeWreckNotes}, $emsg;
1185 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1190 $cl = classify $cur;
1191 $cl->{MergeWreckNotes} //= {};
1192 my $ty = $cl->{Type};
1193 my $st = $cl->{SubType};
1194 $prline->("$cl->{CommitId} $cl->{Type}");
1195 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1196 push @processed, $cl;
1197 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1198 if ($ty eq 'AddPatches') {
1200 $rewrite_from_here->(\@upp_cl);
1202 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1206 } elsif ($ty eq 'BreakwaterStart') {
1207 $last_anchor = $cur;
1208 $build_start->('FirstPackaging', $cur);
1209 } elsif ($ty eq 'Upstream') {
1213 } elsif ($ty eq 'Mixed') {
1216 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1219 $queue->(\@brw_cl, "debian");
1220 $queue->(\@upp_cl, "upstream");
1221 $rewrite_from_here->(\@brw_cl);
1224 } elsif ($ty eq 'Pseudomerge') {
1225 my $contrib = $cl->{Contributor}{CommitId};
1226 print $report " Contributor=$contrib" if $report;
1227 push @pseudomerges, $cl;
1228 $rewrite_from_here->(\@upp_cl);
1231 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1232 $last_anchor = $cur;
1233 $build_start->("Anchor", $cur);
1234 } elsif ($ty eq 'DgitImportUnpatched') {
1235 my $pm = $pseudomerges[-1];
1237 # To an extent, this is heuristic. Imports don't have
1238 # a useful history of the debian/ branch. We assume
1239 # that the first pseudomerge after an import has a
1240 # useful history of debian/, and ignore the histories
1241 # from later pseudomerges. Often the first pseudomerge
1242 # will be the dgit import of the upload to the actual
1243 # suite intended by the non-dgit NMUer, and later
1244 # pseudomerges may represent in-archive copies.
1245 my $ovwrs = $pm->{Overwritten};
1246 printf $report " PM=%s \@Overwr:%d",
1247 $pm->{CommitId}, (scalar @$ovwrs)
1250 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1253 my $ovwr = $ovwrs->[0]{CommitId};
1254 printf $report " Overwr=%s", $ovwr if $report;
1255 # This import has a tree which is just like a
1256 # breakwater tree, but it has the wrong history. It
1257 # ought to have the previous breakwater (which the
1258 # pseudomerge overwrote) as an ancestor. That will
1259 # make the history of the debian/ files correct. As
1260 # for the upstream version: either it's the same as
1261 # was ovewritten (ie, same as the previous
1262 # breakwater), in which case that history is precisely
1263 # right; or, otherwise, it was a non-gitish upload of a
1264 # new upstream version. We can tell these apart by
1265 # looking at the tree of the supposed upstream.
1268 SpecialMethod => 'DgitImportDebianUpdate',
1269 $xmsg->("convert dgit import: debian changes")
1272 SpecialMethod => 'DgitImportUpstreamUpdate',
1273 $xmsg->("convert dgit import: upstream update",
1276 $prline->(" Import");
1277 $rewrite_from_here->(\@brw_cl);
1278 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1282 # Everything is from this import. This kind of import
1283 # is already nearly in valid breakwater format, with the
1284 # patches as commits. Unfortunately it contains
1286 printdebug "*** WALK BOMB bare dgit import\n";
1287 $cl->{Why} = "bare dgit dsc import";
1291 } elsif ($ty eq 'MergedBreakwaters') {
1292 $last_anchor = mergedbreakwaters_anchor $cl;
1293 $build_start->(' MergedBreakwaters', $cur);
1295 } elsif ($ty eq 'VanillaMerge') {
1296 # User may have merged unstitched branch(es). We will
1297 # have now lost what ffq-prev was then (since the later
1298 # pseudomerge may introduce further changes). The effect
1299 # of resolving such a merge is that we may have to go back
1300 # further in history to find a merge base, since the one
1301 # which was reachable via ffq-prev is no longer findable.
1302 # This is suboptimal, but if it all works we'll have done
1304 # xxx we should warn the user in the docs about this
1308 # We expect to find a dominating anchor amongst the
1309 # inputs' anchors. That will be the new anchor.
1311 # More complicated is finding a merge base for the
1312 # breakwaters. We need a merge base that is a breakwater
1313 # commit. The ancestors of breakwater commits are more
1314 # breakwater commits and possibly upstream commits and the
1315 # ancestors of those upstream. Upstreams might have
1316 # arbitrary ancestors. But any upstream commit U is
1317 # either included in both anchors, in which case the
1318 # earlier anchor is a better merge base than any of U's
1319 # ancestors; or U is not included in the older anchor, in
1320 # which case U is not an ancestor of the vanilla merge at
1321 # all. So no upstream commit, nor any ancestor thereof,
1322 # is a best merge base. As for non-breakwater Debian
1323 # commits: these are never ancestors of any breakwater.
1325 # So any best merge base as found by git-merge-base
1326 # is a suitable breakwater anchor. Usually there will
1329 printdebug "*** MERGE\n";
1331 my @bwbcmd = (@git, qw(merge-base));
1332 my @ibcmd = (@git, qw(merge-base --all));
1333 my $might_be_in_bw = 1;
1335 my $ps = $cl->{Parents};
1337 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1339 foreach my $p (@$ps) {
1340 $prline->(" VanillaMerge ".$p->{Ix});
1342 my ($ptip, $pbw, $panchor) =
1343 walk $p->{CommitId}, 0, $report,
1344 $report_lprefix.' ';
1345 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1346 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1347 $p->{Anchor} = $panchor;
1349 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1350 $mwrecknote->("$lr-input", $p->{CommitId});
1352 my $mwrecknote_parent = sub {
1354 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1356 $mwrecknote_parent->('Laundered');
1357 $mwrecknote_parent->('Breakwater');
1358 $mwrecknote_parent->('Anchor');
1360 $best_anchor = $panchor if
1361 !defined $best_anchor or
1362 is_fast_fwd $best_anchor, $panchor;
1364 printdebug " MERGE BA best=".($best_anchor//'-').
1368 $mwrecknote->('result-anchor', $best_anchor);
1370 foreach my $p (@$ps) {
1371 $prline->(" VanillaMerge ".$p->{Ix});
1372 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1373 $nomerge->('divergent anchors');
1374 } elsif ($p->{Anchor} eq $best_anchor) {
1375 print $report " SameAnchor" if $report;
1377 print $report " SupersededAnchor" if $report;
1379 if ($p->{Breakwater} eq $p->{CommitId}) {
1380 # this parent commit was its own breakwater,
1381 # ie it is part of the breakwater
1382 print $report " Breakwater" if $report;
1384 $might_be_in_bw = 0;
1386 push @bwbcmd, $p->{Breakwater};
1387 push @ibcmd, $p->{CommitId};
1390 if ($ok && $might_be_in_bw) {
1391 # We could rewrite this to contaion the metadata
1392 # declaring it to be MergedBreakwaters, but
1393 # unnecessarily rewriting a merge seems unhelpful.
1394 $prline->(" VanillaMerge MergedBreakwaters");
1395 $last_anchor = $best_anchor;
1396 $build_start->('MergedBreakwaters', $cur);
1399 my $bwb = cmdoutput @bwbcmd;
1401 # OK, now we have a breakwater base, but we need the merge
1402 # base for the interchange branch because we need the delta
1405 # This a the best merge base of our inputs which has the
1406 # breakwater merge base as an ancestor.
1413 @ibs or confess 'internal error, expected anchor at least ?';
1417 foreach my $tibix (0..$#ibs) {
1418 my $tib = $ibs[$tibix];
1419 my $ff = is_fast_fwd $bwb, $tib;
1420 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1421 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1422 $mwrecknote->($tibleaf, $tib);
1429 $ib or $nomerge->("no suitable interchange merge base");
1431 $prline->(" VanillaMerge Base");
1433 my ($btip, $bbw, $banchor) = eval {
1434 walk $ib, 0, $report, $report_lprefix.' ';
1436 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1440 $mwrecknote->("mergebase-laundered", $btip);
1441 $mwrecknote->("mergebase-breakwater", $bbw);
1442 $mwrecknote->("mergebase-anchor", $banchor);
1444 my $ibinfo = { SeriesTip => $btip,
1447 LeftRight => 'mergebase' };
1450 or $nomerge->("interchange merge-base ($ib)'s".
1451 " breakwater ($bbw)".
1452 " != breakwaters' merge-base ($bwb)");
1454 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1455 or $nomerge->("interchange merge-base ($ib)'s".
1456 " anchor ($ibinfo->{SeriesBase})".
1457 " != any merge input's anchor (".
1458 (join ' ', map { $_->{Anchor} } @$ps).
1461 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1462 $cl->{MergeBestAnchor} = $best_anchor;
1465 SpecialMethod => 'MergeCreateMergedBreakwaters',
1466 $xmsg->('constructed from vanilla merge',
1467 ' merged-breakwater'),
1471 SpecialMethod => 'MergeMergeSeries',
1473 $build_start->('MergeBreakwaters', $cur);
1475 printdebug "*** WALK BOMB unrecognised\n";
1481 printdebug "*** WALK prep done cur=$cur".
1482 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1484 return if $nogenerate;
1486 # Now we build it back up again
1492 $#upp_cl = $upp_limit if defined $upp_limit;
1494 my $committer_authline = calculate_committer_authline();
1496 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1498 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1501 mkdir $rd or $!==EEXIST or die $!;
1503 my $want_debian = $build;
1504 my $want_upstream = $build;
1506 my $read_tree_upstream = sub { ($want_upstream) = @_; };
1507 my $read_tree_debian = sub { ($want_debian) = @_; };
1509 foreach my $cl (qw(Debian), (reverse @brw_cl),
1510 { SpecialMethod => 'RecordBreakwaterTip' },
1511 qw(Upstream), (reverse @upp_cl)) {
1513 $current_method = $cl;
1516 my $method = $cl->{SpecialMethod} // $current_method;
1517 my @parents = ($build);
1518 my $cltree = $cl->{CommitId};
1519 printdebug "WALK BUILD ".($cltree//'undef').
1520 " $method (rewriting=$rewriting)\n";
1521 if ($method eq 'Debian') {
1522 $read_tree_debian->($cltree);
1523 } elsif ($method eq 'Upstream') {
1524 $read_tree_upstream->($cltree);
1525 } elsif ($method eq 'StartRewrite') {
1528 } elsif ($method eq 'RecordBreakwaterTip') {
1529 $breakwater = $build;
1531 } elsif ($method eq 'DgitImportDebianUpdate') {
1532 $read_tree_debian->($cltree);
1533 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1534 confess unless $rewriting;
1535 my $differs = (get_differs $build, $cltree);
1536 next unless $differs & D_UPS;
1537 $read_tree_upstream->($cltree);
1538 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1539 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1540 print "Found a general merge, will try to tidy it up.\n";
1542 $read_tree_upstream->($cl->{MergeBestAnchor});
1543 $read_tree_debian->($cltree);
1544 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1545 } elsif ($method eq 'MergeMergeSeries') {
1546 my $cachehit = reflog_cache_lookup
1547 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1549 print "Using supplied resolution for $cl->{CommitId}...\n";
1551 $mwrecknote->('cached-resolution', $build);
1553 print "Running merge resolution for $cl->{CommitId}...\n";
1554 $mwrecknote->('new-base', $build);
1555 $build = merge_series
1556 $build, $cl->{MergeWreckNotes},
1557 $cl->{MergeInterchangeBaseInfo},
1558 @{ $cl->{Parents} };
1560 $last_anchor = $cl->{MergeBestAnchor};
1562 # Check for mismerges:
1564 my ($against, $allow, $what) = @_;
1565 my $differs = get_differs $build, $against;
1567 "merge misresolved: %s are not the same (%s %s d.%#x)",
1568 $what, $against, $build, $differs)
1569 if $differs & ~($allow | D_PAT_ADD);
1572 # Breakwater changes which were in each side of the
1573 # merge will have been incorporated into the
1574 # MergeCreateMergedBreakwaters output. Because the
1575 # upstream series was rebased onto the new breakwater,
1576 # so should all of the packaging changes which were in
1578 $check->($input, D_UPS, 'debian files');
1580 # Upstream files are merge_series, which ought to
1581 # have been identical to the original merge.
1582 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1584 print "Merge resolution successful.\n";
1587 confess "$method ?";
1590 my $procd = (pop @processed) // 'UNDEF';
1591 if ($cl ne $procd) {
1593 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1596 if ($rewriting || $opt_careful) {
1597 read_tree_upstream $want_upstream, 0, $want_debian;
1599 my $newtree = cmdoutput @git, qw(write-tree);
1600 my $ch = $cl->{Hdr};
1601 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1602 $ch =~ s{^parent .*\n}{}mg;
1603 $ch =~ s{(?=^author)}{
1604 join '', map { "parent $_\n" } @parents
1605 }me or confess "$ch ?";
1607 $ch =~ s{^committer .*$}{$committer_authline}m
1610 my $cf = "$rd/m$rewriting";
1611 open CD, ">", $cf or die $!;
1612 print CD $ch, "\n", $cl->{Msg} or die $!;
1614 my @cmd = (@git, qw(hash-object));
1615 push @cmd, qw(-w) if $rewriting;
1616 push @cmd, qw(-t commit), $cf;
1617 my $newcommit = cmdoutput @cmd;
1618 confess "$ch ?" unless $rewriting
1619 or $newcommit eq $cl->{CommitId};
1620 $build = $newcommit;
1622 $build = $cl->{CommitId};
1623 trees_diff_walk "$want_upstream:", "$build:", sub {
1625 no warnings qw(exiting);
1626 next if $n eq 'debian/';
1627 confess "mismatch @_ ?";
1629 trees_diff_walk "$want_debian:debian", "$build:debian", sub {
1630 confess "mismatch @_ ?";
1632 my @old_parents = map { $_->{CommitId} } @{ $cl->{Parents} };
1633 confess "mismatch @parents != @old_parents ?"
1634 unless "@parents" eq "@old_parents";
1636 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1637 $last_anchor = $cur;
1642 my $final_check = get_differs $build, $input;
1643 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1644 if $final_check & ~D_PAT_ADD;
1646 my @r = ($build, $breakwater, $last_anchor);
1647 printdebug "*** WALK RETURN @r\n";
1652 git_check_unmodified();
1653 return git_rev_parse qw(HEAD);
1656 sub update_head ($$$) {
1657 my ($old, $new, $mrest) = @_;
1658 push @deferred_updates, "update HEAD $new $old";
1659 run_deferred_updates $mrest;
1662 sub update_head_checkout ($$$) {
1663 my ($old, $new, $mrest) = @_;
1664 update_head $old, $new, $mrest;
1665 runcmd @git, qw(reset --hard);
1668 sub update_head_postlaunder ($$$) {
1669 my ($old, $tip, $reflogmsg) = @_;
1670 return if $tip eq $old;
1671 print "git-debrebase: laundered (head was $old)\n";
1672 update_head $old, $tip, $reflogmsg;
1673 # no tree changes except debian/patches
1674 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1677 sub currently_rebasing() {
1678 foreach (qw(rebase-merge rebase-apply)) {
1679 return 1 if stat_exists "$maindir_gitdir/$_";
1684 sub bail_if_rebasing() {
1685 fail "you are in the middle of a git-rebase already"
1686 if currently_rebasing();
1689 sub do_launder_head ($) {
1690 my ($reflogmsg) = @_;
1691 my $old = get_head();
1693 my ($tip,$breakwater) = walk $old;
1695 update_head_postlaunder $old, $tip, $reflogmsg;
1696 return ($tip,$breakwater);
1699 sub cmd_launder_v0 () {
1700 badusage "no arguments to launder-v0 allowed" if @ARGV;
1701 my $old = get_head();
1702 my ($tip,$breakwater,$last_anchor) = walk $old;
1703 update_head_postlaunder $old, $tip, 'launder';
1704 printf "# breakwater tip\n%s\n", $breakwater;
1705 printf "# working tip\n%s\n", $tip;
1706 printf "# last anchor\n%s\n", $last_anchor;
1709 sub defaultcmd_rebase () {
1710 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1711 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1712 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1715 sub cmd_analyse () {
1716 badusage "analyse does not support any options"
1717 if @ARGV and $ARGV[0] =~ m/^-/;
1718 badusage "too many arguments to analyse" if @ARGV>1;
1721 $old = git_rev_parse $old;
1723 $old = git_rev_parse 'HEAD';
1725 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1726 STDOUT->error and die $!;
1729 sub ffq_prev_branchinfo () {
1730 my $current = git_get_symref();
1731 return gdr_ffq_prev_branchinfo($current);
1734 sub ffq_check ($;$$) {
1735 # calls $ff and/or $notff zero or more times
1736 # then returns either (status,message) where status is
1741 # or (undef,undef, $ffq_prev,$gdrlast)
1742 # $ff and $notff are called like this:
1743 # $ff->("message for stdout\n");
1744 # $notff->('snag-name', $message);
1745 # normally $currentval should be HEAD
1746 my ($currentval, $ff, $notff) =@_;
1748 $ff //= sub { print $_[0] or die $!; };
1751 my ($status, $message, $current, $ffq_prev, $gdrlast)
1752 = ffq_prev_branchinfo();
1753 return ($status, $message) unless $status eq 'branch';
1755 my $exists = git_get_ref $ffq_prev;
1756 return ('exists',"$ffq_prev already exists") if $exists;
1758 return ('not-branch', 'HEAD symref is not to refs/heads/')
1759 unless $current =~ m{^refs/heads/};
1762 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1765 printdebug "ffq check_specs @check_specs\n";
1768 my ($lrref, $desc) = @_;
1769 printdebug "ffq might check $lrref ($desc)\n";
1771 for my $chk (@check_specs) {
1773 $invert = $glob =~ s{^[!^]}{};
1774 last if fnmatch $glob, $lrref;
1777 my $lrval = git_get_ref $lrref;
1778 return unless length $lrval;
1780 if (is_fast_fwd $lrval, $currentval) {
1781 $ff->("OK, you are ahead of $lrref\n");
1782 $checked{$lrref} = 1;
1783 } elsif (is_fast_fwd $currentval, $lrval) {
1784 $checked{$lrref} = -1;
1785 $notff->('behind', "you are behind $lrref, divergence risk");
1787 $checked{$lrref} = -1;
1788 $notff->('diverged', "you have diverged from $lrref");
1792 my $merge = cfg "branch.$branch.merge",1;
1793 if (defined $merge and $merge =~ m{^refs/heads/}) {
1795 printdebug "ffq merge $rhs\n";
1796 my $check_remote = sub {
1797 my ($remote, $desc) = @_;
1798 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1799 return unless defined $remote;
1800 $check->("refs/remotes/$remote/$rhs", $desc);
1802 $check_remote->((scalar cfg "branch.$branch.remote",1),
1803 'remote fetch/merge branch');
1804 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1805 (scalar cfg "branch.$branch.pushDefault",1),
1806 'remote push branch');
1808 if ($branch =~ m{^dgit/}) {
1809 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1810 } elsif ($branch =~ m{^master$}) {
1811 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1813 return (undef, undef, $ffq_prev, $gdrlast);
1816 sub record_ffq_prev_deferred () {
1817 # => ('status', "message")
1819 # deferred message is undef
1824 # if not ff from some branch we should be ff from, is an snag
1825 # if "deferred", will have added something about that to
1826 # @deferred_update_messages, and also maybe printed (already)
1827 # some messages about ff checks
1829 my $currentval = get_head();
1831 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1832 return ($status,$message) if defined $status;
1836 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1837 push @deferred_updates, "delete $gdrlast";
1838 push @deferred_update_messages, "Recorded previous head for preservation";
1839 return ('deferred', undef);
1842 sub record_ffq_auto () {
1843 my ($status, $message) = record_ffq_prev_deferred();
1844 if ($status eq 'deferred' || $status eq 'exists') {
1846 snag $status, "could not record ffq-prev: $message";
1851 sub ffq_prev_info () {
1853 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1854 my ($status, $message, $current, $ffq_prev, $gdrlast)
1855 = ffq_prev_branchinfo();
1856 if ($status ne 'branch') {
1857 snag $status, "could not check ffq-prev: $message";
1860 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1861 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1864 sub stitch ($$$$$) {
1865 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1867 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1869 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1870 my $differs = get_differs $old_head, $ffq_prev_commitish;
1871 unless ($differs & ~D_PAT_ADD) {
1872 # ffq-prev is ahead of us, and the only tree changes it has
1873 # are possibly addition of things in debian/patches/.
1874 # Just wind forwards rather than making a pointless pseudomerge.
1875 push @deferred_updates,
1876 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1877 update_head_checkout $old_head, $ffq_prev_commitish,
1878 "stitch (fast forward)";
1883 # We make pseudomerges with L as the contributing parent.
1884 # This makes git rev-list --first-parent work properly.
1885 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1886 'Declare fast forward / record previous work',
1887 "[git-debrebase pseudomerge: $prose]",
1889 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1890 update_head $old_head, $new_head, "stitch: $prose";
1893 sub do_stitch ($;$) {
1894 my ($prose, $unclean) = @_;
1896 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1897 if (!$ffq_prev_commitish) {
1898 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1901 my $dangling_head = get_head();
1903 keycommits $dangling_head, $unclean,$unclean,$unclean;
1906 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1909 sub upstream_commitish_search ($$) {
1910 my ($upstream_version, $tried) = @_;
1911 # todo: at some point maybe use git-deborig to do this
1912 foreach my $tagpfx ('', 'v', 'upstream/') {
1913 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1914 my $new_upstream = git_get_ref "refs/tags/$tag";
1916 return $new_upstream if length $new_upstream;
1920 sub resolve_upstream_version ($$) {
1921 my ($new_upstream, $upstream_version) = @_;
1923 if (!defined $new_upstream) {
1925 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1926 if (!length $new_upstream) {
1927 fail "Could not determine appropriate upstream commitish.\n".
1928 " (Tried these tags: @tried)\n".
1929 " Check version, and specify upstream commitish explicitly.";
1932 $new_upstream = git_rev_parse $new_upstream;
1934 return $new_upstream;
1937 sub cmd_new_upstream () {
1938 # automatically and unconditionally launders before rebasing
1939 # if rebase --abort is used, laundering has still been done
1943 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1945 # parse args - low commitment
1946 my $spec_version = shift @ARGV;
1947 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1948 fail "bad version number \`$spec_version'" unless defined $new_version;
1949 if ($new_version->is_native()) {
1950 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1953 my $new_upstream = shift @ARGV;
1954 my $new_upstream_version = upstreamversion $new_version;
1956 resolve_upstream_version $new_upstream, $new_upstream_version;
1961 my ($n, @x) = @_; # may be ''
1962 my $pc = $pieces{$n} //= {
1964 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1966 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1971 my $newpiece = sub {
1972 my ($n, @x) = @_; # may be ''
1973 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1974 push @newpieces, $pc;
1979 New => $new_upstream,
1981 while (@ARGV && $ARGV[0] !~ m{^-}) {
1982 my $n = shift @ARGV;
1984 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1985 unless @ARGV && $ARGV[0] !~ m{^-};
1987 my $c = git_rev_parse shift @ARGV;
1988 die unless $n =~ m/^$extra_orig_namepart_re$/;
1989 $newpiece->($n, New => $c);
1992 # now we need to investigate the branch this generates the
1993 # laundered version but we don't switch to it yet
1994 my $old_head = get_head();
1995 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1997 my $old_bw_cl = classify $old_bw;
1998 my $old_anchor_cl = classify $old_anchor;
2000 if (!$old_anchor_cl->{OrigParents}) {
2001 snag 'anchor-treated',
2002 'old anchor is recognised due to --anchor, cannot check upstream';
2004 $old_upstream = parsecommit
2005 $old_anchor_cl->{OrigParents}[0]{CommitId};
2006 $piece->('', Old => $old_upstream->{CommitId});
2009 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
2010 if ($old_upstream->{Msg} =~
2011 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
2013 my @oldpieces = (split / /, $1);
2014 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
2015 if ($old_n_parents != @oldpieces &&
2016 $old_n_parents != @oldpieces + 1) {
2017 snag 'upstream-confusing', sprintf
2018 "previous upstream combine %s".
2019 " mentions %d pieces (each implying one parent)".
2020 " but has %d parents".
2021 " (one per piece plus maybe a previous combine)",
2022 $old_upstream->{CommitId},
2023 (scalar @oldpieces),
2025 } elsif ($oldpieces[0] ne '.') {
2026 snag 'upstream-confusing', sprintf
2027 "previous upstream combine %s".
2028 " first piece is not \`.'",
2032 foreach my $i (0..$#oldpieces) {
2033 my $n = $oldpieces[$i];
2034 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
2035 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
2039 snag 'upstream-confusing',
2040 "previous upstream $old_upstream->{CommitId} is from".
2041 " git-debrebase but not an \`upstream-combine' commit";
2045 foreach my $pc (values %pieces) {
2046 if (!$old_upstream) {
2047 # we have complained already
2048 } elsif (!$pc->{Old}) {
2049 snag 'upstream-new-piece',
2050 "introducing upstream piece \`$pc->{Name}'";
2051 } elsif (!$pc->{New}) {
2052 snag 'upstream-rm-piece',
2053 "dropping upstream piece \`$pc->{Name}'";
2054 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
2055 snag 'upstream-not-ff',
2056 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
2060 printdebug "%pieces = ", (dd \%pieces), "\n";
2061 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
2069 my @upstream_merge_parents;
2072 push @upstream_merge_parents, $old_upstream->{CommitId};
2075 foreach my $pc (@newpieces) { # always has '' first
2077 read_tree_subdir $pc->{Name}, $pc->{New};
2079 runcmd @git, qw(read-tree), $pc->{New};
2081 push @upstream_merge_parents, $pc->{New};
2084 # index now contains the new upstream
2086 if (@newpieces > 1) {
2087 # need to make the upstream subtree merge commit
2088 $new_upstream = make_commit \@upstream_merge_parents,
2089 [ "Combine upstreams for $new_upstream_version",
2090 ("[git-debrebase upstream-combine . ".
2091 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2096 # $new_upstream is either the single upstream commit, or the
2097 # combined commit we just made. Either way it will be the
2098 # "upstream" parent of the anchor merge.
2100 read_tree_subdir 'debian', "$old_bw:debian";
2102 # index now contains the anchor merge contents
2103 $new_bw = make_commit [ $old_bw, $new_upstream ],
2104 [ "Update to upstream $new_upstream_version",
2105 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2108 my $clogsignoff = cmdoutput qw(git show),
2109 '--pretty=format:%an <%ae> %aD',
2112 # Now we have to add a changelog stanza so the Debian version
2114 die if unlink "debian";
2115 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2116 unlink "debian/changelog" or $!==ENOENT or die $!;
2117 mkdir "debian" or die $!;
2118 open CN, ">", "debian/changelog" or die $!;
2119 my $oldclog = git_cat_file ":debian/changelog";
2120 $oldclog =~ m/^($package_re) \(\S+\) / or
2121 fail "cannot parse old changelog to get package name";
2123 print CN <<END, $oldclog or die $!;
2124 $p ($new_version) UNRELEASED; urgency=medium
2126 * Update to new upstream version $new_upstream_version.
2132 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2134 # Now we have the final new breakwater branch in the index
2135 $new_bw = make_commit [ $new_bw ],
2136 [ "Update changelog for new upstream $new_upstream_version",
2137 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2141 # we have constructed the new breakwater. we now need to commit to
2142 # the laundering output, because git-rebase can't easily be made
2143 # to make a replay list which is based on some other branch
2145 update_head_postlaunder $old_head, $old_laundered_tip,
2146 'launder for new upstream';
2148 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2149 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2150 "debrebase new-upstream $new_version: rebase";
2152 # now it's for the user to sort out
2155 sub cmd_record_ffq_prev () {
2156 badusage "no arguments allowed" if @ARGV;
2157 my ($status, $msg) = record_ffq_prev_deferred();
2158 if ($status eq 'exists' && $opt_noop_ok) {
2159 print "Previous head already recorded\n" or die $!;
2160 } elsif ($status eq 'deferred') {
2161 run_deferred_updates 'record-ffq-prev';
2163 fail "Could not preserve: $msg";
2168 badusage "no arguments allowed" if @ARGV;
2169 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2170 print "$bw\n" or die $!;
2173 sub cmd_breakwater () {
2174 badusage "no arguments allowed" if @ARGV;
2175 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2176 print "$bw\n" or die $!;
2180 badusage "no arguments allowed" if @ARGV;
2182 # todo: gdr status should print divergence info
2183 # todo: gdr status should print upstream component(s) info
2184 # todo: gdr should leave/maintain some refs with this kind of info ?
2186 my $oldest = { Badness => 0 };
2189 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2190 if ($oldest->{Badness} < $badness) {
2191 $oldest = $newest = undef;
2194 Badness => $badness,
2195 CommitId => $cl->{CommitId},
2199 $newest //= $oldest;
2201 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2202 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2203 sub { $note->(2, 'branch is unlaundered', @_); },
2204 sub { $note->(3, 'branch needs laundering', @_); },
2205 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2207 my $prcommitinfo = sub {
2209 flush STDOUT or die $!;
2210 runcmd @git, qw(--no-pager log -n1),
2211 '--pretty=format: %h %s%n',
2215 print "current branch contents, in git-debrebase terms:\n";
2216 if (!$oldest->{Badness}) {
2217 print " branch is laundered\n";
2219 print " $oldest->{OurMsg}\n";
2221 foreach my $info ($oldest, $newest) {
2222 my $cid = $info->{CommitId};
2223 next if $cid eq $printed;
2225 print " $info->{KcMsg}\n";
2226 $prcommitinfo->($cid);
2231 my ($cid, $what) = @_;
2232 if (!defined $cid) {
2233 print " $what is not well-defined\n";
2236 $prcommitinfo->($cid);
2239 print "key git-debrebase commits:\n";
2240 $prab->($anchor, 'anchor');
2241 $prab->($bw, 'breakwater');
2243 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2244 ffq_prev_branchinfo();
2246 print "branch and ref status, in git-debrebase terms:\n";
2248 print " $ffq_msg\n";
2250 $ffq_prev = git_get_ref $ffq_prev;
2251 $gdrlast = git_get_ref $gdrlast;
2253 print " unstitched; previous tip was:\n";
2254 $prcommitinfo->($ffq_prev);
2255 } elsif (!$gdrlast) {
2256 print " stitched? (no record of git-debrebase work)\n";
2257 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2258 print " stitched\n";
2260 print " not git-debrebase (diverged since last stitch)\n"
2263 print "you are currently rebasing\n" if currently_rebasing();
2267 my $prose = 'stitch';
2268 getoptions("stitch",
2269 'prose=s', \$prose);
2270 badusage "no arguments allowed" if @ARGV;
2271 do_stitch $prose, 0;
2273 sub cmd_prepush () { cmd_stitch(); }
2276 badusage "no arguments allowed" if @ARGV;
2277 do_launder_head 'launder for git-debrebase quick';
2281 sub cmd_conclude () {
2282 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2283 if (!$ffq_prev_commitish) {
2284 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2287 my $dangling_head = get_head();
2289 badusage "no arguments allowed" if @ARGV;
2290 do_launder_head 'launder for git-debrebase quick';
2295 if (currently_rebasing()) {
2296 runcmd @git, qw(rebase --abort);
2297 push @deferred_updates, 'verify HEAD HEAD';
2298 # noop, but stops us complaining that scrap was a noop
2300 badusage "no arguments allowed" if @ARGV;
2301 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2303 if ($ffq_prev_commitish) {
2304 $scrapping_head = get_head();
2305 push @deferred_updates,
2306 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2307 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2309 if (git_get_ref $merge_cache_ref) {
2310 push @deferred_updates,
2311 "delete $merge_cache_ref";
2313 if (!@deferred_updates) {
2314 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2318 if ($scrapping_head) {
2319 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2321 run_deferred_updates "scrap";
2325 sub make_patches_staged ($) {
2327 # Produces the patches that would result from $head if it were
2329 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2332 gbp_pq_export 'bw', $secret_bw, $secret_head;
2336 sub make_patches ($) {
2338 keycommits $head, 0, \&snag;
2339 make_patches_staged $head;
2342 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2343 runcmd @git, qw(read-tree), $head;
2344 read_tree_subdir 'debian/patches', $ptree;
2345 $out = make_commit [$head], [
2346 'Commit patch queue (exported by git-debrebase)',
2347 '[git-debrebase: export and commit patches]',
2353 sub cmd_make_patches () {
2354 my $opt_quiet_would_amend;
2355 getoptions("make-patches",
2356 'quiet-would-amend!', \$opt_quiet_would_amend);
2357 badusage "no arguments allowed" if @ARGV;
2359 my $old_head = get_head();
2360 my $new = make_patches $old_head;
2361 my $d = get_differs $old_head, $new;
2363 fail "No (more) patches to export." unless $opt_noop_ok;
2365 } elsif ($d == D_PAT_ADD) {
2367 update_head_checkout $old_head, $new, 'make-patches';
2369 print STDERR failmsg
2370 "Patch export produced patch amendments".
2371 " (abandoned output commit $new).".
2372 " Try laundering first."
2373 unless $opt_quiet_would_amend;
2378 sub cmd_convert_from_gbp () {
2379 badusage "want only 1 optional argument, the upstream git commitish"
2382 my $clogp = parsechangelog();
2383 my $version = $clogp->{'Version'}
2384 // die "missing Version from changelog";
2386 my ($upstream_spec) = @ARGV;
2388 my $upstream_version = upstreamversion $version;
2390 resolve_upstream_version($upstream_spec, $upstream_version);
2392 my $old_head = get_head();
2394 my $upsdiff = get_differs $upstream, $old_head;
2395 if ($upsdiff & D_UPS) {
2396 runcmd @git, qw(--no-pager diff --stat),
2397 $upstream, $old_head,
2398 qw( -- :!/debian :/);
2400 upstream ($upstream_spec) and HEAD are not
2401 identical in upstream files. See diffstat above, or run
2402 git diff $upstream_spec HEAD -- :!/debian :/
2406 if (!is_fast_fwd $upstream, $old_head) {
2407 snag 'upstream-not-ancestor',
2408 "upstream ($upstream) is not an ancestor of HEAD";
2410 my $wrong = cmdoutput
2411 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2412 qw(-- :/ :!/debian));
2413 if (length $wrong) {
2414 snag 'unexpected-upstream-changes',
2415 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2416 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2420 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2421 snag 'upstream-has-debian',
2422 "upstream ($upstream) contains debian/ directory";
2425 my $previous_dgit_view = eval {
2426 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2428 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2429 my ($stz, $desc) = @_;
2430 no warnings qw(exiting);
2431 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2432 next unless $stz->{Date};
2433 next unless $stz->{Distribution} ne 'UNRELEASED';
2434 $lvsn = $stz->{Version};
2435 $suite = $stz->{Distribution};
2438 die "neither of the first two changelog entries are released\n"
2439 unless defined $lvsn;
2440 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2441 my $mtag_pat = debiantag_maintview $lvsn, '*';
2442 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2444 die "could not find suitable maintainer view tag $mtag_pat\n"
2445 unless $mtag_pat =~ m{/};
2446 is_fast_fwd $mtag, 'HEAD' or
2447 die "HEAD is not FF from maintainer tag $mtag!";
2448 my $dtag = "archive/$mtag";
2449 is_fast_fwd $mtag, $dtag or
2450 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2451 print "will stitch in dgit view, $dtag\n";
2452 git_rev_parse $dtag;
2454 if (!$previous_dgit_view) {
2457 print STDERR "cannot stitch in dgit view: $@\n";
2460 snags_maybe_bail_early();
2466 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2467 # make a branch out of the patch queue - we'll want this in a mo
2468 runcmd qw(gbp pq import);
2469 # strip the patches out
2470 runcmd @git, qw(checkout -q gdr-internal~0);
2471 rm_subdir_cached 'debian/patches';
2472 $work = make_commit ['HEAD'], [
2473 'git-debrebase convert-from-gbp: drop patches from tree',
2474 'Delete debian/patches, as part of converting to git-debrebase format.',
2475 '[git-debrebase convert-from-gbp: drop patches from tree]'
2477 # make the anchor merge
2478 # the tree is already exactly right
2479 $work = make_commit [$work, $upstream], [
2480 'git-debrebase import: declare upstream',
2481 'First breakwater merge.',
2482 '[git-debrebase anchor: declare upstream]'
2485 # rebase the patch queue onto the new breakwater
2486 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2487 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2488 $work = git_rev_parse 'HEAD';
2490 if ($previous_dgit_view) {
2491 $work = make_commit [$work, $previous_dgit_view], [
2492 'git-debrebase import: declare ff from dgit archive view',
2493 '[git-debrebase pseudomerge: import-from-gbp]',
2500 update_head_checkout $old_head, $work, 'convert-from-gbp';
2503 sub cmd_convert_to_gbp () {
2504 badusage "no arguments allowed" if @ARGV;
2505 my $head = get_head();
2506 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2507 keycommits $head, 0;
2509 make_patches_staged $head;
2511 $out = make_commit ['HEAD'], [
2512 'Commit patch queue (converted from git-debrebase format)',
2513 '[git-debrebase convert-to-gbp: commit patches]',
2517 push @deferred_updates, "delete $ffq";
2518 push @deferred_updates, "delete $gdrlast";
2521 update_head_checkout $head, $out, "convert to gbp (v0)";
2522 print <<END or die $!;
2523 git-debrebase: converted to git-buildpackage branch format
2524 git-debrebase: WARNING: do not now run "git-debrebase" any more
2525 git-debrebase: WARNING: doing so would drop all upstream patches!
2529 sub cmd_convert_from_dgit_view () {
2530 my $clogp = parsechangelog();
2532 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2538 getoptions("convert-from-dgit-view",
2539 'diagnose!', \$diagnose,
2540 'build-products-dir:s', \$bpd,
2541 'origs!', \$do_origs,
2543 'always-convert-anyway!', \$always);
2544 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2549 my $spec = shift @ARGV;
2550 my $commit = git_rev_parse "$spec^{commit}";
2551 push @upstreams, { Commit => $commit,
2552 Source => "$ARGV[0], from command line",
2557 my $head = get_head();
2561 my $trouble = sub { $troubles++; };
2562 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2563 printdebug "troubles=$troubles\n";
2566 $us: Branch already seems to be in git-debrebase format!
2567 $us: --always-convert-anyway would do the conversion operation anyway
2568 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2570 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2575 snags_maybe_bail_early();
2577 my $version = upstreamversion $clogp->{Version};
2578 print STDERR "Considering possible commits corresponding to upstream:\n";
2583 my $ups_tag = upstream_commitish_search $version, \@tried;
2585 my $this = "git tag $tried[-1]";
2586 push @upstreams, { Commit => $ups_tag,
2591 " git tag: no suitable tag found (tried %s)\n",
2596 my $p = $clogp->{'Source'};
2597 # we do a quick check to see if there are plausible origs
2599 if (!opendir BPD, $bpd) {
2600 die "$bpd: opendir: $!" unless $!==ENOENT;
2602 while ($!=0, my $f = readdir BPD) {
2603 next unless is_orig_file_of_p_v $f, $p, $version;
2605 " orig: found what looks like a .orig, %s\n",
2610 die "read $bpd: $!" if $!;
2614 my $tree = cmdoutput
2615 @dgit, qw(--build-products-dir), $bpd,
2616 qw(print-unapplied-treeish);
2619 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2620 rm_subdir_cached 'debian';
2621 $tree = cmdoutput @git, qw(write-tree);
2622 my $ups_synth = make_commit [], [ <<END, <<END,
2623 Import effective orig tree for upstream version $version
2625 This includes the contents of the .orig(s), minus any debian/ directory.
2627 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2630 push @upstreams, { Commit => $ups_synth,
2631 Source => "orig(s) imported via dgit",
2636 " orig: no suitable origs found (looked for %s in %s)\n",
2637 "${p}_".(stripeoch $version)."...", $bpd;
2642 my $some_patches = stat_exists 'debian/patches/series';
2644 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2647 foreach my $u (@upstreams) {
2651 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2652 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2653 runcmd @git, qw(clean -xdff);
2654 runcmd @git, qw(checkout), $head, qw(-- debian);
2655 if ($some_patches) {
2656 rm_subdir_cached 'debian/patches';
2657 $work = make_commit [ $work ], [
2658 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2659 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2660 "to git-debrebase format. Upstream changes will appear as commits.",
2661 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2664 $work = make_commit [ $work, $u->{Commit} ], [
2665 'git-debrebase convert-from-dgit-view: declare upstream',
2666 '(Re)constructed breakwater merge.',
2667 '[git-debrebase anchor: declare upstream]'
2669 runcmd @git, qw(checkout --quiet -b mk), $work;
2670 if ($some_patches) {
2671 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2672 runcmd @git, qw(reset --quiet);
2673 my @gbp_cmd = (qw(gbp pq import));
2675 my $gbp_err = "../gbp-pq-err";
2676 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2678 my $r = system @gbp_cmd;
2681 " %s: couldn't apply patches: gbp pq %s",
2682 $u->{Source}, waitstatusmsg();
2686 my $work = git_rev_parse qw(HEAD);
2687 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2688 if (length $diffout) {
2690 " $u->{Source}: applying patches gives different tree\n";
2691 print STDERR $diffout if $diagnose;
2695 $u->{Result} = $work;
2703 Could not find or construct a suitable upstream commit.
2704 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2705 upstream commmit explicitly or provide suitable origs.
2709 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2711 ffq_check $result->{Result};
2713 update_head_checkout $head, $result->{Result},
2714 'convert-from-dgit-view';
2717 sub cmd_record_resolved_merge () {
2718 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2719 # xxx needs documentation
2720 my $new = get_head();
2723 print "Checking how you have resolved the merge problem\n";
2724 my $nope = sub { print "Not $method: @_"; 0; };
2726 my $maybe = sub { print "Seems to be $method.\n"; };
2728 my ($key, $ref) = @_;
2729 reflog_cache_insert $merge_cache_ref, $key, $ref;
2730 print "OK. You can switch branches and try git-debrebase again.\n";
2734 fresh_workarea 'merge';
2736 $method = 'vanilla-merge patchqueue';
2737 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2738 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2739 foreach my $lr (qw(left right)) {
2740 my $n = "$wrecknoteprefix/$lr-patchqueue";
2741 my $lrpq = git_get_ref $n;
2742 $lrpq or return $nope->("wreckage did not contain patchqueues");
2743 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2746 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2747 or die "wreckage element $wrecknoteprefix/new-base missing";
2748 my $result = merge_series_patchqueue_convert
2750 $yes->("vanilla-merge $vanilla", $result);
2753 fail "No resolved merge method seems applicable.\n";
2757 sub cmd_downstream_rebase_launder_v0 () {
2758 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2760 $base = git_rev_parse $base;
2761 my $old_head = get_head();
2762 my $current = $old_head;
2765 if ($current eq $base) {
2766 $topmost_keep //= $current;
2767 print " $current BASE stop\n";
2770 my $cl = classify $current;
2771 print " $current $cl->{Type}";
2773 my $p0 = $cl->{Parents}[0]{CommitId};
2775 if ($cl->{Type} eq 'Pseudomerge') {
2776 print " ^".($cl->{Contributor}{Ix}+1);
2777 $next = $cl->{Contributor}{CommitId};
2778 } elsif ($cl->{Type} eq 'AddPatches' or
2779 $cl->{Type} eq 'Changelog') {
2789 $topmost_keep //= $current;
2791 die "to-be stripped changes not on top of the branch\n"
2796 if ($topmost_keep eq $old_head) {
2797 print "unchanged\n";
2799 print "updating to $topmost_keep\n";
2800 update_head_checkout
2801 $old_head, $topmost_keep,
2802 'downstream-rebase-launder-v0';
2808 "D+" => \$debuglevel,
2809 'noop-ok', => \$opt_noop_ok,
2810 'f=s' => \@snag_force_opts,
2811 'anchor=s' => \@opt_anchors,
2812 '--dgit=s' => \($dgit[0]),
2815 my ($opt,$val) = @_;
2816 badusage "git-debrebase: no cuddling to -i for git-rebase"
2818 die if $opt_defaultcmd_interactive; # should not happen
2819 $opt_defaultcmd_interactive = [ qw(-i) ];
2820 # This access to @ARGV is excessive familiarity with
2821 # Getopt::Long, but there isn't another sensible
2822 # approach. '-i=s{0,}' does not work with bundling.
2823 push @$opt_defaultcmd_interactive, @ARGV;
2826 'help' => sub { print $usage_message or die $!; finish 0; },
2829 initdebug('git-debrebase ');
2830 enabledebug if $debuglevel;
2832 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2833 chdir $toplevel or die "chdir $toplevel: $!";
2835 $rd = fresh_playground "$playprefix/misc";
2837 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2839 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2840 defaultcmd_rebase();
2842 my $cmd = shift @ARGV;
2845 $cmdfn = ${*::}{"cmd_$cmdfn"};
2847 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";