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);
62 print STDERR "$us: bad usage: $m\n";
68 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
69 GetOptions @_ or badusage $m;
73 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
77 my ($k, $optional) = @_;
79 my @cmd = qw(git config -z);
80 push @cmd, qw(--get-all) if wantarray;
82 my $out = cmdoutput_errok @cmd;
84 fail "missing required git config $k" unless $optional;
87 my @l = split /\0/, $out;
88 return wantarray ? @l : $l[0];
95 my $dd = new Data::Dumper [ $v ];
96 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
102 my $data = (git_cat_file $objid, 'commit');
103 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
107 sub D_UPS () { 0x02; } # upstream files
108 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
109 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
110 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
111 sub D_DEB_OTH () { 0x20; } # debian/changelog
112 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
114 our $playprefix = 'debrebase';
119 our @dgit = qw(dgit);
121 sub in_workarea ($) {
124 my $r = eval { $sub->(); };
125 { local $@; changedir $maindir; }
129 sub fresh_workarea () {
130 $workarea = fresh_playground "$playprefix/work";
131 in_workarea sub { playtree_setup };
134 sub run_ref_updates_now ($$) {
135 my ($mrest, $updates) = @_;
136 # @$updates is a list of lines for git-update-ref, without \ns
138 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
139 debugcmd '>|', @upd_cmd;
140 open U, "|-", @upd_cmd or die $!;
141 foreach (@$updates) {
142 printdebug ">= ", $_, "\n";
143 print U $_, "\n" or die $!;
146 close U or failedcmd @upd_cmd;
149 our $snags_forced = 0;
150 our $snags_tripped = 0;
151 our $snags_summarised = 0;
152 our @deferred_updates;
153 our @deferred_update_messages;
155 sub all_snags_summarised () {
156 $snags_forced + $snags_tripped == $snags_summarised;
158 sub run_deferred_updates ($) {
161 confess 'dangerous internal error' unless all_snags_summarised();
163 run_ref_updates_now $mrest, \@deferred_updates;
164 print $_, "\n" foreach @deferred_update_messages;
166 @deferred_updates = ();
167 @deferred_update_messages = ();
170 sub get_differs ($$) {
172 # This resembles quiltify_trees_differ, in dgit, a bit.
173 # But we don't care about modes, or dpkg-source-unrepresentable
174 # changes, and we don't need the plethora of different modes.
175 # Conversely we need to distinguish different kinds of changes to
176 # debian/ and debian/patches/.
181 my ($opts, $limits, $fn) = @_;
182 my @cmd = (@git, qw(diff-tree -z --no-renames));
184 push @cmd, "$_:" foreach $x, $y;
185 push @cmd, '--', @$limits;
186 my $diffs = cmdoutput @cmd;
187 foreach (split /\0/, $diffs) { $fn->(); }
190 $rundiff->([qw(--name-only)], [], sub {
191 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
194 if ($differs & DS_DEB) {
196 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
198 m{^debian/patches/} ? D_PAT_OTH :
199 $_ eq 'debian/changelog' ? D_DEB_CLOG :
202 die "mysterious debian changes $x..$y"
203 unless $differs & (D_PAT_OTH|DS_DEB);
206 if ($differs & D_PAT_OTH) {
208 $differs &= ~D_PAT_OTH;
210 $differs |= D_PAT_OTH;
211 no warnings qw(exiting); last;
213 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
214 no warnings qw(exiting);
215 if (!defined $mode) {
218 die unless s{^debian/patches/}{};
220 if ($mode eq 'A' && !m/\.series$/s) {
222 } elsif ($mode eq 'M' && $_ eq 'series') {
223 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
224 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
225 chomp $x_s; $x_s .= "\n";
226 $ok = $x_s eq substr($y_s, 0, length $x_s);
231 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
233 die "mysterious debian/patches changes $x..$y"
234 unless $differs & (D_PAT_ADD|D_PAT_OTH);
237 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
242 sub commit_pr_info ($) {
244 return Data::Dumper->dump([$r], [qw(commit)]);
247 sub calculate_committer_authline () {
248 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
249 'DUMMY COMMIT (git-debrebase)', "HEAD:";
250 my ($h,$m) = get_commit $c;
251 $h =~ m/^committer .*$/m or confess "($h) ?";
255 sub rm_subdir_cached ($) {
257 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
260 sub read_tree_subdir ($$) {
261 my ($subdir, $new_tree_object) = @_;
262 rm_subdir_cached $subdir;
263 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
266 sub read_tree_debian ($) {
268 read_tree_subdir 'debian', "$treeish:debian";
269 rm_subdir_cached 'debian/patches';
272 sub read_tree_upstream ($;$$) {
273 my ($treeish, $keep_patches, $tree_with_debian) = @_;
274 # if $tree_with_debian is supplied, will use that for debian/
275 # otherwise will save and restore it.
277 $tree_with_debian ? "$tree_with_debian:debian"
278 : cmdoutput @git, qw(write-tree --prefix=debian/);
279 runcmd @git, qw(read-tree), $treeish;
280 read_tree_subdir 'debian', $debian;
281 rm_subdir_cached 'debian/patches' unless $keep_patches;
284 sub make_commit ($$) {
285 my ($parents, $message_paras) = @_;
286 my $tree = cmdoutput @git, qw(write-tree);
287 my @cmd = (@git, qw(commit-tree), $tree);
288 push @cmd, qw(-p), $_ foreach @$parents;
289 push @cmd, qw(-m), $_ foreach @$message_paras;
290 return cmdoutput @cmd;
293 our @snag_force_opts;
295 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
296 if (grep { $_ eq $tag } @snag_force_opts) {
298 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
301 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
305 # Important: all mainline code must call snags_maybe_bail after
306 # any point where snag might be called, but before making changes
307 # (eg before any call to run_deferred_updates). snags_maybe_bail
308 # may be called more than once if necessary (but this is not ideal
309 # because then the messages about number of snags may be confusing).
310 sub snags_maybe_bail () {
311 return if all_snags_summarised();
314 "%s: snags: %d overriden by individual -f options\n",
317 if ($snags_tripped) {
320 "%s: snags: %d overriden by global --force\n",
324 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
328 $snags_summarised = $snags_forced + $snags_tripped;
330 sub snags_maybe_bail_early () {
331 # useful to bail out early without doing a lot of work;
332 # not a substitute for snags_maybe_bail.
333 snags_maybe_bail() if $snags_tripped && !$opt_force;
336 return $snags_forced || $snags_tripped;
339 sub gbp_pq_export ($$$) {
340 my ($bname, $base, $tip) = @_;
341 # must be run in a workarea. $bname and patch-queue/$bname
342 # ought not to exist. Leaves you on patch-queue/$bname with
343 # the patches staged but not committed.
344 printdebug "gbp_pq_export $bname $base $tip\n";
345 runcmd @git, qw(checkout -q -b), $bname, $base;
346 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
347 my @gbp_cmd = (qw(gbp pq export));
348 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
350 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
353 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
357 # xxx allow merge resolution separately from laundering, before git merge
359 # xxx general gdr docs highlight forbidden things
360 # xxx general gdr docs list allowable things ?
361 # xxx general gdr docs explicitly forbid some rebase
363 # xxx provide a way for the user to help
364 # xxx (eg, provide wreckage provide way to continue)
367 # use git-format-patch?
368 # our own patch identification algorithm?
369 # this is an alternative strategy
371 sub mwrecknote ($$$) {
372 my ($wrecknotes, $reftail, $commitish) = @_;
373 confess unless defined $commitish;
374 $wrecknotes->{$reftail} = $commitish;
377 sub merge_series ($$$;@) {
378 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
379 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
380 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
381 # ^ specifies several patch series (currently we only support exactly 2)
382 # return value is a commit which is the result of
383 # merging the two versions of the same topic branch
384 # $input_q[0] and $input_q[1]
385 # with respect to the old version
389 # Creates, in *_q, a key MR for its private use
391 printdebug "merge_series newbase=$newbase\n";
393 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
394 $base_q->{MR}{S} = 'base';
397 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
398 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
399 # $prereq{<patch filename>} exists or not (even later)
403 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
405 local $workarea = fresh_playground "$playprefix/merge";
406 my $seriesfile = "debian/patches/series";
409 foreach my $q ($base_q, reverse @input_qs) {
411 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
413 if (open S, $seriesfile) {
414 while (my $patch = <S>) {
415 chomp $patch or die $!;
416 $prereq{$patch} //= {};
417 foreach my $earlier (@earlier) {
418 $prereq{$patch}{$earlier}{$s}++ and die;
420 push @earlier, $patch;
421 stat "debian/patches/$patch" or die "$patch ?";
423 S->error and die "$seriesfile $!";
426 die "$seriesfile $!" unless $!==ENOENT;
428 read_tree_upstream $newbase, 1;
429 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
430 "Convert $s to patch queue for merging",
431 "[git-debrebase merge-innards patch-queue import:".
434 printdebug "merge_series pec $pec ";
435 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
436 $pec = make_commit [ $pec ], [
437 "Drop series file from $s to avoid merge trouble",
438 "[git-debrebase merge-innards patch-queue prep:".
442 read_tree_debian $newbase;
444 read_tree_subdir 'debian/patches', "$pec:debian/patches";
446 rm_subdir_cached 'debian/patches';
448 $pec = make_commit [ $pec ], [
449 "Update debian/ (excluding patches) to final to avoid re-merging",
450 "debian/ was already merged and we need to just take that.",
451 "[git-debrebase merge-innards patch-queue packaging:".
455 printdebug "pec' $pec\n";
456 runcmd @git, qw(reset -q --hard), $pec;
457 $q->{MR}{PEC} = $pec;
458 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
460 # now, because of reverse, we are on $input_q->{MR}{OQC}
461 runcmd @git, qw(checkout -q -b merge);
462 printdebug "merge_series merging...\n";
463 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
464 debugcmd '+', @mergecmd;
466 if (system @mergecmd) {
470 printdebug "merge_series merge ok, series...\n";
471 # We need to construct a new series file
472 # Firstly, resolve prereq
473 foreach my $f (sort keys %prereq) {
474 printdebug "merge_series patch\t$f\t";
475 if (!stat_exists "debian/patches/$f") {
476 print DEBUG " drop\n" if $debuglevel;
477 # git merge deleted it; that's how we tell it's not wanted
481 print DEBUG " keep\n" if $debuglevel;
482 foreach my $g (sort keys %{ $prereq{$f} }) {
483 my $gfp = $prereq{$f}{$g};
484 printdebug "merge_series prereq\t$f\t-> $g\t";
485 if (!!$gfp->{0} == !!$gfp->{1}
488 print DEBUG "\tkeep\n" if $debuglevel;
490 print DEBUG "\tdrop\n" if $debuglevel;
491 delete $prereq{$f}{$g};
498 return scalar keys %{ $prereq{$f} };
501 my $nodate = time + 1;
503 # $authordate{<patch filename>};
504 my $authordate = sub {
506 $authordate{$f} //= do {
507 open PF, "<", "debian/patches/$f" or die "$f $!";
509 return $nodate if m/^$/;
510 last if s{^Date: }{};
513 return cmdoutput qw(date +%s -d), $_;
517 open NS, '>', $seriesfile or die $!;
519 while (keys %prereq) {
521 foreach my $try (sort keys %prereq) {
524 $unsat->($try) <=> $unsat->($best) or
525 $authordate->($try) <=> $authordate->($best) or
531 printdebug "merge_series series next $best\n";
532 print NS "$best\n" or die $!;
533 delete $prereq{$best};
534 foreach my $gp (values %prereq) {
539 runcmd @git, qw(add), $seriesfile;
540 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
541 $mwrecknote->('merged-patchqueue', git_rev_parse 'HEAD');
543 printdebug "merge_series series gbp pq import\n";
544 runcmd qw(gbp pq import);
546 # OK now we are on patch-queue/merge, and we need to rebase
547 # onto the intended parent and drop the patches from each one
549 printdebug "merge_series series ok, building...\n";
550 my $build = $newbase;
551 my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
552 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
553 my $commit = git_cat_file $c, 'commit';
554 printdebug "merge_series series ok, building $c\n";
555 read_tree_upstream $c, 0, $newbase;
556 my $tree = cmdoutput @git, qw(write-tree);
557 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
558 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
559 open C, ">", "../mcommit" or die $!;
560 print C $commit or die $!;
562 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
565 $mwrecknote->('merged-result', $result);
567 runcmd @git, qw(update-ref refs/heads/result), $result;
569 runcmd @git, qw(checkout -q -b debug);
570 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
571 runcmd @git, qw(add .);
572 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
573 my $mdebug = git_rev_parse 'HEAD';
574 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
575 $mwrecknote->('merged-debug', $mdebug);
577 printdebug "merge_series returns $result\n";
581 # classify returns an info hash like this
583 # Hdr => # commit headers, including 1 final newline
584 # Msg => # commit message (so one newline is dropped)
586 # Type => (see below)
588 # Ix => $index # ie 0, 1, 2, ...
590 # Differs => return value from get_differs
592 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
594 # NewMsg => # commit message, but with any [dgit import ...] edited
595 # # to say "[was: ...]"
605 # has additional entres in classification result
606 # Overwritten = [ subset of Parents ]
607 # Contributor = $the_remaining_Parent
609 # DgitImportUnpatched
610 # has additional entry in classification result
611 # OrigParents = [ subset of Parents ]
614 # has additional entry in classification result
615 # OrigParents = [ subset of Parents ] # singleton list
622 # has additional entry in classification result
625 sub parsecommit ($;$) {
626 my ($objid, $p_ref) = @_;
627 # => hash with CommitId Hdr Msg Tree Parents
628 # Parents entries have only Ix CommitId
629 # $p_ref, if provided, must be [] and is used as a base for Parents
634 my ($h,$m) = get_commit $objid;
636 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
637 my (@ph) = $h =~ m/^parent (\w+)$/mg;
647 foreach my $ph (@ph) {
649 Ix => scalar @$p_ref,
661 my $r = parsecommit($objid, \@p);
665 $p->{Differs} = (get_differs $p->{CommitId}, $t),
668 printdebug "classify $objid \$t=$t \@p",
669 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
673 my ($type, @rest) = @_;
674 $r = { %$r, Type => $type, @rest };
676 printdebug " = $type ".(dd $r)."\n";
682 $r = { %$r, Type => qw(Unknown), Why => $why };
683 printdebug " ** Unknown\n";
687 if (grep { $_ eq $objid } @opt_anchors) {
688 return $classify->('TreatAsAnchor');
691 my @identical = grep { !$_->{Differs} } @p;
692 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
693 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
695 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
696 # multi-orig upstreams are represented with an anchor merge
697 # from a single upstream commit which combines the orig tarballs
699 # Every anchor tagged this way must be a merge.
700 # We are relying on the
701 # [git-debrebase anchor: ...]
702 # commit message annotation in "declare" anchor merges (which
703 # do not have any upstream changes), to distinguish those
704 # anchor merges from ordinary pseudomerges (which we might
705 # just try to strip).
707 # However, the user is going to be doing git-rebase a lot. We
708 # really don't want them to rewrite an anchor commit.
709 # git-rebase trips up on merges, so that is a useful safety
712 # BreakwaterStart commits are also anchors in the terminology
713 # of git-debrebase(5), but they are untagged (and always
714 # manually generated).
716 # We cannot not tolerate any tagged linear commit (ie,
717 # BreakwaterStart commits tagged `[anchor:') because such a
718 # thing could result from an erroneous linearising raw git
719 # rebase of a merge anchor. That would represent a corruption
720 # of the branch. and we want to detect and reject the results
721 # of such corruption before it makes it out anywhere. If we
722 # reject it here then we avoid making the pseudomerge which
723 # would be needed to push it.
725 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
726 @p == 2 or return $badanchor->("has other than two parents");
727 $haspatches and return $badanchor->("contains debian/patches");
729 # How to decide about l/r ordering of anchors ? git
730 # --topo-order prefers to expand 2nd parent first. There's
731 # already an easy rune to look for debian/ history anyway (git log
732 # debian/) so debian breakwater branch should be 1st parent; that
733 # way also there's also an easy rune to look for the upstream
734 # patches (--topo-order).
736 # Also this makes --first-parent be slightly more likely to
737 # be useful - it makes it provide a linearised breakwater history.
739 # Of course one can say somthing like
740 # gitk -- ':/' ':!/debian'
741 # to get _just_ the commits touching upstream files, and by
742 # the TREESAME logic in git-rev-list this will leave the
743 # breakwater into upstream at the first anchor. But that
744 # doesn't report debian/ changes at all.
746 # Other observations about gitk: by default, gitk seems to
747 # produce output in a different order to git-rev-list. I
748 # can't seem to find this documented anywhere. gitk
749 # --date-order DTRT. But, gitk always seems to put the
750 # parents from left to right, in order, so it's easy to see
751 # which way round a pseudomerge is.
753 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
754 $p[1]{Differs} & ~DS_DEB and
755 $badanchor->("upstream files differ from left parent");
756 $p[0]{Differs} & ~D_UPS and
757 $badanchor->("debian/ differs from right parent");
759 return $classify->(qw(Anchor),
760 OrigParents => [ $p[1] ]);
764 my $d = $r->{Parents}[0]{Differs};
765 if ($d == D_PAT_ADD) {
766 return $classify->(qw(AddPatches));
767 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
768 return $unknown->("edits debian/patches");
769 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
770 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
772 if ($d == D_DEB_CLOG) {
773 return $classify->(qw(Changelog));
775 return $classify->(qw(Packaging));
777 } elsif ($ty eq 'missing') {
778 return $classify->(qw(BreakwaterStart));
780 return $unknown->("parent's debian is not a directory");
782 } elsif ($d == D_UPS) {
783 return $classify->(qw(Upstream));
784 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
785 return $classify->(qw(Mixed));
787 return $unknown->("no changes");
789 confess "internal error $objid ?";
793 return $unknown->("origin commit");
796 if (@p == 2 && @identical == 1) {
797 my @overwritten = grep { $_->{Differs} } @p;
798 confess "internal error $objid ?" unless @overwritten==1;
799 return $classify->(qw(Pseudomerge),
800 Overwritten => [ $overwritten[0] ],
801 Contributor => $identical[0]);
803 if (@p == 2 && @identical == 2) {
805 my ($ph,$pm) = get_commit $_[0]{CommitId};
806 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
810 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
811 if ($order > 0) { # newer first
812 } elsif ($order < 0) {
813 @bytime = reverse @bytime;
815 # same age, default to order made by -s ours
816 # that is, commit was made by someone who preferred L
818 return $classify->(qw(Pseudomerge),
819 SubType => qw(Ambiguous),
820 Contributor => $bytime[0],
821 Overwritten => [ $bytime[1] ]);
824 my ($p_h, $p_m) = get_commit $p->{CommitId};
825 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
826 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
828 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
830 if (!(grep { !$_->{IsOrigin} } @p) and
831 (@orig_ps >= @p - 1) and
832 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
834 return $classify->(qw(DgitImportUnpatched),
835 OrigParents => \@orig_ps);
839 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
840 # xxx ^ metadata tag needs adding to (5)
841 return $classify->("MergedBreakwaters");
843 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
844 return $unknown->("unknown kind of merge from $1");
847 return $unknown->("octopus merge");
850 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
851 return $unknown->("general two-parent merge");
854 return $classify->("VanillaMerge");
857 sub keycommits ($;$$$$$);
859 sub mergedbreakwaters_anchor ($) {
862 foreach my $p (@{ $cl->{Parents} }) {
863 my ($panchor, $pbw) = keycommits $p->{CommitId},
864 undef,undef,undef,undef, 1;
865 $best_anchor = $panchor
866 if !defined $best_anchor
867 or is_fast_fwd $best_anchor, $panchor;
868 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
869 unless is_fast_fwd $panchor, $best_anchor;
874 sub keycommits ($;$$$$$) {
875 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
876 # => ($anchor, $breakwater)
878 # $unclean->("unclean-$tagsfx", $msg, $cl)
879 # $furniture->("unclean-$tagsfx", $msg, $cl)
880 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
881 # is callled for each situation or commit that
882 # wouldn't be found in a laundered branch
883 # $furniture is for furniture commits such as might be found on an
884 # interchange branch (pseudomerge, d/patches, changelog)
885 # $trouble is for things whnich prevent the return of
886 # anchor and breakwater information; if that is ignored,
887 # then keycommits returns (undef, undef) instead.
888 # $fatal is for unprocessable commits, and should normally cause
889 # a failure. If ignored, agaion, (undef, undef) is returned.
891 # If $claimed_bw, this is supposed to be a breakwater commit.
893 # If a callback is undef, fail is called instead.
894 # If a callback is defined but false, the situation is ignored.
896 # no warnings qw(exiting); last;
897 # if the answer is no longer wanted.
899 my ($anchor, $breakwater);
900 $breakwater = $head if $claimed_bw;
904 $fatal //= sub { fail $_[1]; };
906 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
907 my $why = $mainwhy.$xwhy;
908 my $m = "branch needs laundering (run git-debrebase): $why";
909 fail $m unless defined $cb;
911 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
913 my $found_anchor = sub {
915 $breakwater //= $clogonly;
916 $breakwater //= $head;
917 no warnings qw(exiting);
921 $cl = classify $head;
922 my $ty = $cl->{Type};
923 if ($ty eq 'Packaging') {
924 $breakwater //= $clogonly;
925 $breakwater //= $head;
926 } elsif ($ty eq 'Changelog') {
927 # this is going to count as the tip of the breakwater
928 # only if it has no upstream stuff before it
930 } elsif ($ty eq 'Anchor' or
931 $ty eq 'TreatAsAnchor' or
932 $ty eq 'BreakwaterStart') {
933 $found_anchor->($head);
934 } elsif ($ty eq 'Upstream') {
935 $x->($unclean, 'ordering',
936 "packaging change ($breakwater) follows upstream change"," (eg $head)")
937 if defined $breakwater;
940 } elsif ($ty eq 'Mixed') {
941 $x->($unclean, 'mixed',
942 "found mixed upstream/packaging commit"," ($head)");
945 } elsif ($ty eq 'Pseudomerge' or
946 $ty eq 'AddPatches') {
948 $x->($furniture, (lc $ty),
949 "found interchange bureaucracy commit ($ty)"," ($head)");
950 } elsif ($ty eq 'DgitImportUnpatched') {
952 $x->($trouble, 'dgitimport',
953 "found dgit dsc import"," ($head)");
954 return (undef,undef);
956 $x->($fatal, 'unprocessable',
957 "found bare dgit dsc import with no prior history",
959 return (undef,undef);
961 } elsif ($ty eq 'VanillaMerge') {
962 $x->($trouble, 'vanillamerge',
963 "found vanilla merge"," ($head)");
964 return (undef,undef);
965 } elsif ($ty eq 'MergedBreakwaters') {
966 $found_anchor->(mergedbreakwaters_anchor $cl);
968 $x->($fatal, 'unprocessable',
969 "found unprocessable commit, cannot cope: $cl->{Why}",
971 return (undef,undef);
973 $head = $cl->{Parents}[0]{CommitId};
975 return ($anchor, $breakwater);
981 $nogenerate,$report, $report_lprefix) = @_;
982 # => ($tip, $breakwater_tip, $last_anchor)
983 # (or nothing, if $nogenerate)
985 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
986 $report_lprefix //= '';
988 # go through commits backwards
989 # we generate two lists of commits to apply:
990 # breakwater branch and upstream patches
991 my (@brw_cl, @upp_cl, @processed);
998 my ($prose, $info) = @_;
1002 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1003 return (Msg => $ms);
1005 my $rewrite_from_here = sub {
1007 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1009 push @processed, $sp_cl;
1014 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1017 return unless $report;
1018 print $report $prdelim, $report_lprefix, @_;
1022 my $bomb = sub { # usage: return $bomb->();
1023 print $report " Unprocessable" if $report;
1024 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1027 return (undef,undef);
1029 fail "found unprocessable commit, cannot cope".
1030 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1031 " (commit $cur) (d.".
1032 (join ' ', map { sprintf "%#x", $_->{Differs} }
1033 @{ $cl->{Parents} }).
1040 my $build_start = sub {
1041 my ($msg, $parent) = @_;
1044 no warnings qw(exiting); last;
1048 fail "something useful about failed merge attempt @_ xxx".Dumper($cl);
1051 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1056 $cl = classify $cur;
1057 $cl->{MergeWreckNotes} //= {};
1058 my $ty = $cl->{Type};
1059 my $st = $cl->{SubType};
1060 $prline->("$cl->{CommitId} $cl->{Type}");
1061 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1062 push @processed, $cl;
1063 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1064 if ($ty eq 'AddPatches') {
1066 $rewrite_from_here->(\@upp_cl);
1068 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1072 } elsif ($ty eq 'BreakwaterStart') {
1073 $last_anchor = $cur;
1074 $build_start->('FirstPackaging', $cur);
1075 } elsif ($ty eq 'Upstream') {
1079 } elsif ($ty eq 'Mixed') {
1082 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1085 $queue->(\@brw_cl, "debian");
1086 $queue->(\@upp_cl, "upstream");
1087 $rewrite_from_here->(\@brw_cl);
1090 } elsif ($ty eq 'Pseudomerge') {
1091 my $contrib = $cl->{Contributor}{CommitId};
1092 print $report " Contributor=$contrib" if $report;
1093 push @pseudomerges, $cl;
1094 $rewrite_from_here->(\@upp_cl);
1097 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1098 $last_anchor = $cur;
1099 $build_start->("Anchor", $cur);
1100 } elsif ($ty eq 'DgitImportUnpatched') {
1101 my $pm = $pseudomerges[-1];
1103 # To an extent, this is heuristic. Imports don't have
1104 # a useful history of the debian/ branch. We assume
1105 # that the first pseudomerge after an import has a
1106 # useful history of debian/, and ignore the histories
1107 # from later pseudomerges. Often the first pseudomerge
1108 # will be the dgit import of the upload to the actual
1109 # suite intended by the non-dgit NMUer, and later
1110 # pseudomerges may represent in-archive copies.
1111 my $ovwrs = $pm->{Overwritten};
1112 printf $report " PM=%s \@Overwr:%d",
1113 $pm->{CommitId}, (scalar @$ovwrs)
1116 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1119 my $ovwr = $ovwrs->[0]{CommitId};
1120 printf $report " Overwr=%s", $ovwr if $report;
1121 # This import has a tree which is just like a
1122 # breakwater tree, but it has the wrong history. It
1123 # ought to have the previous breakwater (which the
1124 # pseudomerge overwrote) as an ancestor. That will
1125 # make the history of the debian/ files correct. As
1126 # for the upstream version: either it's the same as
1127 # was ovewritten (ie, same as the previous
1128 # breakwater), in which case that history is precisely
1129 # right; or, otherwise, it was a non-gitish upload of a
1130 # new upstream version. We can tell these apart by
1131 # looking at the tree of the supposed upstream.
1134 SpecialMethod => 'DgitImportDebianUpdate',
1135 $xmsg->("convert dgit import: debian changes")
1138 SpecialMethod => 'DgitImportUpstreamUpdate',
1139 $xmsg->("convert dgit import: upstream update",
1142 $prline->(" Import");
1143 $rewrite_from_here->(\@brw_cl);
1144 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1148 # Everything is from this import. This kind of import
1149 # is already nearly in valid breakwater format, with the
1150 # patches as commits. Unfortunately it contains
1152 printdebug "*** WALK BOMB bare dgit import\n";
1153 $cl->{Why} = "bare dgit dsc import";
1157 } elsif ($ty eq 'MergedBreakwaters') {
1158 $last_anchor = mergedbreakwaters_anchor $cl;
1159 $build_start->(' MergedBreakwaters', $cur);
1161 } elsif ($ty eq 'VanillaMerge') {
1162 # User may have merged unstitched branch(es). We will
1163 # have now lost what ffq-prev was then (since the later
1164 # pseudomerge may introduce further changes). The effect
1165 # of resolving such a merge is that we may have to go back
1166 # further in history to find a merge base, since the one
1167 # which was reachable via ffq-prev is no longer findable.
1168 # This is suboptimal, but if it all works we'll have done
1170 # xxx we should warn the user in the docs about this
1174 # We expect to find a dominating anchor amongst the
1175 # inputs' anchors. That will be the new anchor.
1177 # More complicated is finding a merge base for the
1178 # breakwaters. We need a merge base that is a breakwater
1179 # commit. The ancestors of breakwater commits are more
1180 # breakwater commits and possibly upstream commits and the
1181 # ancestors of those upstream. Upstreams might have
1182 # arbitrary ancestors. But any upstream commit U is
1183 # either included in both anchors, in which case the
1184 # earlier anchor is a better merge base than any of U's
1185 # ancestors; or U is not included in the older anchor, in
1186 # which case U is not an ancestor of the vanilla merge at
1187 # all. So no upstream commit, nor any ancestor thereof,
1188 # is a best merge base. As for non-breakwater Debian
1189 # commits: these are never ancestors of any breakwater.
1191 # So any best merge base as found by git-merge-base
1192 # is a suitable breakwater anchor. Usually there will
1195 printdebug "*** MERGE\n";
1197 my @bwbcmd = (@git, qw(merge-base));
1198 my @ibcmd = (@git, qw(merge-base --all));
1199 my $might_be_in_bw = 1;
1201 my $ps = $cl->{Parents};
1203 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1205 foreach my $p (@$ps) {
1206 $prline->(" VanillaMerge ".$p->{Ix});
1208 my ($ptip, $pbw, $panchor) =
1209 walk $p->{CommitId}, 0, $report,
1210 $report_lprefix.' ';
1211 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1212 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1213 $p->{Anchor} = $panchor;
1215 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1216 $mwrecknote->("$lr-input", $p->{CommitId});
1218 my $mwrecknote_parent = sub {
1220 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1222 $mwrecknote_parent->('Laundered');
1223 $mwrecknote_parent->('Breakwater');
1224 $mwrecknote_parent->('Anchor');
1226 $best_anchor = $panchor if
1227 !defined $best_anchor or
1228 is_fast_fwd $best_anchor, $panchor;
1230 printdebug " MERGE BA best=".($best_anchor//'-').
1234 $mwrecknote->('result-anchor', $best_anchor);
1236 foreach my $p (@$ps) {
1237 $prline->(" VanillaMerge ".$p->{Ix});
1238 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1239 $nomerge->('divergent anchors');
1240 } elsif ($p->{Anchor} eq $best_anchor) {
1241 print $report " SameAnchor" if $report;
1243 print $report " SupersededAnchor" if $report;
1245 if ($p->{Breakwater} eq $p->{CommitId}) {
1246 # this parent commit was its own breakwater,
1247 # ie it is part of the breakwater
1248 print $report " Breakwater" if $report;
1250 $might_be_in_bw = 0;
1252 push @bwbcmd, $p->{Breakwater};
1253 push @ibcmd, $p->{CommitId};
1256 if ($ok && $might_be_in_bw) {
1257 # We could rewrite this to contaion the metadata
1258 # declaring it to be MergedBreakwaters, but
1259 # unnecessarily rewriting a merge seems unhelpful.
1260 $prline->(" VanillaMerge MergedBreakwaters");
1261 $last_anchor = $best_anchor;
1262 $build_start->('MergedBreakwaters', $cur);
1265 my $bwb = cmdoutput @bwbcmd;
1267 # OK, now we have a breakwater base, but we need the merge
1268 # base for the interchange branch because we need the delta
1271 # This a the best merge base of our inputs which has the
1272 # breakwater merge base as an ancestor.
1279 @ibs or confess 'internal error, expected anchor at least ?';
1283 foreach my $tibix (0..$#ibs) {
1284 my $tib = $ibs[$tibix];
1285 my $ff = is_fast_fwd $bwb, $tib;
1286 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1287 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1288 $mwrecknote->($tibleaf, $tib);
1295 $ib or $nomerge->("no suitable interchange merge base");
1297 $prline->(" VanillaMerge Base");
1299 my ($btip, $bbw, $banchor) = eval {
1300 walk $ib, 0, $report, $report_lprefix.' ';
1302 $nomerge->("walking interchange branch merge base ($ibleaf): ".
1305 $mwrecknote->("mergebase-laundered", $btip);
1306 $mwrecknote->("mergebase-breakwater", $bbw);
1307 $mwrecknote->("mergebase-anchor", $banchor);
1309 my $ibinfo = { SeriesTip => $btip,
1312 LeftRight => 'mergebase' };
1315 or $nomerge->("interchange merge-base ($ib)'s".
1316 " breakwater ($bbw)".
1317 " != breakwaters' merge-base ($bwb)");
1319 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1320 or $nomerge->("interchange merge-base ($ib)'s".
1321 " anchor ($ibinfo->{SeriesBase})".
1322 " != any merge input's anchor (".
1323 (join ' ', map { $_->{Anchor} } @$ps).
1326 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1327 $cl->{MergeBestAnchor} = $best_anchor;
1330 SpecialMethod => 'MergeCreateMergedBreakwaters',
1331 $xmsg->('constructed from vanilla merge',
1332 ' merged-breakwater'),
1336 SpecialMethod => 'MergeMergeSeries',
1338 $build_start->('MergeBreakwaters', $cur);
1340 printdebug "*** WALK BOMB unrecognised\n";
1346 printdebug "*** WALK prep done cur=$cur".
1347 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1349 return if $nogenerate;
1351 # Now we build it back up again
1357 my $read_tree_upstream = sub {
1359 read_tree_upstream $treeish, 0, $build;
1362 $#upp_cl = $upp_limit if defined $upp_limit;
1364 my $committer_authline = calculate_committer_authline();
1366 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1368 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1371 mkdir $rd or $!==EEXIST or die $!;
1373 runcmd @git, qw(read-tree), $build;
1374 foreach my $cl (qw(Debian), (reverse @brw_cl),
1375 { SpecialMethod => 'RecordBreakwaterTip' },
1376 qw(Upstream), (reverse @upp_cl)) {
1378 $current_method = $cl;
1381 my $method = $cl->{SpecialMethod} // $current_method;
1382 my @parents = ($build);
1383 my $cltree = $cl->{CommitId};
1384 printdebug "WALK BUILD ".($cltree//'undef').
1385 " $method (rewriting=$rewriting)\n";
1386 if ($method eq 'Debian') {
1387 read_tree_debian($cltree);
1388 } elsif ($method eq 'Upstream') {
1389 $read_tree_upstream->($cltree);
1390 } elsif ($method eq 'StartRewrite') {
1393 } elsif ($method eq 'RecordBreakwaterTip') {
1394 $breakwater = $build;
1396 } elsif ($method eq 'DgitImportDebianUpdate') {
1397 read_tree_debian($cltree);
1398 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1399 confess unless $rewriting;
1400 my $differs = (get_differs $build, $cltree);
1401 next unless $differs & D_UPS;
1402 $read_tree_upstream->($cltree);
1403 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1404 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1405 print "Found a general merge, will try to tidy it up.\n";
1407 $read_tree_upstream->($cl->{MergeBestAnchor});
1408 $read_tree_upstream->($cl->{MergeBestAnchor});
1409 read_tree_debian($cltree);
1410 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1411 } elsif ($method eq 'MergeMergeSeries') {
1412 print "Running merge resolution for $cl->{CommitId}...\n";
1413 $build = merge_series
1414 $build, $cl->{MergeWreckNotes},
1415 $cl->{MergeInterchangeBaseInfo},
1416 @{ $cl->{Parents} };
1417 $last_anchor = $cl->{MergeBestAnchor};
1419 # Check for mismerges:
1421 my ($against, $allow, $what) = @_;
1422 my $differs = get_differs $build, $against;
1424 "merge misresolved: %s are not the same (%s %s d.%#x)",
1425 $what, $against, $build, $differs)
1426 if $differs & ~($allow | D_PAT_ADD);
1429 # Breakwater changes which were in each side of the
1430 # merge will have been incorporated into the
1431 # MergeCreateMergedBreakwaters output. Because the
1432 # upstream series was rebased onto the new breakwater,
1433 # so should all of the packaging changes which were in
1435 $check->($input, D_UPS, 'debian files');
1437 # Upstream files are merge_series, which ought to
1438 # have been identical to the original merge.
1439 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1441 print "Merge resolution successful.\n";
1444 confess "$method ?";
1447 my $procd = (pop @processed) // 'UNDEF';
1448 if ($cl ne $procd) {
1450 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1453 my $newtree = cmdoutput @git, qw(write-tree);
1454 my $ch = $cl->{Hdr};
1455 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1456 $ch =~ s{^parent .*\n}{}mg;
1457 $ch =~ s{(?=^author)}{
1458 join '', map { "parent $_\n" } @parents
1459 }me or confess "$ch ?";
1461 $ch =~ s{^committer .*$}{$committer_authline}m
1464 my $cf = "$rd/m$rewriting";
1465 open CD, ">", $cf or die $!;
1466 print CD $ch, "\n", $cl->{Msg} or die $!;
1468 my @cmd = (@git, qw(hash-object));
1469 push @cmd, qw(-w) if $rewriting;
1470 push @cmd, qw(-t commit), $cf;
1471 my $newcommit = cmdoutput @cmd;
1472 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1473 $build = $newcommit;
1474 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1475 $last_anchor = $cur;
1480 my $final_check = get_differs $build, $input;
1481 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1482 if $final_check & ~D_PAT_ADD;
1484 my @r = ($build, $breakwater, $last_anchor);
1485 printdebug "*** WALK RETURN @r\n";
1490 git_check_unmodified();
1491 return git_rev_parse qw(HEAD);
1494 sub update_head ($$$) {
1495 my ($old, $new, $mrest) = @_;
1496 push @deferred_updates, "update HEAD $new $old";
1497 run_deferred_updates $mrest;
1500 sub update_head_checkout ($$$) {
1501 my ($old, $new, $mrest) = @_;
1502 update_head $old, $new, $mrest;
1503 runcmd @git, qw(reset --hard);
1506 sub update_head_postlaunder ($$$) {
1507 my ($old, $tip, $reflogmsg) = @_;
1508 return if $tip eq $old;
1509 print "git-debrebase: laundered (head was $old)\n";
1510 update_head $old, $tip, $reflogmsg;
1511 # no tree changes except debian/patches
1512 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1515 sub currently_rebasing() {
1516 foreach (qw(rebase-merge rebase-apply)) {
1517 return 1 if stat_exists "$maindir_gitdir/$_";
1522 sub bail_if_rebasing() {
1523 fail "you are in the middle of a git-rebase already"
1524 if currently_rebasing();
1527 sub do_launder_head ($) {
1528 my ($reflogmsg) = @_;
1529 my $old = get_head();
1531 my ($tip,$breakwater) = walk $old;
1533 update_head_postlaunder $old, $tip, $reflogmsg;
1534 return ($tip,$breakwater);
1537 sub cmd_launder_v0 () {
1538 badusage "no arguments to launder-v0 allowed" if @ARGV;
1539 my $old = get_head();
1540 my ($tip,$breakwater,$last_anchor) = walk $old;
1541 update_head_postlaunder $old, $tip, 'launder';
1542 printf "# breakwater tip\n%s\n", $breakwater;
1543 printf "# working tip\n%s\n", $tip;
1544 printf "# last anchor\n%s\n", $last_anchor;
1547 sub defaultcmd_rebase () {
1548 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1549 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1550 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1553 sub cmd_analyse () {
1554 badusage "analyse does not support any options"
1555 if @ARGV and $ARGV[0] =~ m/^-/;
1556 badusage "too many arguments to analyse" if @ARGV>1;
1559 $old = git_rev_parse $old;
1561 $old = git_rev_parse 'HEAD';
1563 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1564 STDOUT->error and die $!;
1567 sub ffq_prev_branchinfo () {
1568 my $current = git_get_symref();
1569 return gdr_ffq_prev_branchinfo($current);
1572 sub ffq_check ($;$$) {
1573 # calls $ff and/or $notff zero or more times
1574 # then returns either (status,message) where status is
1579 # or (undef,undef, $ffq_prev,$gdrlast)
1580 # $ff and $notff are called like this:
1581 # $ff->("message for stdout\n");
1582 # $notff->('snag-name', $message);
1583 # normally $currentval should be HEAD
1584 my ($currentval, $ff, $notff) =@_;
1586 $ff //= sub { print $_[0] or die $!; };
1589 my ($status, $message, $current, $ffq_prev, $gdrlast)
1590 = ffq_prev_branchinfo();
1591 return ($status, $message) unless $status eq 'branch';
1593 my $exists = git_get_ref $ffq_prev;
1594 return ('exists',"$ffq_prev already exists") if $exists;
1596 return ('not-branch', 'HEAD symref is not to refs/heads/')
1597 unless $current =~ m{^refs/heads/};
1600 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1603 printdebug "ffq check_specs @check_specs\n";
1606 my ($lrref, $desc) = @_;
1607 printdebug "ffq might check $lrref ($desc)\n";
1609 for my $chk (@check_specs) {
1611 $invert = $glob =~ s{^[!^]}{};
1612 last if fnmatch $glob, $lrref;
1615 my $lrval = git_get_ref $lrref;
1616 return unless length $lrval;
1618 if (is_fast_fwd $lrval, $currentval) {
1619 $ff->("OK, you are ahead of $lrref\n");
1620 $checked{$lrref} = 1;
1621 } elsif (is_fast_fwd $currentval, $lrval) {
1622 $checked{$lrref} = -1;
1623 $notff->('behind', "you are behind $lrref, divergence risk");
1625 $checked{$lrref} = -1;
1626 $notff->('diverged', "you have diverged from $lrref");
1630 my $merge = cfg "branch.$branch.merge",1;
1631 if (defined $merge and $merge =~ m{^refs/heads/}) {
1633 printdebug "ffq merge $rhs\n";
1634 my $check_remote = sub {
1635 my ($remote, $desc) = @_;
1636 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1637 return unless defined $remote;
1638 $check->("refs/remotes/$remote/$rhs", $desc);
1640 $check_remote->((scalar cfg "branch.$branch.remote",1),
1641 'remote fetch/merge branch');
1642 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1643 (scalar cfg "branch.$branch.pushDefault",1),
1644 'remote push branch');
1646 if ($branch =~ m{^dgit/}) {
1647 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1648 } elsif ($branch =~ m{^master$}) {
1649 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1651 return (undef, undef, $ffq_prev, $gdrlast);
1654 sub record_ffq_prev_deferred () {
1655 # => ('status', "message")
1657 # deferred message is undef
1662 # if not ff from some branch we should be ff from, is an snag
1663 # if "deferred", will have added something about that to
1664 # @deferred_update_messages, and also maybe printed (already)
1665 # some messages about ff checks
1667 my $currentval = get_head();
1669 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1670 return ($status,$message) if defined $status;
1674 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1675 push @deferred_updates, "delete $gdrlast";
1676 push @deferred_update_messages, "Recorded previous head for preservation";
1677 return ('deferred', undef);
1680 sub record_ffq_auto () {
1681 my ($status, $message) = record_ffq_prev_deferred();
1682 if ($status eq 'deferred' || $status eq 'exists') {
1684 snag $status, "could not record ffq-prev: $message";
1689 sub ffq_prev_info () {
1691 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1692 my ($status, $message, $current, $ffq_prev, $gdrlast)
1693 = ffq_prev_branchinfo();
1694 if ($status ne 'branch') {
1695 snag $status, "could not check ffq-prev: $message";
1698 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1699 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1702 sub stitch ($$$$$) {
1703 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1705 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1707 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1708 my $differs = get_differs $old_head, $ffq_prev_commitish;
1709 unless ($differs & ~D_PAT_ADD) {
1710 # ffq-prev is ahead of us, and the only tree changes it has
1711 # are possibly addition of things in debian/patches/.
1712 # Just wind forwards rather than making a pointless pseudomerge.
1713 push @deferred_updates,
1714 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1715 update_head_checkout $old_head, $ffq_prev_commitish,
1716 "stitch (fast forward)";
1721 # We make pseudomerges with L as the contributing parent.
1722 # This makes git rev-list --first-parent work properly.
1723 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1724 'Declare fast forward / record previous work',
1725 "[git-debrebase pseudomerge: $prose]",
1727 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1728 update_head $old_head, $new_head, "stitch: $prose";
1731 sub do_stitch ($;$) {
1732 my ($prose, $unclean) = @_;
1734 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1735 if (!$ffq_prev_commitish) {
1736 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1739 my $dangling_head = get_head();
1741 keycommits $dangling_head, $unclean,$unclean,$unclean;
1744 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1747 sub upstream_commitish_search ($$) {
1748 my ($upstream_version, $tried) = @_;
1749 # todo: at some point maybe use git-deborig to do this
1750 foreach my $tagpfx ('', 'v', 'upstream/') {
1751 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1752 my $new_upstream = git_get_ref "refs/tags/$tag";
1754 return $new_upstream if length $new_upstream;
1758 sub resolve_upstream_version ($$) {
1759 my ($new_upstream, $upstream_version) = @_;
1761 if (!defined $new_upstream) {
1763 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1764 if (!length $new_upstream) {
1765 fail "Could not determine appropriate upstream commitish.\n".
1766 " (Tried these tags: @tried)\n".
1767 " Check version, and specify upstream commitish explicitly.";
1770 $new_upstream = git_rev_parse $new_upstream;
1772 return $new_upstream;
1775 sub cmd_new_upstream () {
1776 # automatically and unconditionally launders before rebasing
1777 # if rebase --abort is used, laundering has still been done
1781 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1783 # parse args - low commitment
1784 my $spec_version = shift @ARGV;
1785 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1786 fail "bad version number \`$spec_version'" unless defined $new_version;
1787 if ($new_version->is_native()) {
1788 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1791 my $new_upstream = shift @ARGV;
1792 my $new_upstream_version = upstreamversion $new_version;
1794 resolve_upstream_version $new_upstream, $new_upstream_version;
1799 my ($n, @x) = @_; # may be ''
1800 my $pc = $pieces{$n} //= {
1802 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1804 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1809 my $newpiece = sub {
1810 my ($n, @x) = @_; # may be ''
1811 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1812 push @newpieces, $pc;
1817 New => $new_upstream,
1819 while (@ARGV && $ARGV[0] !~ m{^-}) {
1820 my $n = shift @ARGV;
1822 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1823 unless @ARGV && $ARGV[0] !~ m{^-};
1825 my $c = git_rev_parse shift @ARGV;
1826 die unless $n =~ m/^$extra_orig_namepart_re$/;
1827 $newpiece->($n, New => $c);
1830 # now we need to investigate the branch this generates the
1831 # laundered version but we don't switch to it yet
1832 my $old_head = get_head();
1833 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1835 my $old_bw_cl = classify $old_bw;
1836 my $old_anchor_cl = classify $old_anchor;
1838 if (!$old_anchor_cl->{OrigParents}) {
1839 snag 'anchor-treated',
1840 'old anchor is recognised due to --anchor, cannot check upstream';
1842 $old_upstream = parsecommit
1843 $old_anchor_cl->{OrigParents}[0]{CommitId};
1844 $piece->('', Old => $old_upstream->{CommitId});
1847 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1848 if ($old_upstream->{Msg} =~
1849 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1851 my @oldpieces = (split / /, $1);
1852 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1853 if ($old_n_parents != @oldpieces &&
1854 $old_n_parents != @oldpieces + 1) {
1855 snag 'upstream-confusing', sprintf
1856 "previous upstream combine %s".
1857 " mentions %d pieces (each implying one parent)".
1858 " but has %d parents".
1859 " (one per piece plus maybe a previous combine)",
1860 $old_upstream->{CommitId},
1861 (scalar @oldpieces),
1863 } elsif ($oldpieces[0] ne '.') {
1864 snag 'upstream-confusing', sprintf
1865 "previous upstream combine %s".
1866 " first piece is not \`.'",
1870 foreach my $i (0..$#oldpieces) {
1871 my $n = $oldpieces[$i];
1872 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1873 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1877 snag 'upstream-confusing',
1878 "previous upstream $old_upstream->{CommitId} is from".
1879 " git-debrebase but not an \`upstream-combine' commit";
1883 foreach my $pc (values %pieces) {
1884 if (!$old_upstream) {
1885 # we have complained already
1886 } elsif (!$pc->{Old}) {
1887 snag 'upstream-new-piece',
1888 "introducing upstream piece \`$pc->{Name}'";
1889 } elsif (!$pc->{New}) {
1890 snag 'upstream-rm-piece',
1891 "dropping upstream piece \`$pc->{Name}'";
1892 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1893 snag 'upstream-not-ff',
1894 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1898 printdebug "%pieces = ", (dd \%pieces), "\n";
1899 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1907 my @upstream_merge_parents;
1910 push @upstream_merge_parents, $old_upstream->{CommitId};
1913 foreach my $pc (@newpieces) { # always has '' first
1915 read_tree_subdir $pc->{Name}, $pc->{New};
1917 runcmd @git, qw(read-tree), $pc->{New};
1919 push @upstream_merge_parents, $pc->{New};
1922 # index now contains the new upstream
1924 if (@newpieces > 1) {
1925 # need to make the upstream subtree merge commit
1926 $new_upstream = make_commit \@upstream_merge_parents,
1927 [ "Combine upstreams for $new_upstream_version",
1928 ("[git-debrebase upstream-combine . ".
1929 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1934 # $new_upstream is either the single upstream commit, or the
1935 # combined commit we just made. Either way it will be the
1936 # "upstream" parent of the anchor merge.
1938 read_tree_subdir 'debian', "$old_bw:debian";
1940 # index now contains the anchor merge contents
1941 $new_bw = make_commit [ $old_bw, $new_upstream ],
1942 [ "Update to upstream $new_upstream_version",
1943 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1946 my $clogsignoff = cmdoutput qw(git show),
1947 '--pretty=format:%an <%ae> %aD',
1950 # Now we have to add a changelog stanza so the Debian version
1952 die if unlink "debian";
1953 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1954 unlink "debian/changelog" or $!==ENOENT or die $!;
1955 mkdir "debian" or die $!;
1956 open CN, ">", "debian/changelog" or die $!;
1957 my $oldclog = git_cat_file ":debian/changelog";
1958 $oldclog =~ m/^($package_re) \(\S+\) / or
1959 fail "cannot parse old changelog to get package name";
1961 print CN <<END, $oldclog or die $!;
1962 $p ($new_version) UNRELEASED; urgency=medium
1964 * Update to new upstream version $new_upstream_version.
1970 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1972 # Now we have the final new breakwater branch in the index
1973 $new_bw = make_commit [ $new_bw ],
1974 [ "Update changelog for new upstream $new_upstream_version",
1975 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1979 # we have constructed the new breakwater. we now need to commit to
1980 # the laundering output, because git-rebase can't easily be made
1981 # to make a replay list which is based on some other branch
1983 update_head_postlaunder $old_head, $old_laundered_tip,
1984 'launder for new upstream';
1986 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1987 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1988 "debrebase new-upstream $new_version: rebase";
1990 # now it's for the user to sort out
1993 sub cmd_record_ffq_prev () {
1994 badusage "no arguments allowed" if @ARGV;
1995 my ($status, $msg) = record_ffq_prev_deferred();
1996 if ($status eq 'exists' && $opt_noop_ok) {
1997 print "Previous head already recorded\n" or die $!;
1998 } elsif ($status eq 'deferred') {
1999 run_deferred_updates 'record-ffq-prev';
2001 fail "Could not preserve: $msg";
2006 badusage "no arguments allowed" if @ARGV;
2007 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2008 print "$bw\n" or die $!;
2011 sub cmd_breakwater () {
2012 badusage "no arguments allowed" if @ARGV;
2013 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2014 print "$bw\n" or die $!;
2018 badusage "no arguments allowed" if @ARGV;
2020 # todo: gdr status should print divergence info
2021 # todo: gdr status should print upstream component(s) info
2022 # todo: gdr should leave/maintain some refs with this kind of info ?
2024 my $oldest = { Badness => 0 };
2027 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2028 if ($oldest->{Badness} < $badness) {
2029 $oldest = $newest = undef;
2032 Badness => $badness,
2033 CommitId => $cl->{CommitId},
2037 $newest //= $oldest;
2039 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2040 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2041 sub { $note->(2, 'branch is unlaundered', @_); },
2042 sub { $note->(3, 'branch needs laundering', @_); },
2043 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2045 my $prcommitinfo = sub {
2047 flush STDOUT or die $!;
2048 runcmd @git, qw(--no-pager log -n1),
2049 '--pretty=format: %h %s%n',
2053 print "current branch contents, in git-debrebase terms:\n";
2054 if (!$oldest->{Badness}) {
2055 print " branch is laundered\n";
2057 print " $oldest->{OurMsg}\n";
2059 foreach my $info ($oldest, $newest) {
2060 my $cid = $info->{CommitId};
2061 next if $cid eq $printed;
2063 print " $info->{KcMsg}\n";
2064 $prcommitinfo->($cid);
2069 my ($cid, $what) = @_;
2070 if (!defined $cid) {
2071 print " $what is not well-defined\n";
2074 $prcommitinfo->($cid);
2077 print "key git-debrebase commits:\n";
2078 $prab->($anchor, 'anchor');
2079 $prab->($bw, 'breakwater');
2081 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2082 ffq_prev_branchinfo();
2084 print "branch and ref status, in git-debrebase terms:\n";
2086 print " $ffq_msg\n";
2088 $ffq_prev = git_get_ref $ffq_prev;
2089 $gdrlast = git_get_ref $gdrlast;
2091 print " unstitched; previous tip was:\n";
2092 $prcommitinfo->($ffq_prev);
2093 } elsif (!$gdrlast) {
2094 print " stitched? (no record of git-debrebase work)\n";
2095 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2096 print " stitched\n";
2098 print " not git-debrebase (diverged since last stitch)\n"
2101 print "you are currently rebasing\n" if currently_rebasing();
2105 my $prose = 'stitch';
2106 getoptions("stitch",
2107 'prose=s', \$prose);
2108 badusage "no arguments allowed" if @ARGV;
2109 do_stitch $prose, 0;
2111 sub cmd_prepush () { cmd_stitch(); }
2114 badusage "no arguments allowed" if @ARGV;
2115 do_launder_head 'launder for git-debrebase quick';
2119 sub cmd_conclude () {
2120 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2121 if (!$ffq_prev_commitish) {
2122 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2125 my $dangling_head = get_head();
2127 badusage "no arguments allowed" if @ARGV;
2128 do_launder_head 'launder for git-debrebase quick';
2133 if (currently_rebasing()) {
2134 runcmd @git, qw(rebase --abort);
2136 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2137 if (!$ffq_prev_commitish) {
2138 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2141 my $scrapping_head = get_head();
2142 badusage "no arguments allowed" if @ARGV;
2143 push @deferred_updates,
2144 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2145 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2147 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2150 sub make_patches_staged ($) {
2152 # Produces the patches that would result from $head if it were
2154 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2157 gbp_pq_export 'bw', $secret_bw, $secret_head;
2161 sub make_patches ($) {
2163 keycommits $head, 0, \&snag;
2164 make_patches_staged $head;
2167 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2168 runcmd @git, qw(read-tree), $head;
2169 read_tree_subdir 'debian/patches', $ptree;
2170 $out = make_commit [$head], [
2171 'Commit patch queue (exported by git-debrebase)',
2172 '[git-debrebase: export and commit patches]',
2178 sub cmd_make_patches () {
2179 my $opt_quiet_would_amend;
2180 getoptions("make-patches",
2181 'quiet-would-amend!', \$opt_quiet_would_amend);
2182 badusage "no arguments allowed" if @ARGV;
2184 my $old_head = get_head();
2185 my $new = make_patches $old_head;
2186 my $d = get_differs $old_head, $new;
2188 fail "No (more) patches to export." unless $opt_noop_ok;
2190 } elsif ($d == D_PAT_ADD) {
2192 update_head_checkout $old_head, $new, 'make-patches';
2194 print STDERR failmsg
2195 "Patch export produced patch amendments".
2196 " (abandoned output commit $new).".
2197 " Try laundering first."
2198 unless $opt_quiet_would_amend;
2203 sub cmd_convert_from_gbp () {
2204 badusage "want only 1 optional argument, the upstream git commitish"
2207 my $clogp = parsechangelog();
2208 my $version = $clogp->{'Version'}
2209 // die "missing Version from changelog";
2211 my ($upstream_spec) = @ARGV;
2213 my $upstream_version = upstreamversion $version;
2215 resolve_upstream_version($upstream_spec, $upstream_version);
2217 my $old_head = get_head();
2219 my $upsdiff = get_differs $upstream, $old_head;
2220 if ($upsdiff & D_UPS) {
2221 runcmd @git, qw(--no-pager diff --stat),
2222 $upstream, $old_head,
2223 qw( -- :!/debian :/);
2225 upstream ($upstream_spec) and HEAD are not
2226 identical in upstream files. See diffstat above, or run
2227 git diff $upstream_spec HEAD -- :!/debian :/
2231 if (!is_fast_fwd $upstream, $old_head) {
2232 snag 'upstream-not-ancestor',
2233 "upstream ($upstream) is not an ancestor of HEAD";
2235 my $wrong = cmdoutput
2236 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2237 qw(-- :/ :!/debian));
2238 if (length $wrong) {
2239 snag 'unexpected-upstream-changes',
2240 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2241 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2245 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2246 snag 'upstream-has-debian',
2247 "upstream ($upstream) contains debian/ directory";
2250 my $previous_dgit_view = eval {
2251 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2253 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2254 my ($stz, $desc) = @_;
2255 no warnings qw(exiting);
2256 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2257 next unless $stz->{Date};
2258 next unless $stz->{Distribution} ne 'UNRELEASED';
2259 $lvsn = $stz->{Version};
2260 $suite = $stz->{Distribution};
2263 die "neither of the first two changelog entries are released\n"
2264 unless defined $lvsn;
2265 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2266 my $mtag_pat = debiantag_maintview $lvsn, '*';
2267 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2269 die "could not find suitable maintainer view tag $mtag_pat\n"
2270 unless $mtag_pat =~ m{/};
2271 is_fast_fwd $mtag, 'HEAD' or
2272 die "HEAD is not FF from maintainer tag $mtag!";
2273 my $dtag = "archive/$mtag";
2274 is_fast_fwd $mtag, $dtag or
2275 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2276 print "will stitch in dgit view, $dtag\n";
2277 git_rev_parse $dtag;
2279 if (!$previous_dgit_view) {
2282 print STDERR "cannot stitch in dgit view: $@\n";
2285 snags_maybe_bail_early();
2291 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2292 # make a branch out of the patch queue - we'll want this in a mo
2293 runcmd qw(gbp pq import);
2294 # strip the patches out
2295 runcmd @git, qw(checkout -q gdr-internal~0);
2296 rm_subdir_cached 'debian/patches';
2297 $work = make_commit ['HEAD'], [
2298 'git-debrebase convert-from-gbp: drop patches from tree',
2299 'Delete debian/patches, as part of converting to git-debrebase format.',
2300 '[git-debrebase convert-from-gbp: drop patches from tree]'
2302 # make the anchor merge
2303 # the tree is already exactly right
2304 $work = make_commit [$work, $upstream], [
2305 'git-debrebase import: declare upstream',
2306 'First breakwater merge.',
2307 '[git-debrebase anchor: declare upstream]'
2310 # rebase the patch queue onto the new breakwater
2311 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2312 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2313 $work = git_rev_parse 'HEAD';
2315 if ($previous_dgit_view) {
2316 $work = make_commit [$work, $previous_dgit_view], [
2317 'git-debrebase import: declare ff from dgit archive view',
2318 '[git-debrebase pseudomerge: import-from-gbp]',
2325 update_head_checkout $old_head, $work, 'convert-from-gbp';
2328 sub cmd_convert_to_gbp () {
2329 badusage "no arguments allowed" if @ARGV;
2330 my $head = get_head();
2331 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2332 keycommits $head, 0;
2334 make_patches_staged $head;
2336 $out = make_commit ['HEAD'], [
2337 'Commit patch queue (converted from git-debrebase format)',
2338 '[git-debrebase convert-to-gbp: commit patches]',
2342 push @deferred_updates, "delete $ffq";
2343 push @deferred_updates, "delete $gdrlast";
2346 update_head_checkout $head, $out, "convert to gbp (v0)";
2347 print <<END or die $!;
2348 git-debrebase: converted to git-buildpackage branch format
2349 git-debrebase: WARNING: do not now run "git-debrebase" any more
2350 git-debrebase: WARNING: doing so would drop all upstream patches!
2354 sub cmd_convert_from_dgit_view () {
2355 my $clogp = parsechangelog();
2357 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2363 getoptions("convert-from-dgit-view",
2364 'diagnose!', \$diagnose,
2365 'build-products-dir:s', \$bpd,
2366 'origs!', \$do_origs,
2368 'always-convert-anyway!', \$always);
2369 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2374 my $spec = shift @ARGV;
2375 my $commit = git_rev_parse "$spec^{commit}";
2376 push @upstreams, { Commit => $commit,
2377 Source => "$ARGV[0], from command line",
2382 my $head = get_head();
2386 my $trouble = sub { $troubles++; };
2387 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2388 printdebug "troubles=$troubles\n";
2391 $us: Branch already seems to be in git-debrebase format!
2392 $us: --always-convert-anyway would do the conversion operation anyway
2393 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2395 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2400 snags_maybe_bail_early();
2402 my $version = upstreamversion $clogp->{Version};
2403 print STDERR "Considering possible commits corresponding to upstream:\n";
2408 my $ups_tag = upstream_commitish_search $version, \@tried;
2410 my $this = "git tag $tried[-1]";
2411 push @upstreams, { Commit => $ups_tag,
2416 " git tag: no suitable tag found (tried %s)\n",
2421 my $p = $clogp->{'Source'};
2422 # we do a quick check to see if there are plausible origs
2424 if (!opendir BPD, $bpd) {
2425 die "$bpd: opendir: $!" unless $!==ENOENT;
2427 while ($!=0, my $f = readdir BPD) {
2428 next unless is_orig_file_of_p_v $f, $p, $version;
2430 " orig: found what looks like a .orig, %s\n",
2435 die "read $bpd: $!" if $!;
2439 my $tree = cmdoutput
2440 @dgit, qw(--build-products-dir), $bpd,
2441 qw(print-unapplied-treeish);
2444 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2445 rm_subdir_cached 'debian';
2446 $tree = cmdoutput @git, qw(write-tree);
2447 my $ups_synth = make_commit [], [ <<END, <<END,
2448 Import effective orig tree for upstream version $version
2450 This includes the contents of the .orig(s), minus any debian/ directory.
2452 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2455 push @upstreams, { Commit => $ups_synth,
2456 Source => "orig(s) imported via dgit",
2461 " orig: no suitable origs found (looked for %s in %s)\n",
2462 "${p}_".(stripeoch $version)."...", $bpd;
2467 my $some_patches = stat_exists 'debian/patches/series';
2469 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2472 foreach my $u (@upstreams) {
2476 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2477 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2478 runcmd @git, qw(clean -xdff);
2479 runcmd @git, qw(checkout), $head, qw(-- debian);
2480 if ($some_patches) {
2481 rm_subdir_cached 'debian/patches';
2482 $work = make_commit [ $work ], [
2483 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2484 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2485 "to git-debrebase format. Upstream changes will appear as commits.",
2486 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2489 $work = make_commit [ $work, $u->{Commit} ], [
2490 'git-debrebase convert-from-dgit-view: declare upstream',
2491 '(Re)constructed breakwater merge.',
2492 '[git-debrebase anchor: declare upstream]'
2494 runcmd @git, qw(checkout --quiet -b mk), $work;
2495 if ($some_patches) {
2496 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2497 runcmd @git, qw(reset --quiet);
2498 my @gbp_cmd = (qw(gbp pq import));
2500 my $gbp_err = "../gbp-pq-err";
2501 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2503 my $r = system @gbp_cmd;
2506 " %s: couldn't apply patches: gbp pq %s",
2507 $u->{Source}, waitstatusmsg();
2511 my $work = git_rev_parse qw(HEAD);
2512 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2513 if (length $diffout) {
2515 " $u->{Source}: applying patches gives different tree\n";
2516 print STDERR $diffout if $diagnose;
2520 $u->{Result} = $work;
2528 Could not find or construct a suitable upstream commit.
2529 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2530 upstream commmit explicitly or provide suitable origs.
2534 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2536 ffq_check $result->{Result};
2538 update_head_checkout $head, $result->{Result},
2539 'convert-from-dgit-view';
2542 sub cmd_downstream_rebase_launder_v0 () {
2543 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2545 $base = git_rev_parse $base;
2546 my $old_head = get_head();
2547 my $current = $old_head;
2550 if ($current eq $base) {
2551 $topmost_keep //= $current;
2552 print " $current BASE stop\n";
2555 my $cl = classify $current;
2556 print " $current $cl->{Type}";
2558 my $p0 = $cl->{Parents}[0]{CommitId};
2560 if ($cl->{Type} eq 'Pseudomerge') {
2561 print " ^".($cl->{Contributor}{Ix}+1);
2562 $next = $cl->{Contributor}{CommitId};
2563 } elsif ($cl->{Type} eq 'AddPatches' or
2564 $cl->{Type} eq 'Changelog') {
2574 $topmost_keep //= $current;
2576 die "to-be stripped changes not on top of the branch\n"
2581 if ($topmost_keep eq $old_head) {
2582 print "unchanged\n";
2584 print "updating to $topmost_keep\n";
2585 update_head_checkout
2586 $old_head, $topmost_keep,
2587 'downstream-rebase-launder-v0';
2593 "D+" => \$debuglevel,
2594 'noop-ok', => \$opt_noop_ok,
2595 'f=s' => \@snag_force_opts,
2596 'anchor=s' => \@opt_anchors,
2597 '--dgit=s' => \($dgit[0]),
2600 my ($opt,$val) = @_;
2601 badusage "git-debrebase: no cuddling to -i for git-rebase"
2603 die if $opt_defaultcmd_interactive; # should not happen
2604 $opt_defaultcmd_interactive = [ qw(-i) ];
2605 # This access to @ARGV is excessive familiarity with
2606 # Getopt::Long, but there isn't another sensible
2607 # approach. '-i=s{0,}' does not work with bundling.
2608 push @$opt_defaultcmd_interactive, @ARGV;
2611 'help' => sub { print $usage_message or die $!; finish 0; },
2614 initdebug('git-debrebase ');
2615 enabledebug if $debuglevel;
2617 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2618 chdir $toplevel or die "chdir $toplevel: $!";
2620 $rd = fresh_playground "$playprefix/misc";
2622 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2624 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2625 defaultcmd_rebase();
2627 my $cmd = shift @ARGV;
2630 $cmdfn = ${*::}{"cmd_$cmdfn"};
2632 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";