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 (@oldpieces != $old_n_parents) {
1220 snag 'upstream-confusing', sprintf
1221 "previous upstream combine %s".
1222 " mentions %d pieces (each implying one orig commit)".
1223 " but has %d parents",
1224 $old_upstream->{CommitId},
1225 (scalar @oldpieces),
1227 } elsif ($oldpieces[0] ne '.') {
1228 snag 'upstream-confusing', sprintf
1229 "previous upstream combine %s".
1230 " first piece is not \`.'",
1234 foreach my $i (0..$#oldpieces) {
1235 my $n = $oldpieces[$i];
1236 $piece->($n, Old => $old_upstream->{CommitId}.'^'.($i+1));
1240 snag 'upstream-confusing',
1241 "previous upstream $old_upstream->{CommitId} is from".
1242 " git-debrebase but not an \`upstream-combine' commit";
1246 foreach my $pc (values %pieces) {
1247 if (!$old_upstream) {
1248 # we have complained already
1249 } elsif (!$pc->{Old}) {
1250 snag 'upstream-new-piece',
1251 "introducing upstream piece \`$pc->{Name}'";
1252 } elsif (!$pc->{New}) {
1253 snag 'upstream-rm-piece',
1254 "dropping upstream piece \`$pc->{Name}'";
1255 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1256 snag 'upstream-not-ff',
1257 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1261 printdebug "%pieces = ", (dd \%pieces), "\n";
1262 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1270 my @upstream_merge_parents;
1273 push @upstream_merge_parents, $old_upstream->{CommitId};
1276 foreach my $pc (@newpieces) { # always has '' first
1278 read_tree_subdir $pc->{Name}, $pc->{New};
1280 runcmd @git, qw(read-tree), $pc->{New};
1282 push @upstream_merge_parents, $pc->{New};
1285 # index now contains the new upstream
1287 if (@newpieces > 1) {
1288 # need to make the upstream subtree merge commit
1289 $new_upstream = make_commit \@upstream_merge_parents,
1290 [ "Combine upstreams for $new_upstream_version",
1291 ("[git-debrebase upstream-combine . ".
1292 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1297 # $new_upstream is either the single upstream commit, or the
1298 # combined commit we just made. Either way it will be the
1299 # "upstream" parent of the anchor merge.
1301 read_tree_subdir 'debian', "$old_bw:debian";
1303 # index now contains the anchor merge contents
1304 $new_bw = make_commit [ $old_bw, $new_upstream ],
1305 [ "Update to upstream $new_upstream_version",
1306 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1309 my $clogsignoff = cmdoutput qw(git show),
1310 '--pretty=format:%an <%ae> %aD',
1313 # Now we have to add a changelog stanza so the Debian version
1315 die if unlink "debian";
1316 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1317 unlink "debian/changelog" or $!==ENOENT or die $!;
1318 mkdir "debian" or die $!;
1319 open CN, ">", "debian/changelog" or die $!;
1320 my $oldclog = git_cat_file ":debian/changelog";
1321 $oldclog =~ m/^($package_re) \(\S+\) / or
1322 fail "cannot parse old changelog to get package name";
1324 print CN <<END, $oldclog or die $!;
1325 $p ($new_version) UNRELEASED; urgency=medium
1327 * Update to new upstream version $new_upstream_version.
1333 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1335 # Now we have the final new breakwater branch in the index
1336 $new_bw = make_commit [ $new_bw ],
1337 [ "Update changelog for new upstream $new_upstream_version",
1338 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1342 # we have constructed the new breakwater. we now need to commit to
1343 # the laundering output, because git-rebase can't easily be made
1344 # to make a replay list which is based on some other branch
1346 update_head_postlaunder $old_head, $old_laundered_tip,
1347 'launder for new upstream';
1349 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1351 # now it's for the user to sort out
1354 sub cmd_record_ffq_prev () {
1355 badusage "no arguments allowed" if @ARGV;
1356 my ($status, $msg) = record_ffq_prev_deferred();
1357 if ($status eq 'exists' && $opt_noop_ok) {
1358 print "Previous head already recorded\n" or die $!;
1359 } elsif ($status eq 'deferred') {
1360 run_deferred_updates 'record-ffq-prev';
1362 fail "Could not preserve: $msg";
1367 badusage "no arguments allowed" if @ARGV;
1368 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1369 print "$bw\n" or die $!;
1372 sub cmd_breakwater () {
1373 badusage "no arguments allowed" if @ARGV;
1374 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1375 print "$bw\n" or die $!;
1379 badusage "no arguments allowed" if @ARGV;
1381 # todo: gdr status should print divergence info
1382 # todo: gdr status should print upstream component(s) info
1383 # todo: gdr should leave/maintain some refs with this kind of info ?
1388 my ($badness, $ourmsg, $snagname, $kcmsg, $cl) = @_;
1389 if ($oldest->[0] < $badness) {
1390 $oldest = $newest = undef;
1392 $oldest = \@_; # we're walking backwards
1395 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1396 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1397 sub { $note->(2, 'branch is unlaundered', @_); },
1398 sub { $note->(3, 'branch needs laundering', @_); },
1399 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1401 my $prcommitinfo = sub {
1403 flush STDOUT or die $!;
1404 runcmd @git, qw(--no-pager log -n1),
1405 '--pretty=format: %h %s%n',
1409 print "current branch contents, in git-debrebase terms:\n";
1410 if (!$oldest->[0]) {
1411 print " branch is laundered\n";
1413 print " $oldest->[1]\n";
1415 foreach my $info ($oldest, $newest) {
1416 my $cid = $info->[4]{CommitId};
1417 next if $cid eq $printed;
1419 print " $info->[3]\n";
1420 $prcommitinfo->($cid);
1425 my ($cid, $what) = @_;
1426 if (!defined $cid) {
1427 print " $what is not well-defined\n";
1430 $prcommitinfo->($cid);
1433 print "key git-debrebase commits:\n";
1434 $prab->($anchor, 'anchor');
1435 $prab->($bw, 'breakwater');
1437 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1438 ffq_prev_branchinfo();
1440 print "branch and ref status, in git-debrebase terms:\n";
1442 print " $ffq_msg\n";
1444 $ffq_prev = git_get_ref $ffq_prev;
1445 $gdrlast = git_get_ref $gdrlast;
1447 print " unstitched; previous tip was:\n";
1448 $prcommitinfo->($ffq_prev);
1449 } elsif (!$gdrlast) {
1450 print " stitched? (no record of git-debrebase work)\n";
1451 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1452 print " stitched\n";
1454 print " not git-debrebase (diverged since last stitch)\n"
1460 my $prose = 'stitch';
1461 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1462 badusage "no arguments allowed" if @ARGV;
1463 do_stitch $prose, 0;
1465 sub cmd_prepush () { cmd_stitch(); }
1468 badusage "no arguments allowed" if @ARGV;
1469 do_launder_head 'launder for git-debrebase quick';
1473 sub cmd_conclude () {
1474 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1475 if (!$ffq_prev_commitish) {
1476 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1479 my $dangling_head = get_head();
1481 badusage "no arguments allowed" if @ARGV;
1482 do_launder_head 'launder for git-debrebase quick';
1486 sub make_patches_staged ($) {
1488 # Produces the patches that would result from $head if it were
1490 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1493 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1494 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1495 runcmd qw(gbp pq export);
1496 runcmd @git, qw(add debian/patches);
1500 sub make_patches ($) {
1502 keycommits $head, 0, \&snag;
1503 make_patches_staged $head;
1506 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1507 runcmd @git, qw(read-tree), $head;
1508 read_tree_subdir 'debian/patches', $ptree;
1509 $out = make_commit [$head], [
1510 'Commit patch queue (exported by git-debrebase)',
1511 '[git-debrebase: export and commit patches]',
1517 sub cmd_make_patches () {
1518 my $opt_quiet_would_amend;
1519 GetOptions('quiet-would-amend!', \$opt_quiet_would_amend)
1520 or die badusage("bad options to make-patches");
1521 badusage "no arguments allowed" if @ARGV;
1522 my $old_head = get_head();
1523 my $new = make_patches $old_head;
1524 my $d = get_differs $old_head, $new;
1526 fail "No (more) patches to export." unless $opt_noop_ok;
1528 } elsif ($d == D_PAT_ADD) {
1530 update_head_checkout $old_head, $new, 'make-patches';
1532 print STDERR failmsg
1533 "Patch export produced patch amendments".
1534 " (abandoned output commit $new).".
1535 " Try laundering first."
1536 unless $opt_quiet_would_amend;
1541 sub cmd_convert_from_gbp () {
1542 badusage "needs 1 optional argument, the upstream git rev"
1544 my ($upstream_spec) = @ARGV;
1545 $upstream_spec //= 'refs/heads/upstream';
1546 my $upstream = git_rev_parse $upstream_spec;
1547 my $old_head = get_head();
1549 my $upsdiff = get_differs $upstream, $old_head;
1550 if ($upsdiff & D_UPS) {
1551 runcmd @git, qw(--no-pager diff),
1552 $upstream, $old_head,
1553 qw( -- :!/debian :/);
1554 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1557 if (!is_fast_fwd $upstream, $old_head) {
1558 snag 'upstream-not-ancestor',
1559 "upstream ($upstream) is not an ancestor of HEAD";
1561 my $wrong = cmdoutput
1562 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1563 qw(-- :/ :!/debian));
1564 if (length $wrong) {
1565 snag 'unexpected-upstream-changes',
1566 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1567 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1571 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1572 snag 'upstream-has-debian',
1573 "upstream ($upstream) contains debian/ directory";
1582 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1583 # make a branch out of the patch queue - we'll want this in a mo
1584 runcmd qw(gbp pq import);
1585 # strip the patches out
1586 runcmd @git, qw(checkout -q gdr-internal~0);
1587 rm_subdir_cached 'debian/patches';
1588 $work = make_commit ['HEAD'], [
1589 'git-debrebase convert-from-gbp: drop patches from tree',
1590 'Delete debian/patches, as part of converting to git-debrebase format.',
1591 '[git-debrebase convert-from-gbp: drop patches from tree]'
1593 # make the anchor merge
1594 # the tree is already exactly right
1595 $work = make_commit [$work, $upstream], [
1596 'git-debrebase import: declare upstream',
1597 'First breakwater merge.',
1598 '[git-debrebase anchor: declare upstream]'
1601 # rebase the patch queue onto the new breakwater
1602 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1603 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1604 $work = git_rev_parse 'HEAD';
1607 update_head_checkout $old_head, $work, 'convert-from-gbp';
1610 sub cmd_convert_to_gbp () {
1611 badusage "no arguments allowed" if @ARGV;
1612 my $head = get_head();
1613 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1614 keycommits $head, 0;
1616 make_patches_staged $head;
1618 $out = make_commit ['HEAD'], [
1619 'Commit patch queue (converted from git-debrebase format)',
1620 '[git-debrebase convert-to-gbp: commit patches]',
1624 push @deferred_updates, "delete $ffq";
1625 push @deferred_updates, "delete $gdrlast";
1628 update_head_checkout $head, $out, "convert to gbp (v0)";
1629 print <<END or die $!;
1630 git-debrebase: converted to git-buildpackage branch format
1631 git-debrebase: WARNING: do not now run "git-debrebase" any more
1632 git-debrebase: WARNING: doing so would drop all upstream patches!
1636 sub cmd_downstream_rebase_launder_v0 () {
1637 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1639 $base = git_rev_parse $base;
1640 my $old_head = get_head();
1641 my $current = $old_head;
1644 if ($current eq $base) {
1645 $topmost_keep //= $current;
1646 print " $current BASE stop\n";
1649 my $cl = classify $current;
1650 print " $current $cl->{Type}";
1652 my $p0 = $cl->{Parents}[0]{CommitId};
1654 if ($cl->{Type} eq 'Pseudomerge') {
1655 print " ^".($cl->{Contributor}{Ix}+1);
1656 $next = $cl->{Contributor}{CommitId};
1657 } elsif ($cl->{Type} eq 'AddPatches' or
1658 $cl->{Type} eq 'Changelog') {
1668 $topmost_keep //= $current;
1670 die "to-be stripped changes not on top of the branch\n"
1675 if ($topmost_keep eq $old_head) {
1676 print "unchanged\n";
1678 print "updating to $topmost_keep\n";
1679 update_head_checkout
1680 $old_head, $topmost_keep,
1681 'downstream-rebase-launder-v0';
1685 GetOptions("D+" => \$debuglevel,
1686 'noop-ok', => \$opt_noop_ok,
1687 'f=s' => \@snag_force_opts,
1688 'anchor=s' => \@opt_anchors,
1691 my ($opt,$val) = @_;
1692 badusage "git-debrebase: no cuddling to -i for git-rebase"
1694 die if $opt_defaultcmd_interactive; # should not happen
1695 $opt_defaultcmd_interactive = [ qw(-i) ];
1696 # This access to @ARGV is excessive familiarity with
1697 # Getopt::Long, but there isn't another sensible
1698 # approach. '-i=s{0,}' does not work with bundling.
1699 push @$opt_defaultcmd_interactive, @ARGV;
1701 }) or die badusage "bad options\n";
1702 initdebug('git-debrebase ');
1703 enabledebug if $debuglevel;
1705 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1706 chdir $toplevel or die "chdir $toplevel: $!";
1708 $rd = fresh_playground "$playprefix/misc";
1710 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1712 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1713 defaultcmd_rebase();
1715 my $cmd = shift @ARGV;
1718 $cmdfn = ${*::}{"cmd_$cmdfn"};
1720 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";