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_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/ (not patches/ or changelog)
114 sub D_DEB_OTH () { 0x20; } # debian/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_differs ($$) {
186 # This resembles quiltify_trees_differ, in dgit, a bit.
187 # But we don't care about modes, or dpkg-source-unrepresentable
188 # changes, and we don't need the plethora of different modes.
189 # Conversely we need to distinguish different kinds of changes to
190 # debian/ and debian/patches/.
195 my ($opts, $limits, $fn) = @_;
196 my @cmd = (@git, qw(diff-tree -z --no-renames));
198 push @cmd, "$_:" foreach $x, $y;
199 push @cmd, '--', @$limits;
200 my $diffs = cmdoutput @cmd;
201 foreach (split /\0/, $diffs) { $fn->(); }
204 $rundiff->([qw(--name-only)], [], sub {
205 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
208 if ($differs & DS_DEB) {
210 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
212 m{^debian/patches/} ? D_PAT_OTH :
213 $_ eq 'debian/changelog' ? D_DEB_CLOG :
216 die "mysterious debian changes $x..$y"
217 unless $differs & (D_PAT_OTH|DS_DEB);
220 if ($differs & D_PAT_OTH) {
222 $differs &= ~D_PAT_OTH;
224 $differs |= D_PAT_OTH;
225 no warnings qw(exiting); last;
227 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
228 no warnings qw(exiting);
229 if (!defined $mode) {
232 die unless s{^debian/patches/}{};
234 if ($mode eq 'A' && !m/\.series$/s) {
236 } elsif ($mode eq 'M' && $_ eq 'series') {
237 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
238 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
239 chomp $x_s; $x_s .= "\n";
240 $ok = $x_s eq substr($y_s, 0, length $x_s);
245 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
247 die "mysterious debian/patches changes $x..$y"
248 unless $differs & (D_PAT_ADD|D_PAT_OTH);
251 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
256 sub commit_pr_info ($) {
258 return Data::Dumper->dump([$r], [qw(commit)]);
261 sub calculate_committer_authline () {
262 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
263 'DUMMY COMMIT (git-debrebase)', "HEAD:";
264 my ($h,$m) = get_commit $c;
265 $h =~ m/^committer .*$/m or confess "($h) ?";
269 sub rm_subdir_cached ($) {
271 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
274 sub read_tree_subdir ($$) {
275 my ($subdir, $new_tree_object) = @_;
276 rm_subdir_cached $subdir;
277 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
280 sub read_tree_debian ($) {
282 read_tree_subdir 'debian', "$treeish:debian";
283 rm_subdir_cached 'debian/patches';
286 sub read_tree_upstream ($;$$) {
287 my ($treeish, $keep_patches, $tree_with_debian) = @_;
288 # if $tree_with_debian is supplied, will use that for debian/
289 # otherwise will save and restore it.
291 $tree_with_debian ? "$tree_with_debian:debian"
292 : cmdoutput @git, qw(write-tree --prefix=debian/);
293 runcmd @git, qw(read-tree), $treeish;
294 read_tree_subdir 'debian', $debian;
295 rm_subdir_cached 'debian/patches' unless $keep_patches;
298 sub make_commit ($$) {
299 my ($parents, $message_paras) = @_;
300 my $tree = cmdoutput @git, qw(write-tree);
301 my @cmd = (@git, qw(commit-tree), $tree);
302 push @cmd, qw(-p), $_ foreach @$parents;
303 push @cmd, qw(-m), $_ foreach @$message_paras;
304 return cmdoutput @cmd;
307 our @snag_force_opts;
309 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
310 if (grep { $_ eq $tag } @snag_force_opts) {
312 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
315 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
319 # Important: all mainline code must call snags_maybe_bail after
320 # any point where snag might be called, but before making changes
321 # (eg before any call to run_deferred_updates). snags_maybe_bail
322 # may be called more than once if necessary (but this is not ideal
323 # because then the messages about number of snags may be confusing).
324 sub snags_maybe_bail () {
325 return if all_snags_summarised();
328 "%s: snags: %d overriden by individual -f options\n",
331 if ($snags_tripped) {
334 "%s: snags: %d overriden by global --force\n",
338 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
342 $snags_summarised = $snags_forced + $snags_tripped;
344 sub snags_maybe_bail_early () {
345 # useful to bail out early without doing a lot of work;
346 # not a substitute for snags_maybe_bail.
347 snags_maybe_bail() if $snags_tripped && !$opt_force;
350 return $snags_forced || $snags_tripped;
353 sub gbp_pq_export ($$$) {
354 my ($bname, $base, $tip) = @_;
355 # must be run in a workarea. $bname and patch-queue/$bname
356 # ought not to exist. Leaves you on patch-queue/$bname with
357 # the patches staged but not committed.
358 printdebug "gbp_pq_export $bname $base $tip\n";
359 runcmd @git, qw(checkout -q -b), $bname, $base;
360 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
361 my @gbp_cmd = (qw(gbp pq export));
362 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
364 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
367 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
371 # xxx allow merge resolution separately from laundering, before git merge
373 # xxx general gdr docs highlight forbidden things
374 # xxx general gdr docs list allowable things ?
375 # xxx general gdr docs explicitly forbid some rebase
377 # xxx provide a way for the user to help
378 # xxx (eg, provide wreckage provide way to continue)
381 # use git-format-patch?
382 # our own patch identification algorithm?
383 # this is an alternative strategy
385 sub merge_failed ($$;@) {
386 my ($wrecknotes, $emsg, @xmsgs) = @_;
388 push @m, "Merge resolution failed: $emsg";
394 merge_wreckage_cleaning \@updates;
395 run_ref_updates_now "merge failed", \@updates;
399 while (my ($k,$v) = each %$wrecknotes) {
400 push @updates, "create $wrecknoteprefix/$k $v";
402 run_ref_updates_now "merge failed", \@updates;
403 push @m, "Wreckage left in $wrecknoteprefix/*.";
405 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
407 # use finish rather than fail, in case we are within an eval
408 # (that can happen inside walk!)
410 print STDERR "$us: $_\n" foreach @m;
414 sub mwrecknote ($$$) {
415 my ($wrecknotes, $reftail, $commitish) = @_;
416 confess unless defined $commitish;
417 printdebug "mwrecknote $reftail $commitish\n";
418 $wrecknotes->{$reftail} = $commitish;
421 sub merge_attempt_cmd {
422 my $wrecknotes = shift @_;
426 merge_failed $wrecknotes,
427 failedcmd_waitstatus(),
428 "failed command: @_";
432 sub merge_series_patchqueue_convert ($$$);
434 sub merge_series ($$$;@) {
435 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
436 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
437 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
438 # ^ specifies several patch series (currently we only support exactly 2)
439 # return value is a commit which is the result of
440 # merging the two versions of the same topic branch
441 # $input_q[0] and $input_q[1]
442 # with respect to the old version
446 # Creates, in *_q, a key MR for its private use
448 printdebug "merge_series newbase=$newbase\n";
450 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
451 $base_q->{MR}{S} = 'base';
454 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
455 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
456 # $prereq{<patch filename>} exists or not (even later)
460 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
462 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
465 fresh_workarea "merge";
466 my $seriesfile = "debian/patches/series";
469 foreach my $q ($base_q, reverse @input_qs) {
471 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
473 if (open S, $seriesfile) {
474 while (my $patch = <S>) {
475 chomp $patch or die $!;
476 $prereq{$patch} //= {};
477 foreach my $earlier (@earlier) {
478 $prereq{$patch}{$earlier}{$s}++ and die;
480 push @earlier, $patch;
481 stat "debian/patches/$patch" or die "$patch ?";
483 S->error and die "$seriesfile $!";
486 die "$seriesfile $!" unless $!==ENOENT;
488 read_tree_upstream $newbase, 1;
489 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
490 "Convert $s to patch queue for merging",
491 "[git-debrebase merge-innards patch-queue import:".
494 printdebug "merge_series pec $pec ";
495 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
496 $pec = make_commit [ $pec ], [
497 "Drop series file from $s to avoid merge trouble",
498 "[git-debrebase merge-innards patch-queue prep:".
502 read_tree_debian $newbase;
504 read_tree_subdir 'debian/patches', "$pec:debian/patches";
506 rm_subdir_cached 'debian/patches';
508 $pec = make_commit [ $pec ], [
509 "Update debian/ (excluding patches) to final to avoid re-merging",
510 "debian/ was already merged and we need to just take that.",
511 "[git-debrebase merge-innards patch-queue packaging:".
515 printdebug "pec' $pec\n";
516 runcmd @git, qw(reset -q --hard), $pec;
517 $q->{MR}{PEC} = $pec;
518 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
520 # now, because of reverse, we are on $input_q->{MR}{OQC}
521 runcmd @git, qw(checkout -q -b merge);
522 printdebug "merge_series merging...\n";
523 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
525 $attempt_cmd->(@mergecmd);
527 printdebug "merge_series merge ok, series...\n";
528 # We need to construct a new series file
529 # Firstly, resolve prereq
530 foreach my $f (sort keys %prereq) {
531 printdebug "merge_series patch\t$f\t";
532 if (!stat_exists "debian/patches/$f") {
533 print DEBUG " drop\n" if $debuglevel;
534 # git merge deleted it; that's how we tell it's not wanted
538 print DEBUG " keep\n" if $debuglevel;
539 foreach my $g (sort keys %{ $prereq{$f} }) {
540 my $gfp = $prereq{$f}{$g};
541 printdebug "merge_series prereq\t$f\t-> $g\t";
542 if (!!$gfp->{0} == !!$gfp->{1}
545 print DEBUG "\tkeep\n" if $debuglevel;
547 print DEBUG "\tdrop\n" if $debuglevel;
548 delete $prereq{$f}{$g};
555 return scalar keys %{ $prereq{$f} };
558 my $nodate = time + 1;
560 # $authordate{<patch filename>};
561 my $authordate = sub {
563 $authordate{$f} //= do {
564 open PF, "<", "debian/patches/$f" or die "$f $!";
566 return $nodate if m/^$/;
567 last if s{^Date: }{};
570 return cmdoutput qw(date +%s -d), $_;
574 open NS, '>', $seriesfile or die $!;
576 while (keys %prereq) {
578 foreach my $try (sort keys %prereq) {
581 $unsat->($try) <=> $unsat->($best) or
582 $authordate->($try) <=> $authordate->($best) or
588 printdebug "merge_series series next $best\n";
589 print NS "$best\n" or die $!;
590 delete $prereq{$best};
591 foreach my $gp (values %prereq) {
596 runcmd @git, qw(add), $seriesfile;
597 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
598 $merged_pq = git_rev_parse 'HEAD';
599 $mwrecknote->('merged-patchqueue', $merged_pq);
601 return merge_series_patchqueue_convert
602 $wrecknotes, $newbase, $merged_pq;
605 sub merge_series_patchqueue_convert ($$$) {
606 my ($wrecknotes, $newbase, $merged_pq) = @_;
611 printdebug "merge_series series gbp pq import\n";
612 runcmd @git, qw(checkout -q -b mergec), $merged_pq;
614 merge_attempt_cmd($wrecknotes, qw(gbp pq import));
616 # OK now we are on patch-queue/merge, and we need to rebase
617 # onto the intended parent and drop the patches from each one
619 printdebug "merge_series series ok, building...\n";
620 my $build = $newbase;
621 my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
622 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
623 my $commit = git_cat_file $c, 'commit';
624 printdebug "merge_series series ok, building $c\n";
625 read_tree_upstream $c, 0, $newbase;
626 my $tree = cmdoutput @git, qw(write-tree);
627 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
628 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
629 open C, ">", "../mcommit" or die $!;
630 print C $commit or die $!;
632 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
635 mwrecknote($wrecknotes, 'merged-result', $result);
637 runcmd @git, qw(update-ref refs/heads/result), $result;
639 runcmd @git, qw(checkout -q -b debug);
640 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
641 runcmd @git, qw(add .);
642 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
643 my $mdebug = git_rev_parse 'HEAD';
644 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
645 mwrecknote($wrecknotes, 'merged-debug', $mdebug);
647 printdebug "merge_series returns $result\n";
651 # classify returns an info hash like this
653 # Hdr => # commit headers, including 1 final newline
654 # Msg => # commit message (so one newline is dropped)
656 # Type => (see below)
658 # Ix => $index # ie 0, 1, 2, ...
660 # Differs => return value from get_differs
662 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
664 # NewMsg => # commit message, but with any [dgit import ...] edited
665 # # to say "[was: ...]"
675 # has additional entres in classification result
676 # Overwritten = [ subset of Parents ]
677 # Contributor = $the_remaining_Parent
679 # DgitImportUnpatched
680 # has additional entry in classification result
681 # OrigParents = [ subset of Parents ]
684 # has additional entry in classification result
685 # OrigParents = [ subset of Parents ] # singleton list
692 # has additional entry in classification result
695 sub parsecommit ($;$) {
696 my ($objid, $p_ref) = @_;
697 # => hash with CommitId Hdr Msg Tree Parents
698 # Parents entries have only Ix CommitId
699 # $p_ref, if provided, must be [] and is used as a base for Parents
704 my ($h,$m) = get_commit $objid;
706 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
707 my (@ph) = $h =~ m/^parent (\w+)$/mg;
717 foreach my $ph (@ph) {
719 Ix => scalar @$p_ref,
731 my $r = parsecommit($objid, \@p);
735 $p->{Differs} = (get_differs $p->{CommitId}, $t),
738 printdebug "classify $objid \$t=$t \@p",
739 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
743 my ($type, @rest) = @_;
744 $r = { %$r, Type => $type, @rest };
746 printdebug " = $type ".(dd $r)."\n";
752 $r = { %$r, Type => qw(Unknown), Why => $why };
753 printdebug " ** Unknown\n";
757 if (grep { $_ eq $objid } @opt_anchors) {
758 return $classify->('TreatAsAnchor');
761 my @identical = grep { !$_->{Differs} } @p;
762 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
763 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
765 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
766 # multi-orig upstreams are represented with an anchor merge
767 # from a single upstream commit which combines the orig tarballs
769 # Every anchor tagged this way must be a merge.
770 # We are relying on the
771 # [git-debrebase anchor: ...]
772 # commit message annotation in "declare" anchor merges (which
773 # do not have any upstream changes), to distinguish those
774 # anchor merges from ordinary pseudomerges (which we might
775 # just try to strip).
777 # However, the user is going to be doing git-rebase a lot. We
778 # really don't want them to rewrite an anchor commit.
779 # git-rebase trips up on merges, so that is a useful safety
782 # BreakwaterStart commits are also anchors in the terminology
783 # of git-debrebase(5), but they are untagged (and always
784 # manually generated).
786 # We cannot not tolerate any tagged linear commit (ie,
787 # BreakwaterStart commits tagged `[anchor:') because such a
788 # thing could result from an erroneous linearising raw git
789 # rebase of a merge anchor. That would represent a corruption
790 # of the branch. and we want to detect and reject the results
791 # of such corruption before it makes it out anywhere. If we
792 # reject it here then we avoid making the pseudomerge which
793 # would be needed to push it.
795 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
796 @p == 2 or return $badanchor->("has other than two parents");
797 $haspatches and return $badanchor->("contains debian/patches");
799 # How to decide about l/r ordering of anchors ? git
800 # --topo-order prefers to expand 2nd parent first. There's
801 # already an easy rune to look for debian/ history anyway (git log
802 # debian/) so debian breakwater branch should be 1st parent; that
803 # way also there's also an easy rune to look for the upstream
804 # patches (--topo-order).
806 # Also this makes --first-parent be slightly more likely to
807 # be useful - it makes it provide a linearised breakwater history.
809 # Of course one can say somthing like
810 # gitk -- ':/' ':!/debian'
811 # to get _just_ the commits touching upstream files, and by
812 # the TREESAME logic in git-rev-list this will leave the
813 # breakwater into upstream at the first anchor. But that
814 # doesn't report debian/ changes at all.
816 # Other observations about gitk: by default, gitk seems to
817 # produce output in a different order to git-rev-list. I
818 # can't seem to find this documented anywhere. gitk
819 # --date-order DTRT. But, gitk always seems to put the
820 # parents from left to right, in order, so it's easy to see
821 # which way round a pseudomerge is.
823 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
824 $p[1]{Differs} & ~DS_DEB and
825 $badanchor->("upstream files differ from left parent");
826 $p[0]{Differs} & ~D_UPS and
827 $badanchor->("debian/ differs from right parent");
829 return $classify->(qw(Anchor),
830 OrigParents => [ $p[1] ]);
834 my $d = $r->{Parents}[0]{Differs};
835 if ($d == D_PAT_ADD) {
836 return $classify->(qw(AddPatches));
837 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
838 return $unknown->("edits debian/patches");
839 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
840 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
842 if ($d == D_DEB_CLOG) {
843 return $classify->(qw(Changelog));
845 return $classify->(qw(Packaging));
847 } elsif ($ty eq 'missing') {
848 return $classify->(qw(BreakwaterStart));
850 return $unknown->("parent's debian is not a directory");
852 } elsif ($d == D_UPS) {
853 return $classify->(qw(Upstream));
854 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
855 return $classify->(qw(Mixed));
857 return $unknown->("no changes");
859 confess "internal error $objid ?";
863 return $unknown->("origin commit");
866 if (@p == 2 && @identical == 1) {
867 my @overwritten = grep { $_->{Differs} } @p;
868 confess "internal error $objid ?" unless @overwritten==1;
869 return $classify->(qw(Pseudomerge),
870 Overwritten => [ $overwritten[0] ],
871 Contributor => $identical[0]);
873 if (@p == 2 && @identical == 2) {
875 my ($ph,$pm) = get_commit $_[0]{CommitId};
876 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
880 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
881 if ($order > 0) { # newer first
882 } elsif ($order < 0) {
883 @bytime = reverse @bytime;
885 # same age, default to order made by -s ours
886 # that is, commit was made by someone who preferred L
888 return $classify->(qw(Pseudomerge),
889 SubType => qw(Ambiguous),
890 Contributor => $bytime[0],
891 Overwritten => [ $bytime[1] ]);
894 my ($p_h, $p_m) = get_commit $p->{CommitId};
895 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
896 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
898 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
900 if (!(grep { !$_->{IsOrigin} } @p) and
901 (@orig_ps >= @p - 1) and
902 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
904 return $classify->(qw(DgitImportUnpatched),
905 OrigParents => \@orig_ps);
909 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
910 # xxx ^ metadata tag needs adding to (5)
911 return $classify->("MergedBreakwaters");
913 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
914 return $unknown->("unknown kind of merge from $1");
917 return $unknown->("octopus merge");
920 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
921 return $unknown->("general two-parent merge");
924 return $classify->("VanillaMerge");
927 sub keycommits ($;$$$$$);
929 sub mergedbreakwaters_anchor ($) {
932 foreach my $p (@{ $cl->{Parents} }) {
933 my ($panchor, $pbw) = keycommits $p->{CommitId},
934 undef,undef,undef,undef, 1;
935 $best_anchor = $panchor
936 if !defined $best_anchor
937 or is_fast_fwd $best_anchor, $panchor;
938 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
939 unless is_fast_fwd $panchor, $best_anchor;
944 sub keycommits ($;$$$$$) {
945 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
946 # => ($anchor, $breakwater)
948 # $unclean->("unclean-$tagsfx", $msg, $cl)
949 # $furniture->("unclean-$tagsfx", $msg, $cl)
950 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
951 # is callled for each situation or commit that
952 # wouldn't be found in a laundered branch
953 # $furniture is for furniture commits such as might be found on an
954 # interchange branch (pseudomerge, d/patches, changelog)
955 # $trouble is for things whnich prevent the return of
956 # anchor and breakwater information; if that is ignored,
957 # then keycommits returns (undef, undef) instead.
958 # $fatal is for unprocessable commits, and should normally cause
959 # a failure. If ignored, agaion, (undef, undef) is returned.
961 # If $claimed_bw, this is supposed to be a breakwater commit.
963 # If a callback is undef, fail is called instead.
964 # If a callback is defined but false, the situation is ignored.
966 # no warnings qw(exiting); last;
967 # if the answer is no longer wanted.
969 my ($anchor, $breakwater);
970 $breakwater = $head if $claimed_bw;
974 $fatal //= sub { fail $_[1]; };
976 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
977 my $why = $mainwhy.$xwhy;
978 my $m = "branch needs laundering (run git-debrebase): $why";
979 fail $m unless defined $cb;
981 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
983 my $found_anchor = sub {
985 $breakwater //= $clogonly;
986 $breakwater //= $head;
987 no warnings qw(exiting);
991 $cl = classify $head;
992 my $ty = $cl->{Type};
993 if ($ty eq 'Packaging') {
994 $breakwater //= $clogonly;
995 $breakwater //= $head;
996 } elsif ($ty eq 'Changelog') {
997 # this is going to count as the tip of the breakwater
998 # only if it has no upstream stuff before it
1000 } elsif ($ty eq 'Anchor' or
1001 $ty eq 'TreatAsAnchor' or
1002 $ty eq 'BreakwaterStart') {
1003 $found_anchor->($head);
1004 } elsif ($ty eq 'Upstream') {
1005 $x->($unclean, 'ordering',
1006 "packaging change ($breakwater) follows upstream change"," (eg $head)")
1007 if defined $breakwater;
1009 $breakwater = undef;
1010 } elsif ($ty eq 'Mixed') {
1011 $x->($unclean, 'mixed',
1012 "found mixed upstream/packaging commit"," ($head)");
1014 $breakwater = undef;
1015 } elsif ($ty eq 'Pseudomerge' or
1016 $ty eq 'AddPatches') {
1018 $x->($furniture, (lc $ty),
1019 "found interchange bureaucracy commit ($ty)"," ($head)");
1020 } elsif ($ty eq 'DgitImportUnpatched') {
1022 $x->($trouble, 'dgitimport',
1023 "found dgit dsc import"," ($head)");
1024 return (undef,undef);
1026 $x->($fatal, 'unprocessable',
1027 "found bare dgit dsc import with no prior history",
1029 return (undef,undef);
1031 } elsif ($ty eq 'VanillaMerge') {
1032 $x->($trouble, 'vanillamerge',
1033 "found vanilla merge"," ($head)");
1034 return (undef,undef);
1035 } elsif ($ty eq 'MergedBreakwaters') {
1036 $found_anchor->(mergedbreakwaters_anchor $cl);
1038 $x->($fatal, 'unprocessable',
1039 "found unprocessable commit, cannot cope: $cl->{Why}",
1041 return (undef,undef);
1043 $head = $cl->{Parents}[0]{CommitId};
1045 return ($anchor, $breakwater);
1051 $nogenerate,$report, $report_lprefix) = @_;
1052 # => ($tip, $breakwater_tip, $last_anchor)
1053 # (or nothing, if $nogenerate)
1055 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1056 $report_lprefix //= '';
1058 # go through commits backwards
1059 # we generate two lists of commits to apply:
1060 # breakwater branch and upstream patches
1061 my (@brw_cl, @upp_cl, @processed);
1068 my ($prose, $info) = @_;
1069 my $ms = $cl->{Msg};
1072 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1073 return (Msg => $ms);
1075 my $rewrite_from_here = sub {
1077 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1079 push @processed, $sp_cl;
1084 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1087 return unless $report;
1088 print $report $prdelim, $report_lprefix, @_;
1092 my $bomb = sub { # usage: return $bomb->();
1093 print $report " Unprocessable" if $report;
1094 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1097 return (undef,undef);
1099 fail "found unprocessable commit, cannot cope".
1100 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1101 " (commit $cur) (d.".
1102 (join ' ', map { sprintf "%#x", $_->{Differs} }
1103 @{ $cl->{Parents} }).
1110 my $build_start = sub {
1111 my ($msg, $parent) = @_;
1114 no warnings qw(exiting); last;
1119 merge_failed $cl->{MergeWreckNotes}, $emsg;
1122 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1127 $cl = classify $cur;
1128 $cl->{MergeWreckNotes} //= {};
1129 my $ty = $cl->{Type};
1130 my $st = $cl->{SubType};
1131 $prline->("$cl->{CommitId} $cl->{Type}");
1132 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1133 push @processed, $cl;
1134 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1135 if ($ty eq 'AddPatches') {
1137 $rewrite_from_here->(\@upp_cl);
1139 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1143 } elsif ($ty eq 'BreakwaterStart') {
1144 $last_anchor = $cur;
1145 $build_start->('FirstPackaging', $cur);
1146 } elsif ($ty eq 'Upstream') {
1150 } elsif ($ty eq 'Mixed') {
1153 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1156 $queue->(\@brw_cl, "debian");
1157 $queue->(\@upp_cl, "upstream");
1158 $rewrite_from_here->(\@brw_cl);
1161 } elsif ($ty eq 'Pseudomerge') {
1162 my $contrib = $cl->{Contributor}{CommitId};
1163 print $report " Contributor=$contrib" if $report;
1164 push @pseudomerges, $cl;
1165 $rewrite_from_here->(\@upp_cl);
1168 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1169 $last_anchor = $cur;
1170 $build_start->("Anchor", $cur);
1171 } elsif ($ty eq 'DgitImportUnpatched') {
1172 my $pm = $pseudomerges[-1];
1174 # To an extent, this is heuristic. Imports don't have
1175 # a useful history of the debian/ branch. We assume
1176 # that the first pseudomerge after an import has a
1177 # useful history of debian/, and ignore the histories
1178 # from later pseudomerges. Often the first pseudomerge
1179 # will be the dgit import of the upload to the actual
1180 # suite intended by the non-dgit NMUer, and later
1181 # pseudomerges may represent in-archive copies.
1182 my $ovwrs = $pm->{Overwritten};
1183 printf $report " PM=%s \@Overwr:%d",
1184 $pm->{CommitId}, (scalar @$ovwrs)
1187 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1190 my $ovwr = $ovwrs->[0]{CommitId};
1191 printf $report " Overwr=%s", $ovwr if $report;
1192 # This import has a tree which is just like a
1193 # breakwater tree, but it has the wrong history. It
1194 # ought to have the previous breakwater (which the
1195 # pseudomerge overwrote) as an ancestor. That will
1196 # make the history of the debian/ files correct. As
1197 # for the upstream version: either it's the same as
1198 # was ovewritten (ie, same as the previous
1199 # breakwater), in which case that history is precisely
1200 # right; or, otherwise, it was a non-gitish upload of a
1201 # new upstream version. We can tell these apart by
1202 # looking at the tree of the supposed upstream.
1205 SpecialMethod => 'DgitImportDebianUpdate',
1206 $xmsg->("convert dgit import: debian changes")
1209 SpecialMethod => 'DgitImportUpstreamUpdate',
1210 $xmsg->("convert dgit import: upstream update",
1213 $prline->(" Import");
1214 $rewrite_from_here->(\@brw_cl);
1215 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1219 # Everything is from this import. This kind of import
1220 # is already nearly in valid breakwater format, with the
1221 # patches as commits. Unfortunately it contains
1223 printdebug "*** WALK BOMB bare dgit import\n";
1224 $cl->{Why} = "bare dgit dsc import";
1228 } elsif ($ty eq 'MergedBreakwaters') {
1229 $last_anchor = mergedbreakwaters_anchor $cl;
1230 $build_start->(' MergedBreakwaters', $cur);
1232 } elsif ($ty eq 'VanillaMerge') {
1233 # User may have merged unstitched branch(es). We will
1234 # have now lost what ffq-prev was then (since the later
1235 # pseudomerge may introduce further changes). The effect
1236 # of resolving such a merge is that we may have to go back
1237 # further in history to find a merge base, since the one
1238 # which was reachable via ffq-prev is no longer findable.
1239 # This is suboptimal, but if it all works we'll have done
1241 # xxx we should warn the user in the docs about this
1245 # We expect to find a dominating anchor amongst the
1246 # inputs' anchors. That will be the new anchor.
1248 # More complicated is finding a merge base for the
1249 # breakwaters. We need a merge base that is a breakwater
1250 # commit. The ancestors of breakwater commits are more
1251 # breakwater commits and possibly upstream commits and the
1252 # ancestors of those upstream. Upstreams might have
1253 # arbitrary ancestors. But any upstream commit U is
1254 # either included in both anchors, in which case the
1255 # earlier anchor is a better merge base than any of U's
1256 # ancestors; or U is not included in the older anchor, in
1257 # which case U is not an ancestor of the vanilla merge at
1258 # all. So no upstream commit, nor any ancestor thereof,
1259 # is a best merge base. As for non-breakwater Debian
1260 # commits: these are never ancestors of any breakwater.
1262 # So any best merge base as found by git-merge-base
1263 # is a suitable breakwater anchor. Usually there will
1266 printdebug "*** MERGE\n";
1268 my @bwbcmd = (@git, qw(merge-base));
1269 my @ibcmd = (@git, qw(merge-base --all));
1270 my $might_be_in_bw = 1;
1272 my $ps = $cl->{Parents};
1274 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1276 foreach my $p (@$ps) {
1277 $prline->(" VanillaMerge ".$p->{Ix});
1279 my ($ptip, $pbw, $panchor) =
1280 walk $p->{CommitId}, 0, $report,
1281 $report_lprefix.' ';
1282 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1283 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1284 $p->{Anchor} = $panchor;
1286 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1287 $mwrecknote->("$lr-input", $p->{CommitId});
1289 my $mwrecknote_parent = sub {
1291 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1293 $mwrecknote_parent->('Laundered');
1294 $mwrecknote_parent->('Breakwater');
1295 $mwrecknote_parent->('Anchor');
1297 $best_anchor = $panchor if
1298 !defined $best_anchor or
1299 is_fast_fwd $best_anchor, $panchor;
1301 printdebug " MERGE BA best=".($best_anchor//'-').
1305 $mwrecknote->('result-anchor', $best_anchor);
1307 foreach my $p (@$ps) {
1308 $prline->(" VanillaMerge ".$p->{Ix});
1309 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1310 $nomerge->('divergent anchors');
1311 } elsif ($p->{Anchor} eq $best_anchor) {
1312 print $report " SameAnchor" if $report;
1314 print $report " SupersededAnchor" if $report;
1316 if ($p->{Breakwater} eq $p->{CommitId}) {
1317 # this parent commit was its own breakwater,
1318 # ie it is part of the breakwater
1319 print $report " Breakwater" if $report;
1321 $might_be_in_bw = 0;
1323 push @bwbcmd, $p->{Breakwater};
1324 push @ibcmd, $p->{CommitId};
1327 if ($ok && $might_be_in_bw) {
1328 # We could rewrite this to contaion the metadata
1329 # declaring it to be MergedBreakwaters, but
1330 # unnecessarily rewriting a merge seems unhelpful.
1331 $prline->(" VanillaMerge MergedBreakwaters");
1332 $last_anchor = $best_anchor;
1333 $build_start->('MergedBreakwaters', $cur);
1336 my $bwb = cmdoutput @bwbcmd;
1338 # OK, now we have a breakwater base, but we need the merge
1339 # base for the interchange branch because we need the delta
1342 # This a the best merge base of our inputs which has the
1343 # breakwater merge base as an ancestor.
1350 @ibs or confess 'internal error, expected anchor at least ?';
1354 foreach my $tibix (0..$#ibs) {
1355 my $tib = $ibs[$tibix];
1356 my $ff = is_fast_fwd $bwb, $tib;
1357 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1358 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1359 $mwrecknote->($tibleaf, $tib);
1366 $ib or $nomerge->("no suitable interchange merge base");
1368 $prline->(" VanillaMerge Base");
1370 my ($btip, $bbw, $banchor) = eval {
1371 walk $ib, 0, $report, $report_lprefix.' ';
1373 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1377 $mwrecknote->("mergebase-laundered", $btip);
1378 $mwrecknote->("mergebase-breakwater", $bbw);
1379 $mwrecknote->("mergebase-anchor", $banchor);
1381 my $ibinfo = { SeriesTip => $btip,
1384 LeftRight => 'mergebase' };
1387 or $nomerge->("interchange merge-base ($ib)'s".
1388 " breakwater ($bbw)".
1389 " != breakwaters' merge-base ($bwb)");
1391 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1392 or $nomerge->("interchange merge-base ($ib)'s".
1393 " anchor ($ibinfo->{SeriesBase})".
1394 " != any merge input's anchor (".
1395 (join ' ', map { $_->{Anchor} } @$ps).
1398 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1399 $cl->{MergeBestAnchor} = $best_anchor;
1402 SpecialMethod => 'MergeCreateMergedBreakwaters',
1403 $xmsg->('constructed from vanilla merge',
1404 ' merged-breakwater'),
1408 SpecialMethod => 'MergeMergeSeries',
1410 $build_start->('MergeBreakwaters', $cur);
1412 printdebug "*** WALK BOMB unrecognised\n";
1418 printdebug "*** WALK prep done cur=$cur".
1419 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1421 return if $nogenerate;
1423 # Now we build it back up again
1429 my $read_tree_upstream = sub {
1431 read_tree_upstream $treeish, 0, $build;
1434 $#upp_cl = $upp_limit if defined $upp_limit;
1436 my $committer_authline = calculate_committer_authline();
1438 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1440 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1443 mkdir $rd or $!==EEXIST or die $!;
1445 runcmd @git, qw(read-tree), $build;
1446 foreach my $cl (qw(Debian), (reverse @brw_cl),
1447 { SpecialMethod => 'RecordBreakwaterTip' },
1448 qw(Upstream), (reverse @upp_cl)) {
1450 $current_method = $cl;
1453 my $method = $cl->{SpecialMethod} // $current_method;
1454 my @parents = ($build);
1455 my $cltree = $cl->{CommitId};
1456 printdebug "WALK BUILD ".($cltree//'undef').
1457 " $method (rewriting=$rewriting)\n";
1458 if ($method eq 'Debian') {
1459 read_tree_debian($cltree);
1460 } elsif ($method eq 'Upstream') {
1461 $read_tree_upstream->($cltree);
1462 } elsif ($method eq 'StartRewrite') {
1465 } elsif ($method eq 'RecordBreakwaterTip') {
1466 $breakwater = $build;
1468 } elsif ($method eq 'DgitImportDebianUpdate') {
1469 read_tree_debian($cltree);
1470 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1471 confess unless $rewriting;
1472 my $differs = (get_differs $build, $cltree);
1473 next unless $differs & D_UPS;
1474 $read_tree_upstream->($cltree);
1475 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1476 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1477 print "Found a general merge, will try to tidy it up.\n";
1479 $read_tree_upstream->($cl->{MergeBestAnchor});
1480 $read_tree_upstream->($cl->{MergeBestAnchor});
1481 read_tree_debian($cltree);
1482 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1483 } elsif ($method eq 'MergeMergeSeries') {
1484 my $cachehit = reflog_cache_lookup
1485 $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1487 print "Using supplied resolution for $cl->{CommitId}...\n";
1489 $mwrecknote->('cached-resolution', $build);
1491 print "Running merge resolution for $cl->{CommitId}...\n";
1492 $mwrecknote->('new-base', $build);
1493 $build = merge_series
1494 $build, $cl->{MergeWreckNotes},
1495 $cl->{MergeInterchangeBaseInfo},
1496 @{ $cl->{Parents} };
1498 $last_anchor = $cl->{MergeBestAnchor};
1500 # Check for mismerges:
1502 my ($against, $allow, $what) = @_;
1503 my $differs = get_differs $build, $against;
1505 "merge misresolved: %s are not the same (%s %s d.%#x)",
1506 $what, $against, $build, $differs)
1507 if $differs & ~($allow | D_PAT_ADD);
1510 # Breakwater changes which were in each side of the
1511 # merge will have been incorporated into the
1512 # MergeCreateMergedBreakwaters output. Because the
1513 # upstream series was rebased onto the new breakwater,
1514 # so should all of the packaging changes which were in
1516 $check->($input, D_UPS, 'debian files');
1518 # Upstream files are merge_series, which ought to
1519 # have been identical to the original merge.
1520 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1522 print "Merge resolution successful.\n";
1525 confess "$method ?";
1528 my $procd = (pop @processed) // 'UNDEF';
1529 if ($cl ne $procd) {
1531 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1534 my $newtree = cmdoutput @git, qw(write-tree);
1535 my $ch = $cl->{Hdr};
1536 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1537 $ch =~ s{^parent .*\n}{}mg;
1538 $ch =~ s{(?=^author)}{
1539 join '', map { "parent $_\n" } @parents
1540 }me or confess "$ch ?";
1542 $ch =~ s{^committer .*$}{$committer_authline}m
1545 my $cf = "$rd/m$rewriting";
1546 open CD, ">", $cf or die $!;
1547 print CD $ch, "\n", $cl->{Msg} or die $!;
1549 my @cmd = (@git, qw(hash-object));
1550 push @cmd, qw(-w) if $rewriting;
1551 push @cmd, qw(-t commit), $cf;
1552 my $newcommit = cmdoutput @cmd;
1553 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1554 $build = $newcommit;
1555 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1556 $last_anchor = $cur;
1561 my $final_check = get_differs $build, $input;
1562 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1563 if $final_check & ~D_PAT_ADD;
1565 my @r = ($build, $breakwater, $last_anchor);
1566 printdebug "*** WALK RETURN @r\n";
1571 git_check_unmodified();
1572 return git_rev_parse qw(HEAD);
1575 sub update_head ($$$) {
1576 my ($old, $new, $mrest) = @_;
1577 push @deferred_updates, "update HEAD $new $old";
1578 run_deferred_updates $mrest;
1581 sub update_head_checkout ($$$) {
1582 my ($old, $new, $mrest) = @_;
1583 update_head $old, $new, $mrest;
1584 runcmd @git, qw(reset --hard);
1587 sub update_head_postlaunder ($$$) {
1588 my ($old, $tip, $reflogmsg) = @_;
1589 return if $tip eq $old;
1590 print "git-debrebase: laundered (head was $old)\n";
1591 update_head $old, $tip, $reflogmsg;
1592 # no tree changes except debian/patches
1593 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1596 sub currently_rebasing() {
1597 foreach (qw(rebase-merge rebase-apply)) {
1598 return 1 if stat_exists "$maindir_gitdir/$_";
1603 sub bail_if_rebasing() {
1604 fail "you are in the middle of a git-rebase already"
1605 if currently_rebasing();
1608 sub do_launder_head ($) {
1609 my ($reflogmsg) = @_;
1610 my $old = get_head();
1612 my ($tip,$breakwater) = walk $old;
1614 update_head_postlaunder $old, $tip, $reflogmsg;
1615 return ($tip,$breakwater);
1618 sub cmd_launder_v0 () {
1619 badusage "no arguments to launder-v0 allowed" if @ARGV;
1620 my $old = get_head();
1621 my ($tip,$breakwater,$last_anchor) = walk $old;
1622 update_head_postlaunder $old, $tip, 'launder';
1623 printf "# breakwater tip\n%s\n", $breakwater;
1624 printf "# working tip\n%s\n", $tip;
1625 printf "# last anchor\n%s\n", $last_anchor;
1628 sub defaultcmd_rebase () {
1629 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1630 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1631 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1634 sub cmd_analyse () {
1635 badusage "analyse does not support any options"
1636 if @ARGV and $ARGV[0] =~ m/^-/;
1637 badusage "too many arguments to analyse" if @ARGV>1;
1640 $old = git_rev_parse $old;
1642 $old = git_rev_parse 'HEAD';
1644 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1645 STDOUT->error and die $!;
1648 sub ffq_prev_branchinfo () {
1649 my $current = git_get_symref();
1650 return gdr_ffq_prev_branchinfo($current);
1653 sub ffq_check ($;$$) {
1654 # calls $ff and/or $notff zero or more times
1655 # then returns either (status,message) where status is
1660 # or (undef,undef, $ffq_prev,$gdrlast)
1661 # $ff and $notff are called like this:
1662 # $ff->("message for stdout\n");
1663 # $notff->('snag-name', $message);
1664 # normally $currentval should be HEAD
1665 my ($currentval, $ff, $notff) =@_;
1667 $ff //= sub { print $_[0] or die $!; };
1670 my ($status, $message, $current, $ffq_prev, $gdrlast)
1671 = ffq_prev_branchinfo();
1672 return ($status, $message) unless $status eq 'branch';
1674 my $exists = git_get_ref $ffq_prev;
1675 return ('exists',"$ffq_prev already exists") if $exists;
1677 return ('not-branch', 'HEAD symref is not to refs/heads/')
1678 unless $current =~ m{^refs/heads/};
1681 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1684 printdebug "ffq check_specs @check_specs\n";
1687 my ($lrref, $desc) = @_;
1688 printdebug "ffq might check $lrref ($desc)\n";
1690 for my $chk (@check_specs) {
1692 $invert = $glob =~ s{^[!^]}{};
1693 last if fnmatch $glob, $lrref;
1696 my $lrval = git_get_ref $lrref;
1697 return unless length $lrval;
1699 if (is_fast_fwd $lrval, $currentval) {
1700 $ff->("OK, you are ahead of $lrref\n");
1701 $checked{$lrref} = 1;
1702 } elsif (is_fast_fwd $currentval, $lrval) {
1703 $checked{$lrref} = -1;
1704 $notff->('behind', "you are behind $lrref, divergence risk");
1706 $checked{$lrref} = -1;
1707 $notff->('diverged', "you have diverged from $lrref");
1711 my $merge = cfg "branch.$branch.merge",1;
1712 if (defined $merge and $merge =~ m{^refs/heads/}) {
1714 printdebug "ffq merge $rhs\n";
1715 my $check_remote = sub {
1716 my ($remote, $desc) = @_;
1717 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1718 return unless defined $remote;
1719 $check->("refs/remotes/$remote/$rhs", $desc);
1721 $check_remote->((scalar cfg "branch.$branch.remote",1),
1722 'remote fetch/merge branch');
1723 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1724 (scalar cfg "branch.$branch.pushDefault",1),
1725 'remote push branch');
1727 if ($branch =~ m{^dgit/}) {
1728 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1729 } elsif ($branch =~ m{^master$}) {
1730 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1732 return (undef, undef, $ffq_prev, $gdrlast);
1735 sub record_ffq_prev_deferred () {
1736 # => ('status', "message")
1738 # deferred message is undef
1743 # if not ff from some branch we should be ff from, is an snag
1744 # if "deferred", will have added something about that to
1745 # @deferred_update_messages, and also maybe printed (already)
1746 # some messages about ff checks
1748 my $currentval = get_head();
1750 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1751 return ($status,$message) if defined $status;
1755 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1756 push @deferred_updates, "delete $gdrlast";
1757 push @deferred_update_messages, "Recorded previous head for preservation";
1758 return ('deferred', undef);
1761 sub record_ffq_auto () {
1762 my ($status, $message) = record_ffq_prev_deferred();
1763 if ($status eq 'deferred' || $status eq 'exists') {
1765 snag $status, "could not record ffq-prev: $message";
1770 sub ffq_prev_info () {
1772 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1773 my ($status, $message, $current, $ffq_prev, $gdrlast)
1774 = ffq_prev_branchinfo();
1775 if ($status ne 'branch') {
1776 snag $status, "could not check ffq-prev: $message";
1779 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1780 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1783 sub stitch ($$$$$) {
1784 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1786 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1788 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1789 my $differs = get_differs $old_head, $ffq_prev_commitish;
1790 unless ($differs & ~D_PAT_ADD) {
1791 # ffq-prev is ahead of us, and the only tree changes it has
1792 # are possibly addition of things in debian/patches/.
1793 # Just wind forwards rather than making a pointless pseudomerge.
1794 push @deferred_updates,
1795 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1796 update_head_checkout $old_head, $ffq_prev_commitish,
1797 "stitch (fast forward)";
1802 # We make pseudomerges with L as the contributing parent.
1803 # This makes git rev-list --first-parent work properly.
1804 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1805 'Declare fast forward / record previous work',
1806 "[git-debrebase pseudomerge: $prose]",
1808 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1809 update_head $old_head, $new_head, "stitch: $prose";
1812 sub do_stitch ($;$) {
1813 my ($prose, $unclean) = @_;
1815 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1816 if (!$ffq_prev_commitish) {
1817 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1820 my $dangling_head = get_head();
1822 keycommits $dangling_head, $unclean,$unclean,$unclean;
1825 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1828 sub upstream_commitish_search ($$) {
1829 my ($upstream_version, $tried) = @_;
1830 # todo: at some point maybe use git-deborig to do this
1831 foreach my $tagpfx ('', 'v', 'upstream/') {
1832 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1833 my $new_upstream = git_get_ref "refs/tags/$tag";
1835 return $new_upstream if length $new_upstream;
1839 sub resolve_upstream_version ($$) {
1840 my ($new_upstream, $upstream_version) = @_;
1842 if (!defined $new_upstream) {
1844 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1845 if (!length $new_upstream) {
1846 fail "Could not determine appropriate upstream commitish.\n".
1847 " (Tried these tags: @tried)\n".
1848 " Check version, and specify upstream commitish explicitly.";
1851 $new_upstream = git_rev_parse $new_upstream;
1853 return $new_upstream;
1856 sub cmd_new_upstream () {
1857 # automatically and unconditionally launders before rebasing
1858 # if rebase --abort is used, laundering has still been done
1862 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1864 # parse args - low commitment
1865 my $spec_version = shift @ARGV;
1866 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1867 fail "bad version number \`$spec_version'" unless defined $new_version;
1868 if ($new_version->is_native()) {
1869 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1872 my $new_upstream = shift @ARGV;
1873 my $new_upstream_version = upstreamversion $new_version;
1875 resolve_upstream_version $new_upstream, $new_upstream_version;
1880 my ($n, @x) = @_; # may be ''
1881 my $pc = $pieces{$n} //= {
1883 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1885 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1890 my $newpiece = sub {
1891 my ($n, @x) = @_; # may be ''
1892 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1893 push @newpieces, $pc;
1898 New => $new_upstream,
1900 while (@ARGV && $ARGV[0] !~ m{^-}) {
1901 my $n = shift @ARGV;
1903 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1904 unless @ARGV && $ARGV[0] !~ m{^-};
1906 my $c = git_rev_parse shift @ARGV;
1907 die unless $n =~ m/^$extra_orig_namepart_re$/;
1908 $newpiece->($n, New => $c);
1911 # now we need to investigate the branch this generates the
1912 # laundered version but we don't switch to it yet
1913 my $old_head = get_head();
1914 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1916 my $old_bw_cl = classify $old_bw;
1917 my $old_anchor_cl = classify $old_anchor;
1919 if (!$old_anchor_cl->{OrigParents}) {
1920 snag 'anchor-treated',
1921 'old anchor is recognised due to --anchor, cannot check upstream';
1923 $old_upstream = parsecommit
1924 $old_anchor_cl->{OrigParents}[0]{CommitId};
1925 $piece->('', Old => $old_upstream->{CommitId});
1928 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1929 if ($old_upstream->{Msg} =~
1930 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1932 my @oldpieces = (split / /, $1);
1933 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1934 if ($old_n_parents != @oldpieces &&
1935 $old_n_parents != @oldpieces + 1) {
1936 snag 'upstream-confusing', sprintf
1937 "previous upstream combine %s".
1938 " mentions %d pieces (each implying one parent)".
1939 " but has %d parents".
1940 " (one per piece plus maybe a previous combine)",
1941 $old_upstream->{CommitId},
1942 (scalar @oldpieces),
1944 } elsif ($oldpieces[0] ne '.') {
1945 snag 'upstream-confusing', sprintf
1946 "previous upstream combine %s".
1947 " first piece is not \`.'",
1951 foreach my $i (0..$#oldpieces) {
1952 my $n = $oldpieces[$i];
1953 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1954 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1958 snag 'upstream-confusing',
1959 "previous upstream $old_upstream->{CommitId} is from".
1960 " git-debrebase but not an \`upstream-combine' commit";
1964 foreach my $pc (values %pieces) {
1965 if (!$old_upstream) {
1966 # we have complained already
1967 } elsif (!$pc->{Old}) {
1968 snag 'upstream-new-piece',
1969 "introducing upstream piece \`$pc->{Name}'";
1970 } elsif (!$pc->{New}) {
1971 snag 'upstream-rm-piece',
1972 "dropping upstream piece \`$pc->{Name}'";
1973 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1974 snag 'upstream-not-ff',
1975 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1979 printdebug "%pieces = ", (dd \%pieces), "\n";
1980 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1988 my @upstream_merge_parents;
1991 push @upstream_merge_parents, $old_upstream->{CommitId};
1994 foreach my $pc (@newpieces) { # always has '' first
1996 read_tree_subdir $pc->{Name}, $pc->{New};
1998 runcmd @git, qw(read-tree), $pc->{New};
2000 push @upstream_merge_parents, $pc->{New};
2003 # index now contains the new upstream
2005 if (@newpieces > 1) {
2006 # need to make the upstream subtree merge commit
2007 $new_upstream = make_commit \@upstream_merge_parents,
2008 [ "Combine upstreams for $new_upstream_version",
2009 ("[git-debrebase upstream-combine . ".
2010 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2015 # $new_upstream is either the single upstream commit, or the
2016 # combined commit we just made. Either way it will be the
2017 # "upstream" parent of the anchor merge.
2019 read_tree_subdir 'debian', "$old_bw:debian";
2021 # index now contains the anchor merge contents
2022 $new_bw = make_commit [ $old_bw, $new_upstream ],
2023 [ "Update to upstream $new_upstream_version",
2024 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2027 my $clogsignoff = cmdoutput qw(git show),
2028 '--pretty=format:%an <%ae> %aD',
2031 # Now we have to add a changelog stanza so the Debian version
2033 die if unlink "debian";
2034 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2035 unlink "debian/changelog" or $!==ENOENT or die $!;
2036 mkdir "debian" or die $!;
2037 open CN, ">", "debian/changelog" or die $!;
2038 my $oldclog = git_cat_file ":debian/changelog";
2039 $oldclog =~ m/^($package_re) \(\S+\) / or
2040 fail "cannot parse old changelog to get package name";
2042 print CN <<END, $oldclog or die $!;
2043 $p ($new_version) UNRELEASED; urgency=medium
2045 * Update to new upstream version $new_upstream_version.
2051 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2053 # Now we have the final new breakwater branch in the index
2054 $new_bw = make_commit [ $new_bw ],
2055 [ "Update changelog for new upstream $new_upstream_version",
2056 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2060 # we have constructed the new breakwater. we now need to commit to
2061 # the laundering output, because git-rebase can't easily be made
2062 # to make a replay list which is based on some other branch
2064 update_head_postlaunder $old_head, $old_laundered_tip,
2065 'launder for new upstream';
2067 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2068 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2069 "debrebase new-upstream $new_version: rebase";
2071 # now it's for the user to sort out
2074 sub cmd_record_ffq_prev () {
2075 badusage "no arguments allowed" if @ARGV;
2076 my ($status, $msg) = record_ffq_prev_deferred();
2077 if ($status eq 'exists' && $opt_noop_ok) {
2078 print "Previous head already recorded\n" or die $!;
2079 } elsif ($status eq 'deferred') {
2080 run_deferred_updates 'record-ffq-prev';
2082 fail "Could not preserve: $msg";
2087 badusage "no arguments allowed" if @ARGV;
2088 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2089 print "$bw\n" or die $!;
2092 sub cmd_breakwater () {
2093 badusage "no arguments allowed" if @ARGV;
2094 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2095 print "$bw\n" or die $!;
2099 badusage "no arguments allowed" if @ARGV;
2101 # todo: gdr status should print divergence info
2102 # todo: gdr status should print upstream component(s) info
2103 # todo: gdr should leave/maintain some refs with this kind of info ?
2105 my $oldest = { Badness => 0 };
2108 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2109 if ($oldest->{Badness} < $badness) {
2110 $oldest = $newest = undef;
2113 Badness => $badness,
2114 CommitId => $cl->{CommitId},
2118 $newest //= $oldest;
2120 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2121 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2122 sub { $note->(2, 'branch is unlaundered', @_); },
2123 sub { $note->(3, 'branch needs laundering', @_); },
2124 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2126 my $prcommitinfo = sub {
2128 flush STDOUT or die $!;
2129 runcmd @git, qw(--no-pager log -n1),
2130 '--pretty=format: %h %s%n',
2134 print "current branch contents, in git-debrebase terms:\n";
2135 if (!$oldest->{Badness}) {
2136 print " branch is laundered\n";
2138 print " $oldest->{OurMsg}\n";
2140 foreach my $info ($oldest, $newest) {
2141 my $cid = $info->{CommitId};
2142 next if $cid eq $printed;
2144 print " $info->{KcMsg}\n";
2145 $prcommitinfo->($cid);
2150 my ($cid, $what) = @_;
2151 if (!defined $cid) {
2152 print " $what is not well-defined\n";
2155 $prcommitinfo->($cid);
2158 print "key git-debrebase commits:\n";
2159 $prab->($anchor, 'anchor');
2160 $prab->($bw, 'breakwater');
2162 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2163 ffq_prev_branchinfo();
2165 print "branch and ref status, in git-debrebase terms:\n";
2167 print " $ffq_msg\n";
2169 $ffq_prev = git_get_ref $ffq_prev;
2170 $gdrlast = git_get_ref $gdrlast;
2172 print " unstitched; previous tip was:\n";
2173 $prcommitinfo->($ffq_prev);
2174 } elsif (!$gdrlast) {
2175 print " stitched? (no record of git-debrebase work)\n";
2176 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2177 print " stitched\n";
2179 print " not git-debrebase (diverged since last stitch)\n"
2182 print "you are currently rebasing\n" if currently_rebasing();
2186 my $prose = 'stitch';
2187 getoptions("stitch",
2188 'prose=s', \$prose);
2189 badusage "no arguments allowed" if @ARGV;
2190 do_stitch $prose, 0;
2192 sub cmd_prepush () { cmd_stitch(); }
2195 badusage "no arguments allowed" if @ARGV;
2196 do_launder_head 'launder for git-debrebase quick';
2200 sub cmd_conclude () {
2201 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2202 if (!$ffq_prev_commitish) {
2203 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2206 my $dangling_head = get_head();
2208 badusage "no arguments allowed" if @ARGV;
2209 do_launder_head 'launder for git-debrebase quick';
2214 if (currently_rebasing()) {
2215 runcmd @git, qw(rebase --abort);
2216 push @deferred_updates, 'verify HEAD HEAD';
2217 # noop, but stops us complaining that scrap was a noop
2219 badusage "no arguments allowed" if @ARGV;
2220 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2222 if ($ffq_prev_commitish) {
2223 $scrapping_head = get_head();
2224 push @deferred_updates,
2225 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2226 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2228 if (git_get_ref $merge_cache_ref) {
2229 push @deferred_updates,
2230 "delete $merge_cache_ref";
2232 if (!@deferred_updates) {
2233 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2237 if ($scrapping_head) {
2238 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2240 run_deferred_updates "scrap";
2244 sub make_patches_staged ($) {
2246 # Produces the patches that would result from $head if it were
2248 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2251 gbp_pq_export 'bw', $secret_bw, $secret_head;
2255 sub make_patches ($) {
2257 keycommits $head, 0, \&snag;
2258 make_patches_staged $head;
2261 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2262 runcmd @git, qw(read-tree), $head;
2263 read_tree_subdir 'debian/patches', $ptree;
2264 $out = make_commit [$head], [
2265 'Commit patch queue (exported by git-debrebase)',
2266 '[git-debrebase: export and commit patches]',
2272 sub cmd_make_patches () {
2273 my $opt_quiet_would_amend;
2274 getoptions("make-patches",
2275 'quiet-would-amend!', \$opt_quiet_would_amend);
2276 badusage "no arguments allowed" if @ARGV;
2278 my $old_head = get_head();
2279 my $new = make_patches $old_head;
2280 my $d = get_differs $old_head, $new;
2282 fail "No (more) patches to export." unless $opt_noop_ok;
2284 } elsif ($d == D_PAT_ADD) {
2286 update_head_checkout $old_head, $new, 'make-patches';
2288 print STDERR failmsg
2289 "Patch export produced patch amendments".
2290 " (abandoned output commit $new).".
2291 " Try laundering first."
2292 unless $opt_quiet_would_amend;
2297 sub cmd_convert_from_gbp () {
2298 badusage "want only 1 optional argument, the upstream git commitish"
2301 my $clogp = parsechangelog();
2302 my $version = $clogp->{'Version'}
2303 // die "missing Version from changelog";
2305 my ($upstream_spec) = @ARGV;
2307 my $upstream_version = upstreamversion $version;
2309 resolve_upstream_version($upstream_spec, $upstream_version);
2311 my $old_head = get_head();
2313 my $upsdiff = get_differs $upstream, $old_head;
2314 if ($upsdiff & D_UPS) {
2315 runcmd @git, qw(--no-pager diff --stat),
2316 $upstream, $old_head,
2317 qw( -- :!/debian :/);
2319 upstream ($upstream_spec) and HEAD are not
2320 identical in upstream files. See diffstat above, or run
2321 git diff $upstream_spec HEAD -- :!/debian :/
2325 if (!is_fast_fwd $upstream, $old_head) {
2326 snag 'upstream-not-ancestor',
2327 "upstream ($upstream) is not an ancestor of HEAD";
2329 my $wrong = cmdoutput
2330 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2331 qw(-- :/ :!/debian));
2332 if (length $wrong) {
2333 snag 'unexpected-upstream-changes',
2334 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2335 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2339 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2340 snag 'upstream-has-debian',
2341 "upstream ($upstream) contains debian/ directory";
2344 my $previous_dgit_view = eval {
2345 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2347 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2348 my ($stz, $desc) = @_;
2349 no warnings qw(exiting);
2350 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2351 next unless $stz->{Date};
2352 next unless $stz->{Distribution} ne 'UNRELEASED';
2353 $lvsn = $stz->{Version};
2354 $suite = $stz->{Distribution};
2357 die "neither of the first two changelog entries are released\n"
2358 unless defined $lvsn;
2359 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2360 my $mtag_pat = debiantag_maintview $lvsn, '*';
2361 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2363 die "could not find suitable maintainer view tag $mtag_pat\n"
2364 unless $mtag_pat =~ m{/};
2365 is_fast_fwd $mtag, 'HEAD' or
2366 die "HEAD is not FF from maintainer tag $mtag!";
2367 my $dtag = "archive/$mtag";
2368 is_fast_fwd $mtag, $dtag or
2369 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2370 print "will stitch in dgit view, $dtag\n";
2371 git_rev_parse $dtag;
2373 if (!$previous_dgit_view) {
2376 print STDERR "cannot stitch in dgit view: $@\n";
2379 snags_maybe_bail_early();
2385 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2386 # make a branch out of the patch queue - we'll want this in a mo
2387 runcmd qw(gbp pq import);
2388 # strip the patches out
2389 runcmd @git, qw(checkout -q gdr-internal~0);
2390 rm_subdir_cached 'debian/patches';
2391 $work = make_commit ['HEAD'], [
2392 'git-debrebase convert-from-gbp: drop patches from tree',
2393 'Delete debian/patches, as part of converting to git-debrebase format.',
2394 '[git-debrebase convert-from-gbp: drop patches from tree]'
2396 # make the anchor merge
2397 # the tree is already exactly right
2398 $work = make_commit [$work, $upstream], [
2399 'git-debrebase import: declare upstream',
2400 'First breakwater merge.',
2401 '[git-debrebase anchor: declare upstream]'
2404 # rebase the patch queue onto the new breakwater
2405 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2406 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2407 $work = git_rev_parse 'HEAD';
2409 if ($previous_dgit_view) {
2410 $work = make_commit [$work, $previous_dgit_view], [
2411 'git-debrebase import: declare ff from dgit archive view',
2412 '[git-debrebase pseudomerge: import-from-gbp]',
2419 update_head_checkout $old_head, $work, 'convert-from-gbp';
2422 sub cmd_convert_to_gbp () {
2423 badusage "no arguments allowed" if @ARGV;
2424 my $head = get_head();
2425 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2426 keycommits $head, 0;
2428 make_patches_staged $head;
2430 $out = make_commit ['HEAD'], [
2431 'Commit patch queue (converted from git-debrebase format)',
2432 '[git-debrebase convert-to-gbp: commit patches]',
2436 push @deferred_updates, "delete $ffq";
2437 push @deferred_updates, "delete $gdrlast";
2440 update_head_checkout $head, $out, "convert to gbp (v0)";
2441 print <<END or die $!;
2442 git-debrebase: converted to git-buildpackage branch format
2443 git-debrebase: WARNING: do not now run "git-debrebase" any more
2444 git-debrebase: WARNING: doing so would drop all upstream patches!
2448 sub cmd_convert_from_dgit_view () {
2449 my $clogp = parsechangelog();
2451 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2457 getoptions("convert-from-dgit-view",
2458 'diagnose!', \$diagnose,
2459 'build-products-dir:s', \$bpd,
2460 'origs!', \$do_origs,
2462 'always-convert-anyway!', \$always);
2463 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2468 my $spec = shift @ARGV;
2469 my $commit = git_rev_parse "$spec^{commit}";
2470 push @upstreams, { Commit => $commit,
2471 Source => "$ARGV[0], from command line",
2476 my $head = get_head();
2480 my $trouble = sub { $troubles++; };
2481 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2482 printdebug "troubles=$troubles\n";
2485 $us: Branch already seems to be in git-debrebase format!
2486 $us: --always-convert-anyway would do the conversion operation anyway
2487 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2489 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2494 snags_maybe_bail_early();
2496 my $version = upstreamversion $clogp->{Version};
2497 print STDERR "Considering possible commits corresponding to upstream:\n";
2502 my $ups_tag = upstream_commitish_search $version, \@tried;
2504 my $this = "git tag $tried[-1]";
2505 push @upstreams, { Commit => $ups_tag,
2510 " git tag: no suitable tag found (tried %s)\n",
2515 my $p = $clogp->{'Source'};
2516 # we do a quick check to see if there are plausible origs
2518 if (!opendir BPD, $bpd) {
2519 die "$bpd: opendir: $!" unless $!==ENOENT;
2521 while ($!=0, my $f = readdir BPD) {
2522 next unless is_orig_file_of_p_v $f, $p, $version;
2524 " orig: found what looks like a .orig, %s\n",
2529 die "read $bpd: $!" if $!;
2533 my $tree = cmdoutput
2534 @dgit, qw(--build-products-dir), $bpd,
2535 qw(print-unapplied-treeish);
2538 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2539 rm_subdir_cached 'debian';
2540 $tree = cmdoutput @git, qw(write-tree);
2541 my $ups_synth = make_commit [], [ <<END, <<END,
2542 Import effective orig tree for upstream version $version
2544 This includes the contents of the .orig(s), minus any debian/ directory.
2546 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2549 push @upstreams, { Commit => $ups_synth,
2550 Source => "orig(s) imported via dgit",
2555 " orig: no suitable origs found (looked for %s in %s)\n",
2556 "${p}_".(stripeoch $version)."...", $bpd;
2561 my $some_patches = stat_exists 'debian/patches/series';
2563 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2566 foreach my $u (@upstreams) {
2570 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2571 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2572 runcmd @git, qw(clean -xdff);
2573 runcmd @git, qw(checkout), $head, qw(-- debian);
2574 if ($some_patches) {
2575 rm_subdir_cached 'debian/patches';
2576 $work = make_commit [ $work ], [
2577 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2578 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2579 "to git-debrebase format. Upstream changes will appear as commits.",
2580 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2583 $work = make_commit [ $work, $u->{Commit} ], [
2584 'git-debrebase convert-from-dgit-view: declare upstream',
2585 '(Re)constructed breakwater merge.',
2586 '[git-debrebase anchor: declare upstream]'
2588 runcmd @git, qw(checkout --quiet -b mk), $work;
2589 if ($some_patches) {
2590 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2591 runcmd @git, qw(reset --quiet);
2592 my @gbp_cmd = (qw(gbp pq import));
2594 my $gbp_err = "../gbp-pq-err";
2595 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2597 my $r = system @gbp_cmd;
2600 " %s: couldn't apply patches: gbp pq %s",
2601 $u->{Source}, waitstatusmsg();
2605 my $work = git_rev_parse qw(HEAD);
2606 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2607 if (length $diffout) {
2609 " $u->{Source}: applying patches gives different tree\n";
2610 print STDERR $diffout if $diagnose;
2614 $u->{Result} = $work;
2622 Could not find or construct a suitable upstream commit.
2623 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2624 upstream commmit explicitly or provide suitable origs.
2628 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2630 ffq_check $result->{Result};
2632 update_head_checkout $head, $result->{Result},
2633 'convert-from-dgit-view';
2636 sub cmd_record_resolved_merge () {
2637 badusage "record-resolved-merge takes no further arguments" if @ARGV;
2638 # xxx needs documentation
2639 my $new = get_head();
2642 print "Checking how you have resolved the merge problem\n";
2643 my $nope = sub { print "Not $method: @_"; 0; };
2645 my $maybe = sub { print "Seems to be $method.\n"; };
2647 my ($key, $ref) = @_;
2648 reflog_cache_insert $merge_cache_ref, $key, $ref;
2649 print "OK. You can switch branches and try git-debrebase again.\n";
2653 fresh_workarea 'merge';
2655 $method = 'vanilla-merge patchqueue';
2656 my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2657 $vanilla or return $nope->("wreckage was not of vanilla-merge");
2658 foreach my $lr (qw(left right)) {
2659 my $n = "$wrecknoteprefix/$lr-patchqueue";
2660 my $lrpq = git_get_ref $n;
2661 $lrpq or return $nope->("wreckage did not contain patchqueues");
2662 is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2665 my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2666 or die "wreckage element $wrecknoteprefix/new-base missing";
2667 my $result = merge_series_patchqueue_convert
2669 $yes->("vanilla-merge $vanilla", $result);
2672 fail "No resolved merge method seems applicable.\n";
2676 sub cmd_downstream_rebase_launder_v0 () {
2677 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2679 $base = git_rev_parse $base;
2680 my $old_head = get_head();
2681 my $current = $old_head;
2684 if ($current eq $base) {
2685 $topmost_keep //= $current;
2686 print " $current BASE stop\n";
2689 my $cl = classify $current;
2690 print " $current $cl->{Type}";
2692 my $p0 = $cl->{Parents}[0]{CommitId};
2694 if ($cl->{Type} eq 'Pseudomerge') {
2695 print " ^".($cl->{Contributor}{Ix}+1);
2696 $next = $cl->{Contributor}{CommitId};
2697 } elsif ($cl->{Type} eq 'AddPatches' or
2698 $cl->{Type} eq 'Changelog') {
2708 $topmost_keep //= $current;
2710 die "to-be stripped changes not on top of the branch\n"
2715 if ($topmost_keep eq $old_head) {
2716 print "unchanged\n";
2718 print "updating to $topmost_keep\n";
2719 update_head_checkout
2720 $old_head, $topmost_keep,
2721 'downstream-rebase-launder-v0';
2727 "D+" => \$debuglevel,
2728 'noop-ok', => \$opt_noop_ok,
2729 'f=s' => \@snag_force_opts,
2730 'anchor=s' => \@opt_anchors,
2731 '--dgit=s' => \($dgit[0]),
2734 my ($opt,$val) = @_;
2735 badusage "git-debrebase: no cuddling to -i for git-rebase"
2737 die if $opt_defaultcmd_interactive; # should not happen
2738 $opt_defaultcmd_interactive = [ qw(-i) ];
2739 # This access to @ARGV is excessive familiarity with
2740 # Getopt::Long, but there isn't another sensible
2741 # approach. '-i=s{0,}' does not work with bundling.
2742 push @$opt_defaultcmd_interactive, @ARGV;
2745 'help' => sub { print $usage_message or die $!; finish 0; },
2748 initdebug('git-debrebase ');
2749 enabledebug if $debuglevel;
2751 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2752 chdir $toplevel or die "chdir $toplevel: $!";
2754 $rd = fresh_playground "$playprefix/misc";
2756 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2758 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2759 defaultcmd_rebase();
2761 my $cmd = shift @ARGV;
2764 $cmdfn = ${*::}{"cmd_$cmdfn"};
2766 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";