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>] stitch [--prose=<for commit message>]
33 # git-debrebase [<options>] downstream-rebase-launder-v0 # experimental
35 # git-debrebase [<options>] gbp2debrebase-v0 \
38 # problems / outstanding questions:
40 # * dgit push with a `3.0 (quilt)' package means doing quilt
41 # fixup. Usually this involves recommitting the whole patch
42 # series, one at a time, with dpkg-source --commit. This is
43 # terribly terribly slow. (Maybe this should be fixed in dgit.)
45 # * dgit push usually needs to (re)make a pseudomerge. The "first"
46 # git-debrebase stripped out the previous pseudomerge and could
47 # have remembeed the HEAD. But it's not quite clear what history
48 # ought to be preserved and what should be discarded. For now
49 # the user will have to tell dgit --overwrite.
51 # To fix this, do we need a new push hook for dgit ?
53 # * Workflow is currently clumsy. Lots of spurious runes to type.
54 # There's not even a guide.
56 # * There are no tests.
58 # * new-upstream-v0 has a terrible UI. You end up with giant
59 # runic command lines.
61 # One consequence of the lack of richness it can need --force in
62 # fairly sensible situations and there is no way to tell it what
63 # you are really trying to do, other than just --force. There
64 # should be an interface with some default branch names.
66 # * There should be a standard convention for the version number,
67 # and unfinalised or not changelog, after new-upstream.
69 # * Handing of multi-orig dgit new-upstream .dsc imports is known to
70 # be broken. They may be not recognised, improperly converted, or
71 # their conversion may be unrecognised.
73 # * Docs need writing and updating. Even README.git-debrebase
74 # describes a design but may not reflect the implementation.
76 # * We need to develop a plausible model that works for derivatives,
77 # who probably want to maintain their stack on top of Debian's.
78 # downstream-rebase-launder-v0 may be a starting point?
82 use Debian::Dgit qw(:DEFAULT :playground);
89 use Getopt::Long qw(:config posix_default gnu_compat bundling);
91 use File::FnMatch qw(:fnmatch);
93 our ($opt_force, $opt_noop_ok);
95 our $us = qw(git-debrebase);
99 die "bad usage: $m\n";
103 my ($k, $optional) = @_;
105 my @cmd = qw(git config -z);
106 push @cmd, qw(--get-all) if wantarray;
108 my $out = cmdoutput_errok @cmd;
110 fail "missing required git config $k" unless $optional;
113 return split /\0/, $out;
120 my $dd = new Data::Dumper [ $v ];
121 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
127 my $data = (git_cat_file $objid, 'commit');
128 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
132 sub D_UPS () { 0x02; } # upstream files
133 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
134 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
135 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
136 sub D_DEB_OTH () { 0x20; } # debian/changelog
137 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
139 our $playprefix = 'debrebase';
145 sub in_workarea ($) {
148 my $r = eval { $sub->(); };
149 { local $@; changedir $maindir; }
153 sub fresh_workarea () {
154 $workarea = fresh_playground "$playprefix/work";
155 in_workarea sub { playtree_setup };
158 sub get_differs ($$) {
160 # This resembles quiltify_trees_differ, in dgit, a bit.
161 # But we don't care about modes, or dpkg-source-unrepresentable
162 # changes, and we don't need the plethora of different modes.
163 # Conversely we need to distinguish different kinds of changes to
164 # debian/ and debian/patches/.
169 my ($opts, $limits, $fn) = @_;
170 my @cmd = (@git, qw(diff-tree -z --no-renames));
172 push @cmd, "$_:" foreach $x, $y;
173 push @cmd, '--', @$limits;
174 my $diffs = cmdoutput @cmd;
175 foreach (split /\0/, $diffs) { $fn->(); }
178 $rundiff->([qw(--name-only)], [], sub {
179 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
182 if ($differs & DS_DEB) {
184 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
186 m{^debian/patches/} ? D_PAT_OTH :
187 $_ eq 'debian/changelog' ? D_DEB_CLOG :
190 die "mysterious debian changes $x..$y"
191 unless $differs & (D_PAT_OTH|DS_DEB);
194 if ($differs & D_PAT_OTH) {
196 $differs &= ~D_PAT_OTH;
198 $differs |= D_PAT_OTH;
199 no warnings qw(exiting); last;
201 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
202 no warnings qw(exiting);
203 if (!defined $mode) {
206 die unless s{^debian/patches/}{};
208 if ($mode eq 'A' && !m/\.series$/s) {
210 } elsif ($mode eq 'M' && $_ eq 'series') {
211 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
212 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
213 chomp $x_s; $x_s .= "\n";
214 $ok = $x_s eq substr($y_s, 0, length $x_s);
219 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
221 die "mysterious debian/patches changes $x..$y"
222 unless $differs & (D_PAT_ADD|D_PAT_OTH);
225 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
230 sub commit_pr_info ($) {
232 return Data::Dumper->dump([$r], [qw(commit)]);
235 sub calculate_committer_authline () {
236 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
237 'DUMMY COMMIT (git-debrebase)', "HEAD:";
238 my ($h,$m) = get_commit $c;
239 $h =~ m/^committer .*$/m or confess "($h) ?";
243 sub rm_subdir_cached ($) {
245 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
248 sub read_tree_subdir ($$) {
249 my ($subdir, $new_tree_object) = @_;
250 rm_subdir_cached $subdir;
251 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
254 sub make_commit ($$) {
255 my ($parents, $message_paras) = @_;
256 my $tree = cmdoutput @git, qw(write-tree);
257 my @cmd = (@git, qw(commit-tree), $tree);
258 push @cmd, qw(-p), $_ foreach @$parents;
259 push @cmd, qw(-m), $_ foreach @$message_paras;
260 return cmdoutput @cmd;
263 our @fproblem_force_opts;
264 our $fproblems_forced;
265 our $fproblems_tripped;
268 if (grep { $_ eq $tag } @fproblem_force_opts) {
270 print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
272 $fproblems_tripped++;
273 print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
277 sub fproblems_maybe_bail () {
278 if ($fproblems_forced) {
280 "%s: safety catch trips: %d overriden by individual -f options\n",
281 $us, $fproblems_forced;
283 if ($fproblems_tripped) {
286 "%s: safety catch trips: %d overriden by global --force\n",
287 $us, $fproblems_tripped;
290 "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
291 $us, $fproblems_tripped;
295 sub any_fproblems () {
296 return $fproblems_forced || $fproblems_tripped;
299 # classify returns an info hash like this
301 # Hdr => # commit headers, including 1 final newline
302 # Msg => # commit message (so one newline is dropped)
304 # Type => (see below)
306 # Ix => $index # ie 0, 1, 2, ...
308 # Differs => return value from get_differs
310 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
312 # NewMsg => # commit message, but with any [dgit import ...] edited
313 # # to say "[was: ...]"
324 # has additional entres in classification result
325 # Overwritten = [ subset of Parents ]
326 # Contributor = $the_remaining_Parent
328 # DgitImportUnpatched
329 # has additional entry in classification result
330 # OrigParents = [ subset of Parents ]
332 # BreakwaterUpstreamMerge
333 # has additional entry in classification result
334 # OrigParents = [ subset of Parents ] # singleton list
336 sub parsecommit ($;$) {
337 my ($objid, $p_ref) = @_;
338 # => hash with CommitId Hdr Msg Tree Parents
339 # Parents entries have only Ix CommitId
340 # $p_ref, if provided, must be [] and is used as a base for Parents
345 my ($h,$m) = get_commit $objid;
347 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
348 my (@ph) = $h =~ m/^parent (\w+)$/mg;
358 foreach my $ph (@ph) {
360 Ix => scalar @$p_ref,
372 my $r = parsecommit($objid, \@p);
376 $p->{Differs} = (get_differs $p->{CommitId}, $t),
379 printdebug "classify $objid \$t=$t \@p",
380 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
384 my ($type, @rest) = @_;
385 $r = { %$r, Type => $type, @rest };
387 printdebug " = $type ".(dd $r)."\n";
393 $r = { %$r, Type => qw(Unknown) };
394 printdebug " ** Unknown\n";
398 my $claims_to_be_breakwater =
399 $r->{Msg} =~ m{^\[git-debrebase breakwater.*\]$}m;
402 if ($claims_to_be_breakwater) {
403 return $unknown->("single-parent git-debrebase breakwater \`merge'");
405 my $d = $r->{Parents}[0]{Differs};
406 if ($d == D_PAT_ADD) {
407 return $classify->(qw(AddPatches));
408 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
409 return $unknown->("edits debian/patches");
410 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
411 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
413 if ($d == D_DEB_CLOG) {
414 return $classify->(qw(Changelog));
416 return $classify->(qw(Packaging));
418 } elsif ($ty eq 'missing') {
419 return $classify->(qw(BreakwaterStart));
421 return $unknown->("parent's debian is not a directory");
423 } elsif ($d == D_UPS) {
424 return $classify->(qw(Upstream));
425 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
426 return $classify->(qw(Mixed));
428 return $unknown->("no changes");
430 confess "internal error $objid ?";
434 return $unknown->("origin commit");
437 my @identical = grep { !$_->{Differs} } @p;
438 if (@p == 2 && @identical == 1 && !$claims_to_be_breakwater
439 # breakwater merges can look like pseudomerges, if they are
440 # "declare" commits (ie, there are no upstream changes)
442 my @overwritten = grep { $_->{Differs} } @p;
443 confess "internal error $objid ?" unless @overwritten==1;
444 return $classify->(qw(Pseudomerge),
445 Overwritten => [ $overwritten[0] ],
446 Contributor => $identical[0]);
448 if (@p == 2 && @identical == 2) {
449 my @bytime = nsort_by {
450 my ($ph,$pm) = get_commit $_->{CommitId};
451 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
454 return $classify->(qw(Pseudomerge),
455 SubType => qw(Ambiguous),
456 Overwritten => [ $bytime[0] ],
457 Contributor => $bytime[1]);
460 my ($p_h, $p_m) = get_commit $p->{CommitId};
461 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
462 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
464 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
466 if (!(grep { !$_->{IsOrigin} } @p) and
467 (@orig_ps >= @p - 1) and
468 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
470 return $classify->(qw(DgitImportUnpatched),
471 OrigParents => \@orig_ps);
474 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
475 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
477 # How to decide about l/r ordering of breakwater merges ? git
478 # --topo-order prefers to expand 2nd parent first. There's
479 # already an easy rune to look for debian/ history anyway (git log
480 # debian/) so debian breakwater branch should be 1st parent; that
481 # way also there's also an easy rune to look for the upstream
482 # patches (--topo-order).
484 # The above tells us which way *we* will generate them. But we
485 # might encounter ad-hoc breakwater merges generated manually,
486 # which might be the other way around. In principle, in some odd
487 # situations, a breakwater merge might have two identical parents.
488 # In that case we guess which way round it is (ie, which parent
489 # has the upstream history). The order of the 2-iteration loop
490 # controls which guess we make.
492 foreach my $prevbrw (qw(0 1)) {
495 !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
496 !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
497 !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
498 return $classify->(qw(BreakwaterUpstreamMerge),
499 OrigParents => [ $p[!$prevbrw] ]);
503 # multi-orig upstreams are represented with a breakwater merge
504 # from a single upstream commit which combines the orig tarballs
506 return $unknown->("complex merge");
512 $nogenerate,$report) = @_;
513 # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
514 # (or nothing, if $nogenerate)
516 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
518 # go through commits backwards
519 # we generate two lists of commits to apply:
520 # breakwater branch and upstream patches
521 my (@brw_cl, @upp_cl, @processed);
528 my ($prose, $info) = @_;
532 $ms .= "\n\n[git-debrebase$info: $prose]\n";
535 my $rewrite_from_here = sub {
536 my $sp_cl = { SpecialMethod => 'StartRewrite' };
537 push @brw_cl, $sp_cl;
538 push @processed, $sp_cl;
543 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
546 return unless $report;
547 print $report $prdelim, @_;
551 my $bomb = sub { # usage: return $bomb->();
552 print $report " Unprocessable" if $report;
555 return (undef,undef);
557 die "commit $cur: Cannot cope with this commit (d.".
558 (join ' ', map { sprintf "%#x", $_->{Differs} }
559 @{ $cl->{Parents} }). ")";
565 my $build_start = sub {
566 my ($msg, $parent) = @_;
569 no warnings qw(exiting); last;
572 my $last_upstream_update;
576 my $ty = $cl->{Type};
577 my $st = $cl->{SubType};
578 $prline->("$cl->{CommitId} $cl->{Type}");
579 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
580 push @processed, $cl;
581 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
582 if ($ty eq 'AddPatches') {
584 $rewrite_from_here->();
586 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
590 } elsif ($ty eq 'BreakwaterStart') {
591 $last_upstream_update = $cur;
592 $build_start->('FirstPackaging', $cur);
593 } elsif ($ty eq 'Upstream') {
597 } elsif ($ty eq 'Mixed') {
600 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
603 $queue->(\@brw_cl, "debian");
604 $queue->(\@upp_cl, "upstream");
605 $rewrite_from_here->();
608 } elsif ($ty eq 'Pseudomerge') {
609 my $contrib = $cl->{Contributor}{CommitId};
610 print $report " Contributor=$contrib" if $report;
611 push @pseudomerges, $cl;
612 $rewrite_from_here->();
615 } elsif ($ty eq 'BreakwaterUpstreamMerge') {
616 $last_upstream_update = $cur;
617 $build_start->("PreviousBreakwater", $cur);
618 } elsif ($ty eq 'DgitImportUnpatched') {
619 my $pm = $pseudomerges[-1];
621 # To an extent, this is heuristic. Imports don't have
622 # a useful history of the debian/ branch. We assume
623 # that the first pseudomerge after an import has a
624 # useful history of debian/, and ignore the histories
625 # from later pseudomerges. Often the first pseudomerge
626 # will be the dgit import of the upload to the actual
627 # suite intended by the non-dgit NMUer, and later
628 # pseudomerges may represent in-archive copies.
629 my $ovwrs = $pm->{Overwritten};
630 printf $report " PM=%s \@Overwr:%d",
631 $pm->{CommitId}, (scalar @$ovwrs)
634 printdebug "*** WALK BOMB DgitImportUnpatched\n";
637 my $ovwr = $ovwrs->[0]{CommitId};
638 printf $report " Overwr=%s", $ovwr if $report;
639 # This import has a tree which is just like a
640 # breakwater tree, but it has the wrong history. It
641 # ought to have the previous breakwater (which the
642 # pseudomerge overwrote) as an ancestor. That will
643 # make the history of the debian/ files correct. As
644 # for the upstream version: either it's the same as
645 # was ovewritten (ie, same as the previous
646 # breakwater), in which case that history is precisely
647 # right; or, otherwise, it was a non-gitish upload of a
648 # new upstream version. We can tell these apart by
649 # looking at the tree of the supposed upstream.
652 SpecialMethod => 'DgitImportDebianUpdate',
653 $xmsg->("convert dgit import: debian changes")
656 SpecialMethod => 'DgitImportUpstreamUpdate',
657 $xmsg->("convert dgit import: upstream update",
660 $prline->(" Import");
661 $rewrite_from_here->();
662 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
666 # Everything is from this import. This kind of import
667 # is already in valid breakwater format, with the
668 # patches as commits.
669 printf $report " NoPM" if $report;
670 # last thing we processed will have been the first patch,
671 # if there is one; which is fine, so no need to rewrite
672 # on account of this import
673 $build_start->("ImportOrigin", $cur);
677 printdebug "*** WALK BOMB unrecognised\n";
683 printdebug "*** WALK prep done cur=$cur".
684 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
686 return if $nogenerate;
688 # Now we build it back up again
694 my $read_tree_debian = sub {
696 read_tree_subdir 'debian', "$treeish:debian";
697 rm_subdir_cached 'debian/patches';
699 my $read_tree_upstream = sub {
701 runcmd @git, qw(read-tree), $treeish;
702 $read_tree_debian->($build);
705 $#upp_cl = $upp_limit if defined $upp_limit;
707 my $committer_authline = calculate_committer_authline();
709 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
711 confess "internal error" unless $build eq (pop @processed)->{CommitId};
714 mkdir $rd or $!==EEXIST or die $!;
716 runcmd @git, qw(read-tree), $build;
717 foreach my $cl (qw(Debian), (reverse @brw_cl),
718 { SpecialMethod => 'RecordBreakwaterTip' },
719 qw(Upstream), (reverse @upp_cl)) {
721 $current_method = $cl;
724 my $method = $cl->{SpecialMethod} // $current_method;
725 my @parents = ($build);
726 my $cltree = $cl->{CommitId};
727 printdebug "WALK BUILD ".($cltree//'undef').
728 " $method (rewriting=$rewriting)\n";
729 if ($method eq 'Debian') {
730 $read_tree_debian->($cltree);
731 } elsif ($method eq 'Upstream') {
732 $read_tree_upstream->($cltree);
733 } elsif ($method eq 'StartRewrite') {
736 } elsif ($method eq 'RecordBreakwaterTip') {
737 $breakwater = $build;
739 } elsif ($method eq 'DgitImportDebianUpdate') {
740 $read_tree_debian->($cltree);
741 } elsif ($method eq 'DgitImportUpstreamUpdate') {
742 confess unless $rewriting;
743 my $differs = (get_differs $build, $cltree);
744 next unless $differs & D_UPS;
745 $read_tree_upstream->($cltree);
746 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
751 my $procd = (pop @processed) // 'UNDEF';
754 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
757 my $newtree = cmdoutput @git, qw(write-tree);
759 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
760 $ch =~ s{^parent .*\n}{}m;
761 $ch =~ s{(?=^author)}{
762 join '', map { "parent $_\n" } @parents
763 }me or confess "$ch ?";
765 $ch =~ s{^committer .*$}{$committer_authline}m
768 my $cf = "$rd/m$rewriting";
769 open CD, ">", $cf or die $!;
770 print CD $ch, "\n", $cl->{Msg} or die $!;
772 my @cmd = (@git, qw(hash-object));
773 push @cmd, qw(-w) if $rewriting;
774 push @cmd, qw(-t commit), $cf;
775 my $newcommit = cmdoutput @cmd;
776 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
778 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
779 $last_upstream_update = $cur;
784 my $final_check = get_differs $build, $input;
785 die sprintf "internal error %#x %s %s", $final_check, $build, $input
786 if $final_check & ~D_PAT_ADD;
788 my @r = ($build, $breakwater, $last_upstream_update);
789 printdebug "*** WALK RETURN @r\n";
794 git_check_unmodified();
795 return git_rev_parse qw(HEAD);
798 sub update_head ($$$) {
799 my ($old, $new, $mrest) = @_;
800 runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
803 sub update_head_checkout ($$$) {
804 my ($old, $new, $mrest) = @_;
805 update_head $old, $new, $mrest;
806 runcmd @git, qw(reset --hard);
809 sub update_head_postlaunder ($$$) {
810 my ($old, $tip, $reflogmsg) = @_;
811 return if $tip eq $old;
812 print "git-debrebase: laundered (head was $old)\n";
813 update_head $old, $tip, $reflogmsg;
814 # no tree changes except debian/patches
815 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
819 badusage "no arguments to launder allowed" if @ARGV;
820 my $old = get_head();
821 my ($tip,$breakwater,$last_upstream_merge) = walk $old;
822 update_head_postlaunder $old, $tip, 'launder';
823 printf "# breakwater tip\n%s\n", $breakwater;
824 printf "# working tip\n%s\n", $tip;
825 printf "# last upstream merge\n%s\n", $last_upstream_merge;
828 sub defaultcmd_rebase () {
829 my $old = get_head();
830 my ($status, $message) = record_ffq_prev();
831 if ($status eq 'written' || $status eq 'exists') {
833 fproblem $status, "could not record ffq-prev: $message";
834 fproblems_maybe_bail();
836 my ($tip,$breakwater) = walk $old;
837 update_head_postlaunder $old, $tip, 'launder for rebase';
838 runcmd @git, qw(rebase), @ARGV, $breakwater;
842 die if ($ARGV[0]//'') =~ m/^-/;
843 badusage "too many arguments to analyse" if @ARGV>1;
846 $old = git_rev_parse $old;
848 $old = git_rev_parse 'HEAD';
850 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
851 STDOUT->error and die $!;
854 sub ffq_prev_branchinfo () {
855 # => ('status', "message", [$current, $ffq_prev])
857 # branch message is undef
858 # weird-symref } no $current,
859 # notbranch } no $ffq_prev
860 my $current = git_get_symref();
861 return ('detached', 'detached HEAD') unless defined $current;
862 return ('weird-symref', 'HEAD symref is not to refs/')
863 unless $current =~ m{^refs/};
864 my $ffq_prev = "refs/$ffq_refprefix/$'";
865 return ('branch', undef, $current, $ffq_prev);
868 sub record_ffq_prev () {
869 # => ('status', "message")
871 # written message is undef
876 # if not ff from some branch we should be ff from, is an fproblem
877 # if "written", will have printed something about that to stdout,
878 # and also some messages about ff checks
879 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
880 return ($status, $message) unless $status eq 'branch';
882 my $currentval = get_head();
884 my $exists = git_get_ref $ffq_prev;
885 return ('exists',"$ffq_prev already exists") if $exists;
887 return ('not-branch', 'HEAD symref is not to refs/heads/')
888 unless $current =~ m{^refs/heads/};
891 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
895 my ($lrref, $desc) = @_;
897 for my $chk (@check_specs) {
899 $invert = $glob =~ s{^[^!]}{};
900 last if fnmatch $glob, $lrref;
903 my $lrval = git_get_ref $lrref;
904 return unless defined $lrval;
906 if (is_fast_fwd $lrval, $currentval) {
907 print "OK, you are ahead of $lrref\n" or die $!;
908 $checked{$lrref} = 1;
909 } if (is_fast_fwd $currentval, $lrval) {
910 $checked{$lrref} = -1;
911 fproblem 'behind', "you are behind $lrref, divergence risk";
913 $checked{$lrref} = -1;
914 fproblem 'diverged', "you have diverged from $lrref";
918 my $merge = cfg "branch.$branch.merge",1;
919 if (defined $merge && $merge =~ m{^refs/heads/}) {
921 my $check_remote = sub {
922 my ($remote, $desc) = (@_);
923 return unless defined $remote;
924 $check->("refs/remotes/$remote/$rhs", $desc);
926 $check_remote->((cfg "branch.$branch.remote",1),
927 'remote fetch/merge branch');
928 $check_remote->((cfg "branch.$branch.pushRemote",1) //
929 (cfg "branch.$branch.pushDefault",1),
930 'remote push branch');
932 if ($branch =~ m{^dgit/}) {
933 $check->("remotes/dgit/$branch", 'remote dgit branch');
934 } elsif ($branch =~ m{^master$}) {
935 $check->("remotes/dgit/dgit/sid", 'remote dgit branch for sid');
938 fproblems_maybe_bail();
939 runcmd @git, qw(update-ref -m), "record current head for preservation",
940 $ffq_prev, $currentval, $git_null_obj;
941 print "Recorded current head for preservation\n" or die $!;
942 return ('written', undef);
945 sub cmd_new_upstream_v0 () {
946 # automatically and unconditionally launders before rebasing
947 # if rebase --abort is used, laundering has still been done
951 badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
953 # parse args - low commitment
954 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
955 my $new_upstream_version = $new_version->version();
957 my $new_upstream = git_rev_parse shift @ARGV;
960 my ($n, @x) = @_; # may be ''
961 my $pc = $pieces{$n} //= {
963 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
965 while (my $k = shift @x) { $pc->{$k} = shift @x; }
971 my ($n, @x) = @_; # may be ''
972 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
973 push @newpieces, $pc;
978 New => $new_upstream,
980 while (@ARGV && $ARGV[0] !~ m{^-}) {
983 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
984 unless @ARGV && $ARGV[0] !~ m{^-};
986 my $c = git_rev_parse shift @ARGV;
987 die unless $n =~ m/^$extra_orig_namepart_re$/;
988 $newpiece->($n, New => $c);
991 # now we need to investigate the branch this generates the
992 # laundered version but we don't switch to it yet
993 my $old_head = get_head();
994 my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
996 my $old_bw_cl = classify $old_bw;
997 my $old_upstream_update_cl = classify $old_upstream_update;
998 confess unless $old_upstream_update_cl->{OrigParents};
999 my $old_upstream = parsecommit
1000 $old_upstream_update_cl->{OrigParents}[0]{CommitId};
1002 $piece->('', Old => $old_upstream->{CommitId});
1004 if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1005 if ($old_upstream->{Msg} =~
1006 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1008 my @oldpieces = ('', split / /, $1);
1009 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1010 foreach my $i (0..$#oldpieces) {
1011 my $n = $oldpieces[$i];
1012 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1015 fproblem 'upstream-confusing',
1016 "previous upstream $old_upstream->{CommitId} is from".
1017 " git-debrebase but not an \`upstream-combine' commit";
1021 foreach my $pc (values %pieces) {
1023 fproblem 'upstream-new-piece',
1024 "introducing upstream piece \`$pc->{Name}'";
1025 } elsif (!$pc->{New}) {
1026 fproblem 'upstream-rm-piece',
1027 "dropping upstream piece \`$pc->{Name}'";
1028 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1029 fproblem 'upstream-not-ff',
1030 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1034 printdebug "%pieces = ", (dd \%pieces), "\n";
1035 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1037 fproblems_maybe_bail();
1043 my @upstream_merge_parents;
1045 if (!any_fproblems()) {
1046 push @upstream_merge_parents, $old_upstream->{CommitId};
1049 foreach my $pc (@newpieces) { # always has '' first
1051 read_tree_subdir $pc->{Name}, $pc->{New};
1053 runcmd @git, qw(read-tree), $pc->{New};
1055 push @upstream_merge_parents, $pc->{New};
1058 # index now contains the new upstream
1060 if (@newpieces > 1) {
1061 # need to make the upstream subtree merge commit
1062 $new_upstream = make_commit \@upstream_merge_parents,
1063 [ "Combine upstreams for $new_upstream_version",
1064 ("[git-debrebase upstream-combine . ".
1065 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1070 # $new_upstream is either the single upstream commit, or the
1071 # combined commit we just made. Either way it will be the
1072 # "upstream" parent of the breakwater special merge.
1074 read_tree_subdir 'debian', "$old_bw:debian";
1076 # index now contains the breakwater merge contents
1077 $new_bw = make_commit [ $old_bw, $new_upstream ],
1078 [ "Update to upstream $new_upstream_version",
1079 "[git-debrebase breakwater: new upstream $new_upstream_version, merge]",
1082 # Now we have to add a changelog stanza so the Debian version
1084 die if unlink "debian";
1085 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1086 unlink "debian/changelog" or $!==ENOENT or die $!;
1087 mkdir "debian" or die $!;
1088 open CN, ">", "debian/changelog" or die $!;
1089 my $oldclog = git_cat_file ":debian/changelog";
1090 $oldclog =~ m/^($package_re) \(\S+\) / or
1091 fail "cannot parse old changelog to get package name";
1093 print CN <<END, $oldclog or die $!;
1094 $p ($new_version) UNRELEASED; urgency=medium
1096 * Update to new upstream version $new_upstream_version.
1102 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1104 # Now we have the final new breakwater branch in the index
1105 $new_bw = make_commit [ $new_bw ],
1106 [ "Update changelog for new upstream $new_upstream_version",
1107 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1111 # we have constructed the new breakwater. we now need to commit to
1112 # the laundering output, because git-rebase can't easily be made
1113 # to make a replay list which is based on some other branch
1115 update_head_postlaunder $old_head, $old_laundered_tip,
1116 'launder for new upstream';
1118 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1120 # now it's for the user to sort out
1123 sub cmd_record_ffq_prev () {
1124 badusage "no arguments allowed" if @ARGV;
1125 my ($status, $msg) = record_ffq_prev();
1126 if ($status eq 'exists' && $opt_noop_ok) {
1127 print "Previous head already recorded\n" or die $!;
1128 } elsif ($status eq 'written') {
1130 fail "Could not preserve: $msg";
1136 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1137 badusage "no arguments allowed" if @ARGV;
1138 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1139 if ($status ne 'branch') {
1140 fproblem $status, "could not check ffq-prev: $message";
1141 fproblems_maybe_bail();
1143 my $prev = $ffq_prev && git_get_ref $ffq_prev;
1145 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1148 my $old_head = get_head();
1149 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1150 'Declare fast forward / record previous work',
1151 "[git-debrebase pseudomerge: stitch$prose]",
1153 my @upd_cmd = (@git, qw(update-ref --stdin));
1154 debugcmd '>|', @upd_cmd;
1155 open U, "|-", @upd_cmd or die $!;
1157 update HEAD $new_head $old_head
1158 delete $ffq_prev $prev
1160 printdebug ">= ", $_, "\n" foreach split /\n/, $u;
1163 close U or failedcmd @upd_cmd;
1166 sub cmd_gbp2debrebase () {
1167 badusage "needs 1 optional argument, the upstream" unless @ARGV<=1;
1168 my ($upstream_spec) = @ARGV;
1169 $upstream_spec //= 'refs/heads/upstream';
1170 my $upstream = git_rev_parse $upstream_spec;
1171 my $old_head = get_head();
1173 my $upsdiff = get_differs $upstream, $old_head;
1174 if ($upsdiff & D_UPS) {
1175 runcmd @git, qw(--no-pager diff),
1176 $upstream, $old_head,
1177 qw( -- :!/debian :/);
1178 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1181 if (!is_fast_fwd $upstream, $old_head) {
1182 fproblem 'upstream-not-ancestor',
1183 "upstream ($upstream) is not an ancestor of HEAD";
1185 my $wrong = cmdoutput
1186 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1187 qw(-- :/ :!/debian));
1188 if (length $wrong) {
1189 fproblem 'unexpected-upstream-changes',
1190 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1191 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1195 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1196 fproblem 'upstream-has-debian',
1197 "upstream ($upstream) contains debian/ directory";
1200 fproblems_maybe_bail();
1206 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1207 # make a branch out of the patch queue - we'll want this in a mo
1208 runcmd qw(gbp pq import);
1209 # strip the patches out
1210 runcmd @git, qw(checkout -q gdr-internal~0);
1211 rm_subdir_cached 'debian/patches';
1212 $work = make_commit ['HEAD'], [
1213 'git-debrebase import: drop patch queue',
1214 'Delete debian/patches, as part of converting to git-debrebase format.',
1215 '[git-debrebase: gbp2debrebase, drop patches]'
1217 # make the breakwater pseudomerge
1218 # the tree is already exactly right
1219 $work = make_commit [$work, $upstream], [
1220 'git-debrebase import: declare upstream',
1221 'First breakwater merge.',
1222 '[git-debrebase breakwater: declare upstream]'
1225 # rebase the patch queue onto the new breakwater
1226 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1227 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1228 $work = git_rev_parse 'HEAD';
1231 update_head_checkout $old_head, $work, 'gbp2debrebase';
1234 sub cmd_downstream_rebase_launder_v0 () {
1235 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1237 $base = git_rev_parse $base;
1238 my $old_head = get_head();
1239 my $current = $old_head;
1242 if ($current eq $base) {
1243 $topmost_keep //= $current;
1244 print " $current BASE stop\n";
1247 my $cl = classify $current;
1248 print " $current $cl->{Type}";
1250 my $p0 = $cl->{Parents}[0]{CommitId};
1252 if ($cl->{Type} eq 'Pseudomerge') {
1253 print " ^".($cl->{Contributor}{Ix}+1);
1254 $next = $cl->{Contributor}{CommitId};
1255 } elsif ($cl->{Type} eq 'AddPatches' or
1256 $cl->{Type} eq 'Changelog') {
1266 $topmost_keep //= $current;
1268 die "to-be stripped changes not on top of the branch\n"
1273 if ($topmost_keep eq $old_head) {
1274 print "unchanged\n";
1276 print "updating to $topmost_keep\n";
1277 update_head_checkout
1278 $old_head, $topmost_keep,
1279 'downstream-rebase-launder-v0';
1283 GetOptions("D+" => \$debuglevel,
1284 'noop-ok', => \$opt_noop_ok,
1285 'f=s' => \@fproblem_force_opts,
1286 'force!') or die badusage "bad options\n";
1287 initdebug('git-debrebase ');
1288 enabledebug if $debuglevel;
1290 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1291 chdir $toplevel or die "chdir $toplevel: $!";
1293 $rd = fresh_playground "$playprefix/misc";
1295 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1296 defaultcmd_rebase();
1298 my $cmd = shift @ARGV;
1301 $cmdfn = ${*::}{"cmd_$cmdfn"};
1303 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";