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);
90 use File::FnMatch qw(:fnmatch);
92 our ($opt_force, $opt_noop_ok);
94 our $us = qw(git-debrebase);
98 die "bad usage: $m\n";
102 my ($k, $optional) = @_;
104 my @cmd = qw(git config -z);
105 push @cmd, qw(--get-all) if wantarray;
107 my $out = cmdoutput_errok @cmd;
109 fail "missing required git config $k" unless $optional;
112 return split /\0/, $out;
119 my $dd = new Data::Dumper [ $v ];
120 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
126 my $data = (git_cat_file $objid, 'commit');
127 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
131 sub D_UPS () { 0x02; } # upstream files
132 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
133 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
134 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
135 sub D_DEB_OTH () { 0x20; } # debian/changelog
136 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
138 our $playprefix = 'debrebase';
144 sub in_workarea ($) {
147 my $r = eval { $sub->(); };
148 { local $@; changedir $maindir; }
152 sub fresh_workarea () {
153 $workarea = fresh_playground "$playprefix/work";
154 in_workarea sub { playtree_setup };
157 sub get_differs ($$) {
159 # This resembles quiltify_trees_differ, in dgit, a bit.
160 # But we don't care about modes, or dpkg-source-unrepresentable
161 # changes, and we don't need the plethora of different modes.
162 # Conversely we need to distinguish different kinds of changes to
163 # debian/ and debian/patches/.
168 my ($opts, $limits, $fn) = @_;
169 my @cmd = (@git, qw(diff-tree -z --no-renames));
171 push @cmd, "$_:" foreach $x, $y;
172 push @cmd, '--', @$limits;
173 my $diffs = cmdoutput @cmd;
174 foreach (split /\0/, $diffs) { $fn->(); }
177 $rundiff->([qw(--name-only)], [], sub {
178 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
181 if ($differs & DS_DEB) {
183 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
185 m{^debian/patches/} ? D_PAT_OTH :
186 $_ eq 'debian/changelog' ? D_DEB_CLOG :
189 die "mysterious debian changes $x..$y"
190 unless $differs & (D_PAT_OTH|DS_DEB);
193 if ($differs & D_PAT_OTH) {
195 $differs &= ~D_PAT_OTH;
197 $differs |= D_PAT_OTH;
198 no warnings qw(exiting); last;
200 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
201 no warnings qw(exiting);
202 if (!defined $mode) {
205 die unless s{^debian/patches/}{};
207 if ($mode eq 'A' && !m/\.series$/s) {
209 } elsif ($mode eq 'M' && $_ eq 'series') {
210 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
211 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
212 chomp $x_s; $x_s .= "\n";
213 $ok = $x_s eq substr($y_s, 0, length $x_s);
218 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
220 die "mysterious debian/patches changes $x..$y"
221 unless $differs & (D_PAT_ADD|D_PAT_OTH);
224 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
229 sub commit_pr_info ($) {
231 return Data::Dumper->dump([$r], [qw(commit)]);
234 sub calculate_committer_authline () {
235 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
236 'DUMMY COMMIT (git-debrebase)', "HEAD:";
237 my ($h,$m) = get_commit $c;
238 $h =~ m/^committer .*$/m or confess "($h) ?";
242 sub rm_subdir_cached ($) {
244 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
247 sub read_tree_subdir ($$) {
248 my ($subdir, $new_tree_object) = @_;
249 rm_subdir_cached $subdir;
250 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
253 sub make_commit ($$) {
254 my ($parents, $message_paras) = @_;
255 my $tree = cmdoutput @git, qw(write-tree);
256 my @cmd = (@git, qw(commit-tree), $tree);
257 push @cmd, qw(-p), $_ foreach @$parents;
258 push @cmd, qw(-m), $_ foreach @$message_paras;
259 return cmdoutput @cmd;
262 our @fproblem_force_opts;
263 our $fproblems_forced;
264 our $fproblems_tripped;
267 if (grep { $_ eq $tag } @fproblem_force_opts) {
269 print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
271 $fproblems_tripped++;
272 print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
276 sub fproblems_maybe_bail () {
277 if ($fproblems_forced) {
279 "%s: safety catch trips: %d overriden by individual -f options\n",
280 $us, $fproblems_forced;
282 if ($fproblems_tripped) {
285 "%s: safety catch trips: %d overriden by global --force\n",
286 $us, $fproblems_tripped;
289 "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
290 $us, $fproblems_tripped;
294 sub any_fproblems () {
295 return $fproblems_forced || $fproblems_tripped;
298 # classify returns an info hash like this
300 # Hdr => # commit headers, including 1 final newline
301 # Msg => # commit message (so one newline is dropped)
303 # Type => (see below)
305 # Ix => $index # ie 0, 1, 2, ...
307 # Differs => return value from get_differs
309 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
311 # NewMsg => # commit message, but with any [dgit import ...] edited
312 # # to say "[was: ...]"
323 # has additional entres in classification result
324 # Overwritten = [ subset of Parents ]
325 # Contributor = $the_remaining_Parent
327 # DgitImportUnpatched
328 # has additional entry in classification result
329 # OrigParents = [ subset of Parents ]
331 # BreakwaterUpstreamMerge
332 # has additional entry in classification result
333 # OrigParents = [ subset of Parents ] # singleton list
335 sub parsecommit ($;$) {
336 my ($objid, $p_ref) = @_;
337 # => hash with CommitId Hdr Msg Tree Parents
338 # Parents entries have only Ix CommitId
339 # $p_ref, if provided, must be [] and is used as a base for Parents
344 my ($h,$m) = get_commit $objid;
346 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
347 my (@ph) = $h =~ m/^parent (\w+)$/mg;
357 foreach my $ph (@ph) {
359 Ix => scalar @$p_ref,
371 my $r = parsecommit($objid, \@p);
375 $p->{Differs} = (get_differs $p->{CommitId}, $t),
378 printdebug "classify $objid \$t=$t \@p",
379 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
383 my ($type, @rest) = @_;
384 $r = { %$r, Type => $type, @rest };
386 printdebug " = $type ".(dd $r)."\n";
392 $r = { %$r, Type => qw(Unknown) };
393 printdebug " ** Unknown\n";
397 my $claims_to_be_breakwater =
398 $r->{Msg} =~ m{^\[git-debrebase breakwater.*\]$}m;
401 if ($claims_to_be_breakwater) {
402 return $unknown->("single-parent git-debrebase breakwater \`merge'");
404 my $d = $r->{Parents}[0]{Differs};
405 if ($d == D_PAT_ADD) {
406 return $classify->(qw(AddPatches));
407 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
408 return $unknown->("edits debian/patches");
409 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
410 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
412 if ($d == D_DEB_CLOG) {
413 return $classify->(qw(Changelog));
415 return $classify->(qw(Packaging));
417 } elsif ($ty eq 'missing') {
418 return $classify->(qw(BreakwaterStart));
420 return $unknown->("parent's debian is not a directory");
422 } elsif ($d == D_UPS) {
423 return $classify->(qw(Upstream));
424 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
425 return $classify->(qw(Mixed));
427 return $unknown->("no changes");
429 confess "internal error $objid ?";
433 return $unknown->("origin commit");
436 my @identical = grep { !$_->{Differs} } @p;
437 if (@p == 2 && @identical == 1 && !$claims_to_be_breakwater
438 # breakwater merges can look like pseudomerges, if they are
439 # "declare" commits (ie, there are no upstream changes)
441 my @overwritten = grep { $_->{Differs} } @p;
442 confess "internal error $objid ?" unless @overwritten==1;
443 return $classify->(qw(Pseudomerge),
444 Overwritten => $overwritten[0],
445 Contributor => $identical[0]);
447 if (@p == 2 && @identical == 2) {
448 my @bytime = nsort_by {
449 my ($ph,$pm) = get_commit $_->{CommitId};
450 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
453 return $classify->(qw(Pseudomerge),
454 SubType => qw(Ambiguous),
455 Overwritten => $bytime[0],
456 Contributor => $bytime[1]);
459 my ($p_h, $p_m) = get_commit $p->{CommitId};
460 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
461 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
463 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
465 if (!(grep { !$_->{IsOrigin} } @p) and
466 (@orig_ps >= @p - 1) and
467 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
469 return $classify->(qw(DgitImportUnpatched),
470 OrigParents => \@orig_ps);
473 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
474 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
476 # How to decide about l/r ordering of breakwater merges ? git
477 # --topo-order prefers to expand 2nd parent first. There's
478 # already an easy rune to look for debian/ history anyway (git log
479 # debian/) so debian breakwater branch should be 1st parent; that
480 # way also there's also an easy rune to look for the upstream
481 # patches (--topo-order).
483 # The above tells us which way *we* will generate them. But we
484 # might encounter ad-hoc breakwater merges generated manually,
485 # which might be the other way around. In principle, in some odd
486 # situations, a breakwater merge might have two identical parents.
487 # In that case we guess which way round it is (ie, which parent
488 # has the upstream history). The order of the 2-iteration loop
489 # controls which guess we make.
491 foreach my $prevbrw (qw(0 1)) {
494 !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
495 !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
496 !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
497 return $classify->(qw(BreakwaterUpstreamMerge),
498 OrigParents => [ $p[!$prevbrw] ]);
502 # multi-orig upstreams are represented with a breakwater merge
503 # from a single upstream commit which combines the orig tarballs
505 return $unknown->("complex merge");
511 $nogenerate,$report) = @_;
512 # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
513 # (or nothing, if $nogenerate)
515 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
517 # go through commits backwards
518 # we generate two lists of commits to apply:
519 # breakwater branch and upstream patches
520 my (@brw_cl, @upp_cl, @processed);
527 my ($prose, $info) = @_;
531 $ms .= "\n\n[git-debrebase$info: $prose]\n";
534 my $rewrite_from_here = sub {
535 my $sp_cl = { SpecialMethod => 'StartRewrite' };
536 push @brw_cl, $sp_cl;
537 push @processed, $sp_cl;
542 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
545 return unless $report;
546 print $report $prdelim, @_;
550 my $bomb = sub { # usage: return $bomb->();
551 print $report " Unprocessable" if $report;
554 return (undef,undef);
556 die "commit $cur: Cannot cope with this commit (d.".
557 (join ' ', map { sprintf "%#x", $_->{Differs} }
558 @{ $cl->{Parents} }). ")";
564 my $build_start = sub {
565 my ($msg, $parent) = @_;
568 no warnings qw(exiting); last;
571 my $last_upstream_update;
575 my $ty = $cl->{Type};
576 my $st = $cl->{SubType};
577 $prline->("$cl->{CommitId} $cl->{Type}");
578 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
579 push @processed, $cl;
580 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
581 if ($ty eq 'AddPatches') {
583 $rewrite_from_here->();
585 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
589 } elsif ($ty eq 'BreakwaterStart') {
590 $last_upstream_update = $cur;
591 $build_start->('FirstPackaging', $cur);
592 } elsif ($ty eq 'Upstream') {
596 } elsif ($ty eq 'Mixed') {
599 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
602 $queue->(\@brw_cl, "debian");
603 $queue->(\@upp_cl, "upstream");
604 $rewrite_from_here->();
607 } elsif ($ty eq 'Pseudomerge') {
608 my $contrib = $cl->{Contributor}{CommitId};
609 print $report " Contributor=$contrib" if $report;
610 push @pseudomerges, $cl;
611 $rewrite_from_here->();
614 } elsif ($ty eq 'BreakwaterUpstreamMerge') {
615 $last_upstream_update = $cur;
616 $build_start->("PreviousBreakwater", $cur);
617 } elsif ($ty eq 'DgitImportUnpatched') {
618 my $pm = $pseudomerges[-1];
620 # To an extent, this is heuristic. Imports don't have
621 # a useful history of the debian/ branch. We assume
622 # that the first pseudomerge after an import has a
623 # useful history of debian/, and ignore the histories
624 # from later pseudomerges. Often the first pseudomerge
625 # will be the dgit import of the upload to the actual
626 # suite intended by the non-dgit NMUer, and later
627 # pseudomerges may represent in-archive copies.
628 my $ovwrs = $pm->{Overwritten};
629 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
632 printdebug "*** WALK BOMB DgitImportUnpatched\n";
635 my $ovwr = $ovwrs->[0]{CommitId};
636 printf $report " Overwr=%s", $ovwr if $report;
637 # This import has a tree which is just like a
638 # breakwater tree, but it has the wrong history. It
639 # ought to have the previous breakwater (which the
640 # pseudomerge overwrote) as an ancestor. That will
641 # make the history of the debian/ files correct. As
642 # for the upstream version: either it's the same as
643 # was ovewritten (ie, same as the previous
644 # breakwater), in which case that history is precisely
645 # right; or, otherwise, it was a non-gitish upload of a
646 # new upstream version. We can tell these apart by
647 # looking at the tree of the supposed upstream.
650 SpecialMethod => 'DgitImportDebianUpdate',
651 $xmsg->("convert dgit import: debian changes")
653 my $differs = (get_differs $ovwr, $cl->{Tree});
654 printf $report " Differs=%#x", $differs if $report;
655 if ($differs & D_UPS) {
656 printf $report " D_UPS" if $report;
657 # This will also trigger if a non-dgit git-based NMU
658 # deleted .gitignore (which is a thing that some of
659 # the existing git tools do if the user doesn't
660 # somehow tell them not to). Ah well.
663 SpecialMethod => 'DgitImportUpstreamUpdate',
664 $xmsg->("convert dgit import: upstream changes",
668 $prline->(" Import");
669 $rewrite_from_here->();
670 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
671 die 'BUG $upp_limit is not used anywhere?';
675 # Everything is from this import. This kind of import
676 # is already in valid breakwater format, with the
677 # patches as commits.
678 printf $report " NoPM" if $report;
679 # last thing we processed will have been the first patch,
680 # if there is one; which is fine, so no need to rewrite
681 # on account of this import
682 $build_start->("ImportOrigin", $cur);
686 printdebug "*** WALK BOMB unrecognised\n";
692 printdebug "*** WALK prep done cur=$cur".
693 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
695 return if $nogenerate;
697 # Now we build it back up again
703 my $read_tree_debian = sub {
705 read_tree_subdir 'debian', "$treeish:debian";
706 rm_subdir_cached 'debian/patches';
708 my $read_tree_upstream = sub {
710 runcmd @git, qw(read-tree), $treeish;
711 $read_tree_debian->($build);
714 my $committer_authline = calculate_committer_authline();
716 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
718 confess "internal error" unless $build eq (pop @processed)->{CommitId};
721 mkdir $rd or $!==EEXIST or die $!;
723 runcmd @git, qw(read-tree), $build;
724 foreach my $cl (qw(Debian), (reverse @brw_cl),
725 { SpecialMethod => 'RecordBreakwaterTip' },
726 qw(Upstream), (reverse @upp_cl)) {
728 $current_method = $cl;
731 my $method = $cl->{SpecialMethod} // $current_method;
732 my @parents = ($build);
733 my $cltree = $cl->{CommitId};
734 printdebug "WALK BUILD ".($cltree//'undef').
735 " $method (rewriting=$rewriting)\n";
736 if ($method eq 'Debian') {
737 $read_tree_debian->($cltree);
738 } elsif ($method eq 'Upstream') {
739 $read_tree_upstream->($cltree);
740 } elsif ($method eq 'StartRewrite') {
743 } elsif ($method eq 'RecordBreakwaterTip') {
744 $breakwater = $build;
746 } elsif ($method eq 'DgitImportDebianUpdate') {
747 $read_tree_debian->($cltree);
748 rm_subdir_cached qw(debian/patches);
749 } elsif ($method eq 'DgitImportUpstreamUpdate') {
750 $read_tree_upstream->($cltree);
751 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
756 my $procd = (pop @processed) // 'UNDEF';
759 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
762 my $newtree = cmdoutput @git, qw(write-tree);
764 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
765 $ch =~ s{^parent .*\n}{}m;
766 $ch =~ s{(?=^author)}{
767 join '', map { "parent $_\n" } @parents
768 }me or confess "$ch ?";
770 $ch =~ s{^committer .*$}{$committer_authline}m
773 my $cf = "$rd/m$rewriting";
774 open CD, ">", $cf or die $!;
775 print CD $ch, "\n", $cl->{Msg} or die $!;
777 my @cmd = (@git, qw(hash-object));
778 push @cmd, qw(-w) if $rewriting;
779 push @cmd, qw(-t commit), $cf;
780 my $newcommit = cmdoutput @cmd;
781 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
783 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
784 $last_upstream_update = $cur;
789 my $final_check = get_differs $build, $input;
790 die sprintf "internal error %#x %s %s", $final_check, $build, $input
791 if $final_check & ~D_PAT_ADD;
793 my @r = ($build, $breakwater, $last_upstream_update);
794 printdebug "*** WALK RETURN @r\n";
798 sub get_head () { return git_rev_parse qw(HEAD); }
800 sub update_head ($$$) {
801 my ($old, $new, $mrest) = @_;
802 runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
805 sub update_head_checkout ($$$) {
806 my ($old, $new, $mrest) = @_;
807 update_head $old, $new, $mrest;
808 runcmd @git, qw(reset --hard);
811 sub update_head_postlaunder ($$$) {
812 my ($old, $tip, $reflogmsg) = @_;
813 return if $tip eq $old;
814 print "git-debrebase: laundered (head was $old)\n";
815 update_head $old, $tip, $reflogmsg;
816 # no tree changes except debian/patches
817 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
821 badusage "no arguments to launder allowed" if @ARGV;
822 my $old = get_head();
823 my ($tip,$breakwater,$last_upstream_merge) = walk $old;
824 update_head_postlaunder $old, $tip, 'launder';
825 printf "# breakwater tip\n%s\n", $breakwater;
826 printf "# working tip\n%s\n", $tip;
827 printf "# last upstream merge\n%s\n", $last_upstream_merge;
830 sub defaultcmd_rebase () {
831 my $old = get_head();
832 my ($tip,$breakwater) = walk $old;
833 update_head_postlaunder $old, $tip, 'launder for rebase';
834 @ARGV = qw(-i) unless @ARGV; # make configurable
835 runcmd @git, qw(rebase), @ARGV, $breakwater;
839 die if ($ARGV[0]//'') =~ m/^-/;
840 badusage "too many arguments to analyse" if @ARGV>1;
843 $old = git_rev_parse $old;
847 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
848 STDOUT->error and die $!;
851 sub record_ffq_prev () {
852 # => ('status', "message")
854 # written message is undef
859 # if not ff from some branch we should be ff from, is an fproblem
860 # if "written", will have printed something about that to stdout,
861 # and also some messages about ff checks
862 my $current = git_get_symref();
863 return ('detached', 'detached HEAD') unless defined $current;
864 return ('weird-symref', 'HEAD symref is not to refs/')
865 unless $current =~ m{^refs/};
866 my $ffq_prev = "refs/$ffq_refprefix/$'";
868 my $currentval = get_head();
870 my $exists = git_get_ref $ffq_prev;
871 return ('exists',"$ffq_prev already exists") if $exists;
873 return ('not-branch', 'HEAD symref is not to refs/heads/')
874 unless $current =~ m{^refs/heads/};
877 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
881 my ($lrref, $desc) = @_;
883 for my $chk (@check_specs) {
885 $invert = $glob =~ s{^[^!]}{};
886 last if fnmatch $glob, $lrref;
889 my $lrval = git_get_ref $lrref;
890 return unless defined $lrval;
892 if (is_fast_fwd $lrval, $currentval) {
893 print "OK, you are ahead of $lrref\n" or die $!;
894 $checked{$lrref} = 1;
895 } if (is_fast_fwd $currentval, $lrval) {
896 $checked{$lrref} = -1;
897 fproblem 'behind', "you are behind $lrref, divergence risk";
899 $checked{$lrref} = -1;
900 fproblem 'diverged', "you have diverged from $lrref";
904 my $merge = cfg "branch.$branch.merge",1;
905 if (defined $merge && $merge =~ m{^refs/heads/}) {
907 my $check_remote = sub {
908 my ($remote, $desc) = (@_);
909 return unless defined $remote;
910 $check->("refs/remotes/$remote/$rhs", $desc);
912 $check_remote->((cfg "branch.$branch.remote",1),
913 'remote fetch/merge branch');
914 $check_remote->((cfg "branch.$branch.pushRemote",1) //
915 (cfg "branch.$branch.pushDefault",1),
916 'remote push branch');
918 if ($branch =~ m{^dgit/}) {
919 $check->("remotes/dgit/$branch", 'remote dgit branch');
922 fproblems_maybe_bail();
923 runcmd @git, qw(update-ref -m), "record current head for preservation",
924 $ffq_prev, $currentval, $git_null_obj;
925 print "Recorded current head for preservation\n" or die $!;
926 return ('written', undef);
929 sub cmd_new_upstream_v0 () {
930 # tree should be clean and this is not checked
931 # automatically and unconditionally launders before rebasing
932 # if rebase --abort is used, laundering has still been done
936 badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
938 # parse args - low commitment
939 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
940 my $new_upstream_version = $new_version->version();
942 my $new_upstream = git_rev_parse shift @ARGV;
945 my ($n, @x) = @_; # may be ''
946 my $pc = $pieces{$n} //= {
948 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
950 while (my $k = shift @x) { $pc->{$k} = shift @x; }
956 my ($n, @x) = @_; # may be ''
957 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
958 push @newpieces, $pc;
963 New => $new_upstream,
965 while (@ARGV && $ARGV[0] !~ m{^-}) {
968 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
969 unless @ARGV && $ARGV[0] !~ m{^-};
971 my $c = git_rev_parse shift @ARGV;
972 die unless $n =~ m/^$extra_orig_namepart_re$/;
973 $newpiece->($n, New => $c);
976 # now we need to investigate the branch this generates the
977 # laundered version but we don't switch to it yet
978 my $old_head = get_head();
979 my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
981 my $old_bw_cl = classify $old_bw;
982 my $old_upstream_update_cl = classify $old_upstream_update;
983 confess unless $old_upstream_update_cl->{OrigParents};
984 my $old_upstream = parsecommit
985 $old_upstream_update_cl->{OrigParents}[0]{CommitId};
987 $piece->('', Old => $old_upstream->{CommitId});
989 if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
990 if ($old_upstream->{Msg} =~
991 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
993 my @oldpieces = ('', split / /, $1);
994 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
995 foreach my $i (0..$#oldpieces) {
996 my $n = $oldpieces[$i];
997 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1000 fproblem 'upstream-confusing',
1001 "previous upstream $old_upstream->{CommitId} is from".
1002 " git-debrebase but not an \`upstream-combine' commit";
1006 foreach my $pc (values %pieces) {
1008 fproblem 'upstream-new-piece',
1009 "introducing upstream piece \`$pc->{Name}'";
1010 } elsif (!$pc->{New}) {
1011 fproblem 'upstream-rm-piece',
1012 "dropping upstream piece \`$pc->{Name}'";
1013 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1014 fproblem 'upstream-not-ff',
1015 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1019 printdebug "%pieces = ", (dd \%pieces), "\n";
1020 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1022 fproblems_maybe_bail();
1028 my @upstream_merge_parents;
1030 if (!any_fproblems()) {
1031 push @upstream_merge_parents, $old_upstream->{CommitId};
1034 foreach my $pc (@newpieces) { # always has '' first
1036 read_tree_subdir $pc->{Name}, $pc->{New};
1038 runcmd @git, qw(read-tree), $pc->{New};
1040 push @upstream_merge_parents, $pc->{New};
1043 # index now contains the new upstream
1045 if (@newpieces > 1) {
1046 # need to make the upstream subtree merge commit
1047 $new_upstream = make_commit \@upstream_merge_parents,
1048 [ "Combine upstreams for $new_upstream_version",
1049 ("[git-debrebase upstream-combine . ".
1050 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1055 # $new_upstream is either the single upstream commit, or the
1056 # combined commit we just made. Either way it will be the
1057 # "upstream" parent of the breakwater special merge.
1059 read_tree_subdir 'debian', "$old_bw:debian";
1061 # index now contains the breakwater merge contents
1062 $new_bw = make_commit [ $old_bw, $new_upstream ],
1063 [ "Update to upstream $new_upstream_version",
1064 "[git-debrebase breakwater: new upstream $new_upstream_version, merge]",
1067 # Now we have to add a changelog stanza so the Debian version
1069 die if unlink "debian";
1070 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1071 unlink "debian/changelog" or $!==ENOENT or die $!;
1072 mkdir "debian" or die $!;
1073 open CN, ">", "debian/changelog" or die $!;
1074 my $oldclog = git_cat_file ":debian/changelog";
1075 $oldclog =~ m/^($package_re) \(\S+\) / or
1076 fail "cannot parse old changelog to get package name";
1078 print CN <<END, $oldclog or die $!;
1079 $p ($new_version) UNRELEASED; urgency=medium
1081 * Update to new upstream version $new_upstream_version.
1087 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1089 # Now we have the final new breakwater branch in the index
1090 $new_bw = make_commit [ $new_bw ],
1091 [ "Update changelog for new upstream $new_upstream_version",
1092 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1096 # we have constructed the new breakwater. we now need to commit to
1097 # the laundering output, because git-rebase can't easily be made
1098 # to make a replay list which is based on some other branch
1100 update_head_postlaunder $old_head, $old_laundered_tip,
1101 'launder for new upstream';
1103 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1105 # now it's for the user to sort out
1108 sub cmd_record_ffq_prev () {
1109 badusage "no arguments allowed" if @ARGV;
1110 my ($status, $msg) = record_ffq_prev();
1111 if ($status eq 'exists' && $opt_noop_ok) {
1112 print "Previous head already recorded\n" or die $!;
1113 } elsif ($status eq 'written') {
1115 fail "Could not preserve: $msg";
1119 sub cmd_gbp2debrebase () {
1120 badusage "needs 1 optional argument, the upstream" unless @ARGV<=1;
1121 my ($upstream_spec) = @ARGV;
1122 $upstream_spec //= 'refs/heads/upstream';
1123 my $upstream = git_rev_parse $upstream_spec;
1124 my $old_head = get_head();
1126 my $upsdiff = get_differs $upstream, $old_head;
1127 if ($upsdiff & D_UPS) {
1128 runcmd @git, qw(--no-pager diff),
1129 $upstream, $old_head,
1130 qw( -- :!/debian :/);
1131 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1134 if (!is_fast_fwd $upstream, $old_head) {
1135 fproblem 'upstream-not-ancestor',
1136 "upstream ($upstream) is not an ancestor of HEAD";
1138 my $wrong = cmdoutput
1139 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1140 qw(-- :/ :!/debian));
1141 if (length $wrong) {
1142 fproblem 'unexpected-upstream-changes',
1143 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1144 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1148 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1149 fproblem 'upstream-has-debian',
1150 "upstream ($upstream) contains debian/ directory";
1153 fproblems_maybe_bail();
1159 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1160 # make a branch out of the patch queue - we'll want this in a mo
1161 runcmd qw(gbp pq import);
1162 # strip the patches out
1163 runcmd @git, qw(checkout -q gdr-internal~0);
1164 rm_subdir_cached 'debian/patches';
1165 $work = make_commit ['HEAD'], [
1166 'git-debrebase import: drop patch queue',
1167 'Delete debian/patches, as part of converting to git-debrebase format.',
1168 '[git-debrebase: gbp2debrebase, drop patches]'
1170 # make the breakwater pseudomerge
1171 # the tree is already exactly right
1172 $work = make_commit [$work, $upstream], [
1173 'git-debrebase import: declare upstream',
1174 'First breakwater merge.',
1175 '[git-debrebase breakwater: declare upstream]'
1178 # rebase the patch queue onto the new breakwater
1179 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1180 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1184 update_head_checkout $old_head, $work, 'gbp2debrebase';
1187 sub cmd_downstream_rebase_launder_v0 () {
1188 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1190 $base = git_rev_parse $base;
1191 my $old_head = get_head();
1192 my $current = $old_head;
1195 if ($current eq $base) {
1196 $topmost_keep //= $current;
1197 print " $current BASE stop\n";
1200 my $cl = classify $current;
1201 print " $current $cl->{Type}";
1203 my $p0 = $cl->{Parents}[0]{CommitId};
1205 if ($cl->{Type} eq 'Pseudomerge') {
1206 print " ^".($cl->{Contributor}{Ix}+1);
1207 $next = $cl->{Contributor}{CommitId};
1208 } elsif ($cl->{Type} eq 'AddPatches' or
1209 $cl->{Type} eq 'Changelog') {
1219 $topmost_keep //= $current;
1221 die "to-be stripped changes not on top of the branch\n"
1226 if ($topmost_keep eq $old_head) {
1227 print "unchanged\n";
1229 print "updating to $topmost_keep\n";
1230 update_head_checkout
1231 $old_head, $topmost_keep,
1232 'downstream-rebase-launder-v0';
1236 GetOptions("D+" => \$debuglevel,
1237 'noop-ok', => \$opt_noop_ok,
1238 'f=s' => \@fproblem_force_opts,
1239 'force!') or die badusage "bad options\n";
1240 initdebug('git-debrebase ');
1241 enabledebug if $debuglevel;
1243 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1244 chdir $toplevel or die "chdir $toplevel: $!";
1246 $rd = fresh_playground "$playprefix/misc";
1248 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1249 defaultcmd_rebase();
1251 my $cmd = shift @ARGV;
1254 $cmdfn = ${*::}{"cmd_$cmdfn"};
1256 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";