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>] breakwater # prints breakwater tip only
32 # git-debrebase [<options>] stitch [--prose=<for commit message>]
33 # git-debrebase [<options>] launder-v0 # prints breakwater tip etc.
34 # git-debrebase [<options>] downstream-rebase-launder-v0 # experimental
36 # git-debrebase [<options>] convert-from-gbp [<upstream-git-rev>]
37 # git-debrebase [<options>] convert-to-gbp
39 # problems / outstanding questions:
41 # * dgit push with a `3.0 (quilt)' package means doing quilt
42 # fixup. Usually this involves recommitting the whole patch
43 # series, one at a time, with dpkg-source --commit. This is
44 # terribly terribly slow. (Maybe this should be fixed in dgit.)
46 # * dgit push usually needs to (re)make a pseudomerge. The "first"
47 # git-debrebase stripped out the previous pseudomerge and could
48 # have remembeed the HEAD. But it's not quite clear what history
49 # ought to be preserved and what should be discarded. For now
50 # the user will have to tell dgit --overwrite.
52 # To fix this, do we need a new push hook for dgit ?
54 # * Workflow is currently clumsy. Lots of spurious runes to type.
55 # There's not even a guide.
57 # * There are no tests.
59 # * new-upstream-v0 has a terrible UI. You end up with giant
60 # runic command lines.
62 # One consequence of the lack of richness it can need --force in
63 # fairly sensible situations and there is no way to tell it what
64 # you are really trying to do, other than just --force. There
65 # should be an interface with some default branch names.
67 # * There should be a standard convention for the version number,
68 # and unfinalised or not changelog, after new-upstream.
70 # * Handing of multi-orig dgit new-upstream .dsc imports is known to
71 # be broken. They may be not recognised, improperly converted, or
72 # their conversion may be unrecognised.
74 # * Docs need writing and updating. Even README.git-debrebase
75 # describes a design but may not reflect the implementation.
77 # * We need to develop a plausible model that works for derivatives,
78 # who probably want to maintain their stack on top of Debian's.
79 # downstream-rebase-launder-v0 may be a starting point?
83 use Debian::Dgit qw(:DEFAULT :playground);
90 use Getopt::Long qw(:config posix_default gnu_compat bundling);
92 use File::FnMatch qw(:fnmatch);
94 our ($opt_force, $opt_noop_ok);
96 our $us = qw(git-debrebase);
100 die "bad usage: $m\n";
104 my ($k, $optional) = @_;
106 my @cmd = qw(git config -z);
107 push @cmd, qw(--get-all) if wantarray;
109 my $out = cmdoutput_errok @cmd;
111 fail "missing required git config $k" unless $optional;
114 my @l = split /\0/, $out;
115 return wantarray ? @l : $l[0];
122 my $dd = new Data::Dumper [ $v ];
123 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
129 my $data = (git_cat_file $objid, 'commit');
130 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
134 sub D_UPS () { 0x02; } # upstream files
135 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
136 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
137 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
138 sub D_DEB_OTH () { 0x20; } # debian/changelog
139 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
141 our $playprefix = 'debrebase';
147 sub in_workarea ($) {
150 my $r = eval { $sub->(); };
151 { local $@; changedir $maindir; }
155 sub fresh_workarea () {
156 $workarea = fresh_playground "$playprefix/work";
157 in_workarea sub { playtree_setup };
160 sub get_differs ($$) {
162 # This resembles quiltify_trees_differ, in dgit, a bit.
163 # But we don't care about modes, or dpkg-source-unrepresentable
164 # changes, and we don't need the plethora of different modes.
165 # Conversely we need to distinguish different kinds of changes to
166 # debian/ and debian/patches/.
171 my ($opts, $limits, $fn) = @_;
172 my @cmd = (@git, qw(diff-tree -z --no-renames));
174 push @cmd, "$_:" foreach $x, $y;
175 push @cmd, '--', @$limits;
176 my $diffs = cmdoutput @cmd;
177 foreach (split /\0/, $diffs) { $fn->(); }
180 $rundiff->([qw(--name-only)], [], sub {
181 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
184 if ($differs & DS_DEB) {
186 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
188 m{^debian/patches/} ? D_PAT_OTH :
189 $_ eq 'debian/changelog' ? D_DEB_CLOG :
192 die "mysterious debian changes $x..$y"
193 unless $differs & (D_PAT_OTH|DS_DEB);
196 if ($differs & D_PAT_OTH) {
198 $differs &= ~D_PAT_OTH;
200 $differs |= D_PAT_OTH;
201 no warnings qw(exiting); last;
203 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
204 no warnings qw(exiting);
205 if (!defined $mode) {
208 die unless s{^debian/patches/}{};
210 if ($mode eq 'A' && !m/\.series$/s) {
212 } elsif ($mode eq 'M' && $_ eq 'series') {
213 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
214 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
215 chomp $x_s; $x_s .= "\n";
216 $ok = $x_s eq substr($y_s, 0, length $x_s);
221 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
223 die "mysterious debian/patches changes $x..$y"
224 unless $differs & (D_PAT_ADD|D_PAT_OTH);
227 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
232 sub commit_pr_info ($) {
234 return Data::Dumper->dump([$r], [qw(commit)]);
237 sub calculate_committer_authline () {
238 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
239 'DUMMY COMMIT (git-debrebase)', "HEAD:";
240 my ($h,$m) = get_commit $c;
241 $h =~ m/^committer .*$/m or confess "($h) ?";
245 sub rm_subdir_cached ($) {
247 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
250 sub read_tree_subdir ($$) {
251 my ($subdir, $new_tree_object) = @_;
252 rm_subdir_cached $subdir;
253 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
256 sub make_commit ($$) {
257 my ($parents, $message_paras) = @_;
258 my $tree = cmdoutput @git, qw(write-tree);
259 my @cmd = (@git, qw(commit-tree), $tree);
260 push @cmd, qw(-p), $_ foreach @$parents;
261 push @cmd, qw(-m), $_ foreach @$message_paras;
262 return cmdoutput @cmd;
265 our @fproblem_force_opts;
266 our $fproblems_forced;
267 our $fproblems_tripped;
270 if (grep { $_ eq $tag } @fproblem_force_opts) {
272 print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
274 $fproblems_tripped++;
275 print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
279 sub fproblems_maybe_bail () {
280 if ($fproblems_forced) {
282 "%s: safety catch trips: %d overriden by individual -f options\n",
283 $us, $fproblems_forced;
285 if ($fproblems_tripped) {
288 "%s: safety catch trips: %d overriden by global --force\n",
289 $us, $fproblems_tripped;
292 "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
293 $us, $fproblems_tripped;
297 sub any_fproblems () {
298 return $fproblems_forced || $fproblems_tripped;
301 # classify returns an info hash like this
303 # Hdr => # commit headers, including 1 final newline
304 # Msg => # commit message (so one newline is dropped)
306 # Type => (see below)
308 # Ix => $index # ie 0, 1, 2, ...
310 # Differs => return value from get_differs
312 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
314 # NewMsg => # commit message, but with any [dgit import ...] edited
315 # # to say "[was: ...]"
325 # has additional entres in classification result
326 # Overwritten = [ subset of Parents ]
327 # Contributor = $the_remaining_Parent
329 # DgitImportUnpatched
330 # has additional entry in classification result
331 # OrigParents = [ subset of Parents ]
334 # has additional entry in classification result
335 # OrigParents = [ subset of Parents ] # singleton list
340 # has additional entry in classification result
343 sub parsecommit ($;$) {
344 my ($objid, $p_ref) = @_;
345 # => hash with CommitId Hdr Msg Tree Parents
346 # Parents entries have only Ix CommitId
347 # $p_ref, if provided, must be [] and is used as a base for Parents
352 my ($h,$m) = get_commit $objid;
354 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
355 my (@ph) = $h =~ m/^parent (\w+)$/mg;
365 foreach my $ph (@ph) {
367 Ix => scalar @$p_ref,
379 my $r = parsecommit($objid, \@p);
383 $p->{Differs} = (get_differs $p->{CommitId}, $t),
386 printdebug "classify $objid \$t=$t \@p",
387 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
391 my ($type, @rest) = @_;
392 $r = { %$r, Type => $type, @rest };
394 printdebug " = $type ".(dd $r)."\n";
400 $r = { %$r, Type => qw(Unknown), Why => $why };
401 printdebug " ** Unknown\n";
405 my @identical = grep { !$_->{Differs} } @p;
406 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
407 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
409 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
410 # multi-orig upstreams are represented with an anchor merge
411 # from a single upstream commit which combines the orig tarballs
413 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
414 @p == 2 or return $badanchor->("has other than two parents");
415 $haspatches and return $badanchor->("contains debian/patches");
417 # How to decide about l/r ordering of anchors ? git
418 # --topo-order prefers to expand 2nd parent first. There's
419 # already an easy rune to look for debian/ history anyway (git log
420 # debian/) so debian breakwater branch should be 1st parent; that
421 # way also there's also an easy rune to look for the upstream
422 # patches (--topo-order).
424 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
425 $p[1]{Differs} & ~DS_DEB and
426 $badanchor->("upstream files differ from left parent");
427 $p[0]{Differs} & ~D_UPS and
428 $badanchor->("debian/ differs from right parent");
430 return $classify->(qw(Anchor),
431 OrigParents => [ $p[1] ]);
435 my $d = $r->{Parents}[0]{Differs};
436 if ($d == D_PAT_ADD) {
437 return $classify->(qw(AddPatches));
438 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
439 return $unknown->("edits debian/patches");
440 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
441 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
443 if ($d == D_DEB_CLOG) {
444 return $classify->(qw(Changelog));
446 return $classify->(qw(Packaging));
448 } elsif ($ty eq 'missing') {
449 return $classify->(qw(BreakwaterStart));
451 return $unknown->("parent's debian is not a directory");
453 } elsif ($d == D_UPS) {
454 return $classify->(qw(Upstream));
455 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
456 return $classify->(qw(Mixed));
458 return $unknown->("no changes");
460 confess "internal error $objid ?";
464 return $unknown->("origin commit");
467 if (@p == 2 && @identical == 1) {
468 my @overwritten = grep { $_->{Differs} } @p;
469 confess "internal error $objid ?" unless @overwritten==1;
470 return $classify->(qw(Pseudomerge),
471 Overwritten => [ $overwritten[0] ],
472 Contributor => $identical[0]);
474 if (@p == 2 && @identical == 2) {
476 my ($ph,$pm) = get_commit $_[0]{CommitId};
477 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
481 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
482 if ($order > 0) { # newer first
483 } elsif ($order < 0) {
484 @bytime = reverse @bytime;
486 # same age, default to order made by -s ours
487 # that is, commit was made by someone who preferred L
489 return $classify->(qw(Pseudomerge),
490 SubType => qw(Ambiguous),
491 Contributor => $bytime[0],
492 Overwritten => [ $bytime[1] ]);
495 my ($p_h, $p_m) = get_commit $p->{CommitId};
496 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
497 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
499 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
501 if (!(grep { !$_->{IsOrigin} } @p) and
502 (@orig_ps >= @p - 1) and
503 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
505 return $classify->(qw(DgitImportUnpatched),
506 OrigParents => \@orig_ps);
509 return $unknown->("complex merge");
512 sub breakwater_of ($) {
513 my ($head) = @_; # must be laundered
517 fail "branch needs laundering (run git-debrebase): $why";
520 my $cl = classify $head;
521 my $ty = $cl->{Type};
522 if ($ty eq 'Packaging' or
523 $ty eq 'Changelog') {
524 $breakwater //= $head;
525 } elsif ($ty eq 'Anchor' or
526 $ty eq 'BreakwaterStart') {
527 $breakwater //= $head;
529 } elsif ($ty eq 'Upstream') {
530 $unclean->("packaging change ($breakwater)".
531 " follows upstream change (eg $head)")
532 if defined $breakwater;
533 } elsif ($ty eq 'Mixed') {
534 $unclean->('found mixed upstream/packaging commit ($head)');
535 } elsif ($ty eq 'Pseudomerge' or
536 $ty eq 'AddPatches') {
537 $unclean->("found interchange conversion commit ($ty, $head)");
538 } elsif ($ty eq 'DgitImportUnpatched') {
539 $unclean->("found dgit dsc import ($head)");
541 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
543 $head = $cl->{Parents}[0]{CommitId};
551 $nogenerate,$report) = @_;
552 # => ($tip, $breakwater_tip, $last_anchor)
553 # (or nothing, if $nogenerate)
555 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
557 # go through commits backwards
558 # we generate two lists of commits to apply:
559 # breakwater branch and upstream patches
560 my (@brw_cl, @upp_cl, @processed);
567 my ($prose, $info) = @_;
571 $ms .= "\n\n[git-debrebase$info: $prose]\n";
574 my $rewrite_from_here = sub {
576 my $sp_cl = { SpecialMethod => 'StartRewrite' };
578 push @processed, $sp_cl;
583 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
586 return unless $report;
587 print $report $prdelim, @_;
591 my $bomb = sub { # usage: return $bomb->();
592 print $report " Unprocessable" if $report;
593 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
596 return (undef,undef);
598 die "commit $cur: Cannot cope with this commit (d.".
599 (join ' ', map { sprintf "%#x", $_->{Differs} }
600 @{ $cl->{Parents} }).
601 (defined $cl->{Why} ? "; $cl->{Why}": '').
608 my $build_start = sub {
609 my ($msg, $parent) = @_;
612 no warnings qw(exiting); last;
619 my $ty = $cl->{Type};
620 my $st = $cl->{SubType};
621 $prline->("$cl->{CommitId} $cl->{Type}");
622 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
623 push @processed, $cl;
624 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
625 if ($ty eq 'AddPatches') {
627 $rewrite_from_here->(\@upp_cl);
629 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
633 } elsif ($ty eq 'BreakwaterStart') {
635 $build_start->('FirstPackaging', $cur);
636 } elsif ($ty eq 'Upstream') {
640 } elsif ($ty eq 'Mixed') {
643 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
646 $queue->(\@brw_cl, "debian");
647 $queue->(\@upp_cl, "upstream");
648 $rewrite_from_here->(\@brw_cl);
651 } elsif ($ty eq 'Pseudomerge') {
652 my $contrib = $cl->{Contributor}{CommitId};
653 print $report " Contributor=$contrib" if $report;
654 push @pseudomerges, $cl;
655 $rewrite_from_here->(\@upp_cl);
658 } elsif ($ty eq 'Anchor') {
660 $build_start->("Anchor", $cur);
661 } elsif ($ty eq 'DgitImportUnpatched') {
662 my $pm = $pseudomerges[-1];
664 # To an extent, this is heuristic. Imports don't have
665 # a useful history of the debian/ branch. We assume
666 # that the first pseudomerge after an import has a
667 # useful history of debian/, and ignore the histories
668 # from later pseudomerges. Often the first pseudomerge
669 # will be the dgit import of the upload to the actual
670 # suite intended by the non-dgit NMUer, and later
671 # pseudomerges may represent in-archive copies.
672 my $ovwrs = $pm->{Overwritten};
673 printf $report " PM=%s \@Overwr:%d",
674 $pm->{CommitId}, (scalar @$ovwrs)
677 printdebug "*** WALK BOMB DgitImportUnpatched\n";
680 my $ovwr = $ovwrs->[0]{CommitId};
681 printf $report " Overwr=%s", $ovwr if $report;
682 # This import has a tree which is just like a
683 # breakwater tree, but it has the wrong history. It
684 # ought to have the previous breakwater (which the
685 # pseudomerge overwrote) as an ancestor. That will
686 # make the history of the debian/ files correct. As
687 # for the upstream version: either it's the same as
688 # was ovewritten (ie, same as the previous
689 # breakwater), in which case that history is precisely
690 # right; or, otherwise, it was a non-gitish upload of a
691 # new upstream version. We can tell these apart by
692 # looking at the tree of the supposed upstream.
695 SpecialMethod => 'DgitImportDebianUpdate',
696 $xmsg->("convert dgit import: debian changes")
699 SpecialMethod => 'DgitImportUpstreamUpdate',
700 $xmsg->("convert dgit import: upstream update",
703 $prline->(" Import");
704 $rewrite_from_here->(\@brw_cl);
705 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
709 # Everything is from this import. This kind of import
710 # is already in valid breakwater format, with the
711 # patches as commits.
712 printf $report " NoPM" if $report;
713 # last thing we processed will have been the first patch,
714 # if there is one; which is fine, so no need to rewrite
715 # on account of this import
716 $build_start->("ImportOrigin", $cur);
720 printdebug "*** WALK BOMB unrecognised\n";
726 printdebug "*** WALK prep done cur=$cur".
727 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
729 return if $nogenerate;
731 # Now we build it back up again
737 my $read_tree_debian = sub {
739 read_tree_subdir 'debian', "$treeish:debian";
740 rm_subdir_cached 'debian/patches';
742 my $read_tree_upstream = sub {
744 runcmd @git, qw(read-tree), $treeish;
745 $read_tree_debian->($build);
748 $#upp_cl = $upp_limit if defined $upp_limit;
750 my $committer_authline = calculate_committer_authline();
752 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
754 confess "internal error" unless $build eq (pop @processed)->{CommitId};
757 mkdir $rd or $!==EEXIST or die $!;
759 runcmd @git, qw(read-tree), $build;
760 foreach my $cl (qw(Debian), (reverse @brw_cl),
761 { SpecialMethod => 'RecordBreakwaterTip' },
762 qw(Upstream), (reverse @upp_cl)) {
764 $current_method = $cl;
767 my $method = $cl->{SpecialMethod} // $current_method;
768 my @parents = ($build);
769 my $cltree = $cl->{CommitId};
770 printdebug "WALK BUILD ".($cltree//'undef').
771 " $method (rewriting=$rewriting)\n";
772 if ($method eq 'Debian') {
773 $read_tree_debian->($cltree);
774 } elsif ($method eq 'Upstream') {
775 $read_tree_upstream->($cltree);
776 } elsif ($method eq 'StartRewrite') {
779 } elsif ($method eq 'RecordBreakwaterTip') {
780 $breakwater = $build;
782 } elsif ($method eq 'DgitImportDebianUpdate') {
783 $read_tree_debian->($cltree);
784 } elsif ($method eq 'DgitImportUpstreamUpdate') {
785 confess unless $rewriting;
786 my $differs = (get_differs $build, $cltree);
787 next unless $differs & D_UPS;
788 $read_tree_upstream->($cltree);
789 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
794 my $procd = (pop @processed) // 'UNDEF';
797 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
800 my $newtree = cmdoutput @git, qw(write-tree);
802 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
803 $ch =~ s{^parent .*\n}{}mg;
804 $ch =~ s{(?=^author)}{
805 join '', map { "parent $_\n" } @parents
806 }me or confess "$ch ?";
808 $ch =~ s{^committer .*$}{$committer_authline}m
811 my $cf = "$rd/m$rewriting";
812 open CD, ">", $cf or die $!;
813 print CD $ch, "\n", $cl->{Msg} or die $!;
815 my @cmd = (@git, qw(hash-object));
816 push @cmd, qw(-w) if $rewriting;
817 push @cmd, qw(-t commit), $cf;
818 my $newcommit = cmdoutput @cmd;
819 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
821 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
827 my $final_check = get_differs $build, $input;
828 die sprintf "internal error %#x %s %s", $final_check, $build, $input
829 if $final_check & ~D_PAT_ADD;
831 my @r = ($build, $breakwater, $last_anchor);
832 printdebug "*** WALK RETURN @r\n";
837 git_check_unmodified();
838 return git_rev_parse qw(HEAD);
841 sub update_head ($$$) {
842 my ($old, $new, $mrest) = @_;
843 runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
846 sub update_head_checkout ($$$) {
847 my ($old, $new, $mrest) = @_;
848 update_head $old, $new, $mrest;
849 runcmd @git, qw(reset --hard);
852 sub update_head_postlaunder ($$$) {
853 my ($old, $tip, $reflogmsg) = @_;
854 return if $tip eq $old;
855 print "git-debrebase: laundered (head was $old)\n";
856 update_head $old, $tip, $reflogmsg;
857 # no tree changes except debian/patches
858 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
861 sub cmd_launder_v0 () {
862 badusage "no arguments to launder-v0 allowed" if @ARGV;
863 my $old = get_head();
864 my ($tip,$breakwater,$last_anchor) = walk $old;
865 update_head_postlaunder $old, $tip, 'launder';
866 printf "# breakwater tip\n%s\n", $breakwater;
867 printf "# working tip\n%s\n", $tip;
868 printf "# last anchor\n%s\n", $last_anchor;
871 sub defaultcmd_rebase () {
872 my $old = get_head();
873 my ($status, $message) = record_ffq_prev();
874 if ($status eq 'written' || $status eq 'exists') {
876 fproblem $status, "could not record ffq-prev: $message";
877 fproblems_maybe_bail();
879 my ($tip,$breakwater) = walk $old;
880 update_head_postlaunder $old, $tip, 'launder for rebase';
881 runcmd @git, qw(rebase), @ARGV, $breakwater;
885 die if ($ARGV[0]//'') =~ m/^-/;
886 badusage "too many arguments to analyse" if @ARGV>1;
889 $old = git_rev_parse $old;
891 $old = git_rev_parse 'HEAD';
893 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
894 STDOUT->error and die $!;
897 sub ffq_prev_branchinfo () {
898 # => ('status', "message", [$current, $ffq_prev])
900 # branch message is undef
901 # weird-symref } no $current,
902 # notbranch } no $ffq_prev
903 my $current = git_get_symref();
904 return ('detached', 'detached HEAD') unless defined $current;
905 return ('weird-symref', 'HEAD symref is not to refs/')
906 unless $current =~ m{^refs/};
907 my $ffq_prev = "refs/$ffq_refprefix/$'";
908 printdebug "ffq_prev_branchinfo branch current $current\n";
909 return ('branch', undef, $current, $ffq_prev);
912 sub record_ffq_prev () {
913 # => ('status', "message")
915 # written message is undef
920 # if not ff from some branch we should be ff from, is an fproblem
921 # if "written", will have printed something about that to stdout,
922 # and also some messages about ff checks
923 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
924 return ($status, $message) unless $status eq 'branch';
926 my $currentval = get_head();
928 my $exists = git_get_ref $ffq_prev;
929 return ('exists',"$ffq_prev already exists") if $exists;
931 return ('not-branch', 'HEAD symref is not to refs/heads/')
932 unless $current =~ m{^refs/heads/};
935 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
938 printdebug "ffq check_specs @check_specs\n";
941 my ($lrref, $desc) = @_;
942 printdebug "ffq might check $lrref ($desc)\n";
944 for my $chk (@check_specs) {
946 $invert = $glob =~ s{^[!^]}{};
947 last if fnmatch $glob, $lrref;
950 my $lrval = git_get_ref $lrref;
951 return unless defined $lrval;
953 if (is_fast_fwd $lrval, $currentval) {
954 print "OK, you are ahead of $lrref\n" or die $!;
955 $checked{$lrref} = 1;
956 } elsif (is_fast_fwd $currentval, $lrval) {
957 $checked{$lrref} = -1;
958 fproblem 'behind', "you are behind $lrref, divergence risk";
960 $checked{$lrref} = -1;
961 fproblem 'diverged', "you have diverged from $lrref";
965 my $merge = cfg "branch.$branch.merge",1;
966 if (defined $merge and $merge =~ m{^refs/heads/}) {
968 printdebug "ffq merge $rhs\n";
969 my $check_remote = sub {
970 my ($remote, $desc) = @_;
971 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
972 return unless defined $remote;
973 $check->("refs/remotes/$remote/$rhs", $desc);
975 $check_remote->((scalar cfg "branch.$branch.remote",1),
976 'remote fetch/merge branch');
977 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
978 (scalar cfg "branch.$branch.pushDefault",1),
979 'remote push branch');
981 if ($branch =~ m{^dgit/}) {
982 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
983 } elsif ($branch =~ m{^master$}) {
984 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
987 fproblems_maybe_bail();
988 runcmd @git, qw(update-ref -m), "record current head for preservation",
989 $ffq_prev, $currentval, $git_null_obj;
990 print "Recorded current head for preservation\n" or die $!;
991 return ('written', undef);
994 sub cmd_new_upstream_v0 () {
995 # automatically and unconditionally launders before rebasing
996 # if rebase --abort is used, laundering has still been done
1000 badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
1002 # parse args - low commitment
1003 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1004 my $new_upstream_version = $new_version->version();
1006 my $new_upstream = git_rev_parse shift @ARGV;
1009 my ($n, @x) = @_; # may be ''
1010 my $pc = $pieces{$n} //= {
1012 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1014 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1019 my $newpiece = sub {
1020 my ($n, @x) = @_; # may be ''
1021 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1022 push @newpieces, $pc;
1027 New => $new_upstream,
1029 while (@ARGV && $ARGV[0] !~ m{^-}) {
1030 my $n = shift @ARGV;
1032 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1033 unless @ARGV && $ARGV[0] !~ m{^-};
1035 my $c = git_rev_parse shift @ARGV;
1036 die unless $n =~ m/^$extra_orig_namepart_re$/;
1037 $newpiece->($n, New => $c);
1040 # now we need to investigate the branch this generates the
1041 # laundered version but we don't switch to it yet
1042 my $old_head = get_head();
1043 my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
1045 my $old_bw_cl = classify $old_bw;
1046 my $old_upstream_update_cl = classify $old_upstream_update;
1047 confess unless $old_upstream_update_cl->{OrigParents};
1048 my $old_upstream = parsecommit
1049 $old_upstream_update_cl->{OrigParents}[0]{CommitId};
1051 $piece->('', Old => $old_upstream->{CommitId});
1053 if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1054 if ($old_upstream->{Msg} =~
1055 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1057 my @oldpieces = ('', split / /, $1);
1058 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1059 foreach my $i (0..$#oldpieces) {
1060 my $n = $oldpieces[$i];
1061 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1064 fproblem 'upstream-confusing',
1065 "previous upstream $old_upstream->{CommitId} is from".
1066 " git-debrebase but not an \`upstream-combine' commit";
1070 foreach my $pc (values %pieces) {
1072 fproblem 'upstream-new-piece',
1073 "introducing upstream piece \`$pc->{Name}'";
1074 } elsif (!$pc->{New}) {
1075 fproblem 'upstream-rm-piece',
1076 "dropping upstream piece \`$pc->{Name}'";
1077 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1078 fproblem 'upstream-not-ff',
1079 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1083 printdebug "%pieces = ", (dd \%pieces), "\n";
1084 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1086 fproblems_maybe_bail();
1092 my @upstream_merge_parents;
1094 if (!any_fproblems()) {
1095 push @upstream_merge_parents, $old_upstream->{CommitId};
1098 foreach my $pc (@newpieces) { # always has '' first
1100 read_tree_subdir $pc->{Name}, $pc->{New};
1102 runcmd @git, qw(read-tree), $pc->{New};
1104 push @upstream_merge_parents, $pc->{New};
1107 # index now contains the new upstream
1109 if (@newpieces > 1) {
1110 # need to make the upstream subtree merge commit
1111 $new_upstream = make_commit \@upstream_merge_parents,
1112 [ "Combine upstreams for $new_upstream_version",
1113 ("[git-debrebase upstream-combine . ".
1114 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1119 # $new_upstream is either the single upstream commit, or the
1120 # combined commit we just made. Either way it will be the
1121 # "upstream" parent of the anchor merge.
1123 read_tree_subdir 'debian', "$old_bw:debian";
1125 # index now contains the anchor merge contents
1126 $new_bw = make_commit [ $old_bw, $new_upstream ],
1127 [ "Update to upstream $new_upstream_version",
1128 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1131 # Now we have to add a changelog stanza so the Debian version
1133 die if unlink "debian";
1134 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1135 unlink "debian/changelog" or $!==ENOENT or die $!;
1136 mkdir "debian" or die $!;
1137 open CN, ">", "debian/changelog" or die $!;
1138 my $oldclog = git_cat_file ":debian/changelog";
1139 $oldclog =~ m/^($package_re) \(\S+\) / or
1140 fail "cannot parse old changelog to get package name";
1142 print CN <<END, $oldclog or die $!;
1143 $p ($new_version) UNRELEASED; urgency=medium
1145 * Update to new upstream version $new_upstream_version.
1151 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1153 # Now we have the final new breakwater branch in the index
1154 $new_bw = make_commit [ $new_bw ],
1155 [ "Update changelog for new upstream $new_upstream_version",
1156 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1160 # we have constructed the new breakwater. we now need to commit to
1161 # the laundering output, because git-rebase can't easily be made
1162 # to make a replay list which is based on some other branch
1164 update_head_postlaunder $old_head, $old_laundered_tip,
1165 'launder for new upstream';
1167 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1169 # now it's for the user to sort out
1172 sub cmd_record_ffq_prev () {
1173 badusage "no arguments allowed" if @ARGV;
1174 my ($status, $msg) = record_ffq_prev();
1175 if ($status eq 'exists' && $opt_noop_ok) {
1176 print "Previous head already recorded\n" or die $!;
1177 } elsif ($status eq 'written') {
1179 fail "Could not preserve: $msg";
1183 sub cmd_breakwater () {
1184 badusage "no arguments allowed" if @ARGV;
1185 my $bw = breakwater_of git_rev_parse 'HEAD';
1186 print "$bw\n" or die $!;
1191 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1192 badusage "no arguments allowed" if @ARGV;
1193 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1194 if ($status ne 'branch') {
1195 fproblem $status, "could not check ffq-prev: $message";
1196 fproblems_maybe_bail();
1198 my $prev = $ffq_prev && git_get_ref $ffq_prev;
1200 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1203 my $old_head = get_head();
1204 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1205 'Declare fast forward / record previous work',
1206 "[git-debrebase pseudomerge: stitch$prose]",
1208 my @upd_cmd = (@git, qw(update-ref --stdin));
1209 debugcmd '>|', @upd_cmd;
1210 open U, "|-", @upd_cmd or die $!;
1212 update HEAD $new_head $old_head
1213 delete $ffq_prev $prev
1215 printdebug ">= ", $_, "\n" foreach split /\n/, $u;
1218 close U or failedcmd @upd_cmd;
1221 sub cmd_convert_from_gbp () {
1222 badusage "needs 1 optional argument, the upstream git rev"
1224 my ($upstream_spec) = @ARGV;
1225 $upstream_spec //= 'refs/heads/upstream';
1226 my $upstream = git_rev_parse $upstream_spec;
1227 my $old_head = get_head();
1229 my $upsdiff = get_differs $upstream, $old_head;
1230 if ($upsdiff & D_UPS) {
1231 runcmd @git, qw(--no-pager diff),
1232 $upstream, $old_head,
1233 qw( -- :!/debian :/);
1234 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1237 if (!is_fast_fwd $upstream, $old_head) {
1238 fproblem 'upstream-not-ancestor',
1239 "upstream ($upstream) is not an ancestor of HEAD";
1241 my $wrong = cmdoutput
1242 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1243 qw(-- :/ :!/debian));
1244 if (length $wrong) {
1245 fproblem 'unexpected-upstream-changes',
1246 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1247 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1251 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1252 fproblem 'upstream-has-debian',
1253 "upstream ($upstream) contains debian/ directory";
1256 fproblems_maybe_bail();
1262 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1263 # make a branch out of the patch queue - we'll want this in a mo
1264 runcmd qw(gbp pq import);
1265 # strip the patches out
1266 runcmd @git, qw(checkout -q gdr-internal~0);
1267 rm_subdir_cached 'debian/patches';
1268 $work = make_commit ['HEAD'], [
1269 'git-debrebase convert-from-gbp: drop patches from tree',
1270 'Delete debian/patches, as part of converting to git-debrebase format.',
1271 '[git-debrebase convert-from-gbp: drop patches from tree]'
1273 # make the anchor merge
1274 # the tree is already exactly right
1275 $work = make_commit [$work, $upstream], [
1276 'git-debrebase import: declare upstream',
1277 'First breakwater merge.',
1278 '[git-debrebase anchor: declare upstream]'
1281 # rebase the patch queue onto the new breakwater
1282 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1283 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1284 $work = git_rev_parse 'HEAD';
1287 update_head_checkout $old_head, $work, 'convert-from-gbp';
1290 sub cmd_convert_to_gbp () {
1291 badusage "no arguments allowed" if @ARGV;
1292 my $head = get_head();
1293 my $ffq = (ffq_prev_branchinfo())[3];
1294 my $bw = breakwater_of $head;
1298 runcmd @git, qw(checkout -q -b bw), $bw;
1299 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1300 runcmd qw(gbp pq export);
1301 runcmd @git, qw(add debian/patches);
1302 $out = make_commit ['HEAD'], [
1303 'Commit patch queue (converted from git-debrebase format)',
1304 '[git-debrebase convert-to-gbp: commit patches]',
1308 runcmd @git, qw(update-ref -m),
1309 "debrebase: converting corresponding main branch to gbp format",
1310 $ffq, $git_null_obj;
1312 update_head_checkout $head, $out, "convert to gbp (v0)";
1313 print <<END or die $!;
1314 git-debrebase: converted to git-buildpackage branch format
1315 git-debrebase: WARNING: do not now run "git-debrebase" any more
1316 git-debrebase: WARNING: doing so would drop all upstream patches!
1320 sub cmd_downstream_rebase_launder_v0 () {
1321 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1323 $base = git_rev_parse $base;
1324 my $old_head = get_head();
1325 my $current = $old_head;
1328 if ($current eq $base) {
1329 $topmost_keep //= $current;
1330 print " $current BASE stop\n";
1333 my $cl = classify $current;
1334 print " $current $cl->{Type}";
1336 my $p0 = $cl->{Parents}[0]{CommitId};
1338 if ($cl->{Type} eq 'Pseudomerge') {
1339 print " ^".($cl->{Contributor}{Ix}+1);
1340 $next = $cl->{Contributor}{CommitId};
1341 } elsif ($cl->{Type} eq 'AddPatches' or
1342 $cl->{Type} eq 'Changelog') {
1352 $topmost_keep //= $current;
1354 die "to-be stripped changes not on top of the branch\n"
1359 if ($topmost_keep eq $old_head) {
1360 print "unchanged\n";
1362 print "updating to $topmost_keep\n";
1363 update_head_checkout
1364 $old_head, $topmost_keep,
1365 'downstream-rebase-launder-v0';
1369 GetOptions("D+" => \$debuglevel,
1370 'noop-ok', => \$opt_noop_ok,
1371 'f=s' => \@fproblem_force_opts,
1372 'force!') or die badusage "bad options\n";
1373 initdebug('git-debrebase ');
1374 enabledebug if $debuglevel;
1376 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1377 chdir $toplevel or die "chdir $toplevel: $!";
1379 $rd = fresh_playground "$playprefix/misc";
1381 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1382 defaultcmd_rebase();
1384 my $cmd = shift @ARGV;
1387 $cmdfn = ${*::}{"cmd_$cmdfn"};
1389 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";