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 our ($usage_message) = <<'END';
41 git-debrebase [<options>] [--|-i <git rebase options...>]
42 git-debrebase [<options>] status
43 git-debrebase [<options>] prepush [--prose=...]
44 git-debrebase [<options>] quick|conclude
45 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
46 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
48 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
51 our ($opt_force, $opt_noop_ok, @opt_anchors);
52 our ($opt_defaultcmd_interactive);
54 our $us = qw(git-debrebase);
60 print STDERR "$us: bad usage: $m\n";
66 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
67 GetOptions @_ or badusage $m;
71 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
75 my ($k, $optional) = @_;
77 my @cmd = qw(git config -z);
78 push @cmd, qw(--get-all) if wantarray;
80 my $out = cmdoutput_errok @cmd;
82 fail "missing required git config $k" unless $optional;
85 my @l = split /\0/, $out;
86 return wantarray ? @l : $l[0];
93 my $dd = new Data::Dumper [ $v ];
94 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
100 my $data = (git_cat_file $objid, 'commit');
101 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
105 sub D_UPS () { 0x02; } # upstream files
106 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
107 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
108 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
109 sub D_DEB_OTH () { 0x20; } # debian/changelog
110 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
112 our $playprefix = 'debrebase';
117 our @dgit = qw(dgit);
119 sub in_workarea ($) {
122 my $r = eval { $sub->(); };
123 { local $@; changedir $maindir; }
127 sub fresh_workarea () {
128 $workarea = fresh_playground "$playprefix/work";
129 in_workarea sub { playtree_setup };
132 our $snags_forced = 0;
133 our $snags_tripped = 0;
134 our $snags_summarised = 0;
135 our @deferred_updates;
136 our @deferred_update_messages;
138 sub all_snags_summarised () {
139 $snags_forced + $snags_tripped == $snags_summarised;
141 sub run_deferred_updates ($) {
144 confess 'dangerous internal error' unless all_snags_summarised();
146 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
147 debugcmd '>|', @upd_cmd;
148 open U, "|-", @upd_cmd or die $!;
149 foreach (@deferred_updates) {
150 printdebug ">= ", $_, "\n";
151 print U $_, "\n" or die $!;
154 close U or failedcmd @upd_cmd;
156 print $_, "\n" foreach @deferred_update_messages;
158 @deferred_updates = ();
159 @deferred_update_messages = ();
162 sub get_differs ($$) {
164 # This resembles quiltify_trees_differ, in dgit, a bit.
165 # But we don't care about modes, or dpkg-source-unrepresentable
166 # changes, and we don't need the plethora of different modes.
167 # Conversely we need to distinguish different kinds of changes to
168 # debian/ and debian/patches/.
173 my ($opts, $limits, $fn) = @_;
174 my @cmd = (@git, qw(diff-tree -z --no-renames));
176 push @cmd, "$_:" foreach $x, $y;
177 push @cmd, '--', @$limits;
178 my $diffs = cmdoutput @cmd;
179 foreach (split /\0/, $diffs) { $fn->(); }
182 $rundiff->([qw(--name-only)], [], sub {
183 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
186 if ($differs & DS_DEB) {
188 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
190 m{^debian/patches/} ? D_PAT_OTH :
191 $_ eq 'debian/changelog' ? D_DEB_CLOG :
194 die "mysterious debian changes $x..$y"
195 unless $differs & (D_PAT_OTH|DS_DEB);
198 if ($differs & D_PAT_OTH) {
200 $differs &= ~D_PAT_OTH;
202 $differs |= D_PAT_OTH;
203 no warnings qw(exiting); last;
205 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
206 no warnings qw(exiting);
207 if (!defined $mode) {
210 die unless s{^debian/patches/}{};
212 if ($mode eq 'A' && !m/\.series$/s) {
214 } elsif ($mode eq 'M' && $_ eq 'series') {
215 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
216 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
217 chomp $x_s; $x_s .= "\n";
218 $ok = $x_s eq substr($y_s, 0, length $x_s);
223 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
225 die "mysterious debian/patches changes $x..$y"
226 unless $differs & (D_PAT_ADD|D_PAT_OTH);
229 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
234 sub commit_pr_info ($) {
236 return Data::Dumper->dump([$r], [qw(commit)]);
239 sub calculate_committer_authline () {
240 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
241 'DUMMY COMMIT (git-debrebase)', "HEAD:";
242 my ($h,$m) = get_commit $c;
243 $h =~ m/^committer .*$/m or confess "($h) ?";
247 sub rm_subdir_cached ($) {
249 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
252 sub read_tree_subdir ($$) {
253 my ($subdir, $new_tree_object) = @_;
254 rm_subdir_cached $subdir;
255 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
258 sub read_tree_debian ($) {
260 read_tree_subdir 'debian', "$treeish:debian";
261 rm_subdir_cached 'debian/patches';
264 sub read_tree_upstream ($;$) {
265 my ($treeish, $keep_patches) = @_;
266 my $save = cmdoutput @git, qw(write-tree --prefix=debian/);
267 runcmd @git, qw(read-tree), $treeish;
268 read_tree_subdir 'debian', $save;
269 rm_subdir_cached 'debian/patches' unless $keep_patches;
272 sub make_commit ($$) {
273 my ($parents, $message_paras) = @_;
274 my $tree = cmdoutput @git, qw(write-tree);
275 my @cmd = (@git, qw(commit-tree), $tree);
276 push @cmd, qw(-p), $_ foreach @$parents;
277 push @cmd, qw(-m), $_ foreach @$message_paras;
278 return cmdoutput @cmd;
281 our @snag_force_opts;
283 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
284 if (grep { $_ eq $tag } @snag_force_opts) {
286 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
289 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
293 # Important: all mainline code must call snags_maybe_bail after
294 # any point where snag might be called, but before making changes
295 # (eg before any call to run_deferred_updates). snags_maybe_bail
296 # may be called more than once if necessary (but this is not ideal
297 # because then the messages about number of snags may be confusing).
298 sub snags_maybe_bail () {
299 return if all_snags_summarised();
302 "%s: snags: %d overriden by individual -f options\n",
305 if ($snags_tripped) {
308 "%s: snags: %d overriden by global --force\n",
312 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
316 $snags_summarised = $snags_forced + $snags_tripped;
318 sub snags_maybe_bail_early () {
319 # useful to bail out early without doing a lot of work;
320 # not a substitute for snags_maybe_bail.
321 snags_maybe_bail() if $snags_tripped && !$opt_force;
324 return $snags_forced || $snags_tripped;
327 sub gbp_pq_export ($$$) {
328 my ($bname, $base, $tip) = @_;
329 # must be run in a workarea. $bname and patch-queue/$bname
330 # ought not to exist. Leaves you on patch-queue/$bname with
331 # the patches staged but not committed.
332 printdebug "gbp_pq_export $bname $base $tip\n";
333 runcmd @git, qw(checkout -q -b), $bname, $base;
334 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
335 my @gbp_cmd = (qw(gbp pq export));
336 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
338 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
341 runcmd @git, qw(add -f debian/patches);
345 # xxx allow merge separately from laundering
347 # xxx docs highlight forbidden things
348 # xxx docs list allowable things ?
349 # xxx docs explicitly forbid some rebase
351 # xxx provide a way for the user to help
352 # xxx (eg, provide wreckage provide way to continue)
355 # use git-format-patch?
356 # our own patch identification algorithm?
357 # this is an alternative strategy
359 sub merge_series ($$;@) {
360 my ($newbase, $base_q, @input_qs) = @_;
361 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
362 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
363 # ^ specifies several patch series (currently we only support exactly 2)
364 # return value is a commit which is the result of
365 # merging the two versions of the same topic branch
366 # $input_q[0] and $input_q[1]
367 # with respect to the old version
371 # Creates, in *_q, a key MR for its private use
373 printdebug "merge_series newbase=$newbase\n";
375 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
376 $base_q->{MR}{S} = 'base';
379 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
380 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
381 # $prereq{<patch filename>} exists or not (even later)
385 local $workarea = fresh_playground "$playprefix/merge";
386 my $seriesfile = "debian/patches/series";
389 foreach my $q ($base_q, reverse @input_qs) {
391 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
392 if (open S, $seriesfile) {
394 while (my $patch = <S>) {
395 chomp $patch or die $!;
396 foreach my $earlier (@earlier) {
397 $prereq{$patch}{$earlier}{$s}++ and die;
399 push @earlier, $patch;
400 stat "debian/patches/$patch" or die "$patch ?";
402 S->error and die "$seriesfile $!";
405 die "$seriesfile $!" unless $!==ENOENT;
407 read_tree_upstream $newbase, 1;
408 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
409 "Convert $s to patch queue for merging",
410 "[git-debrebase merge-innards patch-queue import:".
413 printdebug "merge_series pec $pec ";
414 runcmd @git, qw(rm -q --cached), $seriesfile;
415 $pec = make_commit [ $pec ], [
416 "Drop series file from $s to avoid merge trouble",
417 "[git-debrebase merge-innards patch-queue prep:".
420 printdebug "pec' $pec\n";
421 runcmd @git, qw(reset -q --hard), $pec;
422 $q->{MR}{PEC} = $pec;
424 # now, because of reverse, we are on $input_q->{MR}{OQC}
425 runcmd @git, qw(checkout -q -b merge);
426 printdebug "merge_series merging...\n";
427 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
428 debugcmd '+', @mergecmd;
430 if (system @mergecmd) {
434 printdebug "merge_series merge ok, series...\n";
435 # We need to construct a new series file
436 # Firstly, resolve prereq
437 foreach my $f (sort keys %prereq) {
438 printdebug "merge_series patch\t$f\t";
439 if (!stat_exists "debian/patches/$f") {
440 print DEBUG " drop\n" if $debuglevel;
441 # git merge deleted it; that's how we tell it's not wanted
445 print DEBUG " keep\n" if $debuglevel;
446 foreach my $g (sort keys %{ $prereq{$f} }) {
447 my $gfp = $prereq{$f}{$g};
448 printdebug "merge_series prereq\t$f\t-> $g\t";
449 if (!!$gfp->{0} == !!$gfp->{1}
452 print DEBUG "\tkeep\n" if $debuglevel;
454 print DEBUG "\tdrop\n" if $debuglevel;
455 delete $prereq{$f}{$g};
462 return scalar keys %{ $prereq{$f} };
465 my $nodate = time + 1;
467 # $authordate{<patch filename>};
468 my $authordate = sub {
470 $authordate{$f} //= do {
471 open PF, "<", "debian/patches/$f" or die "$f $!";
473 return $nodate if m/^$/;
474 last if s{^Date: }{};
477 return cmdoutput qw(date +%s -d), $_;
481 open NS, '>', $seriesfile or die $!;
483 while (keys %prereq) {
485 foreach my $try (sort keys %prereq) {
488 $unsat->($try) <=> $unsat->($best) or
489 $authordate->($try) <=> $authordate->($best) or
495 printdebug "merge_series series next $best\n";
496 print NS "$best\n" or die $!;
497 delete $prereq{$best};
498 foreach my $gp (values %prereq) {
503 runcmd @git, qw(add), $seriesfile;
504 runcmd @git, qw(commit --quiet -m), 'Merged series';
506 printdebug "merge_series series gbp pq import\n";
507 runcmd qw(gbp pq import);
509 # OK now we are on patch-queue/merge, and we need to rebase
510 # onto the intended parent and drop the patches from each one
512 printdebug "merge_series series ok, building...\n";
513 my $build = $newbase;
514 my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
515 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
516 my $commit = git_cat_file $c, 'commit';
517 printdebug "merge_series series ok, building $c\n";
518 read_tree_upstream $c;
519 my $tree = cmdoutput @git, qw(write-tree);
520 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
521 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
522 open C, ">", "../mcommit" or die $!;
523 print C $commit or die $!;
525 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
528 runcmd @git, qw(update-ref refs/heads/result), $result;
530 printdebug "merge_series returns $result\n";
534 # classify returns an info hash like this
536 # Hdr => # commit headers, including 1 final newline
537 # Msg => # commit message (so one newline is dropped)
539 # Type => (see below)
541 # Ix => $index # ie 0, 1, 2, ...
543 # Differs => return value from get_differs
545 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
547 # NewMsg => # commit message, but with any [dgit import ...] edited
548 # # to say "[was: ...]"
558 # has additional entres in classification result
559 # Overwritten = [ subset of Parents ]
560 # Contributor = $the_remaining_Parent
562 # DgitImportUnpatched
563 # has additional entry in classification result
564 # OrigParents = [ subset of Parents ]
567 # has additional entry in classification result
568 # OrigParents = [ subset of Parents ] # singleton list
575 # has additional entry in classification result
578 sub parsecommit ($;$) {
579 my ($objid, $p_ref) = @_;
580 # => hash with CommitId Hdr Msg Tree Parents
581 # Parents entries have only Ix CommitId
582 # $p_ref, if provided, must be [] and is used as a base for Parents
587 my ($h,$m) = get_commit $objid;
589 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
590 my (@ph) = $h =~ m/^parent (\w+)$/mg;
600 foreach my $ph (@ph) {
602 Ix => scalar @$p_ref,
614 my $r = parsecommit($objid, \@p);
618 $p->{Differs} = (get_differs $p->{CommitId}, $t),
621 printdebug "classify $objid \$t=$t \@p",
622 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
626 my ($type, @rest) = @_;
627 $r = { %$r, Type => $type, @rest };
629 printdebug " = $type ".(dd $r)."\n";
635 $r = { %$r, Type => qw(Unknown), Why => $why };
636 printdebug " ** Unknown\n";
640 if (grep { $_ eq $objid } @opt_anchors) {
641 return $classify->('TreatAsAnchor');
644 my @identical = grep { !$_->{Differs} } @p;
645 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
646 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
648 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
649 # multi-orig upstreams are represented with an anchor merge
650 # from a single upstream commit which combines the orig tarballs
652 # Every anchor tagged this way must be a merge.
653 # We are relying on the
654 # [git-debrebase anchor: ...]
655 # commit message annotation in "declare" anchor merges (which
656 # do not have any upstream changes), to distinguish those
657 # anchor merges from ordinary pseudomerges (which we might
658 # just try to strip).
660 # However, the user is going to be doing git-rebase a lot. We
661 # really don't want them to rewrite an anchor commit.
662 # git-rebase trips up on merges, so that is a useful safety
665 # BreakwaterStart commits are also anchors in the terminology
666 # of git-debrebase(5), but they are untagged (and always
667 # manually generated).
669 # We cannot not tolerate any tagged linear commit (ie,
670 # BreakwaterStart commits tagged `[anchor:') because such a
671 # thing could result from an erroneous linearising raw git
672 # rebase of a merge anchor. That would represent a corruption
673 # of the branch. and we want to detect and reject the results
674 # of such corruption before it makes it out anywhere. If we
675 # reject it here then we avoid making the pseudomerge which
676 # would be needed to push it.
678 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
679 @p == 2 or return $badanchor->("has other than two parents");
680 $haspatches and return $badanchor->("contains debian/patches");
682 # How to decide about l/r ordering of anchors ? git
683 # --topo-order prefers to expand 2nd parent first. There's
684 # already an easy rune to look for debian/ history anyway (git log
685 # debian/) so debian breakwater branch should be 1st parent; that
686 # way also there's also an easy rune to look for the upstream
687 # patches (--topo-order).
689 # Also this makes --first-parent be slightly more likely to
690 # be useful - it makes it provide a linearised breakwater history.
692 # Of course one can say somthing like
693 # gitk -- ':/' ':!/debian'
694 # to get _just_ the commits touching upstream files, and by
695 # the TREESAME logic in git-rev-list this will leave the
696 # breakwater into upstream at the first anchor. But that
697 # doesn't report debian/ changes at all.
699 # Other observations about gitk: by default, gitk seems to
700 # produce output in a different order to git-rev-list. I
701 # can't seem to find this documented anywhere. gitk
702 # --date-order DTRT. But, gitk always seems to put the
703 # parents from left to right, in order, so it's easy to see
704 # which way round a pseudomerge is.
706 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
707 $p[1]{Differs} & ~DS_DEB and
708 $badanchor->("upstream files differ from left parent");
709 $p[0]{Differs} & ~D_UPS and
710 $badanchor->("debian/ differs from right parent");
712 return $classify->(qw(Anchor),
713 OrigParents => [ $p[1] ]);
717 my $d = $r->{Parents}[0]{Differs};
718 if ($d == D_PAT_ADD) {
719 return $classify->(qw(AddPatches));
720 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
721 return $unknown->("edits debian/patches");
722 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
723 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
725 if ($d == D_DEB_CLOG) {
726 return $classify->(qw(Changelog));
728 return $classify->(qw(Packaging));
730 } elsif ($ty eq 'missing') {
731 return $classify->(qw(BreakwaterStart));
733 return $unknown->("parent's debian is not a directory");
735 } elsif ($d == D_UPS) {
736 return $classify->(qw(Upstream));
737 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
738 return $classify->(qw(Mixed));
740 return $unknown->("no changes");
742 confess "internal error $objid ?";
746 return $unknown->("origin commit");
749 if (@p == 2 && @identical == 1) {
750 my @overwritten = grep { $_->{Differs} } @p;
751 confess "internal error $objid ?" unless @overwritten==1;
752 return $classify->(qw(Pseudomerge),
753 Overwritten => [ $overwritten[0] ],
754 Contributor => $identical[0]);
756 if (@p == 2 && @identical == 2) {
758 my ($ph,$pm) = get_commit $_[0]{CommitId};
759 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
763 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
764 if ($order > 0) { # newer first
765 } elsif ($order < 0) {
766 @bytime = reverse @bytime;
768 # same age, default to order made by -s ours
769 # that is, commit was made by someone who preferred L
771 return $classify->(qw(Pseudomerge),
772 SubType => qw(Ambiguous),
773 Contributor => $bytime[0],
774 Overwritten => [ $bytime[1] ]);
777 my ($p_h, $p_m) = get_commit $p->{CommitId};
778 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
779 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
781 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
783 if (!(grep { !$_->{IsOrigin} } @p) and
784 (@orig_ps >= @p - 1) and
785 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
787 return $classify->(qw(DgitImportUnpatched),
788 OrigParents => \@orig_ps);
792 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
793 # xxx ^ metadata tag needs adding to (5)
794 return $classify->("MergedBreakwaters");
796 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
797 return $unknown->("unknown kind of merge from $1");
800 return $unknown->("octopus merge");
803 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
804 return $unknown->("general two-parent merge");
807 return $classify->("VanillaMerge");
810 sub keycommits ($;$$$$) {
811 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
812 # => ($anchor, $breakwater)
814 # $unclean->("unclean-$tagsfx", $msg, $cl)
815 # $furniture->("unclean-$tagsfx", $msg, $cl)
816 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
817 # is callled for each situation or commit that
818 # wouldn't be found in a laundered branch
819 # $furniture is for furniture commits such as might be found on an
820 # interchange branch (pseudomerge, d/patches, changelog)
821 # $trouble is for things whnich prevent the return of
822 # anchor and breakwater information; if that is ignored,
823 # then keycommits returns (undef, undef) instead.
824 # $fatal is for unprocessable commits, and should normally cause
825 # a failure. If ignored, agaion, (undef, undef) is returned.
827 # If a callback is undef, fail is called instead.
828 # If a callback is defined but false, the situation is ignored.
830 # no warnings qw(exiting); last;
831 # if the answer is no longer wanted.
833 my ($anchor, $breakwater);
837 $fatal //= sub { fail $_[1]; };
839 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
840 my $why = $mainwhy.$xwhy;
841 my $m = "branch needs laundering (run git-debrebase): $why";
842 fail $m unless defined $cb;
844 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
847 $cl = classify $head;
848 my $ty = $cl->{Type};
849 if ($ty eq 'Packaging') {
850 $breakwater //= $clogonly;
851 $breakwater //= $head;
852 } elsif ($ty eq 'Changelog') {
853 # this is going to count as the tip of the breakwater
854 # only if it has no upstream stuff before it
856 } elsif ($ty eq 'Anchor' or
857 $ty eq 'TreatAsAnchor' or
858 $ty eq 'BreakwaterStart') {
860 $breakwater //= $clogonly;
861 $breakwater //= $head;
863 } elsif ($ty eq 'Upstream') {
864 $x->($unclean, 'ordering',
865 "packaging change ($breakwater) follows upstream change"," (eg $head)")
866 if defined $breakwater;
869 } elsif ($ty eq 'Mixed') {
870 $x->($unclean, 'mixed',
871 "found mixed upstream/packaging commit"," ($head)");
874 } elsif ($ty eq 'Pseudomerge' or
875 $ty eq 'AddPatches') {
877 $x->($furniture, (lc $ty),
878 "found interchange bureaucracy commit ($ty)"," ($head)");
879 } elsif ($ty eq 'DgitImportUnpatched') {
881 $x->($trouble, 'dgitimport',
882 "found dgit dsc import"," ($head)");
883 return (undef,undef);
885 $x->($fatal, 'unprocessable',
886 "found bare dgit dsc import with no prior history",
888 return (undef,undef);
890 } elsif ($ty eq 'VanillaMerge') {
891 $x->($trouble, 'vanillamerge',
892 "found vanilla merge"," ($head)");
893 return (undef,undef);
895 $x->($fatal, 'unprocessable',
896 "found unprocessable commit, cannot cope: $cl->{Why}",
898 return (undef,undef);
900 $head = $cl->{Parents}[0]{CommitId};
902 return ($anchor, $breakwater);
908 $nogenerate,$report, $report_lprefix) = @_;
909 # => ($tip, $breakwater_tip, $last_anchor)
910 # (or nothing, if $nogenerate)
912 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
913 $report_lprefix //= '';
915 # go through commits backwards
916 # we generate two lists of commits to apply:
917 # breakwater branch and upstream patches
918 my (@brw_cl, @upp_cl, @processed);
925 my ($prose, $info) = @_;
929 $ms .= "\n\n[git-debrebase$info: $prose]\n";
932 my $rewrite_from_here = sub {
934 my $sp_cl = { SpecialMethod => 'StartRewrite' };
936 push @processed, $sp_cl;
941 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
944 return unless $report;
945 print $report $prdelim, $report_lprefix, @_;
949 my $bomb = sub { # usage: return $bomb->();
950 print $report " Unprocessable" if $report;
951 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
954 return (undef,undef);
956 fail "found unprocessable commit, cannot cope".
957 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
958 " (commit $cur) (d.".
959 (join ' ', map { sprintf "%#x", $_->{Differs} }
960 @{ $cl->{Parents} }).
967 my $build_start = sub {
968 my ($msg, $parent) = @_;
971 no warnings qw(exiting); last;
975 fail "something useful about failed merge attempt @_ xxx".Dumper($cl);
982 my $ty = $cl->{Type};
983 my $st = $cl->{SubType};
984 $prline->("$cl->{CommitId} $cl->{Type}");
985 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
986 push @processed, $cl;
987 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
988 if ($ty eq 'AddPatches') {
990 $rewrite_from_here->(\@upp_cl);
992 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
996 } elsif ($ty eq 'BreakwaterStart') {
998 $build_start->('FirstPackaging', $cur);
999 } elsif ($ty eq 'Upstream') {
1003 } elsif ($ty eq 'Mixed') {
1006 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1009 $queue->(\@brw_cl, "debian");
1010 $queue->(\@upp_cl, "upstream");
1011 $rewrite_from_here->(\@brw_cl);
1014 } elsif ($ty eq 'Pseudomerge') {
1015 my $contrib = $cl->{Contributor}{CommitId};
1016 print $report " Contributor=$contrib" if $report;
1017 push @pseudomerges, $cl;
1018 $rewrite_from_here->(\@upp_cl);
1021 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1022 $last_anchor = $cur;
1023 $build_start->("Anchor", $cur);
1024 } elsif ($ty eq 'DgitImportUnpatched') {
1025 my $pm = $pseudomerges[-1];
1027 # To an extent, this is heuristic. Imports don't have
1028 # a useful history of the debian/ branch. We assume
1029 # that the first pseudomerge after an import has a
1030 # useful history of debian/, and ignore the histories
1031 # from later pseudomerges. Often the first pseudomerge
1032 # will be the dgit import of the upload to the actual
1033 # suite intended by the non-dgit NMUer, and later
1034 # pseudomerges may represent in-archive copies.
1035 my $ovwrs = $pm->{Overwritten};
1036 printf $report " PM=%s \@Overwr:%d",
1037 $pm->{CommitId}, (scalar @$ovwrs)
1040 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1043 my $ovwr = $ovwrs->[0]{CommitId};
1044 printf $report " Overwr=%s", $ovwr if $report;
1045 # This import has a tree which is just like a
1046 # breakwater tree, but it has the wrong history. It
1047 # ought to have the previous breakwater (which the
1048 # pseudomerge overwrote) as an ancestor. That will
1049 # make the history of the debian/ files correct. As
1050 # for the upstream version: either it's the same as
1051 # was ovewritten (ie, same as the previous
1052 # breakwater), in which case that history is precisely
1053 # right; or, otherwise, it was a non-gitish upload of a
1054 # new upstream version. We can tell these apart by
1055 # looking at the tree of the supposed upstream.
1058 SpecialMethod => 'DgitImportDebianUpdate',
1059 $xmsg->("convert dgit import: debian changes")
1062 SpecialMethod => 'DgitImportUpstreamUpdate',
1063 $xmsg->("convert dgit import: upstream update",
1066 $prline->(" Import");
1067 $rewrite_from_here->(\@brw_cl);
1068 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1072 # Everything is from this import. This kind of import
1073 # is already nearly in valid breakwater format, with the
1074 # patches as commits. Unfortunately it contains
1076 printdebug "*** WALK BOMB bare dgit import\n";
1077 $cl->{Why} = "bare dgit dsc import";
1081 } elsif ($ty eq 'VanillaMerge' or $ty eq 'MergedBreakwaters') {
1082 # xxx need to handle ffq if one side was unstitched
1083 # wait both of them may be!
1086 # We expect to find a dominating anchor amongst the
1087 # inputs' anchors. That will be the new anchor.
1089 # More complicated is finding a merge base for the
1090 # breakwaters. We need a merge base that is a breakwater
1091 # commit. The ancestors of breakwater commits are more
1092 # breakwater commits and possibly upstream commits and the
1093 # ancestors of those upstream. Upstreams might have
1094 # arbitrary ancestors. But any upstream commit U is
1095 # either included in both anchors, in which case the
1096 # earlier anchor is a better merge base than any of U's
1097 # ancestors; or U is not included in the older anchor, in
1098 # which case U is not an ancestor of the vanilla merge at
1099 # all. So no upstream commit, nor any ancestor thereof,
1100 # is a best merge base. As for non-breakwater Debian
1101 # commits: these are never ancestors of any breakwater.
1103 # So any best merge base as found by git-merge-base
1104 # is a suitable breakwater anchor. Usually there will
1107 printdebug "*** MERGE\n";
1109 # xxx avoid calling walk without nogenerate when
1110 # we have a MergedBreakwater; instead call keycommits ?
1112 my @bwbcmd = (@git, qw(merge-base));
1113 my @ibcmd = (@git, qw(merge-base --all));
1114 my $might_be_in_bw = 1;
1116 my $ps = $cl->{Parents};
1118 foreach my $p (@$ps) {
1119 $prline->(" VanillaMerge ".$p->{Ix});
1121 my ($ptip, $pbw, $panchor) =
1122 walk $p->{CommitId}, 0, $report,
1123 $report_lprefix.' ';
1124 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1125 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1126 $p->{Anchor} = $panchor;
1128 $best_anchor = $panchor if
1129 !defined $best_anchor or
1130 is_fast_fwd $best_anchor, $panchor;
1132 printdebug " MERGE BA best=".($best_anchor//'-').
1136 foreach my $p (@$ps) {
1137 $prline->(" VanillaMerge ".$p->{Ix});
1138 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1139 $nomerge->('DivergentAnchor');
1140 } elsif ($p->{Anchor} eq $best_anchor) {
1141 print $report " SameAnchor" if $report;
1143 print $report " SupersededAnchor" if $report;
1145 if ($p->{Breakwater} eq $p->{CommitId}) {
1146 # this parent commit was its own breakwater,
1147 # ie it is part of the breakwater
1148 print $report " Breakwater" if $report;
1150 $might_be_in_bw = 0;
1152 push @bwbcmd, $p->{Breakwater};
1153 push @ibcmd, $p->{CommitId};
1156 if ($ok && $might_be_in_bw) {
1157 $prline->(" VanillaMerge MergedBreakwaters");
1158 $last_anchor = $best_anchor;
1159 $build_start->('MergedBreakwaters', $cur);
1162 $nomerge->("alleged merged-breakwater is not a breakwater")
1163 unless $ty eq 'VanillaMerge';
1165 my $bwb = cmdoutput @bwbcmd;
1167 # OK, now we have a breakwater base, but we need the merge
1168 # base for the interchange branch because we need the delta
1171 # This a the best merge base of our inputs which has the
1172 # breakwater merge base as an ancestor.
1175 grep { is_fast_fwd $bwb, $_ }
1180 or $nomerge->("no suitable interchange merge base");
1182 $prline->(" VanillaMerge Base");
1184 my ($btip, $bbw, $banchor) =
1185 walk $ib, 0, $report, $report_lprefix.' ';
1187 my $ibinfo = { SeriesTip => $btip,
1189 Anchor => $banchor };
1191 or $nomerge->("interchange merge-base ($ib)'s".
1192 " breakwater ($bbw)".
1193 " != breakwaters' merge-base ($bwb)");
1194 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1195 or $nomerge->("interchange merge-base ($ib)'s".
1196 " anchor ($ibinfo->{SeriesBase})".
1197 " != any merge input's anchor (".
1198 (join ' ', map { $_->{Anchor} } @$ps).
1202 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1203 $cl->{MergeBestAnchor} = $best_anchor;
1206 SpecialMethod => 'MergeCreateMergedBreakwaters',
1207 $xmsg->('construct merged breakwater from vanilla merge'),
1211 SpecialMethod => 'MergeMergeSeries',
1213 $build_start->('MergeBreakwaters', $cur);
1215 printdebug "*** WALK BOMB unrecognised\n";
1221 printdebug "*** WALK prep done cur=$cur".
1222 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1224 return if $nogenerate;
1226 # Now we build it back up again
1232 $#upp_cl = $upp_limit if defined $upp_limit;
1234 my $committer_authline = calculate_committer_authline();
1236 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1238 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1241 mkdir $rd or $!==EEXIST or die $!;
1243 runcmd @git, qw(read-tree), $build;
1244 foreach my $cl (qw(Debian), (reverse @brw_cl),
1245 { SpecialMethod => 'RecordBreakwaterTip' },
1246 qw(Upstream), (reverse @upp_cl)) {
1248 $current_method = $cl;
1251 my $method = $cl->{SpecialMethod} // $current_method;
1252 my @parents = ($build);
1253 my $cltree = $cl->{CommitId};
1254 printdebug "WALK BUILD ".($cltree//'undef').
1255 " $method (rewriting=$rewriting)\n";
1256 if ($method eq 'Debian') {
1257 read_tree_debian($cltree);
1258 } elsif ($method eq 'Upstream') {
1259 read_tree_upstream($cltree);
1260 } elsif ($method eq 'StartRewrite') {
1263 } elsif ($method eq 'RecordBreakwaterTip') {
1264 $breakwater = $build;
1266 } elsif ($method eq 'DgitImportDebianUpdate') {
1267 read_tree_debian($cltree);
1268 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1269 confess unless $rewriting;
1270 my $differs = (get_differs $build, $cltree);
1271 next unless $differs & D_UPS;
1272 read_tree_upstream($cltree);
1273 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1274 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1275 print "Found a general merge, will try to tidy it up.\n";
1277 read_tree_upstream($cl->{MergeBestAnchor});
1278 read_tree_upstream($cl->{MergeBestAnchor});
1279 read_tree_debian($cltree);
1280 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1281 } elsif ($method eq 'MergeMergeSeries') {
1282 print "Running merge resolution for $cl->{CommitId}...\n";
1283 $build = merge_series
1285 $cl->{MergeInterchangeBaseInfo},
1286 @{ $cl->{Parents} };
1287 $last_anchor = $cl->{MergeBestAnchor};
1288 # xxx need to check the tree somehow
1289 print "Merge resolution successful.\n";
1292 confess "$method ?";
1295 my $procd = (pop @processed) // 'UNDEF';
1296 if ($cl ne $procd) {
1298 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1301 my $newtree = cmdoutput @git, qw(write-tree);
1302 my $ch = $cl->{Hdr};
1303 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1304 $ch =~ s{^parent .*\n}{}mg;
1305 $ch =~ s{(?=^author)}{
1306 join '', map { "parent $_\n" } @parents
1307 }me or confess "$ch ?";
1309 $ch =~ s{^committer .*$}{$committer_authline}m
1312 my $cf = "$rd/m$rewriting";
1313 open CD, ">", $cf or die $!;
1314 print CD $ch, "\n", $cl->{Msg} or die $!;
1316 my @cmd = (@git, qw(hash-object));
1317 push @cmd, qw(-w) if $rewriting;
1318 push @cmd, qw(-t commit), $cf;
1319 my $newcommit = cmdoutput @cmd;
1320 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1321 $build = $newcommit;
1322 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1323 $last_anchor = $cur;
1328 my $final_check = get_differs $build, $input;
1329 die sprintf "internal error %#x %s %s", $final_check, $build, $input
1330 if $final_check & ~D_PAT_ADD;
1332 my @r = ($build, $breakwater, $last_anchor);
1333 printdebug "*** WALK RETURN @r\n";
1338 git_check_unmodified();
1339 return git_rev_parse qw(HEAD);
1342 sub update_head ($$$) {
1343 my ($old, $new, $mrest) = @_;
1344 push @deferred_updates, "update HEAD $new $old";
1345 run_deferred_updates $mrest;
1348 sub update_head_checkout ($$$) {
1349 my ($old, $new, $mrest) = @_;
1350 update_head $old, $new, $mrest;
1351 runcmd @git, qw(reset --hard);
1354 sub update_head_postlaunder ($$$) {
1355 my ($old, $tip, $reflogmsg) = @_;
1356 return if $tip eq $old;
1357 print "git-debrebase: laundered (head was $old)\n";
1358 update_head $old, $tip, $reflogmsg;
1359 # no tree changes except debian/patches
1360 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1363 sub currently_rebasing() {
1364 foreach (qw(rebase-merge rebase-apply)) {
1365 return 1 if stat_exists "$maindir_gitdir/$_";
1370 sub bail_if_rebasing() {
1371 fail "you are in the middle of a git-rebase already"
1372 if currently_rebasing();
1375 sub do_launder_head ($) {
1376 my ($reflogmsg) = @_;
1377 my $old = get_head();
1379 my ($tip,$breakwater) = walk $old;
1381 update_head_postlaunder $old, $tip, $reflogmsg;
1382 return ($tip,$breakwater);
1385 sub cmd_launder_v0 () {
1386 badusage "no arguments to launder-v0 allowed" if @ARGV;
1387 my $old = get_head();
1388 my ($tip,$breakwater,$last_anchor) = walk $old;
1389 update_head_postlaunder $old, $tip, 'launder';
1390 printf "# breakwater tip\n%s\n", $breakwater;
1391 printf "# working tip\n%s\n", $tip;
1392 printf "# last anchor\n%s\n", $last_anchor;
1395 sub defaultcmd_rebase () {
1396 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1397 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1398 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1401 sub cmd_analyse () {
1402 badusage "analyse does not support any options"
1403 if @ARGV and $ARGV[0] =~ m/^-/;
1404 badusage "too many arguments to analyse" if @ARGV>1;
1407 $old = git_rev_parse $old;
1409 $old = git_rev_parse 'HEAD';
1411 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1412 STDOUT->error and die $!;
1415 sub ffq_prev_branchinfo () {
1416 my $current = git_get_symref();
1417 return gdr_ffq_prev_branchinfo($current);
1420 sub ffq_check ($;$$) {
1421 # calls $ff and/or $notff zero or more times
1422 # then returns either (status,message) where status is
1427 # or (undef,undef, $ffq_prev,$gdrlast)
1428 # $ff and $notff are called like this:
1429 # $ff->("message for stdout\n");
1430 # $notff->('snag-name', $message);
1431 # normally $currentval should be HEAD
1432 my ($currentval, $ff, $notff) =@_;
1434 $ff //= sub { print $_[0] or die $!; };
1437 my ($status, $message, $current, $ffq_prev, $gdrlast)
1438 = ffq_prev_branchinfo();
1439 return ($status, $message) unless $status eq 'branch';
1441 my $exists = git_get_ref $ffq_prev;
1442 return ('exists',"$ffq_prev already exists") if $exists;
1444 return ('not-branch', 'HEAD symref is not to refs/heads/')
1445 unless $current =~ m{^refs/heads/};
1448 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1451 printdebug "ffq check_specs @check_specs\n";
1454 my ($lrref, $desc) = @_;
1455 printdebug "ffq might check $lrref ($desc)\n";
1457 for my $chk (@check_specs) {
1459 $invert = $glob =~ s{^[!^]}{};
1460 last if fnmatch $glob, $lrref;
1463 my $lrval = git_get_ref $lrref;
1464 return unless length $lrval;
1466 if (is_fast_fwd $lrval, $currentval) {
1467 $ff->("OK, you are ahead of $lrref\n");
1468 $checked{$lrref} = 1;
1469 } elsif (is_fast_fwd $currentval, $lrval) {
1470 $checked{$lrref} = -1;
1471 $notff->('behind', "you are behind $lrref, divergence risk");
1473 $checked{$lrref} = -1;
1474 $notff->('diverged', "you have diverged from $lrref");
1478 my $merge = cfg "branch.$branch.merge",1;
1479 if (defined $merge and $merge =~ m{^refs/heads/}) {
1481 printdebug "ffq merge $rhs\n";
1482 my $check_remote = sub {
1483 my ($remote, $desc) = @_;
1484 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1485 return unless defined $remote;
1486 $check->("refs/remotes/$remote/$rhs", $desc);
1488 $check_remote->((scalar cfg "branch.$branch.remote",1),
1489 'remote fetch/merge branch');
1490 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1491 (scalar cfg "branch.$branch.pushDefault",1),
1492 'remote push branch');
1494 if ($branch =~ m{^dgit/}) {
1495 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1496 } elsif ($branch =~ m{^master$}) {
1497 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1499 return (undef, undef, $ffq_prev, $gdrlast);
1502 sub record_ffq_prev_deferred () {
1503 # => ('status', "message")
1505 # deferred message is undef
1510 # if not ff from some branch we should be ff from, is an snag
1511 # if "deferred", will have added something about that to
1512 # @deferred_update_messages, and also maybe printed (already)
1513 # some messages about ff checks
1515 my $currentval = get_head();
1517 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1518 return ($status,$message) if defined $status;
1522 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1523 push @deferred_updates, "delete $gdrlast";
1524 push @deferred_update_messages, "Recorded previous head for preservation";
1525 return ('deferred', undef);
1528 sub record_ffq_auto () {
1529 my ($status, $message) = record_ffq_prev_deferred();
1530 if ($status eq 'deferred' || $status eq 'exists') {
1532 snag $status, "could not record ffq-prev: $message";
1537 sub ffq_prev_info () {
1539 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1540 my ($status, $message, $current, $ffq_prev, $gdrlast)
1541 = ffq_prev_branchinfo();
1542 if ($status ne 'branch') {
1543 snag $status, "could not check ffq-prev: $message";
1546 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1547 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1550 sub stitch ($$$$$) {
1551 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1553 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1555 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1556 my $differs = get_differs $old_head, $ffq_prev_commitish;
1557 unless ($differs & ~D_PAT_ADD) {
1558 # ffq-prev is ahead of us, and the only tree changes it has
1559 # are possibly addition of things in debian/patches/.
1560 # Just wind forwards rather than making a pointless pseudomerge.
1561 push @deferred_updates,
1562 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1563 update_head_checkout $old_head, $ffq_prev_commitish,
1564 "stitch (fast forward)";
1569 # We make pseudomerges with L as the contributing parent.
1570 # This makes git rev-list --first-parent work properly.
1571 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1572 'Declare fast forward / record previous work',
1573 "[git-debrebase pseudomerge: $prose]",
1575 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1576 update_head $old_head, $new_head, "stitch: $prose";
1579 sub do_stitch ($;$) {
1580 my ($prose, $unclean) = @_;
1582 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1583 if (!$ffq_prev_commitish) {
1584 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1587 my $dangling_head = get_head();
1589 keycommits $dangling_head, $unclean,$unclean,$unclean;
1592 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1595 sub upstream_commitish_search ($$) {
1596 my ($upstream_version, $tried) = @_;
1597 # todo: at some point maybe use git-deborig to do this
1598 foreach my $tagpfx ('', 'v', 'upstream/') {
1599 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1600 my $new_upstream = git_get_ref "refs/tags/$tag";
1602 return $new_upstream if length $new_upstream;
1606 sub resolve_upstream_version ($$) {
1607 my ($new_upstream, $upstream_version) = @_;
1609 if (!defined $new_upstream) {
1611 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1612 if (!length $new_upstream) {
1613 fail "Could not determine appropriate upstream commitish.\n".
1614 " (Tried these tags: @tried)\n".
1615 " Check version, and specify upstream commitish explicitly.";
1618 $new_upstream = git_rev_parse $new_upstream;
1620 return $new_upstream;
1623 sub cmd_new_upstream () {
1624 # automatically and unconditionally launders before rebasing
1625 # if rebase --abort is used, laundering has still been done
1629 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1631 # parse args - low commitment
1632 my $spec_version = shift @ARGV;
1633 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1634 fail "bad version number \`$spec_version'" unless defined $new_version;
1635 if ($new_version->is_native()) {
1636 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1639 my $new_upstream = shift @ARGV;
1640 my $new_upstream_version = upstreamversion $new_version;
1642 resolve_upstream_version $new_upstream, $new_upstream_version;
1647 my ($n, @x) = @_; # may be ''
1648 my $pc = $pieces{$n} //= {
1650 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1652 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1657 my $newpiece = sub {
1658 my ($n, @x) = @_; # may be ''
1659 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1660 push @newpieces, $pc;
1665 New => $new_upstream,
1667 while (@ARGV && $ARGV[0] !~ m{^-}) {
1668 my $n = shift @ARGV;
1670 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1671 unless @ARGV && $ARGV[0] !~ m{^-};
1673 my $c = git_rev_parse shift @ARGV;
1674 die unless $n =~ m/^$extra_orig_namepart_re$/;
1675 $newpiece->($n, New => $c);
1678 # now we need to investigate the branch this generates the
1679 # laundered version but we don't switch to it yet
1680 my $old_head = get_head();
1681 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1683 my $old_bw_cl = classify $old_bw;
1684 my $old_anchor_cl = classify $old_anchor;
1686 if (!$old_anchor_cl->{OrigParents}) {
1687 snag 'anchor-treated',
1688 'old anchor is recognised due to --anchor, cannot check upstream';
1690 $old_upstream = parsecommit
1691 $old_anchor_cl->{OrigParents}[0]{CommitId};
1692 $piece->('', Old => $old_upstream->{CommitId});
1695 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1696 if ($old_upstream->{Msg} =~
1697 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1699 my @oldpieces = (split / /, $1);
1700 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1701 if ($old_n_parents != @oldpieces &&
1702 $old_n_parents != @oldpieces + 1) {
1703 snag 'upstream-confusing', sprintf
1704 "previous upstream combine %s".
1705 " mentions %d pieces (each implying one parent)".
1706 " but has %d parents".
1707 " (one per piece plus maybe a previous combine)",
1708 $old_upstream->{CommitId},
1709 (scalar @oldpieces),
1711 } elsif ($oldpieces[0] ne '.') {
1712 snag 'upstream-confusing', sprintf
1713 "previous upstream combine %s".
1714 " first piece is not \`.'",
1718 foreach my $i (0..$#oldpieces) {
1719 my $n = $oldpieces[$i];
1720 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1721 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1725 snag 'upstream-confusing',
1726 "previous upstream $old_upstream->{CommitId} is from".
1727 " git-debrebase but not an \`upstream-combine' commit";
1731 foreach my $pc (values %pieces) {
1732 if (!$old_upstream) {
1733 # we have complained already
1734 } elsif (!$pc->{Old}) {
1735 snag 'upstream-new-piece',
1736 "introducing upstream piece \`$pc->{Name}'";
1737 } elsif (!$pc->{New}) {
1738 snag 'upstream-rm-piece',
1739 "dropping upstream piece \`$pc->{Name}'";
1740 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1741 snag 'upstream-not-ff',
1742 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1746 printdebug "%pieces = ", (dd \%pieces), "\n";
1747 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1755 my @upstream_merge_parents;
1758 push @upstream_merge_parents, $old_upstream->{CommitId};
1761 foreach my $pc (@newpieces) { # always has '' first
1763 read_tree_subdir $pc->{Name}, $pc->{New};
1765 runcmd @git, qw(read-tree), $pc->{New};
1767 push @upstream_merge_parents, $pc->{New};
1770 # index now contains the new upstream
1772 if (@newpieces > 1) {
1773 # need to make the upstream subtree merge commit
1774 $new_upstream = make_commit \@upstream_merge_parents,
1775 [ "Combine upstreams for $new_upstream_version",
1776 ("[git-debrebase upstream-combine . ".
1777 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1782 # $new_upstream is either the single upstream commit, or the
1783 # combined commit we just made. Either way it will be the
1784 # "upstream" parent of the anchor merge.
1786 read_tree_subdir 'debian', "$old_bw:debian";
1788 # index now contains the anchor merge contents
1789 $new_bw = make_commit [ $old_bw, $new_upstream ],
1790 [ "Update to upstream $new_upstream_version",
1791 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1794 my $clogsignoff = cmdoutput qw(git show),
1795 '--pretty=format:%an <%ae> %aD',
1798 # Now we have to add a changelog stanza so the Debian version
1800 die if unlink "debian";
1801 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1802 unlink "debian/changelog" or $!==ENOENT or die $!;
1803 mkdir "debian" or die $!;
1804 open CN, ">", "debian/changelog" or die $!;
1805 my $oldclog = git_cat_file ":debian/changelog";
1806 $oldclog =~ m/^($package_re) \(\S+\) / or
1807 fail "cannot parse old changelog to get package name";
1809 print CN <<END, $oldclog or die $!;
1810 $p ($new_version) UNRELEASED; urgency=medium
1812 * Update to new upstream version $new_upstream_version.
1818 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1820 # Now we have the final new breakwater branch in the index
1821 $new_bw = make_commit [ $new_bw ],
1822 [ "Update changelog for new upstream $new_upstream_version",
1823 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1827 # we have constructed the new breakwater. we now need to commit to
1828 # the laundering output, because git-rebase can't easily be made
1829 # to make a replay list which is based on some other branch
1831 update_head_postlaunder $old_head, $old_laundered_tip,
1832 'launder for new upstream';
1834 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1835 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1836 "debrebase new-upstream $new_version: rebase";
1838 # now it's for the user to sort out
1841 sub cmd_record_ffq_prev () {
1842 badusage "no arguments allowed" if @ARGV;
1843 my ($status, $msg) = record_ffq_prev_deferred();
1844 if ($status eq 'exists' && $opt_noop_ok) {
1845 print "Previous head already recorded\n" or die $!;
1846 } elsif ($status eq 'deferred') {
1847 run_deferred_updates 'record-ffq-prev';
1849 fail "Could not preserve: $msg";
1854 badusage "no arguments allowed" if @ARGV;
1855 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1856 print "$bw\n" or die $!;
1859 sub cmd_breakwater () {
1860 badusage "no arguments allowed" if @ARGV;
1861 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1862 print "$bw\n" or die $!;
1866 badusage "no arguments allowed" if @ARGV;
1868 # todo: gdr status should print divergence info
1869 # todo: gdr status should print upstream component(s) info
1870 # todo: gdr should leave/maintain some refs with this kind of info ?
1872 my $oldest = { Badness => 0 };
1875 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1876 if ($oldest->{Badness} < $badness) {
1877 $oldest = $newest = undef;
1880 Badness => $badness,
1881 CommitId => $cl->{CommitId},
1885 $newest //= $oldest;
1887 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1888 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1889 sub { $note->(2, 'branch is unlaundered', @_); },
1890 sub { $note->(3, 'branch needs laundering', @_); },
1891 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1893 my $prcommitinfo = sub {
1895 flush STDOUT or die $!;
1896 runcmd @git, qw(--no-pager log -n1),
1897 '--pretty=format: %h %s%n',
1901 print "current branch contents, in git-debrebase terms:\n";
1902 if (!$oldest->{Badness}) {
1903 print " branch is laundered\n";
1905 print " $oldest->{OurMsg}\n";
1907 foreach my $info ($oldest, $newest) {
1908 my $cid = $info->{CommitId};
1909 next if $cid eq $printed;
1911 print " $info->{KcMsg}\n";
1912 $prcommitinfo->($cid);
1917 my ($cid, $what) = @_;
1918 if (!defined $cid) {
1919 print " $what is not well-defined\n";
1922 $prcommitinfo->($cid);
1925 print "key git-debrebase commits:\n";
1926 $prab->($anchor, 'anchor');
1927 $prab->($bw, 'breakwater');
1929 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1930 ffq_prev_branchinfo();
1932 print "branch and ref status, in git-debrebase terms:\n";
1934 print " $ffq_msg\n";
1936 $ffq_prev = git_get_ref $ffq_prev;
1937 $gdrlast = git_get_ref $gdrlast;
1939 print " unstitched; previous tip was:\n";
1940 $prcommitinfo->($ffq_prev);
1941 } elsif (!$gdrlast) {
1942 print " stitched? (no record of git-debrebase work)\n";
1943 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1944 print " stitched\n";
1946 print " not git-debrebase (diverged since last stitch)\n"
1949 print "you are currently rebasing\n" if currently_rebasing();
1953 my $prose = 'stitch';
1954 getoptions("stitch",
1955 'prose=s', \$prose);
1956 badusage "no arguments allowed" if @ARGV;
1957 do_stitch $prose, 0;
1959 sub cmd_prepush () { cmd_stitch(); }
1962 badusage "no arguments allowed" if @ARGV;
1963 do_launder_head 'launder for git-debrebase quick';
1967 sub cmd_conclude () {
1968 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1969 if (!$ffq_prev_commitish) {
1970 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1973 my $dangling_head = get_head();
1975 badusage "no arguments allowed" if @ARGV;
1976 do_launder_head 'launder for git-debrebase quick';
1981 if (currently_rebasing()) {
1982 runcmd @git, qw(rebase --abort);
1984 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1985 if (!$ffq_prev_commitish) {
1986 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1989 my $scrapping_head = get_head();
1990 badusage "no arguments allowed" if @ARGV;
1991 push @deferred_updates,
1992 "update $gdrlast $ffq_prev_commitish $git_null_obj",
1993 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
1995 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
1998 sub make_patches_staged ($) {
2000 # Produces the patches that would result from $head if it were
2002 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2005 gbp_pq_export 'bw', $secret_bw, $secret_head;
2009 sub make_patches ($) {
2011 keycommits $head, 0, \&snag;
2012 make_patches_staged $head;
2015 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2016 runcmd @git, qw(read-tree), $head;
2017 read_tree_subdir 'debian/patches', $ptree;
2018 $out = make_commit [$head], [
2019 'Commit patch queue (exported by git-debrebase)',
2020 '[git-debrebase: export and commit patches]',
2026 sub cmd_make_patches () {
2027 my $opt_quiet_would_amend;
2028 getoptions("make-patches",
2029 'quiet-would-amend!', \$opt_quiet_would_amend);
2030 badusage "no arguments allowed" if @ARGV;
2032 my $old_head = get_head();
2033 my $new = make_patches $old_head;
2034 my $d = get_differs $old_head, $new;
2036 fail "No (more) patches to export." unless $opt_noop_ok;
2038 } elsif ($d == D_PAT_ADD) {
2040 update_head_checkout $old_head, $new, 'make-patches';
2042 print STDERR failmsg
2043 "Patch export produced patch amendments".
2044 " (abandoned output commit $new).".
2045 " Try laundering first."
2046 unless $opt_quiet_would_amend;
2051 sub cmd_convert_from_gbp () {
2052 badusage "want only 1 optional argument, the upstream git commitish"
2055 my $clogp = parsechangelog();
2056 my $version = $clogp->{'Version'}
2057 // die "missing Version from changelog";
2059 my ($upstream_spec) = @ARGV;
2061 my $upstream_version = upstreamversion $version;
2063 resolve_upstream_version($upstream_spec, $upstream_version);
2065 my $old_head = get_head();
2067 my $upsdiff = get_differs $upstream, $old_head;
2068 if ($upsdiff & D_UPS) {
2069 runcmd @git, qw(--no-pager diff --stat),
2070 $upstream, $old_head,
2071 qw( -- :!/debian :/);
2073 upstream ($upstream_spec) and HEAD are not
2074 identical in upstream files. See diffstat above, or run
2075 git diff $upstream_spec HEAD -- :!/debian :/
2079 if (!is_fast_fwd $upstream, $old_head) {
2080 snag 'upstream-not-ancestor',
2081 "upstream ($upstream) is not an ancestor of HEAD";
2083 my $wrong = cmdoutput
2084 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2085 qw(-- :/ :!/debian));
2086 if (length $wrong) {
2087 snag 'unexpected-upstream-changes',
2088 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2089 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2093 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2094 snag 'upstream-has-debian',
2095 "upstream ($upstream) contains debian/ directory";
2098 my $previous_dgit_view = eval {
2099 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2101 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2102 my ($stz, $desc) = @_;
2103 no warnings qw(exiting);
2104 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2105 next unless $stz->{Date};
2106 next unless $stz->{Distribution} ne 'UNRELEASED';
2107 $lvsn = $stz->{Version};
2108 $suite = $stz->{Distribution};
2111 die "neither of the first two changelog entries are released\n"
2112 unless defined $lvsn;
2113 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2114 my $mtag_pat = debiantag_maintview $lvsn, '*';
2115 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2117 die "could not find suitable maintainer view tag $mtag_pat\n"
2118 unless $mtag_pat =~ m{/};
2119 is_fast_fwd $mtag, 'HEAD' or
2120 die "HEAD is not FF from maintainer tag $mtag!";
2121 my $dtag = "archive/$mtag";
2122 is_fast_fwd $mtag, $dtag or
2123 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2124 print "will stitch in dgit view, $dtag\n";
2125 git_rev_parse $dtag;
2127 if (!$previous_dgit_view) {
2130 print STDERR "cannot stitch in dgit view: $@\n";
2133 snags_maybe_bail_early();
2139 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2140 # make a branch out of the patch queue - we'll want this in a mo
2141 runcmd qw(gbp pq import);
2142 # strip the patches out
2143 runcmd @git, qw(checkout -q gdr-internal~0);
2144 rm_subdir_cached 'debian/patches';
2145 $work = make_commit ['HEAD'], [
2146 'git-debrebase convert-from-gbp: drop patches from tree',
2147 'Delete debian/patches, as part of converting to git-debrebase format.',
2148 '[git-debrebase convert-from-gbp: drop patches from tree]'
2150 # make the anchor merge
2151 # the tree is already exactly right
2152 $work = make_commit [$work, $upstream], [
2153 'git-debrebase import: declare upstream',
2154 'First breakwater merge.',
2155 '[git-debrebase anchor: declare upstream]'
2158 # rebase the patch queue onto the new breakwater
2159 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2160 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2161 $work = git_rev_parse 'HEAD';
2163 if ($previous_dgit_view) {
2164 $work = make_commit [$work, $previous_dgit_view], [
2165 'git-debrebase import: declare ff from dgit archive view',
2166 '[git-debrebase pseudomerge: import-from-gbp]',
2173 update_head_checkout $old_head, $work, 'convert-from-gbp';
2176 sub cmd_convert_to_gbp () {
2177 badusage "no arguments allowed" if @ARGV;
2178 my $head = get_head();
2179 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2180 keycommits $head, 0;
2182 make_patches_staged $head;
2184 $out = make_commit ['HEAD'], [
2185 'Commit patch queue (converted from git-debrebase format)',
2186 '[git-debrebase convert-to-gbp: commit patches]',
2190 push @deferred_updates, "delete $ffq";
2191 push @deferred_updates, "delete $gdrlast";
2194 update_head_checkout $head, $out, "convert to gbp (v0)";
2195 print <<END or die $!;
2196 git-debrebase: converted to git-buildpackage branch format
2197 git-debrebase: WARNING: do not now run "git-debrebase" any more
2198 git-debrebase: WARNING: doing so would drop all upstream patches!
2202 sub cmd_convert_from_dgit_view () {
2203 my $clogp = parsechangelog();
2205 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2211 getoptions("convert-from-dgit-view",
2212 'diagnose!', \$diagnose,
2213 'build-products-dir:s', \$bpd,
2214 'origs!', \$do_origs,
2216 'always-convert-anyway!', \$always);
2217 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2222 my $spec = shift @ARGV;
2223 my $commit = git_rev_parse "$spec^{commit}";
2224 push @upstreams, { Commit => $commit,
2225 Source => "$ARGV[0], from command line",
2230 my $head = get_head();
2234 my $trouble = sub { $troubles++; };
2235 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2236 printdebug "troubles=$troubles\n";
2239 $us: Branch already seems to be in git-debrebase format!
2240 $us: --always-convert-anyway would do the conversion operation anyway
2241 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2243 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2248 snags_maybe_bail_early();
2250 my $version = upstreamversion $clogp->{Version};
2251 print STDERR "Considering possible commits corresponding to upstream:\n";
2256 my $ups_tag = upstream_commitish_search $version, \@tried;
2258 my $this = "git tag $tried[-1]";
2259 push @upstreams, { Commit => $ups_tag,
2264 " git tag: no suitable tag found (tried %s)\n",
2269 my $p = $clogp->{'Source'};
2270 # we do a quick check to see if there are plausible origs
2272 if (!opendir BPD, $bpd) {
2273 die "$bpd: opendir: $!" unless $!==ENOENT;
2275 while ($!=0, my $f = readdir BPD) {
2276 next unless is_orig_file_of_p_v $f, $p, $version;
2278 " orig: found what looks like a .orig, %s\n",
2283 die "read $bpd: $!" if $!;
2287 my $tree = cmdoutput
2288 @dgit, qw(--build-products-dir), $bpd,
2289 qw(print-unapplied-treeish);
2292 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2293 rm_subdir_cached 'debian';
2294 $tree = cmdoutput @git, qw(write-tree);
2295 my $ups_synth = make_commit [], [ <<END, <<END,
2296 Import effective orig tree for upstream version $version
2298 This includes the contents of the .orig(s), minus any debian/ directory.
2300 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2303 push @upstreams, { Commit => $ups_synth,
2304 Source => "orig(s) imported via dgit",
2309 " orig: no suitable origs found (looked for %s in %s)\n",
2310 "${p}_".(stripeoch $version)."...", $bpd;
2315 my $some_patches = stat_exists 'debian/patches/series';
2317 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2320 foreach my $u (@upstreams) {
2324 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2325 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2326 runcmd @git, qw(clean -xdff);
2327 runcmd @git, qw(checkout), $head, qw(-- debian);
2328 if ($some_patches) {
2329 rm_subdir_cached 'debian/patches';
2330 $work = make_commit [ $work ], [
2331 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2332 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2333 "to git-debrebase format. Upstream changes will appear as commits.",
2334 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2337 $work = make_commit [ $work, $u->{Commit} ], [
2338 'git-debrebase convert-from-dgit-view: declare upstream',
2339 '(Re)constructed breakwater merge.',
2340 '[git-debrebase anchor: declare upstream]'
2342 runcmd @git, qw(checkout --quiet -b mk), $work;
2343 if ($some_patches) {
2344 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2345 runcmd @git, qw(reset --quiet);
2346 my @gbp_cmd = (qw(gbp pq import));
2348 my $gbp_err = "../gbp-pq-err";
2349 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2351 my $r = system @gbp_cmd;
2354 " %s: couldn't apply patches: gbp pq %s",
2355 $u->{Source}, waitstatusmsg();
2359 my $work = git_rev_parse qw(HEAD);
2360 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2361 if (length $diffout) {
2363 " $u->{Source}: applying patches gives different tree\n";
2364 print STDERR $diffout if $diagnose;
2368 $u->{Result} = $work;
2376 Could not find or construct a suitable upstream commit.
2377 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2378 upstream commmit explicitly or provide suitable origs.
2382 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2384 ffq_check $result->{Result};
2386 update_head_checkout $head, $result->{Result},
2387 'convert-from-dgit-view';
2390 sub cmd_downstream_rebase_launder_v0 () {
2391 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2393 $base = git_rev_parse $base;
2394 my $old_head = get_head();
2395 my $current = $old_head;
2398 if ($current eq $base) {
2399 $topmost_keep //= $current;
2400 print " $current BASE stop\n";
2403 my $cl = classify $current;
2404 print " $current $cl->{Type}";
2406 my $p0 = $cl->{Parents}[0]{CommitId};
2408 if ($cl->{Type} eq 'Pseudomerge') {
2409 print " ^".($cl->{Contributor}{Ix}+1);
2410 $next = $cl->{Contributor}{CommitId};
2411 } elsif ($cl->{Type} eq 'AddPatches' or
2412 $cl->{Type} eq 'Changelog') {
2422 $topmost_keep //= $current;
2424 die "to-be stripped changes not on top of the branch\n"
2429 if ($topmost_keep eq $old_head) {
2430 print "unchanged\n";
2432 print "updating to $topmost_keep\n";
2433 update_head_checkout
2434 $old_head, $topmost_keep,
2435 'downstream-rebase-launder-v0';
2441 "D+" => \$debuglevel,
2442 'noop-ok', => \$opt_noop_ok,
2443 'f=s' => \@snag_force_opts,
2444 'anchor=s' => \@opt_anchors,
2445 '--dgit=s' => \($dgit[0]),
2448 my ($opt,$val) = @_;
2449 badusage "git-debrebase: no cuddling to -i for git-rebase"
2451 die if $opt_defaultcmd_interactive; # should not happen
2452 $opt_defaultcmd_interactive = [ qw(-i) ];
2453 # This access to @ARGV is excessive familiarity with
2454 # Getopt::Long, but there isn't another sensible
2455 # approach. '-i=s{0,}' does not work with bundling.
2456 push @$opt_defaultcmd_interactive, @ARGV;
2459 'help' => sub { print $usage_message or die $!; finish 0; },
2462 initdebug('git-debrebase ');
2463 enabledebug if $debuglevel;
2465 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2466 chdir $toplevel or die "chdir $toplevel: $!";
2468 $rd = fresh_playground "$playprefix/misc";
2470 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2472 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2473 defaultcmd_rebase();
2475 my $cmd = shift @ARGV;
2478 $cmdfn = ${*::}{"cmd_$cmdfn"};
2480 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";