3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
6 # Copyright (C)2017 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 # git-debrebase new-upstreams-v0 \
22 # NEW-VERSION ORIG-COMMITISH
23 # [EXTRA-ORIG-NAME EXTRA-ORIG-COMMITISH ...]
26 # git-debrebase status
27 # git-debrebase start # like ffqrebase start + debrebase launder
28 # git-debrebase new-upstream [stuff] # see below
29 # git-debrebase <git-rebase options> # does debrebase start if necessary
31 # git-debrebase analyse
32 # git-debrebase launder # prints breakwater tip
33 # git-debrebase create-new-upstream-breakwater [-f] <upstreaminfo>...
36 # [,][<subdir>:][+]<commitid>[,...]
38 # if initial comma is supplied, entries are not positional. Unspecified
39 # <subdir> means root (and there may be only one).
40 # xxx want auto branch names
43 # [+]<commit> [<subdir/> [+]<commit>...]
45 # --new-upstream-different-subtrees
48 # git-debrebase new-upstream
49 # - previous breakwater merge must be gdr-generated
50 # - orig set is the same as before
51 # - implicitly uses upstream branches according to orig set
52 # - not all upstream branches need be updated
53 # - insists on fast-forward of each branch, unless
54 # --force (or --force=<subdir>[/])
55 # branch set adjustments
56 # git-debrebase new-upstream --add <subdir>/
57 # git-debrebase new-upstream --rm <subdir>/
58 # git-debrebase new-upstream / [<subdir>/ ...]
59 # - orig set is adjusted
60 # - otherwise like auto (--add is not checked for ffness, obv)
61 # - multiple --add and --rm may be specified
62 # - --add makes new upstream the last contributor
64 # git-debrebase / [<rootcommitid>] [<subdir>/ [<commitid>] ...]
65 # - orig set is precisely as specified now
66 # - previous breakwater merge is irrelevant
67 # - no fast forward checks
68 # for now only explicit with commitids
70 # implicitly uses `upstream'
71 # # (or multiple other branches)
72 # git-debrebase new-upstream \
73 # [<subdir>/]=<commitid>
75 # UPSTREAM[,[[SUBDIR:]SUBUPSTREAM]
76 # default for SUBDIR: is from previous upstream merge[xxx terminology]
80 # when starting must record original start (for ff)
81 # and new rebase basis
83 # git-ffqrebase start [BASE]
84 # # records previous HEAD so it can be overwritten
85 # # records base for future git-ffqrebase
86 # git-ffqrebase set-base BASE
87 # git-ffqrebase <git-rebase options>
88 # git-ffqrebase finish
89 # git-ffqrebase status [BRANCH]
91 # refs/ffqrebase-prev/BRANCH BRANCH may be refs/...; if not it means
92 # refs/ffqrebase-base/BRANCH refs/heads/BRANCH
93 # zero, one, or both of these may exist
95 # git-debrebase without start, if already started, is willing
96 # to strip pseudomerges provided that they overwrite exactly
98 # xxxx is this right ? what matters is have we pushed
99 # I think in fact the right answer is:
100 # git-debrebase always strips out pseudomerges from its branch
101 # a pseudomerge is put in at the time we want to push
102 # at that time, we make a pseudomerge of the remote tracking
103 # branch (if raw git) or the dgit view (if dgit)
104 # for raw git git-ffqrebase, do want preciseley to record
105 # value of remote tracking branch or our branch, on start, so we
106 # overwrite only things we intend to
107 # the previous pseudomerge check for tags and remote branches ?
111 use Debian::Dgit qw(:DEFAULT :playground);
118 use Getopt::Long qw(:config posix_default gnu_compat bundling);
125 die "bad usage: $m\n";
131 my @cmd = qw(git config -z);
132 push @cmd, qw(--get-all) if wantarray;
134 my $out = cmdoutput @cmd;
135 return split /\0/, $out;
142 my $dd = new Data::Dumper [ $v ];
143 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
149 my $data = git_cat_file $objid, 'commit';
150 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
154 sub D_UPS () { 0x02; } # upstream files
155 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
156 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
157 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
158 sub D_DEB_OTH () { 0x20; } # debian/changelog
159 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
161 our $playprefix = 'debrebase';
167 sub in_workarea ($) {
170 my $r = eval { $sub->(); };
171 { local $@; changedir $maindir; }
175 sub fresh_workarea () {
176 $workarea = fresh_playground "$playprefix/work";
177 in_workarea sub { playtree_setup };
180 sub get_differs ($$) {
182 # This resembles quiltify_trees_differ, in dgit, a bit.
183 # But we don't care about modes, or dpkg-source-unrepresentable
184 # changes, and we don't need the plethora of different modes.
185 # Conversely we need to distinguish different kinds of changes to
186 # debian/ and debian/patches/.
191 my ($opts, $limits, $fn) = @_;
192 my @cmd = (@git, qw(diff-tree -z --no-renames));
194 push @cmd, "$_:" foreach $x, $y;
196 my $diffs = cmdoutput @cmd;
197 foreach (split /\0/, $diffs) { $fn->(); }
200 $rundiff->([qw(--name-only)], [], sub {
201 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
204 if ($differs & DS_DEB) {
206 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
208 m{^debian/patches/} ? D_PAT_OTH :
209 $_ eq 'debian/changelog' ? D_DEB_CLOG :
212 die "mysterious debian changes $x..$y"
213 unless $differs & (D_PAT_OTH|DS_DEB);
216 if ($differs & D_PAT_OTH) {
218 $differs &= ~D_PAT_OTH;
220 $differs |= D_PAT_OTH;
221 no warnings qw(exiting); last;
223 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
224 no warnings qw(exiting);
225 if (!defined $mode) {
228 die unless s{^debian/patches/}{};
230 if ($mode eq 'A' && !m/\.series$/s) {
232 } elsif ($mode eq 'M' && $_ eq 'series') {
233 my $x_s = git_cat_file "$x:debian/patches/series", 'blob';
234 my $y_s = git_cat_file "$y:debian/patches/series", 'blob';
235 chomp $x_s; $x_s .= "\n";
236 $ok = $x_s eq substr($y_s, 0, length $x_s);
241 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
243 die "mysterious debian/patches changes $x..$y"
244 unless $differs & (D_PAT_ADD|D_PAT_OTH);
247 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
252 sub commit_pr_info ($) {
254 return Data::Dumper->dump([$r], [qw(commit)]);
257 sub calculate_committer_authline () {
258 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
259 'DUMMY COMMIT (git-debrebase)', "HEAD:";
260 my ($h,$m) = get_commit $c;
261 $h =~ m/^committer .*$/m or confess "($h) ?";
265 sub rm_subdir_cached ($) {
267 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
270 sub read_tree_subdir ($$) {
271 my ($subdir, $new_tree_object) = @_;
272 rm_subdir_cached $subdir;
273 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
276 # classify returns an info hash like this
278 # Hdr => # commit headers, including 1 final newline
279 # Msg => # commit message (so one newline is dropped)
281 # Type => (see below)
283 # Ix => $index # ie 0, 1, 2, ...
285 # Differs => return value from get_differs
287 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
289 # NewMsg => # commit message, but with any [dgit import ...] edited
290 # # to say "[was: ...]"
301 # has additional entres in classification result
302 # Overwritten = [ subset of Parents ]
303 # Contributor = $the_remaining_Parent
305 # DgitImportUnpatched
306 # has additional entry in classification result
307 # OrigParents = [ subset of Parents ]
309 # BreakwaterUpstreamMerge
310 # has additional entry in classification result
311 # OrigParents = [ subset of Parents ] # singleton list
313 sub parsecommit ($;$) {
314 my ($objid, $p_ref) = @_;
315 # => hash with CommitId Hdr Msg Tree Parents
316 # Parents entries have only Ix CommitId
317 # $p_ref, if provided, must be [] and is used as a base for Parents
322 my ($h,$m) = get_commit $objid;
324 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
325 my (@ph) = $h =~ m/^parent (\w+)$/mg;
335 foreach my $ph (@ph) {
337 Ix => scalar @$p_ref,
349 my $r = parsecommit($objid, \@p);
353 $p->{Differs} = (get_differs $p->{CommitId}, $t),
356 printdebug "classify $objid \$t=$t \@p",
357 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
361 my ($type, @rest) = @_;
362 $r = { %$r, Type => $type, @rest };
364 printdebug " = $type ".(dd $r)."\n";
370 $r = { %$r, Type => qw(Unknown) };
371 printdebug " ** Unknown\n";
376 my $d = $r->{Parents}[0]{Differs};
377 if ($d == D_PAT_ADD) {
378 return $classify->(qw(AddPatches));
379 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
380 return $unknown->("edits debian/patches");
381 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
382 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
384 if ($d == D_DEB_CLOG) {
385 return $classify->(qw(Changelog));
387 return $classify->(qw(Packaging));
389 } elsif ($ty eq 'missing') {
390 return $classify->(qw(BreakwaterStart));
392 return $unknown->("parent's debian is not a directory");
394 } elsif ($d == D_UPS) {
395 return $classify->(qw(Upstream));
396 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
397 return $classify->(qw(Mixed));
399 return $unknown->("no changes");
401 confess "internal error $objid ?";
405 return $unknown->("origin commit");
408 my @identical = grep { !$_->{Differs} } @p;
409 if (@p == 2 && @identical == 1) {
410 my @overwritten = grep { $_->{Differs} } @p;
411 confess "internal error $objid ?" unless @overwritten==1;
412 return $classify->(qw(Pseudomerge),
413 Overwritten => $overwritten[0],
414 Contributor => $identical[0]);
416 if (@p == 2 && @identical == 2) {
417 my @bytime = nsort_by {
418 my ($ph,$pm) = get_commit $_->{CommitId};
419 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
422 return $classify->(qw(Pseudomerge),
423 SubType => qw(Ambiguous),
424 Overwritten => $bytime[0],
425 Contributor => $bytime[1]);
428 my ($p_h, $p_m) = get_commit $p->{CommitId};
429 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
430 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
432 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
434 if (!(grep { !$_->{IsOrigin} } @p) and
435 (@orig_ps >= @p - 1) and
436 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
438 return $classify->(qw(DgitImportUnpatched),
439 OrigParents => \@orig_ps);
442 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
443 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
445 # How to decide about l/r ordering of breakwater merges ? git
446 # --topo-order prefers to expand 2nd parent first. There's
447 # already an easy rune to look for debian/ history anyway (git log
448 # debian/) so debian breakwater branch should be 1st parent; that
449 # way also there's also an easy rune to look for the upstream
450 # patches (--topo-order).
452 # The above tells us which way *we* will generate them. But we
453 # might encounter ad-hoc breakwater merges generated manually,
454 # which might be the other way around. In principle, in some odd
455 # situations, a breakwater merge might have two identical parents.
456 # In that case we guess which way round it is (ie, which parent
457 # has the upstream history). The order of the 2-iteration loop
458 # controls which guess we make.
460 foreach my $prevbrw (qw(0 1)) {
463 !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
464 !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
465 !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
466 return $classify->(qw(BreakwaterUpstreamMerge),
467 OrigParents => [ $p[!$prevbrw] ]);
471 # multi-orig upstreams are represented with a breakwater merge
472 # from a single upstream commit which combines the orig tarballs
474 return $unknown->("complex merge");
480 $nogenerate,$report) = @_;
481 # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
482 # (or nothing, if $nogenerate)
484 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
486 # go through commits backwards
487 # we generate two lists of commits to apply:
488 # breakwater branch and upstream patches
489 my (@brw_cl, @upp_cl, @processed);
496 my ($appendinfo) = @_;
499 $ms .= "\n\n[git-debrebase $appendinfo]\n";
502 my $rewrite_from_here = sub {
503 my $sp_cl = { SpecialMethod => 'StartRewrite' };
504 push @brw_cl, $sp_cl;
505 push @processed, $sp_cl;
510 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
513 return unless $report;
514 print $report $prdelim, @_;
518 my $bomb = sub { # usage: return $bomb->();
519 print $report " Unprocessable" if $report;
522 return (undef,undef);
524 die "commit $cur: Cannot cope with this commit (d.".
525 (join ' ', map { sprintf "%#x", $_->{Differs} }
526 @{ $cl->{Parents} }). ")";
532 my $build_start = sub {
533 my ($msg, $parent) = @_;
536 no warnings qw(exiting); last;
539 my $last_upstream_update;
543 my $ty = $cl->{Type};
544 my $st = $cl->{SubType};
545 $prline->("$cl->{CommitId} $cl->{Type}");
546 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
547 push @processed, $cl;
548 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
549 if ($ty eq 'AddPatches') {
551 $rewrite_from_here->();
553 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
557 } elsif ($ty eq 'BreakwaterStart') {
558 $last_upstream_update = $cur;
559 $build_start->('FirstPackaging', $cur);
560 } elsif ($ty eq 'Upstream') {
564 } elsif ($ty eq 'Mixed') {
567 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
570 $queue->(\@brw_cl, "debian");
571 $queue->(\@upp_cl, "upstream");
572 $rewrite_from_here->();
575 } elsif ($ty eq 'Pseudomerge') {
576 my $contrib = $cl->{Contributor}{CommitId};
577 print $report " Contributor=$contrib" if $report;
578 push @pseudomerges, $cl;
579 $rewrite_from_here->();
582 } elsif ($ty eq 'BreakwaterUpstreamMerge') {
583 $last_upstream_update = $cur;
584 $build_start->("PreviousBreakwater", $cur);
585 } elsif ($ty eq 'DgitImportUnpatched') {
586 my $pm = $pseudomerges[-1];
588 # To an extent, this is heuristic. Imports don't have
589 # a useful history of the debian/ branch. We assume
590 # that the first pseudomerge after an import has a
591 # useful history of debian/, and ignore the histories
592 # from later pseudomerges. Often the first pseudomerge
593 # will be the dgit import of the upload to the actual
594 # suite intended by the non-dgit NMUer, and later
595 # pseudomerges may represent in-archive copies.
596 my $ovwrs = $pm->{Overwritten};
597 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
600 printdebug "*** WALK BOMB DgitImportUnpatched\n";
603 my $ovwr = $ovwrs->[0]{CommitId};
604 printf $report " Overwr=%s", $ovwr if $report;
605 # This import has a tree which is just like a
606 # breakwater tree, but it has the wrong history. It
607 # ought to have the previous breakwater (which the
608 # pseudomerge overwrote) as an ancestor. That will
609 # make the history of the debian/ files correct. As
610 # for the upstream version: either it's the same as
611 # was ovewritten (ie, same as the previous
612 # breakwater), in which case that history is precisely
613 # right; or, otherwise, it was a non-gitish upload of a
614 # new upstream version. We can tell these apart by
615 # looking at the tree of the supposed upstream.
618 SpecialMethod => 'DgitImportDebianUpdate',
619 $xmsg->("convert dgit import: debian changes")
621 my $differs = (get_differs $ovwr, $cl->{Tree});
622 printf $report " Differs=%#x", $differs if $report;
623 if ($differs & D_UPS) {
624 printf $report " D_UPS" if $report;
625 # This will also trigger if a non-dgit git-based NMU
626 # deleted .gitignore (which is a thing that some of
627 # the existing git tools do if the user doesn't
628 # somehow tell them not to). Ah well.
631 SpecialMethod => 'DgitImportUpstreamUpdate',
632 $xmsg->("convert dgit import: upstream changes")
635 $prline->(" Import");
636 $rewrite_from_here->();
637 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
638 die 'BUG $upp_limit is not used anywhere?';
642 # Everything is from this import. This kind of import
643 # is already in valid breakwater format, with the
644 # patches as commits.
645 printf $report " NoPM" if $report;
646 # last thing we processed will have been the first patch,
647 # if there is one; which is fine, so no need to rewrite
648 # on account of this import
649 $build_start->("ImportOrigin", $cur);
653 printdebug "*** WALK BOMB unrecognised\n";
659 printdebug "*** WALK prep done cur=$cur".
660 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
662 return if $nogenerate;
664 # Now we build it back up again
670 my $read_tree_debian = sub {
672 read_tree_subdir 'debian', "$treeish:debian";
673 rm_subdir_cached 'debian/patches';
675 my $read_tree_upstream = sub {
677 runcmd @git, qw(read-tree), $treeish;
678 $read_tree_debian->($build);
681 my $committer_authline = calculate_committer_authline();
683 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
685 confess "internal error" unless $build eq (pop @processed)->{CommitId};
688 mkdir $rd or $!==EEXIST or die $!;
690 runcmd @git, qw(read-tree), $build;
691 foreach my $cl (qw(Debian), (reverse @brw_cl),
692 { SpecialMethod => 'RecordBreakwaterTip' },
693 qw(Upstream), (reverse @upp_cl)) {
695 $current_method = $cl;
698 my $method = $cl->{SpecialMethod} // $current_method;
699 my @parents = ($build);
700 my $cltree = $cl->{CommitId};
701 printdebug "WALK BUILD ".($cltree//'undef').
702 " $method (rewriting=$rewriting)\n";
703 if ($method eq 'Debian') {
704 $read_tree_debian->($cltree);
705 } elsif ($method eq 'Upstream') {
706 $read_tree_upstream->($cltree);
707 } elsif ($method eq 'StartRewrite') {
710 } elsif ($method eq 'RecordBreakwaterTip') {
711 $breakwater = $build;
713 } elsif ($method eq 'DgitImportDebianUpdate') {
714 $read_tree_debian->($cltree);
715 rm_subdir_cached qw(debian/patches);
716 } elsif ($method eq 'DgitImportUpstreamUpdate') {
717 $read_tree_upstream->($cltree);
718 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
723 my $procd = (pop @processed) // 'UNDEF';
726 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
729 my $newtree = cmdoutput @git, qw(write-tree);
731 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
732 $ch =~ s{^parent .*\n}{}m;
733 $ch =~ s{(?=^author)}{
734 join '', map { "parent $_\n" } @parents
735 }me or confess "$ch ?";
737 $ch =~ s{^committer .*$}{$committer_authline}m
740 my $cf = "$rd/m$rewriting";
741 open CD, ">", $cf or die $!;
742 print CD $ch, "\n", $cl->{Msg} or die $!;
744 my @cmd = (@git, qw(hash-object));
745 push @cmd, qw(-w) if $rewriting;
746 push @cmd, qw(-t commit), $cf;
747 my $newcommit = cmdoutput @cmd;
748 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
750 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
751 $last_upstream_update = $cur;
756 my $final_check = get_differs $build, $input;
757 die sprintf "internal error %#x %s %s", $final_check, $build, $input
758 if $final_check & ~D_PAT_ADD;
760 my @r = ($build, $breakwater, $last_upstream_update);
761 printdebug "*** WALK RETURN @r\n";
765 sub get_head () { return git_rev_parse qw(HEAD); }
767 sub update_head ($$$) {
768 my ($old, $new, $mrest) = @_;
769 runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
772 sub update_head_checkout ($$$) {
773 my ($old, $new, $mrest) = @_;
774 my $symref = git_get_symref();
775 runcmd @git, qw(checkout), $new, qw(.);
776 update_head $old, $new, $mrest;
780 badusage "no arguments to launder allowed" if @ARGV;
781 my $old = get_head();
782 my ($tip,$breakwater,$last_upstream_merge) = walk $old;
783 update_head $old, $tip, 'launder';
784 # no tree changes except debian/patches
785 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
786 printf "# breakwater tip\n%s\n", $breakwater;
787 printf "# working tip\n%s\n", $tip;
788 printf "# last upstream merge\n%s\n", $last_upstream_merge;
792 die if ($ARGV[0]//'') =~ m/^-/;
793 badusage "too many arguments to analyse" if @ARGV>1;
796 $old = git_rev_parse $old;
800 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
801 STDOUT->error and die $!;
804 sub cmd_new_upstream_v0 () {
805 # xxx would like to support more git-rebase options
807 "need NEW-VERSION UPS-COMMITISH [EXTRA-UPS-NAME EXTRA-UPS-COMMITISH...]"
808 unless @ARGV % 2 == 0 and @ARGV >= 2;
809 # tree should be clean and this is not checked
810 # automatically and unconditionally launders before rebasing
811 # if rebase --abort is used, laundering has still been done
815 # parse args - low commitment
816 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
817 my $new_upstream_version = $new_version->version();
819 my $new_upstream = git_rev_parse shift @ARGV;
822 my ($n, @x) = @_; # may be ''
823 my $pc = $pieces{$n} //= {
825 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
827 while (my $k = shift @x) { $pc->{$k} = shift @x; }
833 my ($n, @x) = @_; # may be ''
834 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
835 push @newpieces, $pc;
840 New => $new_upstream,
844 my $c = git_rev_parse shift @ARGV;
845 die unless $n =~ m/^$extra_orig_namepart_re$/;
846 $newpiece->($n, New => $c);
849 # now we need to investigate the branch this generates the
850 # laundered version but we don't switch to it yet
851 my $old_head = get_head();
852 my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
854 my $old_bw_cl = classify $old_bw;
855 my $old_upstream_update_cl = classify $old_upstream_update;
856 confess unless $old_upstream_update_cl->{OrigParents};
857 my $old_upstream = parsecommit
858 $old_upstream_update_cl->{OrigParents}[0]{CommitId};
864 print STDERR "preflight check failed: $msg\n";
867 $piece->('', Old => $old_upstream->{CommitId});
869 if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
870 if ($old_upstream->{Msg} =~
871 m{^\[git-debrebase new-upstream combine \.((?: $extra_orig_namepart_re)+)\]}
873 my @oldpieces = ('', split / /, $1);
874 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
875 foreach my $i (0..$#oldpieces) {
876 my $n = $oldpieces[$i];
877 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
880 $problem->("previous upstream $old_upstream->{CommitId} is from".
881 " git-debrebase but not a \`new-upstream combine' commit");
885 foreach my $pc (values %pieces) {
887 $problem->("introducing upstream piece \`$pc->{Name}'");
888 } elsif (!$pc->{New}) {
889 $problem->("dropping upstream piece \`$pc->{Name}'");
890 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
891 $problem->("not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}");
895 printdebug "%pieces = ", (dd \%pieces), "\n";
896 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
901 "preflight check failures (%d) overriden by --force\n",
905 "preflight check failures (%d) (you could --force)",
914 my @upstream_merge_parents;
917 push @upstream_merge_parents, $old_upstream->{CommitId};
920 foreach my $pc (@newpieces) { # always has '' first
922 read_tree_subdir $pc->{Name}, $pc->{New};
924 runcmd @git, qw(read-tree), $pc->{New};
926 push @upstream_merge_parents, $pc->{New};
929 # index now contains the new upstream
931 if (@newpieces > 1) {
932 # need to make the upstream subtree merge commit
933 my $us_tree = cmdoutput @git, qw(write-tree);
934 my @cmd = (@git, qw(commit-tree), $us_tree);
935 push @cmd, qw(-p), $_ foreach @upstream_merge_parents;
936 push @cmd, qw(-m), "Combine upstreams for $new_upstream_version";
938 "[git-debrebase new-upstream combine . ".
939 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
941 $new_upstream = cmdoutput @cmd;
944 # $new_upstream is either the single upstream commit, or the
945 # combined commit we just made. Either way it will be the
946 # "upstream" parent of the breakwater special merge.
948 read_tree_subdir 'debian', "$old_bw:debian";
950 # index now contains the breakwater merge contents
952 my $bw_tree = cmdoutput @git, qw(write-tree);
953 my @cmd = (@git, qw(commit-tree), $bw_tree);
954 push @cmd, qw(-p), $old_bw, qw(-p), $new_upstream;
955 push @cmd, qw(-m), "Update to upstream $new_upstream_version";
957 "[git-debrebase new-upstream breakwater $new_upstream_version]";
958 $new_bw = cmdoutput @cmd;
960 # Now we have to add a changelog stanza so the Debian version
963 die if unlink "debian";
964 die $! unless $!==ENOTEMPTY;
965 unlink "debian/changelog" or die $!;
966 open CN, ">", "debian/changelog" or die $!;
967 my $oldclog = git_cat_file ":debian/changelog";
968 $oldclog =~ m/^($package_re) \(\S+\) / or
969 fail "cannot parse old changelog to get package name";
971 print CN <<END, $oldclog or die $!;
972 $p ($new_version) UNRELEASED; urgency=medium
974 * Update to new upstream version $new_upstream_version.
980 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
982 # Now we have the final new breakwater branch in the index
984 $bw_tree = cmdoutput @git, qw(write-tree);
985 @cmd = (@git, qw(commit-tree), $bw_tree);
986 push @cmd, qw(-p), $new_bw;
988 "Update changelog for new upstream $new_upstream_version";
990 "[git-debrebase new-upstream changelog $new_upstream_version]";
991 $new_bw = cmdoutput @cmd;
994 # we have constructed the new breakwater. we now need to commit to
995 # the laundering output, because git-rebase can't easily be made
996 # to make a replay list which is based on some other branch
998 update_head $old_head, $old_laundered_tip, 'launder for new upstream';
1000 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw);
1002 # now it's for the user to sort out
1005 sub cmd_downstream_rebase_launder_v0 () {
1006 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1008 $base = git_rev_parse $base;
1009 my $old_head = get_head();
1010 my $current = $old_head;
1013 if ($current eq $base) {
1014 $topmost_keep //= $current;
1015 print " $current BASE stop\n";
1018 my $cl = classify $current;
1019 print " $current $cl->{Type}";
1021 my $p0 = $cl->{Parents}[0]{CommitId};
1023 if ($cl->{Type} eq 'Pseudomerge') {
1024 print " ^".($cl->{Contributor}{Ix}+1);
1025 $next = $cl->{Contributor}{CommitId};
1026 } elsif ($cl->{Type} eq 'AddPatches' or
1027 $cl->{Type} eq 'Changelog') {
1037 $topmost_keep //= $current;
1039 die "to-be stripped changes not on top of the branch\n"
1044 if ($topmost_keep eq $old_head) {
1045 print "unchanged\n";
1047 print "updating to $topmost_keep\n";
1048 update_head_checkout
1049 $old_head, $topmost_keep,
1050 'downstream-rebase-launder-v0';
1054 GetOptions("D+" => \$debuglevel,
1055 'force!') or die badusage "bad options\n";
1056 initdebug('git-debrebase ');
1057 enabledebug if $debuglevel;
1059 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1060 chdir $toplevel or die "chdir $toplevel: $!";
1062 $rd = fresh_playground "$playprefix/misc";
1064 my $cmd = shift @ARGV;
1067 $cmdfn = ${*::}{"cmd_$cmdfn"};
1069 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";