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);
38 our ($opt_force, $opt_noop_ok, @opt_anchors);
39 our ($opt_defaultcmd_interactive);
41 our $us = qw(git-debrebase);
45 print STDERR "bad usage: $m\n";
50 my ($k, $optional) = @_;
52 my @cmd = qw(git config -z);
53 push @cmd, qw(--get-all) if wantarray;
55 my $out = cmdoutput_errok @cmd;
57 fail "missing required git config $k" unless $optional;
60 my @l = split /\0/, $out;
61 return wantarray ? @l : $l[0];
68 my $dd = new Data::Dumper [ $v ];
69 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
75 my $data = (git_cat_file $objid, 'commit');
76 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
80 sub D_UPS () { 0x02; } # upstream files
81 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
82 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
83 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
84 sub D_DEB_OTH () { 0x20; } # debian/changelog
85 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
87 our $playprefix = 'debrebase';
96 my $r = eval { $sub->(); };
97 { local $@; changedir $maindir; }
101 sub fresh_workarea () {
102 $workarea = fresh_playground "$playprefix/work";
103 in_workarea sub { playtree_setup };
106 our $snags_forced = 0;
107 our $snags_tripped = 0;
108 our $snags_summarised = 0;
109 our @deferred_updates;
110 our @deferred_update_messages;
112 sub all_snags_summarised () {
113 $snags_forced + $snags_tripped == $snags_summarised;
115 sub run_deferred_updates ($) {
118 confess 'dangerous internal error' unless all_snags_summarised();
120 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
121 debugcmd '>|', @upd_cmd;
122 open U, "|-", @upd_cmd or die $!;
123 foreach (@deferred_updates) {
124 printdebug ">= ", $_, "\n";
125 print U $_, "\n" or die $!;
128 close U or failedcmd @upd_cmd;
130 print $_, "\n" foreach @deferred_update_messages;
132 @deferred_updates = ();
133 @deferred_update_messages = ();
136 sub get_differs ($$) {
138 # This resembles quiltify_trees_differ, in dgit, a bit.
139 # But we don't care about modes, or dpkg-source-unrepresentable
140 # changes, and we don't need the plethora of different modes.
141 # Conversely we need to distinguish different kinds of changes to
142 # debian/ and debian/patches/.
147 my ($opts, $limits, $fn) = @_;
148 my @cmd = (@git, qw(diff-tree -z --no-renames));
150 push @cmd, "$_:" foreach $x, $y;
151 push @cmd, '--', @$limits;
152 my $diffs = cmdoutput @cmd;
153 foreach (split /\0/, $diffs) { $fn->(); }
156 $rundiff->([qw(--name-only)], [], sub {
157 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
160 if ($differs & DS_DEB) {
162 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
164 m{^debian/patches/} ? D_PAT_OTH :
165 $_ eq 'debian/changelog' ? D_DEB_CLOG :
168 die "mysterious debian changes $x..$y"
169 unless $differs & (D_PAT_OTH|DS_DEB);
172 if ($differs & D_PAT_OTH) {
174 $differs &= ~D_PAT_OTH;
176 $differs |= D_PAT_OTH;
177 no warnings qw(exiting); last;
179 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
180 no warnings qw(exiting);
181 if (!defined $mode) {
184 die unless s{^debian/patches/}{};
186 if ($mode eq 'A' && !m/\.series$/s) {
188 } elsif ($mode eq 'M' && $_ eq 'series') {
189 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
190 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
191 chomp $x_s; $x_s .= "\n";
192 $ok = $x_s eq substr($y_s, 0, length $x_s);
197 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
199 die "mysterious debian/patches changes $x..$y"
200 unless $differs & (D_PAT_ADD|D_PAT_OTH);
203 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
208 sub commit_pr_info ($) {
210 return Data::Dumper->dump([$r], [qw(commit)]);
213 sub calculate_committer_authline () {
214 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
215 'DUMMY COMMIT (git-debrebase)', "HEAD:";
216 my ($h,$m) = get_commit $c;
217 $h =~ m/^committer .*$/m or confess "($h) ?";
221 sub rm_subdir_cached ($) {
223 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
226 sub read_tree_subdir ($$) {
227 my ($subdir, $new_tree_object) = @_;
228 rm_subdir_cached $subdir;
229 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
232 sub make_commit ($$) {
233 my ($parents, $message_paras) = @_;
234 my $tree = cmdoutput @git, qw(write-tree);
235 my @cmd = (@git, qw(commit-tree), $tree);
236 push @cmd, qw(-p), $_ foreach @$parents;
237 push @cmd, qw(-m), $_ foreach @$message_paras;
238 return cmdoutput @cmd;
241 our @snag_force_opts;
243 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
244 if (grep { $_ eq $tag } @snag_force_opts) {
246 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
249 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
253 # Important: all mainline code must call snags_maybe_bail after
254 # any point where snag might be called, but before making changes
255 # (eg before any call to run_deferred_updates). snags_maybe_bail
256 # may be called more than once if necessary (but this is not ideal
257 # because then the messages about number of snags may be confusing).
258 sub snags_maybe_bail () {
259 return if all_snags_summarised();
262 "%s: snags: %d overriden by individual -f options\n",
265 if ($snags_tripped) {
268 "%s: snags: %d overriden by global --force\n",
272 "%s: snags: %d blockers (you could -f<tag>, or --force)",
276 $snags_summarised = $snags_forced + $snags_tripped;
279 return $snags_forced || $snags_tripped;
282 # classify returns an info hash like this
284 # Hdr => # commit headers, including 1 final newline
285 # Msg => # commit message (so one newline is dropped)
287 # Type => (see below)
289 # Ix => $index # ie 0, 1, 2, ...
291 # Differs => return value from get_differs
293 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
295 # NewMsg => # commit message, but with any [dgit import ...] edited
296 # # to say "[was: ...]"
306 # has additional entres in classification result
307 # Overwritten = [ subset of Parents ]
308 # Contributor = $the_remaining_Parent
310 # DgitImportUnpatched
311 # has additional entry in classification result
312 # OrigParents = [ subset of Parents ]
315 # has additional entry in classification result
316 # OrigParents = [ subset of Parents ] # singleton list
323 # has additional entry in classification result
326 sub parsecommit ($;$) {
327 my ($objid, $p_ref) = @_;
328 # => hash with CommitId Hdr Msg Tree Parents
329 # Parents entries have only Ix CommitId
330 # $p_ref, if provided, must be [] and is used as a base for Parents
335 my ($h,$m) = get_commit $objid;
337 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
338 my (@ph) = $h =~ m/^parent (\w+)$/mg;
348 foreach my $ph (@ph) {
350 Ix => scalar @$p_ref,
362 my $r = parsecommit($objid, \@p);
366 $p->{Differs} = (get_differs $p->{CommitId}, $t),
369 printdebug "classify $objid \$t=$t \@p",
370 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
374 my ($type, @rest) = @_;
375 $r = { %$r, Type => $type, @rest };
377 printdebug " = $type ".(dd $r)."\n";
383 $r = { %$r, Type => qw(Unknown), Why => $why };
384 printdebug " ** Unknown\n";
388 if (grep { $_ eq $objid } @opt_anchors) {
389 return $classify->('TreatAsAnchor');
392 my @identical = grep { !$_->{Differs} } @p;
393 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
394 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
396 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
397 # multi-orig upstreams are represented with an anchor merge
398 # from a single upstream commit which combines the orig tarballs
400 # Every anchor tagged this way must be a merge.
401 # We are relying on the
402 # [git-debrebase anchor: ...]
403 # commit message annotation in "declare" anchor merges (which
404 # do not have any upstream changes), to distinguish those
405 # anchor merges from ordinary pseudomerges (which we might
406 # just try to strip).
408 # However, the user is going to be doing git-rebase a lot. We
409 # really don't want them to rewrite an anchor commit.
410 # git-rebase trips up on merges, so that is a useful safety
413 # BreakwaterStart commits are also anchors in the terminology
414 # of git-debrebase(5), but they are untagged (and always
415 # manually generated).
417 # We cannot not tolerate any tagged linear commit (ie,
418 # BreakwaterStart commits tagged `[anchor:') because such a
419 # thing could result from an erroneous linearising raw git
420 # rebase of a merge anchor. That would represent a corruption
421 # of the branch. and we want to detect and reject the results
422 # of such corruption before it makes it out anywhere. If we
423 # reject it here then we avoid making the pseudomerge which
424 # would be needed to push it.
426 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
427 @p == 2 or return $badanchor->("has other than two parents");
428 $haspatches and return $badanchor->("contains debian/patches");
430 # How to decide about l/r ordering of anchors ? git
431 # --topo-order prefers to expand 2nd parent first. There's
432 # already an easy rune to look for debian/ history anyway (git log
433 # debian/) so debian breakwater branch should be 1st parent; that
434 # way also there's also an easy rune to look for the upstream
435 # patches (--topo-order).
437 # Also this makes --first-parent be slightly more likely to
438 # be useful - it makes it provide a linearised breakwater history.
440 # Of course one can say somthing like
441 # gitk -- ':/' ':!/debian'
442 # to get _just_ the commits touching upstream files, and by
443 # the TREESAME logic in git-rev-list this will leave the
444 # breakwater into upstream at the first anchor. But that
445 # doesn't report debian/ changes at all.
447 # Other observations about gitk: by default, gitk seems to
448 # produce output in a different order to git-rev-list. I
449 # can't seem to find this documented anywhere. gitk
450 # --date-order DTRT. But, gitk always seems to put the
451 # parents from left to right, in order, so it's easy to see
452 # which way round a pseudomerge is.
454 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
455 $p[1]{Differs} & ~DS_DEB and
456 $badanchor->("upstream files differ from left parent");
457 $p[0]{Differs} & ~D_UPS and
458 $badanchor->("debian/ differs from right parent");
460 return $classify->(qw(Anchor),
461 OrigParents => [ $p[1] ]);
465 my $d = $r->{Parents}[0]{Differs};
466 if ($d == D_PAT_ADD) {
467 return $classify->(qw(AddPatches));
468 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
469 return $unknown->("edits debian/patches");
470 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
471 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
473 if ($d == D_DEB_CLOG) {
474 return $classify->(qw(Changelog));
476 return $classify->(qw(Packaging));
478 } elsif ($ty eq 'missing') {
479 return $classify->(qw(BreakwaterStart));
481 return $unknown->("parent's debian is not a directory");
483 } elsif ($d == D_UPS) {
484 return $classify->(qw(Upstream));
485 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
486 return $classify->(qw(Mixed));
488 return $unknown->("no changes");
490 confess "internal error $objid ?";
494 return $unknown->("origin commit");
497 if (@p == 2 && @identical == 1) {
498 my @overwritten = grep { $_->{Differs} } @p;
499 confess "internal error $objid ?" unless @overwritten==1;
500 return $classify->(qw(Pseudomerge),
501 Overwritten => [ $overwritten[0] ],
502 Contributor => $identical[0]);
504 if (@p == 2 && @identical == 2) {
506 my ($ph,$pm) = get_commit $_[0]{CommitId};
507 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
511 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
512 if ($order > 0) { # newer first
513 } elsif ($order < 0) {
514 @bytime = reverse @bytime;
516 # same age, default to order made by -s ours
517 # that is, commit was made by someone who preferred L
519 return $classify->(qw(Pseudomerge),
520 SubType => qw(Ambiguous),
521 Contributor => $bytime[0],
522 Overwritten => [ $bytime[1] ]);
525 my ($p_h, $p_m) = get_commit $p->{CommitId};
526 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
527 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
529 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
531 if (!(grep { !$_->{IsOrigin} } @p) and
532 (@orig_ps >= @p - 1) and
533 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
535 return $classify->(qw(DgitImportUnpatched),
536 OrigParents => \@orig_ps);
539 return $unknown->("complex merge");
542 sub keycommits ($;$$$$) {
543 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
544 # => ($anchor, $breakwater)
546 # $unclean->("unclean-$tagsfx", $msg, $cl)
547 # $furniture->("unclean-$tagsfx", $msg, $cl)
548 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
549 # is callled for each situation or commit that
550 # wouldn't be found in a laundered branch
551 # $furniture is for furniture commits such as might be found on an
552 # interchange branch (pseudomerge, d/patches, changelog)
553 # $trouble is for things whnich prevent the return of
554 # anchor and breakwater information; if that is ignored,
555 # then keycommits returns (undef, undef) instead.
556 # $fatal is for unprocessable commits, and should normally cause
557 # a failure. If ignored, agaion, (undef, undef) is returned.
559 # If a callback is undef, fail is called instead.
560 # If a callback is defined but false, the situation is ignored.
562 # no warnings qw(exiting); last;
563 # if the answer is no longer wanted.
565 my ($anchor, $breakwater);
568 $fatal //= sub { fail $_[2]; };
570 my ($cb, $tagsfx, $why) = @_;
571 my $m = "branch needs laundering (run git-debrebase): $why";
572 fail $m unless defined $cb;
574 $cb->("unclean-$tagsfx", $why, $cl);
577 $cl = classify $head;
578 my $ty = $cl->{Type};
579 if ($ty eq 'Packaging') {
580 $breakwater //= $clogonly;
581 $breakwater //= $head;
582 } elsif ($ty eq 'Changelog') {
583 # this is going to count as the tip of the breakwater
584 # only if it has no upstream stuff before it
586 } elsif ($ty eq 'Anchor' or
587 $ty eq 'TreatAsAnchor' or
588 $ty eq 'BreakwaterStart') {
590 $breakwater //= $clogonly;
591 $breakwater //= $head;
593 } elsif ($ty eq 'Upstream') {
594 $x->($unclean, 'ordering',
595 "packaging change ($breakwater) follows upstream change (eg $head)")
596 if defined $breakwater;
599 } elsif ($ty eq 'Mixed') {
600 $x->($unclean, 'mixed',
601 "found mixed upstream/packaging commit ($head)");
604 } elsif ($ty eq 'Pseudomerge' or
605 $ty eq 'AddPatches') {
606 $x->($furniture, (lc $ty),
607 "found interchange bureaucracy commit ($ty, $head)");
608 } elsif ($ty eq 'DgitImportUnpatched') {
609 $x->($trouble, 'dgitimport',
610 "found dgit dsc import ($head)");
611 return (undef,undef);
613 $x->($fatal, 'unprocessable',
614 "found unprocessable commit, cannot cope: $head; $cl->{Why}"
616 return (undef,undef);
618 $head = $cl->{Parents}[0]{CommitId};
620 return ($anchor, $breakwater);
626 $nogenerate,$report) = @_;
627 # => ($tip, $breakwater_tip, $last_anchor)
628 # (or nothing, if $nogenerate)
630 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
632 # go through commits backwards
633 # we generate two lists of commits to apply:
634 # breakwater branch and upstream patches
635 my (@brw_cl, @upp_cl, @processed);
642 my ($prose, $info) = @_;
646 $ms .= "\n\n[git-debrebase$info: $prose]\n";
649 my $rewrite_from_here = sub {
651 my $sp_cl = { SpecialMethod => 'StartRewrite' };
653 push @processed, $sp_cl;
658 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
661 return unless $report;
662 print $report $prdelim, @_;
666 my $bomb = sub { # usage: return $bomb->();
667 print $report " Unprocessable" if $report;
668 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
671 return (undef,undef);
673 die "commit $cur: Cannot cope with this commit (d.".
674 (join ' ', map { sprintf "%#x", $_->{Differs} }
675 @{ $cl->{Parents} }).
676 (defined $cl->{Why} ? "; $cl->{Why}": '').
683 my $build_start = sub {
684 my ($msg, $parent) = @_;
687 no warnings qw(exiting); last;
694 my $ty = $cl->{Type};
695 my $st = $cl->{SubType};
696 $prline->("$cl->{CommitId} $cl->{Type}");
697 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
698 push @processed, $cl;
699 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
700 if ($ty eq 'AddPatches') {
702 $rewrite_from_here->(\@upp_cl);
704 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
708 } elsif ($ty eq 'BreakwaterStart') {
710 $build_start->('FirstPackaging', $cur);
711 } elsif ($ty eq 'Upstream') {
715 } elsif ($ty eq 'Mixed') {
718 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
721 $queue->(\@brw_cl, "debian");
722 $queue->(\@upp_cl, "upstream");
723 $rewrite_from_here->(\@brw_cl);
726 } elsif ($ty eq 'Pseudomerge') {
727 my $contrib = $cl->{Contributor}{CommitId};
728 print $report " Contributor=$contrib" if $report;
729 push @pseudomerges, $cl;
730 $rewrite_from_here->(\@upp_cl);
733 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
735 $build_start->("Anchor", $cur);
736 } elsif ($ty eq 'DgitImportUnpatched') {
737 my $pm = $pseudomerges[-1];
739 # To an extent, this is heuristic. Imports don't have
740 # a useful history of the debian/ branch. We assume
741 # that the first pseudomerge after an import has a
742 # useful history of debian/, and ignore the histories
743 # from later pseudomerges. Often the first pseudomerge
744 # will be the dgit import of the upload to the actual
745 # suite intended by the non-dgit NMUer, and later
746 # pseudomerges may represent in-archive copies.
747 my $ovwrs = $pm->{Overwritten};
748 printf $report " PM=%s \@Overwr:%d",
749 $pm->{CommitId}, (scalar @$ovwrs)
752 printdebug "*** WALK BOMB DgitImportUnpatched\n";
755 my $ovwr = $ovwrs->[0]{CommitId};
756 printf $report " Overwr=%s", $ovwr if $report;
757 # This import has a tree which is just like a
758 # breakwater tree, but it has the wrong history. It
759 # ought to have the previous breakwater (which the
760 # pseudomerge overwrote) as an ancestor. That will
761 # make the history of the debian/ files correct. As
762 # for the upstream version: either it's the same as
763 # was ovewritten (ie, same as the previous
764 # breakwater), in which case that history is precisely
765 # right; or, otherwise, it was a non-gitish upload of a
766 # new upstream version. We can tell these apart by
767 # looking at the tree of the supposed upstream.
770 SpecialMethod => 'DgitImportDebianUpdate',
771 $xmsg->("convert dgit import: debian changes")
774 SpecialMethod => 'DgitImportUpstreamUpdate',
775 $xmsg->("convert dgit import: upstream update",
778 $prline->(" Import");
779 $rewrite_from_here->(\@brw_cl);
780 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
784 # Everything is from this import. This kind of import
785 # is already in valid breakwater format, with the
786 # patches as commits.
787 printf $report " NoPM" if $report;
788 # last thing we processed will have been the first patch,
789 # if there is one; which is fine, so no need to rewrite
790 # on account of this import
791 $build_start->("ImportOrigin", $cur);
795 printdebug "*** WALK BOMB unrecognised\n";
801 printdebug "*** WALK prep done cur=$cur".
802 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
804 return if $nogenerate;
806 # Now we build it back up again
812 my $read_tree_debian = sub {
814 read_tree_subdir 'debian', "$treeish:debian";
815 rm_subdir_cached 'debian/patches';
817 my $read_tree_upstream = sub {
819 runcmd @git, qw(read-tree), $treeish;
820 $read_tree_debian->($build);
823 $#upp_cl = $upp_limit if defined $upp_limit;
825 my $committer_authline = calculate_committer_authline();
827 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
829 confess "internal error" unless $build eq (pop @processed)->{CommitId};
832 mkdir $rd or $!==EEXIST or die $!;
834 runcmd @git, qw(read-tree), $build;
835 foreach my $cl (qw(Debian), (reverse @brw_cl),
836 { SpecialMethod => 'RecordBreakwaterTip' },
837 qw(Upstream), (reverse @upp_cl)) {
839 $current_method = $cl;
842 my $method = $cl->{SpecialMethod} // $current_method;
843 my @parents = ($build);
844 my $cltree = $cl->{CommitId};
845 printdebug "WALK BUILD ".($cltree//'undef').
846 " $method (rewriting=$rewriting)\n";
847 if ($method eq 'Debian') {
848 $read_tree_debian->($cltree);
849 } elsif ($method eq 'Upstream') {
850 $read_tree_upstream->($cltree);
851 } elsif ($method eq 'StartRewrite') {
854 } elsif ($method eq 'RecordBreakwaterTip') {
855 $breakwater = $build;
857 } elsif ($method eq 'DgitImportDebianUpdate') {
858 $read_tree_debian->($cltree);
859 } elsif ($method eq 'DgitImportUpstreamUpdate') {
860 confess unless $rewriting;
861 my $differs = (get_differs $build, $cltree);
862 next unless $differs & D_UPS;
863 $read_tree_upstream->($cltree);
864 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
869 my $procd = (pop @processed) // 'UNDEF';
872 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
875 my $newtree = cmdoutput @git, qw(write-tree);
877 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
878 $ch =~ s{^parent .*\n}{}mg;
879 $ch =~ s{(?=^author)}{
880 join '', map { "parent $_\n" } @parents
881 }me or confess "$ch ?";
883 $ch =~ s{^committer .*$}{$committer_authline}m
886 my $cf = "$rd/m$rewriting";
887 open CD, ">", $cf or die $!;
888 print CD $ch, "\n", $cl->{Msg} or die $!;
890 my @cmd = (@git, qw(hash-object));
891 push @cmd, qw(-w) if $rewriting;
892 push @cmd, qw(-t commit), $cf;
893 my $newcommit = cmdoutput @cmd;
894 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
896 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
902 my $final_check = get_differs $build, $input;
903 die sprintf "internal error %#x %s %s", $final_check, $build, $input
904 if $final_check & ~D_PAT_ADD;
906 my @r = ($build, $breakwater, $last_anchor);
907 printdebug "*** WALK RETURN @r\n";
912 git_check_unmodified();
913 return git_rev_parse qw(HEAD);
916 sub update_head ($$$) {
917 my ($old, $new, $mrest) = @_;
918 push @deferred_updates, "update HEAD $new $old";
919 run_deferred_updates $mrest;
922 sub update_head_checkout ($$$) {
923 my ($old, $new, $mrest) = @_;
924 update_head $old, $new, $mrest;
925 runcmd @git, qw(reset --hard);
928 sub update_head_postlaunder ($$$) {
929 my ($old, $tip, $reflogmsg) = @_;
930 return if $tip eq $old;
931 print "git-debrebase: laundered (head was $old)\n";
932 update_head $old, $tip, $reflogmsg;
933 # no tree changes except debian/patches
934 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
937 sub do_launder_head ($) {
938 my ($reflogmsg) = @_;
939 my $old = get_head();
941 my ($tip,$breakwater) = walk $old;
943 update_head_postlaunder $old, $tip, $reflogmsg;
944 return ($tip,$breakwater);
947 sub cmd_launder_v0 () {
948 badusage "no arguments to launder-v0 allowed" if @ARGV;
949 my $old = get_head();
950 my ($tip,$breakwater,$last_anchor) = walk $old;
951 update_head_postlaunder $old, $tip, 'launder';
952 printf "# breakwater tip\n%s\n", $breakwater;
953 printf "# working tip\n%s\n", $tip;
954 printf "# last anchor\n%s\n", $last_anchor;
957 sub defaultcmd_rebase () {
958 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
959 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
960 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
964 die if ($ARGV[0]//'') =~ m/^-/;
965 badusage "too many arguments to analyse" if @ARGV>1;
968 $old = git_rev_parse $old;
970 $old = git_rev_parse 'HEAD';
972 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
973 STDOUT->error and die $!;
976 sub ffq_prev_branchinfo () {
977 my $current = git_get_symref();
978 return gdr_ffq_prev_branchinfo($current);
981 sub record_ffq_prev_deferred () {
982 # => ('status', "message")
984 # deferred message is undef
989 # if not ff from some branch we should be ff from, is an snag
990 # if "deferred", will have added something about that to
991 # @deferred_update_messages, and also maybe printed (already)
992 # some messages about ff checks
993 my ($status, $message, $current, $ffq_prev, $gdrlast)
994 = ffq_prev_branchinfo();
995 return ($status, $message) unless $status eq 'branch';
997 my $currentval = get_head();
999 my $exists = git_get_ref $ffq_prev;
1000 return ('exists',"$ffq_prev already exists") if $exists;
1002 return ('not-branch', 'HEAD symref is not to refs/heads/')
1003 unless $current =~ m{^refs/heads/};
1006 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1009 printdebug "ffq check_specs @check_specs\n";
1012 my ($lrref, $desc) = @_;
1013 printdebug "ffq might check $lrref ($desc)\n";
1015 for my $chk (@check_specs) {
1017 $invert = $glob =~ s{^[!^]}{};
1018 last if fnmatch $glob, $lrref;
1021 my $lrval = git_get_ref $lrref;
1022 return unless length $lrval;
1024 if (is_fast_fwd $lrval, $currentval) {
1025 print "OK, you are ahead of $lrref\n" or die $!;
1026 $checked{$lrref} = 1;
1027 } elsif (is_fast_fwd $currentval, $lrval) {
1028 $checked{$lrref} = -1;
1029 snag 'behind', "you are behind $lrref, divergence risk";
1031 $checked{$lrref} = -1;
1032 snag 'diverged', "you have diverged from $lrref";
1036 my $merge = cfg "branch.$branch.merge",1;
1037 if (defined $merge and $merge =~ m{^refs/heads/}) {
1039 printdebug "ffq merge $rhs\n";
1040 my $check_remote = sub {
1041 my ($remote, $desc) = @_;
1042 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1043 return unless defined $remote;
1044 $check->("refs/remotes/$remote/$rhs", $desc);
1046 $check_remote->((scalar cfg "branch.$branch.remote",1),
1047 'remote fetch/merge branch');
1048 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1049 (scalar cfg "branch.$branch.pushDefault",1),
1050 'remote push branch');
1052 if ($branch =~ m{^dgit/}) {
1053 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1054 } elsif ($branch =~ m{^master$}) {
1055 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1060 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1061 push @deferred_updates, "delete $gdrlast";
1062 push @deferred_update_messages, "Recorded current head for preservation";
1063 return ('deferred', undef);
1066 sub record_ffq_auto () {
1067 my ($status, $message) = record_ffq_prev_deferred();
1068 if ($status eq 'deferred' || $status eq 'exists') {
1070 snag $status, "could not record ffq-prev: $message";
1075 sub ffq_prev_info () {
1076 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1077 my ($status, $message, $current, $ffq_prev, $gdrlast)
1078 = ffq_prev_branchinfo();
1079 if ($status ne 'branch') {
1080 snag $status, "could not check ffq-prev: $message";
1083 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1084 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1087 sub stitch ($$$$$) {
1088 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1090 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1092 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1093 my $differs = get_differs $old_head, $ffq_prev_commitish;
1094 unless ($differs & ~D_PAT_ADD) {
1095 # ffq-prev is ahead of us, and the only tree changes it has
1096 # are possibly addition of things in debian/patches/.
1097 # Just wind forwards rather than making a pointless pseudomerge.
1098 push @deferred_updates,
1099 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1100 update_head_checkout $old_head, $ffq_prev_commitish,
1101 "stitch (fast forward)";
1106 # We make pseudomerges with L as the contributing parent.
1107 # This makes git rev-list --first-parent work properly.
1108 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1109 'Declare fast forward / record previous work',
1110 "[git-debrebase pseudomerge: $prose]",
1112 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1113 update_head $old_head, $new_head, "stitch: $prose";
1116 sub do_stitch ($;$) {
1117 my ($prose, $unclean) = @_;
1119 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1120 if (!$ffq_prev_commitish) {
1121 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1124 my $dangling_head = get_head();
1126 keycommits $dangling_head, $unclean,$unclean,$unclean;
1129 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1132 sub cmd_new_upstream () {
1133 # automatically and unconditionally launders before rebasing
1134 # if rebase --abort is used, laundering has still been done
1138 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1140 # parse args - low commitment
1141 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1142 my $new_upstream_version = $new_version->version();
1144 my $new_upstream = shift @ARGV;
1145 if (!defined $new_upstream) {
1147 # todo: at some point maybe use git-deborig to do this
1148 foreach my $tagpfx ('', 'v', 'upstream/') {
1149 my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1150 $new_upstream = git_get_ref "refs/tags/$tag";
1151 last if length $new_upstream;
1154 if (!length $new_upstream) {
1155 fail "Could not determine appropriate upstream commitish.\n".
1156 " (Tried these tags: @tried)\n".
1157 " Check version, and specify upstream commitish explicitly.";
1160 $new_upstream = git_rev_parse $new_upstream;
1165 my ($n, @x) = @_; # may be ''
1166 my $pc = $pieces{$n} //= {
1168 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1170 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1175 my $newpiece = sub {
1176 my ($n, @x) = @_; # may be ''
1177 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1178 push @newpieces, $pc;
1183 New => $new_upstream,
1185 while (@ARGV && $ARGV[0] !~ m{^-}) {
1186 my $n = shift @ARGV;
1188 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1189 unless @ARGV && $ARGV[0] !~ m{^-};
1191 my $c = git_rev_parse shift @ARGV;
1192 die unless $n =~ m/^$extra_orig_namepart_re$/;
1193 $newpiece->($n, New => $c);
1196 # now we need to investigate the branch this generates the
1197 # laundered version but we don't switch to it yet
1198 my $old_head = get_head();
1199 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1201 my $old_bw_cl = classify $old_bw;
1202 my $old_anchor_cl = classify $old_anchor;
1204 if (!$old_anchor_cl->{OrigParents}) {
1205 snag 'anchor-treated',
1206 'old anchor is recognised due to --anchor, cannot check upstream';
1208 $old_upstream = parsecommit
1209 $old_anchor_cl->{OrigParents}[0]{CommitId};
1210 $piece->('', Old => $old_upstream->{CommitId});
1213 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1214 if ($old_upstream->{Msg} =~
1215 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1217 my @oldpieces = (split / /, $1);
1218 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1219 if ($old_n_parents != @oldpieces &&
1220 $old_n_parents != @oldpieces + 1) {
1221 snag 'upstream-confusing', sprintf
1222 "previous upstream combine %s".
1223 " mentions %d pieces (each implying one parent)".
1224 " but has %d parents".
1225 " (one per piece plus maybe a previous combine)",
1226 $old_upstream->{CommitId},
1227 (scalar @oldpieces),
1229 } elsif ($oldpieces[0] ne '.') {
1230 snag 'upstream-confusing', sprintf
1231 "previous upstream combine %s".
1232 " first piece is not \`.'",
1236 foreach my $i (0..$#oldpieces) {
1237 my $n = $oldpieces[$i];
1238 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1239 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1243 snag 'upstream-confusing',
1244 "previous upstream $old_upstream->{CommitId} is from".
1245 " git-debrebase but not an \`upstream-combine' commit";
1249 foreach my $pc (values %pieces) {
1250 if (!$old_upstream) {
1251 # we have complained already
1252 } elsif (!$pc->{Old}) {
1253 snag 'upstream-new-piece',
1254 "introducing upstream piece \`$pc->{Name}'";
1255 } elsif (!$pc->{New}) {
1256 snag 'upstream-rm-piece',
1257 "dropping upstream piece \`$pc->{Name}'";
1258 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1259 snag 'upstream-not-ff',
1260 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1264 printdebug "%pieces = ", (dd \%pieces), "\n";
1265 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1273 my @upstream_merge_parents;
1276 push @upstream_merge_parents, $old_upstream->{CommitId};
1279 foreach my $pc (@newpieces) { # always has '' first
1281 read_tree_subdir $pc->{Name}, $pc->{New};
1283 runcmd @git, qw(read-tree), $pc->{New};
1285 push @upstream_merge_parents, $pc->{New};
1288 # index now contains the new upstream
1290 if (@newpieces > 1) {
1291 # need to make the upstream subtree merge commit
1292 $new_upstream = make_commit \@upstream_merge_parents,
1293 [ "Combine upstreams for $new_upstream_version",
1294 ("[git-debrebase upstream-combine . ".
1295 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1300 # $new_upstream is either the single upstream commit, or the
1301 # combined commit we just made. Either way it will be the
1302 # "upstream" parent of the anchor merge.
1304 read_tree_subdir 'debian', "$old_bw:debian";
1306 # index now contains the anchor merge contents
1307 $new_bw = make_commit [ $old_bw, $new_upstream ],
1308 [ "Update to upstream $new_upstream_version",
1309 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1312 my $clogsignoff = cmdoutput qw(git show),
1313 '--pretty=format:%an <%ae> %aD',
1316 # Now we have to add a changelog stanza so the Debian version
1318 die if unlink "debian";
1319 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1320 unlink "debian/changelog" or $!==ENOENT or die $!;
1321 mkdir "debian" or die $!;
1322 open CN, ">", "debian/changelog" or die $!;
1323 my $oldclog = git_cat_file ":debian/changelog";
1324 $oldclog =~ m/^($package_re) \(\S+\) / or
1325 fail "cannot parse old changelog to get package name";
1327 print CN <<END, $oldclog or die $!;
1328 $p ($new_version) UNRELEASED; urgency=medium
1330 * Update to new upstream version $new_upstream_version.
1336 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1338 # Now we have the final new breakwater branch in the index
1339 $new_bw = make_commit [ $new_bw ],
1340 [ "Update changelog for new upstream $new_upstream_version",
1341 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1345 # we have constructed the new breakwater. we now need to commit to
1346 # the laundering output, because git-rebase can't easily be made
1347 # to make a replay list which is based on some other branch
1349 update_head_postlaunder $old_head, $old_laundered_tip,
1350 'launder for new upstream';
1352 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1354 # now it's for the user to sort out
1357 sub cmd_record_ffq_prev () {
1358 badusage "no arguments allowed" if @ARGV;
1359 my ($status, $msg) = record_ffq_prev_deferred();
1360 if ($status eq 'exists' && $opt_noop_ok) {
1361 print "Previous head already recorded\n" or die $!;
1362 } elsif ($status eq 'deferred') {
1363 run_deferred_updates 'record-ffq-prev';
1365 fail "Could not preserve: $msg";
1370 badusage "no arguments allowed" if @ARGV;
1371 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1372 print "$bw\n" or die $!;
1375 sub cmd_breakwater () {
1376 badusage "no arguments allowed" if @ARGV;
1377 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1378 print "$bw\n" or die $!;
1382 badusage "no arguments allowed" if @ARGV;
1384 # todo: gdr status should print divergence info
1385 # todo: gdr status should print upstream component(s) info
1386 # todo: gdr should leave/maintain some refs with this kind of info ?
1391 my ($badness, $ourmsg, $snagname, $kcmsg, $cl) = @_;
1392 if ($oldest->[0] < $badness) {
1393 $oldest = $newest = undef;
1395 $oldest = \@_; # we're walking backwards
1398 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1399 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1400 sub { $note->(2, 'branch is unlaundered', @_); },
1401 sub { $note->(3, 'branch needs laundering', @_); },
1402 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1404 my $prcommitinfo = sub {
1406 flush STDOUT or die $!;
1407 runcmd @git, qw(--no-pager log -n1),
1408 '--pretty=format: %h %s%n',
1412 print "current branch contents, in git-debrebase terms:\n";
1413 if (!$oldest->[0]) {
1414 print " branch is laundered\n";
1416 print " $oldest->[1]\n";
1418 foreach my $info ($oldest, $newest) {
1419 my $cid = $info->[4]{CommitId};
1420 next if $cid eq $printed;
1422 print " $info->[3]\n";
1423 $prcommitinfo->($cid);
1428 my ($cid, $what) = @_;
1429 if (!defined $cid) {
1430 print " $what is not well-defined\n";
1433 $prcommitinfo->($cid);
1436 print "key git-debrebase commits:\n";
1437 $prab->($anchor, 'anchor');
1438 $prab->($bw, 'breakwater');
1440 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1441 ffq_prev_branchinfo();
1443 print "branch and ref status, in git-debrebase terms:\n";
1445 print " $ffq_msg\n";
1447 $ffq_prev = git_get_ref $ffq_prev;
1448 $gdrlast = git_get_ref $gdrlast;
1450 print " unstitched; previous tip was:\n";
1451 $prcommitinfo->($ffq_prev);
1452 } elsif (!$gdrlast) {
1453 print " stitched? (no record of git-debrebase work)\n";
1454 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1455 print " stitched\n";
1457 print " not git-debrebase (diverged since last stitch)\n"
1463 my $prose = 'stitch';
1464 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1465 badusage "no arguments allowed" if @ARGV;
1466 do_stitch $prose, 0;
1468 sub cmd_prepush () { cmd_stitch(); }
1471 badusage "no arguments allowed" if @ARGV;
1472 do_launder_head 'launder for git-debrebase quick';
1476 sub cmd_conclude () {
1477 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1478 if (!$ffq_prev_commitish) {
1479 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1482 my $dangling_head = get_head();
1484 badusage "no arguments allowed" if @ARGV;
1485 do_launder_head 'launder for git-debrebase quick';
1489 sub make_patches_staged ($) {
1491 # Produces the patches that would result from $head if it were
1493 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1496 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1497 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1498 runcmd qw(gbp pq export);
1499 runcmd @git, qw(add debian/patches);
1503 sub make_patches ($) {
1505 keycommits $head, 0, \&snag;
1506 make_patches_staged $head;
1509 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1510 runcmd @git, qw(read-tree), $head;
1511 read_tree_subdir 'debian/patches', $ptree;
1512 $out = make_commit [$head], [
1513 'Commit patch queue (exported by git-debrebase)',
1514 '[git-debrebase: export and commit patches]',
1520 sub cmd_make_patches () {
1521 my $opt_quiet_would_amend;
1522 GetOptions('quiet-would-amend!', \$opt_quiet_would_amend)
1523 or die badusage("bad options to make-patches");
1524 badusage "no arguments allowed" if @ARGV;
1525 my $old_head = get_head();
1526 my $new = make_patches $old_head;
1527 my $d = get_differs $old_head, $new;
1529 fail "No (more) patches to export." unless $opt_noop_ok;
1531 } elsif ($d == D_PAT_ADD) {
1533 update_head_checkout $old_head, $new, 'make-patches';
1535 print STDERR failmsg
1536 "Patch export produced patch amendments".
1537 " (abandoned output commit $new).".
1538 " Try laundering first."
1539 unless $opt_quiet_would_amend;
1544 sub cmd_convert_from_gbp () {
1545 badusage "needs 1 optional argument, the upstream git rev"
1547 my ($upstream_spec) = @ARGV;
1548 $upstream_spec //= 'refs/heads/upstream';
1549 my $upstream = git_rev_parse $upstream_spec;
1550 my $old_head = get_head();
1552 my $upsdiff = get_differs $upstream, $old_head;
1553 if ($upsdiff & D_UPS) {
1554 runcmd @git, qw(--no-pager diff),
1555 $upstream, $old_head,
1556 qw( -- :!/debian :/);
1557 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1560 if (!is_fast_fwd $upstream, $old_head) {
1561 snag 'upstream-not-ancestor',
1562 "upstream ($upstream) is not an ancestor of HEAD";
1564 my $wrong = cmdoutput
1565 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1566 qw(-- :/ :!/debian));
1567 if (length $wrong) {
1568 snag 'unexpected-upstream-changes',
1569 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1570 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1574 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1575 snag 'upstream-has-debian',
1576 "upstream ($upstream) contains debian/ directory";
1585 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1586 # make a branch out of the patch queue - we'll want this in a mo
1587 runcmd qw(gbp pq import);
1588 # strip the patches out
1589 runcmd @git, qw(checkout -q gdr-internal~0);
1590 rm_subdir_cached 'debian/patches';
1591 $work = make_commit ['HEAD'], [
1592 'git-debrebase convert-from-gbp: drop patches from tree',
1593 'Delete debian/patches, as part of converting to git-debrebase format.',
1594 '[git-debrebase convert-from-gbp: drop patches from tree]'
1596 # make the anchor merge
1597 # the tree is already exactly right
1598 $work = make_commit [$work, $upstream], [
1599 'git-debrebase import: declare upstream',
1600 'First breakwater merge.',
1601 '[git-debrebase anchor: declare upstream]'
1604 # rebase the patch queue onto the new breakwater
1605 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1606 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1607 $work = git_rev_parse 'HEAD';
1610 update_head_checkout $old_head, $work, 'convert-from-gbp';
1613 sub cmd_convert_to_gbp () {
1614 badusage "no arguments allowed" if @ARGV;
1615 my $head = get_head();
1616 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1617 keycommits $head, 0;
1619 make_patches_staged $head;
1621 $out = make_commit ['HEAD'], [
1622 'Commit patch queue (converted from git-debrebase format)',
1623 '[git-debrebase convert-to-gbp: commit patches]',
1627 push @deferred_updates, "delete $ffq";
1628 push @deferred_updates, "delete $gdrlast";
1631 update_head_checkout $head, $out, "convert to gbp (v0)";
1632 print <<END or die $!;
1633 git-debrebase: converted to git-buildpackage branch format
1634 git-debrebase: WARNING: do not now run "git-debrebase" any more
1635 git-debrebase: WARNING: doing so would drop all upstream patches!
1639 sub cmd_downstream_rebase_launder_v0 () {
1640 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1642 $base = git_rev_parse $base;
1643 my $old_head = get_head();
1644 my $current = $old_head;
1647 if ($current eq $base) {
1648 $topmost_keep //= $current;
1649 print " $current BASE stop\n";
1652 my $cl = classify $current;
1653 print " $current $cl->{Type}";
1655 my $p0 = $cl->{Parents}[0]{CommitId};
1657 if ($cl->{Type} eq 'Pseudomerge') {
1658 print " ^".($cl->{Contributor}{Ix}+1);
1659 $next = $cl->{Contributor}{CommitId};
1660 } elsif ($cl->{Type} eq 'AddPatches' or
1661 $cl->{Type} eq 'Changelog') {
1671 $topmost_keep //= $current;
1673 die "to-be stripped changes not on top of the branch\n"
1678 if ($topmost_keep eq $old_head) {
1679 print "unchanged\n";
1681 print "updating to $topmost_keep\n";
1682 update_head_checkout
1683 $old_head, $topmost_keep,
1684 'downstream-rebase-launder-v0';
1688 GetOptions("D+" => \$debuglevel,
1689 'noop-ok', => \$opt_noop_ok,
1690 'f=s' => \@snag_force_opts,
1691 'anchor=s' => \@opt_anchors,
1694 my ($opt,$val) = @_;
1695 badusage "git-debrebase: no cuddling to -i for git-rebase"
1697 die if $opt_defaultcmd_interactive; # should not happen
1698 $opt_defaultcmd_interactive = [ qw(-i) ];
1699 # This access to @ARGV is excessive familiarity with
1700 # Getopt::Long, but there isn't another sensible
1701 # approach. '-i=s{0,}' does not work with bundling.
1702 push @$opt_defaultcmd_interactive, @ARGV;
1704 }) or die badusage "bad options\n";
1705 initdebug('git-debrebase ');
1706 enabledebug if $debuglevel;
1708 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1709 chdir $toplevel or die "chdir $toplevel: $!";
1711 $rd = fresh_playground "$playprefix/misc";
1713 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1715 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1716 defaultcmd_rebase();
1718 my $cmd = shift @ARGV;
1721 $cmdfn = ${*::}{"cmd_$cmdfn"};
1723 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";