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/>.
24 # git-debrebase [<options>] new-upstream-v0 \
25 # <new-version> <orig-commitish> \
26 # [<extra-orig-name> <extra-orig-commitish> ...] \
27 # [<git-rebase options>...]
29 # git-debrebase [<options> --] [<git-rebase options...>]
30 # git-debrebase [<options>] analyse
31 # git-debrebase [<options>] launder # prints breakwater tip etc.
32 # git-debrebase [<options>] downstream-rebase-launder-v0 # experimental
34 # git-debrebase [<options>] gbp2debrebase-v0 \
37 # problems / outstanding questions:
39 # * dgit push with a `3.0 (quilt)' package means doing quilt
40 # fixup. Usually this involves recommitting the whole patch
41 # series, one at a time, with dpkg-source --commit. This is
42 # terribly terribly slow. (Maybe this should be fixed in dgit.)
44 # * dgit push usually needs to (re)make a pseudomerge. The "first"
45 # git-debrebase stripped out the previous pseudomerge and could
46 # have remembeed the HEAD. But it's not quite clear what history
47 # ought to be preserved and what should be discarded. For now
48 # the user will have to tell dgit --overwrite.
50 # To fix this, do we need a new push hook for dgit ?
52 # * Workflow is currently clumsy. Lots of spurious runes to type.
53 # There's not even a guide.
55 # * There are no tests.
57 # * new-upstream-v0 has a terrible UI. You end up with giant
58 # runic command lines.
60 # One consequence of the lack of richness it can need --force in
61 # fairly sensible situations and there is no way to tell it what
62 # you are really trying to do, other than just --force. There
63 # should be an interface with some default branch names.
65 # * There should be a standard convention for the version number,
66 # and unfinalised or not changelog, after new-upstream.
68 # * Handing of multi-orig dgit new-upstream .dsc imports is known to
69 # be broken. They may be not recognised, improperly converted, or
70 # their conversion may be unrecognised.
72 # * Docs need writing and updating. Even README.git-debrebase
73 # describes a design but may not reflect the implementation.
75 # * We need to develop a plausible model that works for derivatives,
76 # who probably want to maintain their stack on top of Debian's.
77 # downstream-rebase-launder-v0 may be a starting point?
81 use Debian::Dgit qw(:DEFAULT :playground);
88 use Getopt::Long qw(:config posix_default gnu_compat bundling);
95 die "bad usage: $m\n";
101 my @cmd = qw(git config -z);
102 push @cmd, qw(--get-all) if wantarray;
104 my $out = cmdoutput @cmd;
105 return split /\0/, $out;
112 my $dd = new Data::Dumper [ $v ];
113 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
119 my $data = (git_cat_file $objid, 'commit');
120 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
124 sub D_UPS () { 0x02; } # upstream files
125 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
126 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
127 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
128 sub D_DEB_OTH () { 0x20; } # debian/changelog
129 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
131 our $playprefix = 'debrebase';
137 sub in_workarea ($) {
140 my $r = eval { $sub->(); };
141 { local $@; changedir $maindir; }
145 sub fresh_workarea () {
146 $workarea = fresh_playground "$playprefix/work";
147 in_workarea sub { playtree_setup };
150 sub get_differs ($$) {
152 # This resembles quiltify_trees_differ, in dgit, a bit.
153 # But we don't care about modes, or dpkg-source-unrepresentable
154 # changes, and we don't need the plethora of different modes.
155 # Conversely we need to distinguish different kinds of changes to
156 # debian/ and debian/patches/.
161 my ($opts, $limits, $fn) = @_;
162 my @cmd = (@git, qw(diff-tree -z --no-renames));
164 push @cmd, "$_:" foreach $x, $y;
166 my $diffs = cmdoutput @cmd;
167 foreach (split /\0/, $diffs) { $fn->(); }
170 $rundiff->([qw(--name-only)], [], sub {
171 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
174 if ($differs & DS_DEB) {
176 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
178 m{^debian/patches/} ? D_PAT_OTH :
179 $_ eq 'debian/changelog' ? D_DEB_CLOG :
182 die "mysterious debian changes $x..$y"
183 unless $differs & (D_PAT_OTH|DS_DEB);
186 if ($differs & D_PAT_OTH) {
188 $differs &= ~D_PAT_OTH;
190 $differs |= D_PAT_OTH;
191 no warnings qw(exiting); last;
193 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
194 no warnings qw(exiting);
195 if (!defined $mode) {
198 die unless s{^debian/patches/}{};
200 if ($mode eq 'A' && !m/\.series$/s) {
202 } elsif ($mode eq 'M' && $_ eq 'series') {
203 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
204 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
205 chomp $x_s; $x_s .= "\n";
206 $ok = $x_s eq substr($y_s, 0, length $x_s);
211 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
213 die "mysterious debian/patches changes $x..$y"
214 unless $differs & (D_PAT_ADD|D_PAT_OTH);
217 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
222 sub commit_pr_info ($) {
224 return Data::Dumper->dump([$r], [qw(commit)]);
227 sub calculate_committer_authline () {
228 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
229 'DUMMY COMMIT (git-debrebase)', "HEAD:";
230 my ($h,$m) = get_commit $c;
231 $h =~ m/^committer .*$/m or confess "($h) ?";
235 sub rm_subdir_cached ($) {
237 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
240 sub read_tree_subdir ($$) {
241 my ($subdir, $new_tree_object) = @_;
242 rm_subdir_cached $subdir;
243 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
246 sub make_commit ($$) {
247 my ($parents, $message_paras) = @_;
248 my $tree = cmdoutput @git, qw(write-tree);
249 my @cmd = (@git, qw(commit-tree), $tree);
250 push @cmd, qw(-p), $_ foreach @$parents;
251 push @cmd, qw(-m), $_ foreach @$message_paras;
252 return cmdoutput @cmd;
259 print STDERR "git-debrebase: safety catch tripped: $msg\n";
261 sub fproblems_maybe_bail () {
265 "safety catch trips (%d) overriden by --force\n",
269 "safety catch trips (%d) (you could --force)",
275 # classify returns an info hash like this
277 # Hdr => # commit headers, including 1 final newline
278 # Msg => # commit message (so one newline is dropped)
280 # Type => (see below)
282 # Ix => $index # ie 0, 1, 2, ...
284 # Differs => return value from get_differs
286 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
288 # NewMsg => # commit message, but with any [dgit import ...] edited
289 # # to say "[was: ...]"
300 # has additional entres in classification result
301 # Overwritten = [ subset of Parents ]
302 # Contributor = $the_remaining_Parent
304 # DgitImportUnpatched
305 # has additional entry in classification result
306 # OrigParents = [ subset of Parents ]
308 # BreakwaterUpstreamMerge
309 # has additional entry in classification result
310 # OrigParents = [ subset of Parents ] # singleton list
312 sub parsecommit ($;$) {
313 my ($objid, $p_ref) = @_;
314 # => hash with CommitId Hdr Msg Tree Parents
315 # Parents entries have only Ix CommitId
316 # $p_ref, if provided, must be [] and is used as a base for Parents
321 my ($h,$m) = get_commit $objid;
323 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
324 my (@ph) = $h =~ m/^parent (\w+)$/mg;
334 foreach my $ph (@ph) {
336 Ix => scalar @$p_ref,
348 my $r = parsecommit($objid, \@p);
352 $p->{Differs} = (get_differs $p->{CommitId}, $t),
355 printdebug "classify $objid \$t=$t \@p",
356 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
360 my ($type, @rest) = @_;
361 $r = { %$r, Type => $type, @rest };
363 printdebug " = $type ".(dd $r)."\n";
369 $r = { %$r, Type => qw(Unknown) };
370 printdebug " ** Unknown\n";
375 my $d = $r->{Parents}[0]{Differs};
376 if ($d == D_PAT_ADD) {
377 return $classify->(qw(AddPatches));
378 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
379 return $unknown->("edits debian/patches");
380 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
381 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
383 if ($d == D_DEB_CLOG) {
384 return $classify->(qw(Changelog));
386 return $classify->(qw(Packaging));
388 } elsif ($ty eq 'missing') {
389 return $classify->(qw(BreakwaterStart));
391 return $unknown->("parent's debian is not a directory");
393 } elsif ($d == D_UPS) {
394 return $classify->(qw(Upstream));
395 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
396 return $classify->(qw(Mixed));
398 return $unknown->("no changes");
400 confess "internal error $objid ?";
404 return $unknown->("origin commit");
407 my @identical = grep { !$_->{Differs} } @p;
408 if (@p == 2 && @identical == 1) {
409 my @overwritten = grep { $_->{Differs} } @p;
410 confess "internal error $objid ?" unless @overwritten==1;
411 return $classify->(qw(Pseudomerge),
412 Overwritten => $overwritten[0],
413 Contributor => $identical[0]);
415 if (@p == 2 && @identical == 2) {
416 my @bytime = nsort_by {
417 my ($ph,$pm) = get_commit $_->{CommitId};
418 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
421 return $classify->(qw(Pseudomerge),
422 SubType => qw(Ambiguous),
423 Overwritten => $bytime[0],
424 Contributor => $bytime[1]);
427 my ($p_h, $p_m) = get_commit $p->{CommitId};
428 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
429 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
431 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
433 if (!(grep { !$_->{IsOrigin} } @p) and
434 (@orig_ps >= @p - 1) and
435 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
437 return $classify->(qw(DgitImportUnpatched),
438 OrigParents => \@orig_ps);
441 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
442 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
444 # How to decide about l/r ordering of breakwater merges ? git
445 # --topo-order prefers to expand 2nd parent first. There's
446 # already an easy rune to look for debian/ history anyway (git log
447 # debian/) so debian breakwater branch should be 1st parent; that
448 # way also there's also an easy rune to look for the upstream
449 # patches (--topo-order).
451 # The above tells us which way *we* will generate them. But we
452 # might encounter ad-hoc breakwater merges generated manually,
453 # which might be the other way around. In principle, in some odd
454 # situations, a breakwater merge might have two identical parents.
455 # In that case we guess which way round it is (ie, which parent
456 # has the upstream history). The order of the 2-iteration loop
457 # controls which guess we make.
459 foreach my $prevbrw (qw(0 1)) {
462 !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
463 !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
464 !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
465 return $classify->(qw(BreakwaterUpstreamMerge),
466 OrigParents => [ $p[!$prevbrw] ]);
470 # multi-orig upstreams are represented with a breakwater merge
471 # from a single upstream commit which combines the orig tarballs
473 return $unknown->("complex merge");
479 $nogenerate,$report) = @_;
480 # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
481 # (or nothing, if $nogenerate)
483 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
485 # go through commits backwards
486 # we generate two lists of commits to apply:
487 # breakwater branch and upstream patches
488 my (@brw_cl, @upp_cl, @processed);
495 my ($appendinfo) = @_;
498 $ms .= "\n\n[git-debrebase $appendinfo]\n";
501 my $rewrite_from_here = sub {
502 my $sp_cl = { SpecialMethod => 'StartRewrite' };
503 push @brw_cl, $sp_cl;
504 push @processed, $sp_cl;
509 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
512 return unless $report;
513 print $report $prdelim, @_;
517 my $bomb = sub { # usage: return $bomb->();
518 print $report " Unprocessable" if $report;
521 return (undef,undef);
523 die "commit $cur: Cannot cope with this commit (d.".
524 (join ' ', map { sprintf "%#x", $_->{Differs} }
525 @{ $cl->{Parents} }). ")";
531 my $build_start = sub {
532 my ($msg, $parent) = @_;
535 no warnings qw(exiting); last;
538 my $last_upstream_update;
542 my $ty = $cl->{Type};
543 my $st = $cl->{SubType};
544 $prline->("$cl->{CommitId} $cl->{Type}");
545 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
546 push @processed, $cl;
547 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
548 if ($ty eq 'AddPatches') {
550 $rewrite_from_here->();
552 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
556 } elsif ($ty eq 'BreakwaterStart') {
557 $last_upstream_update = $cur;
558 $build_start->('FirstPackaging', $cur);
559 } elsif ($ty eq 'Upstream') {
563 } elsif ($ty eq 'Mixed') {
566 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
569 $queue->(\@brw_cl, "debian");
570 $queue->(\@upp_cl, "upstream");
571 $rewrite_from_here->();
574 } elsif ($ty eq 'Pseudomerge') {
575 my $contrib = $cl->{Contributor}{CommitId};
576 print $report " Contributor=$contrib" if $report;
577 push @pseudomerges, $cl;
578 $rewrite_from_here->();
581 } elsif ($ty eq 'BreakwaterUpstreamMerge') {
582 $last_upstream_update = $cur;
583 $build_start->("PreviousBreakwater", $cur);
584 } elsif ($ty eq 'DgitImportUnpatched') {
585 my $pm = $pseudomerges[-1];
587 # To an extent, this is heuristic. Imports don't have
588 # a useful history of the debian/ branch. We assume
589 # that the first pseudomerge after an import has a
590 # useful history of debian/, and ignore the histories
591 # from later pseudomerges. Often the first pseudomerge
592 # will be the dgit import of the upload to the actual
593 # suite intended by the non-dgit NMUer, and later
594 # pseudomerges may represent in-archive copies.
595 my $ovwrs = $pm->{Overwritten};
596 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
599 printdebug "*** WALK BOMB DgitImportUnpatched\n";
602 my $ovwr = $ovwrs->[0]{CommitId};
603 printf $report " Overwr=%s", $ovwr if $report;
604 # This import has a tree which is just like a
605 # breakwater tree, but it has the wrong history. It
606 # ought to have the previous breakwater (which the
607 # pseudomerge overwrote) as an ancestor. That will
608 # make the history of the debian/ files correct. As
609 # for the upstream version: either it's the same as
610 # was ovewritten (ie, same as the previous
611 # breakwater), in which case that history is precisely
612 # right; or, otherwise, it was a non-gitish upload of a
613 # new upstream version. We can tell these apart by
614 # looking at the tree of the supposed upstream.
617 SpecialMethod => 'DgitImportDebianUpdate',
618 $xmsg->("convert dgit import: debian changes")
620 my $differs = (get_differs $ovwr, $cl->{Tree});
621 printf $report " Differs=%#x", $differs if $report;
622 if ($differs & D_UPS) {
623 printf $report " D_UPS" if $report;
624 # This will also trigger if a non-dgit git-based NMU
625 # deleted .gitignore (which is a thing that some of
626 # the existing git tools do if the user doesn't
627 # somehow tell them not to). Ah well.
630 SpecialMethod => 'DgitImportUpstreamUpdate',
631 $xmsg->("convert dgit import: upstream changes")
634 $prline->(" Import");
635 $rewrite_from_here->();
636 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
637 die 'BUG $upp_limit is not used anywhere?';
641 # Everything is from this import. This kind of import
642 # is already in valid breakwater format, with the
643 # patches as commits.
644 printf $report " NoPM" if $report;
645 # last thing we processed will have been the first patch,
646 # if there is one; which is fine, so no need to rewrite
647 # on account of this import
648 $build_start->("ImportOrigin", $cur);
652 printdebug "*** WALK BOMB unrecognised\n";
658 printdebug "*** WALK prep done cur=$cur".
659 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
661 return if $nogenerate;
663 # Now we build it back up again
669 my $read_tree_debian = sub {
671 read_tree_subdir 'debian', "$treeish:debian";
672 rm_subdir_cached 'debian/patches';
674 my $read_tree_upstream = sub {
676 runcmd @git, qw(read-tree), $treeish;
677 $read_tree_debian->($build);
680 my $committer_authline = calculate_committer_authline();
682 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
684 confess "internal error" unless $build eq (pop @processed)->{CommitId};
687 mkdir $rd or $!==EEXIST or die $!;
689 runcmd @git, qw(read-tree), $build;
690 foreach my $cl (qw(Debian), (reverse @brw_cl),
691 { SpecialMethod => 'RecordBreakwaterTip' },
692 qw(Upstream), (reverse @upp_cl)) {
694 $current_method = $cl;
697 my $method = $cl->{SpecialMethod} // $current_method;
698 my @parents = ($build);
699 my $cltree = $cl->{CommitId};
700 printdebug "WALK BUILD ".($cltree//'undef').
701 " $method (rewriting=$rewriting)\n";
702 if ($method eq 'Debian') {
703 $read_tree_debian->($cltree);
704 } elsif ($method eq 'Upstream') {
705 $read_tree_upstream->($cltree);
706 } elsif ($method eq 'StartRewrite') {
709 } elsif ($method eq 'RecordBreakwaterTip') {
710 $breakwater = $build;
712 } elsif ($method eq 'DgitImportDebianUpdate') {
713 $read_tree_debian->($cltree);
714 rm_subdir_cached qw(debian/patches);
715 } elsif ($method eq 'DgitImportUpstreamUpdate') {
716 $read_tree_upstream->($cltree);
717 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
722 my $procd = (pop @processed) // 'UNDEF';
725 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
728 my $newtree = cmdoutput @git, qw(write-tree);
730 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
731 $ch =~ s{^parent .*\n}{}m;
732 $ch =~ s{(?=^author)}{
733 join '', map { "parent $_\n" } @parents
734 }me or confess "$ch ?";
736 $ch =~ s{^committer .*$}{$committer_authline}m
739 my $cf = "$rd/m$rewriting";
740 open CD, ">", $cf or die $!;
741 print CD $ch, "\n", $cl->{Msg} or die $!;
743 my @cmd = (@git, qw(hash-object));
744 push @cmd, qw(-w) if $rewriting;
745 push @cmd, qw(-t commit), $cf;
746 my $newcommit = cmdoutput @cmd;
747 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
749 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
750 $last_upstream_update = $cur;
755 my $final_check = get_differs $build, $input;
756 die sprintf "internal error %#x %s %s", $final_check, $build, $input
757 if $final_check & ~D_PAT_ADD;
759 my @r = ($build, $breakwater, $last_upstream_update);
760 printdebug "*** WALK RETURN @r\n";
764 sub get_head () { return git_rev_parse qw(HEAD); }
766 sub update_head ($$$) {
767 my ($old, $new, $mrest) = @_;
768 runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
771 sub update_head_checkout ($$$) {
772 my ($old, $new, $mrest) = @_;
773 my $symref = git_get_symref();
774 runcmd @git, qw(checkout), $new, qw(.);
775 update_head $old, $new, $mrest;
778 sub update_head_postlaunder ($$$) {
779 my ($old, $tip, $reflogmsg) = @_;
780 return if $tip eq $old;
781 print "git-debrebase: laundered (head was $old)\n";
782 update_head $old, $tip, $reflogmsg;
783 # no tree changes except debian/patches
784 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
788 badusage "no arguments to launder allowed" if @ARGV;
789 my $old = get_head();
790 my ($tip,$breakwater,$last_upstream_merge) = walk $old;
791 update_head_postlaunder $old, $tip, 'launder';
792 printf "# breakwater tip\n%s\n", $breakwater;
793 printf "# working tip\n%s\n", $tip;
794 printf "# last upstream merge\n%s\n", $last_upstream_merge;
797 sub defaultcmd_rebase () {
798 my $old = get_head();
799 my ($tip,$breakwater) = walk $old;
800 update_head_postlaunder $old, $tip, 'launder for rebase';
801 @ARGV = qw(-i) unless @ARGV; # make configurable
802 runcmd @git, qw(rebase), @ARGV, $breakwater;
806 die if ($ARGV[0]//'') =~ m/^-/;
807 badusage "too many arguments to analyse" if @ARGV>1;
810 $old = git_rev_parse $old;
814 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
815 STDOUT->error and die $!;
818 sub cmd_new_upstream_v0 () {
819 # tree should be clean and this is not checked
820 # automatically and unconditionally launders before rebasing
821 # if rebase --abort is used, laundering has still been done
825 badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
827 # parse args - low commitment
828 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
829 my $new_upstream_version = $new_version->version();
831 my $new_upstream = git_rev_parse shift @ARGV;
834 my ($n, @x) = @_; # may be ''
835 my $pc = $pieces{$n} //= {
837 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
839 while (my $k = shift @x) { $pc->{$k} = shift @x; }
845 my ($n, @x) = @_; # may be ''
846 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
847 push @newpieces, $pc;
852 New => $new_upstream,
854 while (@ARGV && $ARGV[0] !~ m{^-}) {
857 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
858 unless @ARGV && $ARGV[0] !~ m{^-};
860 my $c = git_rev_parse shift @ARGV;
861 die unless $n =~ m/^$extra_orig_namepart_re$/;
862 $newpiece->($n, New => $c);
865 # now we need to investigate the branch this generates the
866 # laundered version but we don't switch to it yet
867 my $old_head = get_head();
868 my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
870 my $old_bw_cl = classify $old_bw;
871 my $old_upstream_update_cl = classify $old_upstream_update;
872 confess unless $old_upstream_update_cl->{OrigParents};
873 my $old_upstream = parsecommit
874 $old_upstream_update_cl->{OrigParents}[0]{CommitId};
876 $piece->('', Old => $old_upstream->{CommitId});
878 if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
879 if ($old_upstream->{Msg} =~
880 m{^\[git-debrebase (?:\w*-)?upstream combine \.((?: $extra_orig_namepart_re)+)\]}
882 my @oldpieces = ('', split / /, $1);
883 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
884 foreach my $i (0..$#oldpieces) {
885 my $n = $oldpieces[$i];
886 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
889 fproblem "previous upstream $old_upstream->{CommitId} is from".
890 " git-debrebase but not an \`upstream combine' commit";
894 foreach my $pc (values %pieces) {
896 fproblem "introducing upstream piece \`$pc->{Name}'";
897 } elsif (!$pc->{New}) {
898 fproblem "dropping upstream piece \`$pc->{Name}'";
899 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
900 fproblem "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
904 printdebug "%pieces = ", (dd \%pieces), "\n";
905 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
907 fproblems_maybe_bail();
913 my @upstream_merge_parents;
916 push @upstream_merge_parents, $old_upstream->{CommitId};
919 foreach my $pc (@newpieces) { # always has '' first
921 read_tree_subdir $pc->{Name}, $pc->{New};
923 runcmd @git, qw(read-tree), $pc->{New};
925 push @upstream_merge_parents, $pc->{New};
928 # index now contains the new upstream
930 if (@newpieces > 1) {
931 # need to make the upstream subtree merge commit
932 $new_upstream = make_commit \@upstream_merge_parents,
933 [ "Combine upstreams for $new_upstream_version",
934 ("[git-debrebase new-upstream combine . ".
935 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
940 # $new_upstream is either the single upstream commit, or the
941 # combined commit we just made. Either way it will be the
942 # "upstream" parent of the breakwater special merge.
944 read_tree_subdir 'debian', "$old_bw:debian";
946 # index now contains the breakwater merge contents
947 $new_bw = make_commit [ $old_bw, $new_upstream ],
948 [ "Update to upstream $new_upstream_version",
949 "[git-debrebase new-upstream breakwater $new_upstream_version]",
952 # Now we have to add a changelog stanza so the Debian version
954 die if unlink "debian";
955 die $! unless $!==ENOENT or $!==ENOTEMPTY;
956 unlink "debian/changelog" or $!==ENOENT or die $!;
957 mkdir "debian" or die $!;
958 open CN, ">", "debian/changelog" or die $!;
959 my $oldclog = git_cat_file ":debian/changelog";
960 $oldclog =~ m/^($package_re) \(\S+\) / or
961 fail "cannot parse old changelog to get package name";
963 print CN <<END, $oldclog or die $!;
964 $p ($new_version) UNRELEASED; urgency=medium
966 * Update to new upstream version $new_upstream_version.
972 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
974 # Now we have the final new breakwater branch in the index
975 $new_bw = make_commit [ $new_bw ],
976 [ "Update changelog for new upstream $new_upstream_version",
977 "[git-debrebase new-upstream changelog $new_upstream_version]",
981 # we have constructed the new breakwater. we now need to commit to
982 # the laundering output, because git-rebase can't easily be made
983 # to make a replay list which is based on some other branch
985 update_head_postlaunder $old_head, $old_laundered_tip,
986 'launder for new upstream';
988 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
990 # now it's for the user to sort out
993 sub cmd_downstream_rebase_launder_v0 () {
994 badusage "needs 1 argument, the baseline" unless @ARGV==1;
996 $base = git_rev_parse $base;
997 my $old_head = get_head();
998 my $current = $old_head;
1001 if ($current eq $base) {
1002 $topmost_keep //= $current;
1003 print " $current BASE stop\n";
1006 my $cl = classify $current;
1007 print " $current $cl->{Type}";
1009 my $p0 = $cl->{Parents}[0]{CommitId};
1011 if ($cl->{Type} eq 'Pseudomerge') {
1012 print " ^".($cl->{Contributor}{Ix}+1);
1013 $next = $cl->{Contributor}{CommitId};
1014 } elsif ($cl->{Type} eq 'AddPatches' or
1015 $cl->{Type} eq 'Changelog') {
1025 $topmost_keep //= $current;
1027 die "to-be stripped changes not on top of the branch\n"
1032 if ($topmost_keep eq $old_head) {
1033 print "unchanged\n";
1035 print "updating to $topmost_keep\n";
1036 update_head_checkout
1037 $old_head, $topmost_keep,
1038 'downstream-rebase-launder-v0';
1042 GetOptions("D+" => \$debuglevel,
1043 'force!') or die badusage "bad options\n";
1044 initdebug('git-debrebase ');
1045 enabledebug if $debuglevel;
1047 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1048 chdir $toplevel or die "chdir $toplevel: $!";
1050 $rd = fresh_playground "$playprefix/misc";
1052 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1053 defaultcmd_rebase();
1055 my $cmd = shift @ARGV;
1058 $cmdfn = ${*::}{"cmd_$cmdfn"};
1060 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";