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>] analyse
25 # git-debrebase [<options>] launder-v0 # prints breakwater tip etc.
26 # git-debrebase [<options>] downstream-rebase-launder-v0 # experimental
28 # git-debrebase [<options>] convert-from-gbp [<upstream-git-rev>]
29 # git-debrebase [<options>] convert-to-gbp
31 # problems / outstanding questions:
33 # * dgit push with a `3.0 (quilt)' package means doing quilt
34 # fixup. Usually this involves recommitting the whole patch
35 # series, one at a time, with dpkg-source --commit. This is
36 # terribly terribly slow. (Maybe this should be fixed in dgit.)
38 # * dgit push usually needs to (re)make a pseudomerge. The "first"
39 # git-debrebase stripped out the previous pseudomerge and could
40 # have remembeed the HEAD. But it's not quite clear what history
41 # ought to be preserved and what should be discarded. For now
42 # the user will have to tell dgit --overwrite.
44 # To fix this, do we need a new push hook for dgit ?
46 # * Workflow is currently clumsy. Lots of spurious runes to type.
47 # There's not even a guide.
49 # * There are no tests.
51 # * new-upstream-v0 has a terrible UI. You end up with giant
52 # runic command lines.
54 # One consequence of the lack of richness it can need --force in
55 # fairly sensible situations and there is no way to tell it what
56 # you are really trying to do, other than just --force. There
57 # should be an interface with some default branch names.
59 # * There should be a standard convention for the version number,
60 # and unfinalised or not changelog, after new-upstream.
62 # * Handing of multi-orig dgit new-upstream .dsc imports is known to
63 # be broken. They may be not recognised, improperly converted, or
64 # their conversion may be unrecognised.
66 # * Docs need writing and updating. Even README.git-debrebase
67 # describes a design but may not reflect the implementation.
69 # * We need to develop a plausible model that works for derivatives,
70 # who probably want to maintain their stack on top of Debian's.
71 # downstream-rebase-launder-v0 may be a starting point?
75 use Debian::Dgit qw(:DEFAULT :playground);
82 use Getopt::Long qw(:config posix_default gnu_compat bundling);
84 use File::FnMatch qw(:fnmatch);
86 our ($opt_force, $opt_noop_ok, @opt_anchors);
88 our $us = qw(git-debrebase);
92 die "bad usage: $m\n";
96 my ($k, $optional) = @_;
98 my @cmd = qw(git config -z);
99 push @cmd, qw(--get-all) if wantarray;
101 my $out = cmdoutput_errok @cmd;
103 fail "missing required git config $k" unless $optional;
106 my @l = split /\0/, $out;
107 return wantarray ? @l : $l[0];
114 my $dd = new Data::Dumper [ $v ];
115 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
121 my $data = (git_cat_file $objid, 'commit');
122 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
126 sub D_UPS () { 0x02; } # upstream files
127 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
128 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
129 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
130 sub D_DEB_OTH () { 0x20; } # debian/changelog
131 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
133 our $playprefix = 'debrebase';
139 sub in_workarea ($) {
142 my $r = eval { $sub->(); };
143 { local $@; changedir $maindir; }
147 sub fresh_workarea () {
148 $workarea = fresh_playground "$playprefix/work";
149 in_workarea sub { playtree_setup };
152 our @deferred_updates;
153 our @deferred_update_messages;
155 sub run_deferred_updates ($) {
158 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
159 debugcmd '>|', @upd_cmd;
160 open U, "|-", @upd_cmd or die $!;
161 foreach (@deferred_updates) {
162 printdebug ">= ", $_, "\n";
163 print U $_, "\n" or die $!;
166 close U or failedcmd @upd_cmd;
168 print $_, "\n" foreach @deferred_update_messages;
170 @deferred_updates = ();
171 @deferred_update_messages = ();
174 sub get_differs ($$) {
176 # This resembles quiltify_trees_differ, in dgit, a bit.
177 # But we don't care about modes, or dpkg-source-unrepresentable
178 # changes, and we don't need the plethora of different modes.
179 # Conversely we need to distinguish different kinds of changes to
180 # debian/ and debian/patches/.
185 my ($opts, $limits, $fn) = @_;
186 my @cmd = (@git, qw(diff-tree -z --no-renames));
188 push @cmd, "$_:" foreach $x, $y;
189 push @cmd, '--', @$limits;
190 my $diffs = cmdoutput @cmd;
191 foreach (split /\0/, $diffs) { $fn->(); }
194 $rundiff->([qw(--name-only)], [], sub {
195 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
198 if ($differs & DS_DEB) {
200 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
202 m{^debian/patches/} ? D_PAT_OTH :
203 $_ eq 'debian/changelog' ? D_DEB_CLOG :
206 die "mysterious debian changes $x..$y"
207 unless $differs & (D_PAT_OTH|DS_DEB);
210 if ($differs & D_PAT_OTH) {
212 $differs &= ~D_PAT_OTH;
214 $differs |= D_PAT_OTH;
215 no warnings qw(exiting); last;
217 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
218 no warnings qw(exiting);
219 if (!defined $mode) {
222 die unless s{^debian/patches/}{};
224 if ($mode eq 'A' && !m/\.series$/s) {
226 } elsif ($mode eq 'M' && $_ eq 'series') {
227 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
228 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
229 chomp $x_s; $x_s .= "\n";
230 $ok = $x_s eq substr($y_s, 0, length $x_s);
235 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
237 die "mysterious debian/patches changes $x..$y"
238 unless $differs & (D_PAT_ADD|D_PAT_OTH);
241 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
246 sub commit_pr_info ($) {
248 return Data::Dumper->dump([$r], [qw(commit)]);
251 sub calculate_committer_authline () {
252 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
253 'DUMMY COMMIT (git-debrebase)', "HEAD:";
254 my ($h,$m) = get_commit $c;
255 $h =~ m/^committer .*$/m or confess "($h) ?";
259 sub rm_subdir_cached ($) {
261 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
264 sub read_tree_subdir ($$) {
265 my ($subdir, $new_tree_object) = @_;
266 rm_subdir_cached $subdir;
267 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
270 sub make_commit ($$) {
271 my ($parents, $message_paras) = @_;
272 my $tree = cmdoutput @git, qw(write-tree);
273 my @cmd = (@git, qw(commit-tree), $tree);
274 push @cmd, qw(-p), $_ foreach @$parents;
275 push @cmd, qw(-m), $_ foreach @$message_paras;
276 return cmdoutput @cmd;
279 our @fproblem_force_opts;
280 our $fproblems_forced;
281 our $fproblems_tripped;
284 if (grep { $_ eq $tag } @fproblem_force_opts) {
286 print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
288 $fproblems_tripped++;
289 print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
293 sub fproblems_maybe_bail () {
294 if ($fproblems_forced) {
296 "%s: safety catch trips: %d overriden by individual -f options\n",
297 $us, $fproblems_forced;
299 if ($fproblems_tripped) {
302 "%s: safety catch trips: %d overriden by global --force\n",
303 $us, $fproblems_tripped;
306 "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
307 $us, $fproblems_tripped;
311 sub any_fproblems () {
312 return $fproblems_forced || $fproblems_tripped;
315 # classify returns an info hash like this
317 # Hdr => # commit headers, including 1 final newline
318 # Msg => # commit message (so one newline is dropped)
320 # Type => (see below)
322 # Ix => $index # ie 0, 1, 2, ...
324 # Differs => return value from get_differs
326 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
328 # NewMsg => # commit message, but with any [dgit import ...] edited
329 # # to say "[was: ...]"
339 # has additional entres in classification result
340 # Overwritten = [ subset of Parents ]
341 # Contributor = $the_remaining_Parent
343 # DgitImportUnpatched
344 # has additional entry in classification result
345 # OrigParents = [ subset of Parents ]
348 # has additional entry in classification result
349 # OrigParents = [ subset of Parents ] # singleton list
356 # has additional entry in classification result
359 sub parsecommit ($;$) {
360 my ($objid, $p_ref) = @_;
361 # => hash with CommitId Hdr Msg Tree Parents
362 # Parents entries have only Ix CommitId
363 # $p_ref, if provided, must be [] and is used as a base for Parents
368 my ($h,$m) = get_commit $objid;
370 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
371 my (@ph) = $h =~ m/^parent (\w+)$/mg;
381 foreach my $ph (@ph) {
383 Ix => scalar @$p_ref,
395 my $r = parsecommit($objid, \@p);
399 $p->{Differs} = (get_differs $p->{CommitId}, $t),
402 printdebug "classify $objid \$t=$t \@p",
403 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
407 my ($type, @rest) = @_;
408 $r = { %$r, Type => $type, @rest };
410 printdebug " = $type ".(dd $r)."\n";
416 $r = { %$r, Type => qw(Unknown), Why => $why };
417 printdebug " ** Unknown\n";
421 if (grep { $_ eq $objid } @opt_anchors) {
422 return $classify->('TreatAsAnchor');
425 my @identical = grep { !$_->{Differs} } @p;
426 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
427 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
429 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
430 # multi-orig upstreams are represented with an anchor merge
431 # from a single upstream commit which combines the orig tarballs
433 # Every anchor tagged this way must be a merge.
434 # We are relying on the
435 # [git-debrebase anchor: ...]
436 # commit message annotation in "declare" anchor merges (which
437 # do not have any upstream changes), to distinguish those
438 # anchor merges from ordinary pseudomerges (which we might
439 # just try to strip).
441 # However, the user is going to be doing git-rebase a lot. We
442 # really don't want them to rewrite an anchor commit.
443 # git-rebase trips up on merges, so that is a useful safety
446 # BreakwaterStart commits are also anchors in the terminology
447 # of git-debrebase(5), but they are untagged (and always
448 # manually generated).
450 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
451 @p == 2 or return $badanchor->("has other than two parents");
452 $haspatches and return $badanchor->("contains debian/patches");
454 # How to decide about l/r ordering of anchors ? git
455 # --topo-order prefers to expand 2nd parent first. There's
456 # already an easy rune to look for debian/ history anyway (git log
457 # debian/) so debian breakwater branch should be 1st parent; that
458 # way also there's also an easy rune to look for the upstream
459 # patches (--topo-order).
461 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
462 $p[1]{Differs} & ~DS_DEB and
463 $badanchor->("upstream files differ from left parent");
464 $p[0]{Differs} & ~D_UPS and
465 $badanchor->("debian/ differs from right parent");
467 return $classify->(qw(Anchor),
468 OrigParents => [ $p[1] ]);
472 my $d = $r->{Parents}[0]{Differs};
473 if ($d == D_PAT_ADD) {
474 return $classify->(qw(AddPatches));
475 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
476 return $unknown->("edits debian/patches");
477 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
478 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
480 if ($d == D_DEB_CLOG) {
481 return $classify->(qw(Changelog));
483 return $classify->(qw(Packaging));
485 } elsif ($ty eq 'missing') {
486 return $classify->(qw(BreakwaterStart));
488 return $unknown->("parent's debian is not a directory");
490 } elsif ($d == D_UPS) {
491 return $classify->(qw(Upstream));
492 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
493 return $classify->(qw(Mixed));
495 return $unknown->("no changes");
497 confess "internal error $objid ?";
501 return $unknown->("origin commit");
504 if (@p == 2 && @identical == 1) {
505 my @overwritten = grep { $_->{Differs} } @p;
506 confess "internal error $objid ?" unless @overwritten==1;
507 return $classify->(qw(Pseudomerge),
508 Overwritten => [ $overwritten[0] ],
509 Contributor => $identical[0]);
511 if (@p == 2 && @identical == 2) {
513 my ($ph,$pm) = get_commit $_[0]{CommitId};
514 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
518 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
519 if ($order > 0) { # newer first
520 } elsif ($order < 0) {
521 @bytime = reverse @bytime;
523 # same age, default to order made by -s ours
524 # that is, commit was made by someone who preferred L
526 return $classify->(qw(Pseudomerge),
527 SubType => qw(Ambiguous),
528 Contributor => $bytime[0],
529 Overwritten => [ $bytime[1] ]);
532 my ($p_h, $p_m) = get_commit $p->{CommitId};
533 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
534 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
536 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
538 if (!(grep { !$_->{IsOrigin} } @p) and
539 (@orig_ps >= @p - 1) and
540 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
542 return $classify->(qw(DgitImportUnpatched),
543 OrigParents => \@orig_ps);
546 return $unknown->("complex merge");
549 sub breakwater_of ($) {
550 my ($head) = @_; # must be laundered
554 fail "branch needs laundering (run git-debrebase): $why";
557 my $cl = classify $head;
558 my $ty = $cl->{Type};
559 if ($ty eq 'Packaging' or
560 $ty eq 'Changelog') {
561 $breakwater //= $head;
562 } elsif ($ty eq 'Anchor' or
563 $ty eq 'TreatAsAnchor' or
564 $ty eq 'BreakwaterStart') {
565 $breakwater //= $head;
567 } elsif ($ty eq 'Upstream') {
568 $unclean->("packaging change ($breakwater)".
569 " follows upstream change (eg $head)")
570 if defined $breakwater;
571 } elsif ($ty eq 'Mixed') {
572 $unclean->('found mixed upstream/packaging commit ($head)');
573 } elsif ($ty eq 'Pseudomerge' or
574 $ty eq 'AddPatches') {
575 $unclean->("found interchange conversion commit ($ty, $head)");
576 } elsif ($ty eq 'DgitImportUnpatched') {
577 $unclean->("found dgit dsc import ($head)");
579 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
581 $head = $cl->{Parents}[0]{CommitId};
589 $nogenerate,$report) = @_;
590 # => ($tip, $breakwater_tip, $last_anchor)
591 # (or nothing, if $nogenerate)
593 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
595 # go through commits backwards
596 # we generate two lists of commits to apply:
597 # breakwater branch and upstream patches
598 my (@brw_cl, @upp_cl, @processed);
605 my ($prose, $info) = @_;
609 $ms .= "\n\n[git-debrebase$info: $prose]\n";
612 my $rewrite_from_here = sub {
614 my $sp_cl = { SpecialMethod => 'StartRewrite' };
616 push @processed, $sp_cl;
621 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
624 return unless $report;
625 print $report $prdelim, @_;
629 my $bomb = sub { # usage: return $bomb->();
630 print $report " Unprocessable" if $report;
631 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
634 return (undef,undef);
636 die "commit $cur: Cannot cope with this commit (d.".
637 (join ' ', map { sprintf "%#x", $_->{Differs} }
638 @{ $cl->{Parents} }).
639 (defined $cl->{Why} ? "; $cl->{Why}": '').
646 my $build_start = sub {
647 my ($msg, $parent) = @_;
650 no warnings qw(exiting); last;
657 my $ty = $cl->{Type};
658 my $st = $cl->{SubType};
659 $prline->("$cl->{CommitId} $cl->{Type}");
660 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
661 push @processed, $cl;
662 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
663 if ($ty eq 'AddPatches') {
665 $rewrite_from_here->(\@upp_cl);
667 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
671 } elsif ($ty eq 'BreakwaterStart') {
673 $build_start->('FirstPackaging', $cur);
674 } elsif ($ty eq 'Upstream') {
678 } elsif ($ty eq 'Mixed') {
681 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
684 $queue->(\@brw_cl, "debian");
685 $queue->(\@upp_cl, "upstream");
686 $rewrite_from_here->(\@brw_cl);
689 } elsif ($ty eq 'Pseudomerge') {
690 my $contrib = $cl->{Contributor}{CommitId};
691 print $report " Contributor=$contrib" if $report;
692 push @pseudomerges, $cl;
693 $rewrite_from_here->(\@upp_cl);
696 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
698 $build_start->("Anchor", $cur);
699 } elsif ($ty eq 'DgitImportUnpatched') {
700 my $pm = $pseudomerges[-1];
702 # To an extent, this is heuristic. Imports don't have
703 # a useful history of the debian/ branch. We assume
704 # that the first pseudomerge after an import has a
705 # useful history of debian/, and ignore the histories
706 # from later pseudomerges. Often the first pseudomerge
707 # will be the dgit import of the upload to the actual
708 # suite intended by the non-dgit NMUer, and later
709 # pseudomerges may represent in-archive copies.
710 my $ovwrs = $pm->{Overwritten};
711 printf $report " PM=%s \@Overwr:%d",
712 $pm->{CommitId}, (scalar @$ovwrs)
715 printdebug "*** WALK BOMB DgitImportUnpatched\n";
718 my $ovwr = $ovwrs->[0]{CommitId};
719 printf $report " Overwr=%s", $ovwr if $report;
720 # This import has a tree which is just like a
721 # breakwater tree, but it has the wrong history. It
722 # ought to have the previous breakwater (which the
723 # pseudomerge overwrote) as an ancestor. That will
724 # make the history of the debian/ files correct. As
725 # for the upstream version: either it's the same as
726 # was ovewritten (ie, same as the previous
727 # breakwater), in which case that history is precisely
728 # right; or, otherwise, it was a non-gitish upload of a
729 # new upstream version. We can tell these apart by
730 # looking at the tree of the supposed upstream.
733 SpecialMethod => 'DgitImportDebianUpdate',
734 $xmsg->("convert dgit import: debian changes")
737 SpecialMethod => 'DgitImportUpstreamUpdate',
738 $xmsg->("convert dgit import: upstream update",
741 $prline->(" Import");
742 $rewrite_from_here->(\@brw_cl);
743 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
747 # Everything is from this import. This kind of import
748 # is already in valid breakwater format, with the
749 # patches as commits.
750 printf $report " NoPM" if $report;
751 # last thing we processed will have been the first patch,
752 # if there is one; which is fine, so no need to rewrite
753 # on account of this import
754 $build_start->("ImportOrigin", $cur);
758 printdebug "*** WALK BOMB unrecognised\n";
764 printdebug "*** WALK prep done cur=$cur".
765 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
767 return if $nogenerate;
769 # Now we build it back up again
775 my $read_tree_debian = sub {
777 read_tree_subdir 'debian', "$treeish:debian";
778 rm_subdir_cached 'debian/patches';
780 my $read_tree_upstream = sub {
782 runcmd @git, qw(read-tree), $treeish;
783 $read_tree_debian->($build);
786 $#upp_cl = $upp_limit if defined $upp_limit;
788 my $committer_authline = calculate_committer_authline();
790 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
792 confess "internal error" unless $build eq (pop @processed)->{CommitId};
795 mkdir $rd or $!==EEXIST or die $!;
797 runcmd @git, qw(read-tree), $build;
798 foreach my $cl (qw(Debian), (reverse @brw_cl),
799 { SpecialMethod => 'RecordBreakwaterTip' },
800 qw(Upstream), (reverse @upp_cl)) {
802 $current_method = $cl;
805 my $method = $cl->{SpecialMethod} // $current_method;
806 my @parents = ($build);
807 my $cltree = $cl->{CommitId};
808 printdebug "WALK BUILD ".($cltree//'undef').
809 " $method (rewriting=$rewriting)\n";
810 if ($method eq 'Debian') {
811 $read_tree_debian->($cltree);
812 } elsif ($method eq 'Upstream') {
813 $read_tree_upstream->($cltree);
814 } elsif ($method eq 'StartRewrite') {
817 } elsif ($method eq 'RecordBreakwaterTip') {
818 $breakwater = $build;
820 } elsif ($method eq 'DgitImportDebianUpdate') {
821 $read_tree_debian->($cltree);
822 } elsif ($method eq 'DgitImportUpstreamUpdate') {
823 confess unless $rewriting;
824 my $differs = (get_differs $build, $cltree);
825 next unless $differs & D_UPS;
826 $read_tree_upstream->($cltree);
827 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
832 my $procd = (pop @processed) // 'UNDEF';
835 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
838 my $newtree = cmdoutput @git, qw(write-tree);
840 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
841 $ch =~ s{^parent .*\n}{}mg;
842 $ch =~ s{(?=^author)}{
843 join '', map { "parent $_\n" } @parents
844 }me or confess "$ch ?";
846 $ch =~ s{^committer .*$}{$committer_authline}m
849 my $cf = "$rd/m$rewriting";
850 open CD, ">", $cf or die $!;
851 print CD $ch, "\n", $cl->{Msg} or die $!;
853 my @cmd = (@git, qw(hash-object));
854 push @cmd, qw(-w) if $rewriting;
855 push @cmd, qw(-t commit), $cf;
856 my $newcommit = cmdoutput @cmd;
857 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
859 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
865 my $final_check = get_differs $build, $input;
866 die sprintf "internal error %#x %s %s", $final_check, $build, $input
867 if $final_check & ~D_PAT_ADD;
869 my @r = ($build, $breakwater, $last_anchor);
870 printdebug "*** WALK RETURN @r\n";
875 git_check_unmodified();
876 return git_rev_parse qw(HEAD);
879 sub update_head ($$$) {
880 my ($old, $new, $mrest) = @_;
881 push @deferred_updates, "update HEAD $new $old";
882 run_deferred_updates $mrest;
885 sub update_head_checkout ($$$) {
886 my ($old, $new, $mrest) = @_;
887 update_head $old, $new, $mrest;
888 runcmd @git, qw(reset --hard);
891 sub update_head_postlaunder ($$$) {
892 my ($old, $tip, $reflogmsg) = @_;
893 return if $tip eq $old;
894 print "git-debrebase: laundered (head was $old)\n";
895 update_head $old, $tip, $reflogmsg;
896 # no tree changes except debian/patches
897 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
900 sub cmd_launder_v0 () {
901 badusage "no arguments to launder-v0 allowed" if @ARGV;
902 my $old = get_head();
903 my ($tip,$breakwater,$last_anchor) = walk $old;
904 update_head_postlaunder $old, $tip, 'launder';
905 printf "# breakwater tip\n%s\n", $breakwater;
906 printf "# working tip\n%s\n", $tip;
907 printf "# last anchor\n%s\n", $last_anchor;
910 sub defaultcmd_rebase () {
911 my $old = get_head();
913 my ($tip,$breakwater) = walk $old;
914 update_head_postlaunder $old, $tip, 'launder for rebase';
915 runcmd @git, qw(rebase), @ARGV, $breakwater;
919 die if ($ARGV[0]//'') =~ m/^-/;
920 badusage "too many arguments to analyse" if @ARGV>1;
923 $old = git_rev_parse $old;
925 $old = git_rev_parse 'HEAD';
927 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
928 STDOUT->error and die $!;
931 sub ffq_prev_branchinfo () {
932 # => ('status', "message", [$current, $ffq_prev])
934 # branch message is undef
935 # weird-symref } no $current,
936 # notbranch } no $ffq_prev
937 my $current = git_get_symref();
938 return ('detached', 'detached HEAD') unless defined $current;
939 return ('weird-symref', 'HEAD symref is not to refs/')
940 unless $current =~ m{^refs/};
941 my $ffq_prev = "refs/$ffq_refprefix/$'";
942 printdebug "ffq_prev_branchinfo branch current $current\n";
943 return ('branch', undef, $current, $ffq_prev);
946 sub record_ffq_prev_deferred () {
947 # => ('status', "message")
949 # deferred message is undef
954 # if not ff from some branch we should be ff from, is an fproblem
955 # if "deferred", will have added something about that to
956 # @deferred_update_messages, and also maybe printed (already)
957 # some messages about ff checks
958 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
959 return ($status, $message) unless $status eq 'branch';
961 my $currentval = get_head();
963 my $exists = git_get_ref $ffq_prev;
964 return ('exists',"$ffq_prev already exists") if $exists;
966 return ('not-branch', 'HEAD symref is not to refs/heads/')
967 unless $current =~ m{^refs/heads/};
970 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
973 printdebug "ffq check_specs @check_specs\n";
976 my ($lrref, $desc) = @_;
977 printdebug "ffq might check $lrref ($desc)\n";
979 for my $chk (@check_specs) {
981 $invert = $glob =~ s{^[!^]}{};
982 last if fnmatch $glob, $lrref;
985 my $lrval = git_get_ref $lrref;
986 return unless defined $lrval;
988 if (is_fast_fwd $lrval, $currentval) {
989 print "OK, you are ahead of $lrref\n" or die $!;
990 $checked{$lrref} = 1;
991 } elsif (is_fast_fwd $currentval, $lrval) {
992 $checked{$lrref} = -1;
993 fproblem 'behind', "you are behind $lrref, divergence risk";
995 $checked{$lrref} = -1;
996 fproblem 'diverged', "you have diverged from $lrref";
1000 my $merge = cfg "branch.$branch.merge",1;
1001 if (defined $merge and $merge =~ m{^refs/heads/}) {
1003 printdebug "ffq merge $rhs\n";
1004 my $check_remote = sub {
1005 my ($remote, $desc) = @_;
1006 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1007 return unless defined $remote;
1008 $check->("refs/remotes/$remote/$rhs", $desc);
1010 $check_remote->((scalar cfg "branch.$branch.remote",1),
1011 'remote fetch/merge branch');
1012 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1013 (scalar cfg "branch.$branch.pushDefault",1),
1014 'remote push branch');
1016 if ($branch =~ m{^dgit/}) {
1017 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1018 } elsif ($branch =~ m{^master$}) {
1019 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1022 fproblems_maybe_bail();
1024 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1025 push @deferred_update_messages, "Recorded current head for preservation";
1026 return ('deferred', undef);
1029 sub record_ffq_auto () {
1030 my ($status, $message) = record_ffq_prev_deferred();
1031 if ($status eq 'deferred' || $status eq 'exists') {
1033 fproblem $status, "could not record ffq-prev: $message";
1034 fproblems_maybe_bail();
1038 sub cmd_new_upstream_v0 () {
1039 # automatically and unconditionally launders before rebasing
1040 # if rebase --abort is used, laundering has still been done
1044 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1046 # parse args - low commitment
1047 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1048 my $new_upstream_version = $new_version->version();
1050 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1055 my ($n, @x) = @_; # may be ''
1056 my $pc = $pieces{$n} //= {
1058 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1060 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1065 my $newpiece = sub {
1066 my ($n, @x) = @_; # may be ''
1067 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1068 push @newpieces, $pc;
1073 New => $new_upstream,
1075 while (@ARGV && $ARGV[0] !~ m{^-}) {
1076 my $n = shift @ARGV;
1078 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1079 unless @ARGV && $ARGV[0] !~ m{^-};
1081 my $c = git_rev_parse shift @ARGV;
1082 die unless $n =~ m/^$extra_orig_namepart_re$/;
1083 $newpiece->($n, New => $c);
1086 # now we need to investigate the branch this generates the
1087 # laundered version but we don't switch to it yet
1088 my $old_head = get_head();
1089 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1091 my $old_bw_cl = classify $old_bw;
1092 my $old_anchor_cl = classify $old_anchor;
1094 if (!$old_anchor_cl->{OrigParents}) {
1095 fproblem 'anchor-treated',
1096 'old anchor is recognised due to --anchor, cannot check upstream';
1098 $old_upstream = parsecommit
1099 $old_anchor_cl->{OrigParents}[0]{CommitId};
1100 $piece->('', Old => $old_upstream->{CommitId});
1103 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1104 if ($old_upstream->{Msg} =~
1105 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1107 my @oldpieces = ('', split / /, $1);
1108 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1109 foreach my $i (0..$#oldpieces) {
1110 my $n = $oldpieces[$i];
1111 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1114 fproblem 'upstream-confusing',
1115 "previous upstream $old_upstream->{CommitId} is from".
1116 " git-debrebase but not an \`upstream-combine' commit";
1120 foreach my $pc (values %pieces) {
1121 if (!$old_upstream) {
1122 # we have complained already
1123 } elsif (!$pc->{Old}) {
1124 fproblem 'upstream-new-piece',
1125 "introducing upstream piece \`$pc->{Name}'";
1126 } elsif (!$pc->{New}) {
1127 fproblem 'upstream-rm-piece',
1128 "dropping upstream piece \`$pc->{Name}'";
1129 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1130 fproblem 'upstream-not-ff',
1131 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1135 printdebug "%pieces = ", (dd \%pieces), "\n";
1136 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1138 fproblems_maybe_bail();
1144 my @upstream_merge_parents;
1146 if (!any_fproblems()) {
1147 push @upstream_merge_parents, $old_upstream->{CommitId};
1150 foreach my $pc (@newpieces) { # always has '' first
1152 read_tree_subdir $pc->{Name}, $pc->{New};
1154 runcmd @git, qw(read-tree), $pc->{New};
1156 push @upstream_merge_parents, $pc->{New};
1159 # index now contains the new upstream
1161 if (@newpieces > 1) {
1162 # need to make the upstream subtree merge commit
1163 $new_upstream = make_commit \@upstream_merge_parents,
1164 [ "Combine upstreams for $new_upstream_version",
1165 ("[git-debrebase upstream-combine . ".
1166 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1171 # $new_upstream is either the single upstream commit, or the
1172 # combined commit we just made. Either way it will be the
1173 # "upstream" parent of the anchor merge.
1175 read_tree_subdir 'debian', "$old_bw:debian";
1177 # index now contains the anchor merge contents
1178 $new_bw = make_commit [ $old_bw, $new_upstream ],
1179 [ "Update to upstream $new_upstream_version",
1180 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1183 # Now we have to add a changelog stanza so the Debian version
1185 die if unlink "debian";
1186 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1187 unlink "debian/changelog" or $!==ENOENT or die $!;
1188 mkdir "debian" or die $!;
1189 open CN, ">", "debian/changelog" or die $!;
1190 my $oldclog = git_cat_file ":debian/changelog";
1191 $oldclog =~ m/^($package_re) \(\S+\) / or
1192 fail "cannot parse old changelog to get package name";
1194 print CN <<END, $oldclog or die $!;
1195 $p ($new_version) UNRELEASED; urgency=medium
1197 * Update to new upstream version $new_upstream_version.
1203 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1205 # Now we have the final new breakwater branch in the index
1206 $new_bw = make_commit [ $new_bw ],
1207 [ "Update changelog for new upstream $new_upstream_version",
1208 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1212 # we have constructed the new breakwater. we now need to commit to
1213 # the laundering output, because git-rebase can't easily be made
1214 # to make a replay list which is based on some other branch
1216 update_head_postlaunder $old_head, $old_laundered_tip,
1217 'launder for new upstream';
1219 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1221 # now it's for the user to sort out
1224 sub cmd_record_ffq_prev () {
1225 badusage "no arguments allowed" if @ARGV;
1226 my ($status, $msg) = record_ffq_prev_deferred();
1227 if ($status eq 'exists' && $opt_noop_ok) {
1228 print "Previous head already recorded\n" or die $!;
1229 } elsif ($status eq 'deferred') {
1230 run_deferred_updates 'record-ffq-prev';
1232 fail "Could not preserve: $msg";
1236 sub cmd_breakwater () {
1237 badusage "no arguments allowed" if @ARGV;
1238 my $bw = breakwater_of git_rev_parse 'HEAD';
1239 print "$bw\n" or die $!;
1244 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1245 badusage "no arguments allowed" if @ARGV;
1246 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1247 if ($status ne 'branch') {
1248 fproblem $status, "could not check ffq-prev: $message";
1249 fproblems_maybe_bail();
1251 my $prev = $ffq_prev && git_get_ref $ffq_prev;
1253 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1255 push @deferred_updates, "delete $ffq_prev $prev";
1257 my $old_head = get_head();
1258 if (is_fast_fwd $old_head, $prev) {
1259 my $differs = get_differs $old_head, $prev;
1260 unless ($differs & ~D_PAT_ADD) {
1261 # ffq-prev is ahead of us, and the only tree changes it has
1262 # are possibly addition of things in debian/patches/.
1263 # Just wind forwards rather than making a pointless pseudomerge.
1264 update_head_checkout $old_head, $prev, "stitch (fast forward)";
1269 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1270 'Declare fast forward / record previous work',
1271 "[git-debrebase pseudomerge: stitch$prose]",
1273 update_head $old_head, $new_head, "stitch";
1276 sub cmd_convert_from_gbp () {
1277 badusage "needs 1 optional argument, the upstream git rev"
1279 my ($upstream_spec) = @ARGV;
1280 $upstream_spec //= 'refs/heads/upstream';
1281 my $upstream = git_rev_parse $upstream_spec;
1282 my $old_head = get_head();
1284 my $upsdiff = get_differs $upstream, $old_head;
1285 if ($upsdiff & D_UPS) {
1286 runcmd @git, qw(--no-pager diff),
1287 $upstream, $old_head,
1288 qw( -- :!/debian :/);
1289 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1292 if (!is_fast_fwd $upstream, $old_head) {
1293 fproblem 'upstream-not-ancestor',
1294 "upstream ($upstream) is not an ancestor of HEAD";
1296 my $wrong = cmdoutput
1297 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1298 qw(-- :/ :!/debian));
1299 if (length $wrong) {
1300 fproblem 'unexpected-upstream-changes',
1301 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1302 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1306 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1307 fproblem 'upstream-has-debian',
1308 "upstream ($upstream) contains debian/ directory";
1311 fproblems_maybe_bail();
1317 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1318 # make a branch out of the patch queue - we'll want this in a mo
1319 runcmd qw(gbp pq import);
1320 # strip the patches out
1321 runcmd @git, qw(checkout -q gdr-internal~0);
1322 rm_subdir_cached 'debian/patches';
1323 $work = make_commit ['HEAD'], [
1324 'git-debrebase convert-from-gbp: drop patches from tree',
1325 'Delete debian/patches, as part of converting to git-debrebase format.',
1326 '[git-debrebase convert-from-gbp: drop patches from tree]'
1328 # make the anchor merge
1329 # the tree is already exactly right
1330 $work = make_commit [$work, $upstream], [
1331 'git-debrebase import: declare upstream',
1332 'First breakwater merge.',
1333 '[git-debrebase anchor: declare upstream]'
1336 # rebase the patch queue onto the new breakwater
1337 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1338 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1339 $work = git_rev_parse 'HEAD';
1342 update_head_checkout $old_head, $work, 'convert-from-gbp';
1345 sub cmd_convert_to_gbp () {
1346 badusage "no arguments allowed" if @ARGV;
1347 my $head = get_head();
1348 my $ffq = (ffq_prev_branchinfo())[3];
1349 my $bw = breakwater_of $head;
1353 runcmd @git, qw(checkout -q -b bw), $bw;
1354 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1355 runcmd qw(gbp pq export);
1356 runcmd @git, qw(add debian/patches);
1357 $out = make_commit ['HEAD'], [
1358 'Commit patch queue (converted from git-debrebase format)',
1359 '[git-debrebase convert-to-gbp: commit patches]',
1363 push @deferred_updates, "delete $ffq";
1365 update_head_checkout $head, $out, "convert to gbp (v0)";
1366 print <<END or die $!;
1367 git-debrebase: converted to git-buildpackage branch format
1368 git-debrebase: WARNING: do not now run "git-debrebase" any more
1369 git-debrebase: WARNING: doing so would drop all upstream patches!
1373 sub cmd_downstream_rebase_launder_v0 () {
1374 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1376 $base = git_rev_parse $base;
1377 my $old_head = get_head();
1378 my $current = $old_head;
1381 if ($current eq $base) {
1382 $topmost_keep //= $current;
1383 print " $current BASE stop\n";
1386 my $cl = classify $current;
1387 print " $current $cl->{Type}";
1389 my $p0 = $cl->{Parents}[0]{CommitId};
1391 if ($cl->{Type} eq 'Pseudomerge') {
1392 print " ^".($cl->{Contributor}{Ix}+1);
1393 $next = $cl->{Contributor}{CommitId};
1394 } elsif ($cl->{Type} eq 'AddPatches' or
1395 $cl->{Type} eq 'Changelog') {
1405 $topmost_keep //= $current;
1407 die "to-be stripped changes not on top of the branch\n"
1412 if ($topmost_keep eq $old_head) {
1413 print "unchanged\n";
1415 print "updating to $topmost_keep\n";
1416 update_head_checkout
1417 $old_head, $topmost_keep,
1418 'downstream-rebase-launder-v0';
1422 GetOptions("D+" => \$debuglevel,
1423 'noop-ok', => \$opt_noop_ok,
1424 'f=s' => \@fproblem_force_opts,
1425 'anchor=s' => \@opt_anchors,
1426 'force!') or die badusage "bad options\n";
1427 initdebug('git-debrebase ');
1428 enabledebug if $debuglevel;
1430 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1431 chdir $toplevel or die "chdir $toplevel: $!";
1433 $rd = fresh_playground "$playprefix/misc";
1435 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1437 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1438 defaultcmd_rebase();
1440 my $cmd = shift @ARGV;
1443 $cmdfn = ${*::}{"cmd_$cmdfn"};
1445 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";