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/>.
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::ExitStatus;
26 use Debian::Dgit qw(:DEFAULT :playground);
33 use Getopt::Long qw(:config posix_default gnu_compat bundling);
35 use File::FnMatch qw(:fnmatch);
37 our ($opt_force, $opt_noop_ok, @opt_anchors);
38 our ($opt_defaultcmd_interactive);
40 our $us = qw(git-debrebase);
44 print STDERR "bad usage: $m\n";
49 my ($k, $optional) = @_;
51 my @cmd = qw(git config -z);
52 push @cmd, qw(--get-all) if wantarray;
54 my $out = cmdoutput_errok @cmd;
56 fail "missing required git config $k" unless $optional;
59 my @l = split /\0/, $out;
60 return wantarray ? @l : $l[0];
67 my $dd = new Data::Dumper [ $v ];
68 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
74 my $data = (git_cat_file $objid, 'commit');
75 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
79 sub D_UPS () { 0x02; } # upstream files
80 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
81 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
82 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
83 sub D_DEB_OTH () { 0x20; } # debian/changelog
84 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
86 our $playprefix = 'debrebase';
95 my $r = eval { $sub->(); };
96 { local $@; changedir $maindir; }
100 sub fresh_workarea () {
101 $workarea = fresh_playground "$playprefix/work";
102 in_workarea sub { playtree_setup };
108 our @deferred_updates;
109 our @deferred_update_messages;
111 sub run_deferred_updates ($) {
114 confess 'dangerous internal error' if
115 !$snags_checked || $snags_tripped || $snags_forced;
117 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
118 debugcmd '>|', @upd_cmd;
119 open U, "|-", @upd_cmd or die $!;
120 foreach (@deferred_updates) {
121 printdebug ">= ", $_, "\n";
122 print U $_, "\n" or die $!;
125 close U or failedcmd @upd_cmd;
127 print $_, "\n" foreach @deferred_update_messages;
129 @deferred_updates = ();
130 @deferred_update_messages = ();
133 sub get_differs ($$) {
135 # This resembles quiltify_trees_differ, in dgit, a bit.
136 # But we don't care about modes, or dpkg-source-unrepresentable
137 # changes, and we don't need the plethora of different modes.
138 # Conversely we need to distinguish different kinds of changes to
139 # debian/ and debian/patches/.
144 my ($opts, $limits, $fn) = @_;
145 my @cmd = (@git, qw(diff-tree -z --no-renames));
147 push @cmd, "$_:" foreach $x, $y;
148 push @cmd, '--', @$limits;
149 my $diffs = cmdoutput @cmd;
150 foreach (split /\0/, $diffs) { $fn->(); }
153 $rundiff->([qw(--name-only)], [], sub {
154 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
157 if ($differs & DS_DEB) {
159 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
161 m{^debian/patches/} ? D_PAT_OTH :
162 $_ eq 'debian/changelog' ? D_DEB_CLOG :
165 die "mysterious debian changes $x..$y"
166 unless $differs & (D_PAT_OTH|DS_DEB);
169 if ($differs & D_PAT_OTH) {
171 $differs &= ~D_PAT_OTH;
173 $differs |= D_PAT_OTH;
174 no warnings qw(exiting); last;
176 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
177 no warnings qw(exiting);
178 if (!defined $mode) {
181 die unless s{^debian/patches/}{};
183 if ($mode eq 'A' && !m/\.series$/s) {
185 } elsif ($mode eq 'M' && $_ eq 'series') {
186 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
187 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
188 chomp $x_s; $x_s .= "\n";
189 $ok = $x_s eq substr($y_s, 0, length $x_s);
194 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
196 die "mysterious debian/patches changes $x..$y"
197 unless $differs & (D_PAT_ADD|D_PAT_OTH);
200 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
205 sub commit_pr_info ($) {
207 return Data::Dumper->dump([$r], [qw(commit)]);
210 sub calculate_committer_authline () {
211 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
212 'DUMMY COMMIT (git-debrebase)', "HEAD:";
213 my ($h,$m) = get_commit $c;
214 $h =~ m/^committer .*$/m or confess "($h) ?";
218 sub rm_subdir_cached ($) {
220 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
223 sub read_tree_subdir ($$) {
224 my ($subdir, $new_tree_object) = @_;
225 rm_subdir_cached $subdir;
226 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
229 sub make_commit ($$) {
230 my ($parents, $message_paras) = @_;
231 my $tree = cmdoutput @git, qw(write-tree);
232 my @cmd = (@git, qw(commit-tree), $tree);
233 push @cmd, qw(-p), $_ foreach @$parents;
234 push @cmd, qw(-m), $_ foreach @$message_paras;
235 return cmdoutput @cmd;
238 our @snag_force_opts;
241 if (grep { $_ eq $tag } @snag_force_opts) {
243 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
246 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
250 sub snags_maybe_bail () {
254 "%s: snags: %d overriden by individual -f options\n",
258 if ($snags_tripped) {
261 "%s: snags: %d overriden by global --force\n",
266 "%s: snags: %d blockers (you could -f<tag>, or --force)",
272 return $snags_forced || $snags_tripped;
275 # classify returns an info hash like this
277 # Hdr => # commit headers, including 1 final newline
278 # Msg => # commit message (so one newline is dropped)
280 # Type => (see below)
282 # Ix => $index # ie 0, 1, 2, ...
284 # Differs => return value from get_differs
286 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
288 # NewMsg => # commit message, but with any [dgit import ...] edited
289 # # to say "[was: ...]"
299 # has additional entres in classification result
300 # Overwritten = [ subset of Parents ]
301 # Contributor = $the_remaining_Parent
303 # DgitImportUnpatched
304 # has additional entry in classification result
305 # OrigParents = [ subset of Parents ]
308 # has additional entry in classification result
309 # OrigParents = [ subset of Parents ] # singleton list
316 # has additional entry in classification result
319 sub parsecommit ($;$) {
320 my ($objid, $p_ref) = @_;
321 # => hash with CommitId Hdr Msg Tree Parents
322 # Parents entries have only Ix CommitId
323 # $p_ref, if provided, must be [] and is used as a base for Parents
328 my ($h,$m) = get_commit $objid;
330 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
331 my (@ph) = $h =~ m/^parent (\w+)$/mg;
341 foreach my $ph (@ph) {
343 Ix => scalar @$p_ref,
355 my $r = parsecommit($objid, \@p);
359 $p->{Differs} = (get_differs $p->{CommitId}, $t),
362 printdebug "classify $objid \$t=$t \@p",
363 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
367 my ($type, @rest) = @_;
368 $r = { %$r, Type => $type, @rest };
370 printdebug " = $type ".(dd $r)."\n";
376 $r = { %$r, Type => qw(Unknown), Why => $why };
377 printdebug " ** Unknown\n";
381 if (grep { $_ eq $objid } @opt_anchors) {
382 return $classify->('TreatAsAnchor');
385 my @identical = grep { !$_->{Differs} } @p;
386 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
387 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
389 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
390 # multi-orig upstreams are represented with an anchor merge
391 # from a single upstream commit which combines the orig tarballs
393 # Every anchor tagged this way must be a merge.
394 # We are relying on the
395 # [git-debrebase anchor: ...]
396 # commit message annotation in "declare" anchor merges (which
397 # do not have any upstream changes), to distinguish those
398 # anchor merges from ordinary pseudomerges (which we might
399 # just try to strip).
401 # However, the user is going to be doing git-rebase a lot. We
402 # really don't want them to rewrite an anchor commit.
403 # git-rebase trips up on merges, so that is a useful safety
406 # BreakwaterStart commits are also anchors in the terminology
407 # of git-debrebase(5), but they are untagged (and always
408 # manually generated).
410 # We cannot not tolerate any tagged linear commit (ie,
411 # BreakwaterStart commits tagged `[anchor:') because such a
412 # thing could result from an erroneous linearising raw git
413 # rebase of a merge anchor. That would represent a corruption
414 # of the branch. and we want to detect and reject the results
415 # of such corruption before it makes it out anywhere. If we
416 # reject it here then we avoid making the pseudomerge which
417 # would be needed to push it.
419 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
420 @p == 2 or return $badanchor->("has other than two parents");
421 $haspatches and return $badanchor->("contains debian/patches");
423 # How to decide about l/r ordering of anchors ? git
424 # --topo-order prefers to expand 2nd parent first. There's
425 # already an easy rune to look for debian/ history anyway (git log
426 # debian/) so debian breakwater branch should be 1st parent; that
427 # way also there's also an easy rune to look for the upstream
428 # patches (--topo-order).
430 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
431 $p[1]{Differs} & ~DS_DEB and
432 $badanchor->("upstream files differ from left parent");
433 $p[0]{Differs} & ~D_UPS and
434 $badanchor->("debian/ differs from right parent");
436 return $classify->(qw(Anchor),
437 OrigParents => [ $p[1] ]);
441 my $d = $r->{Parents}[0]{Differs};
442 if ($d == D_PAT_ADD) {
443 return $classify->(qw(AddPatches));
444 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
445 return $unknown->("edits debian/patches");
446 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
447 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
449 if ($d == D_DEB_CLOG) {
450 return $classify->(qw(Changelog));
452 return $classify->(qw(Packaging));
454 } elsif ($ty eq 'missing') {
455 return $classify->(qw(BreakwaterStart));
457 return $unknown->("parent's debian is not a directory");
459 } elsif ($d == D_UPS) {
460 return $classify->(qw(Upstream));
461 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
462 return $classify->(qw(Mixed));
464 return $unknown->("no changes");
466 confess "internal error $objid ?";
470 return $unknown->("origin commit");
473 if (@p == 2 && @identical == 1) {
474 my @overwritten = grep { $_->{Differs} } @p;
475 confess "internal error $objid ?" unless @overwritten==1;
476 return $classify->(qw(Pseudomerge),
477 Overwritten => [ $overwritten[0] ],
478 Contributor => $identical[0]);
480 if (@p == 2 && @identical == 2) {
482 my ($ph,$pm) = get_commit $_[0]{CommitId};
483 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
487 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
488 if ($order > 0) { # newer first
489 } elsif ($order < 0) {
490 @bytime = reverse @bytime;
492 # same age, default to order made by -s ours
493 # that is, commit was made by someone who preferred L
495 return $classify->(qw(Pseudomerge),
496 SubType => qw(Ambiguous),
497 Contributor => $bytime[0],
498 Overwritten => [ $bytime[1] ]);
501 my ($p_h, $p_m) = get_commit $p->{CommitId};
502 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
503 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
505 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
507 if (!(grep { !$_->{IsOrigin} } @p) and
508 (@orig_ps >= @p - 1) and
509 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
511 return $classify->(qw(DgitImportUnpatched),
512 OrigParents => \@orig_ps);
515 return $unknown->("complex merge");
518 sub keycommits ($;$$$) {
519 my ($head, $furniture, $unclean, $trouble) = @_;
520 # => ($anchor, $breakwater)
522 # $unclean->("unclean-$tagsfx", $msg)
523 # $furniture->("unclean-$tagsfx", $msg)
524 # $dgitimport->("unclean-$tagsfx", $msg)
525 # is callled for each situation or commit that
526 # wouldn't be found in a laundered branch
527 # $furniture is for furniture commits such as might be found on an
528 # interchange branch (pseudomerge, d/patches, changelog)
529 # $trouble is for things whnich prevent the return of
530 # anchor and breakwater information; if that is ignored,
531 # then keycommits returns (undef, undef) instead.
533 # If a callback is undef, fail is called instead.
534 # If a callback is defined but false, the situation is ignored.
536 # no warnings qw(exiting); last;
537 # if the answer is no longer wanted.
539 my ($anchor, $breakwater);
542 my ($cb, $tagsfx, $why) = @_;
543 my $m = "branch needs laundering (run git-debrebase): $why";
544 fail $m unless defined $cb;
546 $cb->("unclean-$tagsfx", $why);
549 my $cl = classify $head;
550 my $ty = $cl->{Type};
551 if ($ty eq 'Packaging') {
552 $breakwater //= $clogonly;
553 $breakwater //= $head;
554 } elsif ($ty eq 'Changelog') {
555 # this is going to count as the tip of the breakwater
556 # only if it has no upstream stuff before it
558 } elsif ($ty eq 'Anchor' or
559 $ty eq 'TreatAsAnchor' or
560 $ty eq 'BreakwaterStart') {
562 $breakwater //= $clogonly;
563 $breakwater //= $head;
565 } elsif ($ty eq 'Upstream') {
566 $x->($unclean, 'ordering',
567 "packaging change ($breakwater) follows upstream change (eg $head)")
568 if defined $breakwater;
571 } elsif ($ty eq 'Mixed') {
572 $x->($unclean, 'mixed',
573 "found mixed upstream/packaging commit ($head)");
576 } elsif ($ty eq 'Pseudomerge' or
577 $ty eq 'AddPatches') {
578 $x->($furniture, (lc $ty),
579 "found interchange bureaucracy commit ($ty, $head)");
580 } elsif ($ty eq 'DgitImportUnpatched') {
581 $x->($trouble, 'dgitimport',
582 "found dgit dsc import ($head)");
585 no warnings qw(exiting);
588 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
590 $head = $cl->{Parents}[0]{CommitId};
592 return ($anchor, $breakwater);
598 $nogenerate,$report) = @_;
599 # => ($tip, $breakwater_tip, $last_anchor)
600 # (or nothing, if $nogenerate)
602 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
604 # go through commits backwards
605 # we generate two lists of commits to apply:
606 # breakwater branch and upstream patches
607 my (@brw_cl, @upp_cl, @processed);
614 my ($prose, $info) = @_;
618 $ms .= "\n\n[git-debrebase$info: $prose]\n";
621 my $rewrite_from_here = sub {
623 my $sp_cl = { SpecialMethod => 'StartRewrite' };
625 push @processed, $sp_cl;
630 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
633 return unless $report;
634 print $report $prdelim, @_;
638 my $bomb = sub { # usage: return $bomb->();
639 print $report " Unprocessable" if $report;
640 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
643 return (undef,undef);
645 die "commit $cur: Cannot cope with this commit (d.".
646 (join ' ', map { sprintf "%#x", $_->{Differs} }
647 @{ $cl->{Parents} }).
648 (defined $cl->{Why} ? "; $cl->{Why}": '').
655 my $build_start = sub {
656 my ($msg, $parent) = @_;
659 no warnings qw(exiting); last;
666 my $ty = $cl->{Type};
667 my $st = $cl->{SubType};
668 $prline->("$cl->{CommitId} $cl->{Type}");
669 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
670 push @processed, $cl;
671 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
672 if ($ty eq 'AddPatches') {
674 $rewrite_from_here->(\@upp_cl);
676 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
680 } elsif ($ty eq 'BreakwaterStart') {
682 $build_start->('FirstPackaging', $cur);
683 } elsif ($ty eq 'Upstream') {
687 } elsif ($ty eq 'Mixed') {
690 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
693 $queue->(\@brw_cl, "debian");
694 $queue->(\@upp_cl, "upstream");
695 $rewrite_from_here->(\@brw_cl);
698 } elsif ($ty eq 'Pseudomerge') {
699 my $contrib = $cl->{Contributor}{CommitId};
700 print $report " Contributor=$contrib" if $report;
701 push @pseudomerges, $cl;
702 $rewrite_from_here->(\@upp_cl);
705 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
707 $build_start->("Anchor", $cur);
708 } elsif ($ty eq 'DgitImportUnpatched') {
709 my $pm = $pseudomerges[-1];
711 # To an extent, this is heuristic. Imports don't have
712 # a useful history of the debian/ branch. We assume
713 # that the first pseudomerge after an import has a
714 # useful history of debian/, and ignore the histories
715 # from later pseudomerges. Often the first pseudomerge
716 # will be the dgit import of the upload to the actual
717 # suite intended by the non-dgit NMUer, and later
718 # pseudomerges may represent in-archive copies.
719 my $ovwrs = $pm->{Overwritten};
720 printf $report " PM=%s \@Overwr:%d",
721 $pm->{CommitId}, (scalar @$ovwrs)
724 printdebug "*** WALK BOMB DgitImportUnpatched\n";
727 my $ovwr = $ovwrs->[0]{CommitId};
728 printf $report " Overwr=%s", $ovwr if $report;
729 # This import has a tree which is just like a
730 # breakwater tree, but it has the wrong history. It
731 # ought to have the previous breakwater (which the
732 # pseudomerge overwrote) as an ancestor. That will
733 # make the history of the debian/ files correct. As
734 # for the upstream version: either it's the same as
735 # was ovewritten (ie, same as the previous
736 # breakwater), in which case that history is precisely
737 # right; or, otherwise, it was a non-gitish upload of a
738 # new upstream version. We can tell these apart by
739 # looking at the tree of the supposed upstream.
742 SpecialMethod => 'DgitImportDebianUpdate',
743 $xmsg->("convert dgit import: debian changes")
746 SpecialMethod => 'DgitImportUpstreamUpdate',
747 $xmsg->("convert dgit import: upstream update",
750 $prline->(" Import");
751 $rewrite_from_here->(\@brw_cl);
752 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
756 # Everything is from this import. This kind of import
757 # is already in valid breakwater format, with the
758 # patches as commits.
759 printf $report " NoPM" if $report;
760 # last thing we processed will have been the first patch,
761 # if there is one; which is fine, so no need to rewrite
762 # on account of this import
763 $build_start->("ImportOrigin", $cur);
767 printdebug "*** WALK BOMB unrecognised\n";
773 printdebug "*** WALK prep done cur=$cur".
774 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
776 return if $nogenerate;
778 # Now we build it back up again
784 my $read_tree_debian = sub {
786 read_tree_subdir 'debian', "$treeish:debian";
787 rm_subdir_cached 'debian/patches';
789 my $read_tree_upstream = sub {
791 runcmd @git, qw(read-tree), $treeish;
792 $read_tree_debian->($build);
795 $#upp_cl = $upp_limit if defined $upp_limit;
797 my $committer_authline = calculate_committer_authline();
799 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
801 confess "internal error" unless $build eq (pop @processed)->{CommitId};
804 mkdir $rd or $!==EEXIST or die $!;
806 runcmd @git, qw(read-tree), $build;
807 foreach my $cl (qw(Debian), (reverse @brw_cl),
808 { SpecialMethod => 'RecordBreakwaterTip' },
809 qw(Upstream), (reverse @upp_cl)) {
811 $current_method = $cl;
814 my $method = $cl->{SpecialMethod} // $current_method;
815 my @parents = ($build);
816 my $cltree = $cl->{CommitId};
817 printdebug "WALK BUILD ".($cltree//'undef').
818 " $method (rewriting=$rewriting)\n";
819 if ($method eq 'Debian') {
820 $read_tree_debian->($cltree);
821 } elsif ($method eq 'Upstream') {
822 $read_tree_upstream->($cltree);
823 } elsif ($method eq 'StartRewrite') {
826 } elsif ($method eq 'RecordBreakwaterTip') {
827 $breakwater = $build;
829 } elsif ($method eq 'DgitImportDebianUpdate') {
830 $read_tree_debian->($cltree);
831 } elsif ($method eq 'DgitImportUpstreamUpdate') {
832 confess unless $rewriting;
833 my $differs = (get_differs $build, $cltree);
834 next unless $differs & D_UPS;
835 $read_tree_upstream->($cltree);
836 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
841 my $procd = (pop @processed) // 'UNDEF';
844 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
847 my $newtree = cmdoutput @git, qw(write-tree);
849 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
850 $ch =~ s{^parent .*\n}{}mg;
851 $ch =~ s{(?=^author)}{
852 join '', map { "parent $_\n" } @parents
853 }me or confess "$ch ?";
855 $ch =~ s{^committer .*$}{$committer_authline}m
858 my $cf = "$rd/m$rewriting";
859 open CD, ">", $cf or die $!;
860 print CD $ch, "\n", $cl->{Msg} or die $!;
862 my @cmd = (@git, qw(hash-object));
863 push @cmd, qw(-w) if $rewriting;
864 push @cmd, qw(-t commit), $cf;
865 my $newcommit = cmdoutput @cmd;
866 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
868 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
874 my $final_check = get_differs $build, $input;
875 die sprintf "internal error %#x %s %s", $final_check, $build, $input
876 if $final_check & ~D_PAT_ADD;
878 my @r = ($build, $breakwater, $last_anchor);
879 printdebug "*** WALK RETURN @r\n";
884 git_check_unmodified();
885 return git_rev_parse qw(HEAD);
888 sub update_head ($$$) {
889 my ($old, $new, $mrest) = @_;
890 push @deferred_updates, "update HEAD $new $old";
891 run_deferred_updates $mrest;
894 sub update_head_checkout ($$$) {
895 my ($old, $new, $mrest) = @_;
896 update_head $old, $new, $mrest;
897 runcmd @git, qw(reset --hard);
900 sub update_head_postlaunder ($$$) {
901 my ($old, $tip, $reflogmsg) = @_;
902 return if $tip eq $old;
903 print "git-debrebase: laundered (head was $old)\n";
904 update_head $old, $tip, $reflogmsg;
905 # no tree changes except debian/patches
906 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
909 sub do_launder_head ($) {
910 my ($reflogmsg) = @_;
911 my $old = get_head();
913 my ($tip,$breakwater) = walk $old;
915 update_head_postlaunder $old, $tip, $reflogmsg;
916 return ($tip,$breakwater);
919 sub cmd_launder_v0 () {
920 badusage "no arguments to launder-v0 allowed" if @ARGV;
921 my $old = get_head();
922 my ($tip,$breakwater,$last_anchor) = walk $old;
923 update_head_postlaunder $old, $tip, 'launder';
924 printf "# breakwater tip\n%s\n", $breakwater;
925 printf "# working tip\n%s\n", $tip;
926 printf "# last anchor\n%s\n", $last_anchor;
929 sub defaultcmd_rebase () {
930 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
931 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
932 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
936 die if ($ARGV[0]//'') =~ m/^-/;
937 badusage "too many arguments to analyse" if @ARGV>1;
940 $old = git_rev_parse $old;
942 $old = git_rev_parse 'HEAD';
944 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
945 STDOUT->error and die $!;
948 sub ffq_prev_branchinfo () {
949 # => ('status', "message", [$current, $ffq_prev, $gdrlast])
951 # branch message is undef
952 # weird-symref } no $current,
953 # notbranch } no $ffq_prev
954 my $current = git_get_symref();
955 return ('detached', 'detached HEAD') unless defined $current;
956 return ('weird-symref', 'HEAD symref is not to refs/')
957 unless $current =~ m{^refs/};
958 my $ffq_prev = "refs/$ffq_refprefix/$'";
959 my $gdrlast = "refs/$gdrlast_refprefix/$'";
960 printdebug "ffq_prev_branchinfo branch current $current\n";
961 return ('branch', undef, $current, $ffq_prev, $gdrlast);
964 sub record_ffq_prev_deferred () {
965 # => ('status', "message")
967 # deferred message is undef
972 # if not ff from some branch we should be ff from, is an snag
973 # if "deferred", will have added something about that to
974 # @deferred_update_messages, and also maybe printed (already)
975 # some messages about ff checks
976 my ($status, $message, $current, $ffq_prev, $gdrlast)
977 = ffq_prev_branchinfo();
978 return ($status, $message) unless $status eq 'branch';
980 my $currentval = get_head();
982 my $exists = git_get_ref $ffq_prev;
983 return ('exists',"$ffq_prev already exists") if $exists;
985 return ('not-branch', 'HEAD symref is not to refs/heads/')
986 unless $current =~ m{^refs/heads/};
989 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
992 printdebug "ffq check_specs @check_specs\n";
995 my ($lrref, $desc) = @_;
996 printdebug "ffq might check $lrref ($desc)\n";
998 for my $chk (@check_specs) {
1000 $invert = $glob =~ s{^[!^]}{};
1001 last if fnmatch $glob, $lrref;
1004 my $lrval = git_get_ref $lrref;
1005 return unless defined $lrval;
1007 if (is_fast_fwd $lrval, $currentval) {
1008 print "OK, you are ahead of $lrref\n" or die $!;
1009 $checked{$lrref} = 1;
1010 } elsif (is_fast_fwd $currentval, $lrval) {
1011 $checked{$lrref} = -1;
1012 snag 'behind', "you are behind $lrref, divergence risk";
1014 $checked{$lrref} = -1;
1015 snag 'diverged', "you have diverged from $lrref";
1019 my $merge = cfg "branch.$branch.merge",1;
1020 if (defined $merge and $merge =~ m{^refs/heads/}) {
1022 printdebug "ffq merge $rhs\n";
1023 my $check_remote = sub {
1024 my ($remote, $desc) = @_;
1025 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1026 return unless defined $remote;
1027 $check->("refs/remotes/$remote/$rhs", $desc);
1029 $check_remote->((scalar cfg "branch.$branch.remote",1),
1030 'remote fetch/merge branch');
1031 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1032 (scalar cfg "branch.$branch.pushDefault",1),
1033 'remote push branch');
1035 if ($branch =~ m{^dgit/}) {
1036 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1037 } elsif ($branch =~ m{^master$}) {
1038 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1043 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1044 push @deferred_updates, "delete $gdrlast";
1045 push @deferred_update_messages, "Recorded current head for preservation";
1046 return ('deferred', undef);
1049 sub record_ffq_auto () {
1050 my ($status, $message) = record_ffq_prev_deferred();
1051 if ($status eq 'deferred' || $status eq 'exists') {
1053 snag $status, "could not record ffq-prev: $message";
1058 sub ffq_prev_info () {
1059 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1060 my ($status, $message, $current, $ffq_prev, $gdrlast)
1061 = ffq_prev_branchinfo();
1062 if ($status ne 'branch') {
1063 snag $status, "could not check ffq-prev: $message";
1066 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1067 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1070 sub stitch ($$$$$) {
1071 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1073 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1075 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1076 my $differs = get_differs $old_head, $ffq_prev_commitish;
1077 unless ($differs & ~D_PAT_ADD) {
1078 # ffq-prev is ahead of us, and the only tree changes it has
1079 # are possibly addition of things in debian/patches/.
1080 # Just wind forwards rather than making a pointless pseudomerge.
1081 push @deferred_updates,
1082 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1083 update_head_checkout $old_head, $ffq_prev_commitish,
1084 "stitch (fast forward)";
1089 # We make pseudomerges with L as the contributing parent.
1090 # This makes git rev-list --first-parent work properly.
1091 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1092 'Declare fast forward / record previous work',
1093 "[git-debrebase pseudomerge: $prose]",
1095 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1096 update_head $old_head, $new_head, "stitch: $prose";
1099 sub do_stitch ($;$) {
1100 my ($prose, $unclean) = @_;
1102 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1103 if (!$ffq_prev_commitish) {
1104 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1107 my $dangling_head = get_head();
1109 keycommits $dangling_head, $unclean,$unclean,$unclean;
1112 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1115 sub cmd_new_upstream_v0 () {
1116 # automatically and unconditionally launders before rebasing
1117 # if rebase --abort is used, laundering has still been done
1121 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1123 # parse args - low commitment
1124 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1125 my $new_upstream_version = $new_version->version();
1127 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1132 my ($n, @x) = @_; # may be ''
1133 my $pc = $pieces{$n} //= {
1135 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1137 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1142 my $newpiece = sub {
1143 my ($n, @x) = @_; # may be ''
1144 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1145 push @newpieces, $pc;
1150 New => $new_upstream,
1152 while (@ARGV && $ARGV[0] !~ m{^-}) {
1153 my $n = shift @ARGV;
1155 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1156 unless @ARGV && $ARGV[0] !~ m{^-};
1158 my $c = git_rev_parse shift @ARGV;
1159 die unless $n =~ m/^$extra_orig_namepart_re$/;
1160 $newpiece->($n, New => $c);
1163 # now we need to investigate the branch this generates the
1164 # laundered version but we don't switch to it yet
1165 my $old_head = get_head();
1166 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1168 my $old_bw_cl = classify $old_bw;
1169 my $old_anchor_cl = classify $old_anchor;
1171 if (!$old_anchor_cl->{OrigParents}) {
1172 snag 'anchor-treated',
1173 'old anchor is recognised due to --anchor, cannot check upstream';
1175 $old_upstream = parsecommit
1176 $old_anchor_cl->{OrigParents}[0]{CommitId};
1177 $piece->('', Old => $old_upstream->{CommitId});
1180 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1181 if ($old_upstream->{Msg} =~
1182 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1184 my @oldpieces = ('', split / /, $1);
1185 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1186 foreach my $i (0..$#oldpieces) {
1187 my $n = $oldpieces[$i];
1188 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1191 snag 'upstream-confusing',
1192 "previous upstream $old_upstream->{CommitId} is from".
1193 " git-debrebase but not an \`upstream-combine' commit";
1197 foreach my $pc (values %pieces) {
1198 if (!$old_upstream) {
1199 # we have complained already
1200 } elsif (!$pc->{Old}) {
1201 snag 'upstream-new-piece',
1202 "introducing upstream piece \`$pc->{Name}'";
1203 } elsif (!$pc->{New}) {
1204 snag 'upstream-rm-piece',
1205 "dropping upstream piece \`$pc->{Name}'";
1206 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1207 snag 'upstream-not-ff',
1208 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1212 printdebug "%pieces = ", (dd \%pieces), "\n";
1213 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1221 my @upstream_merge_parents;
1224 push @upstream_merge_parents, $old_upstream->{CommitId};
1227 foreach my $pc (@newpieces) { # always has '' first
1229 read_tree_subdir $pc->{Name}, $pc->{New};
1231 runcmd @git, qw(read-tree), $pc->{New};
1233 push @upstream_merge_parents, $pc->{New};
1236 # index now contains the new upstream
1238 if (@newpieces > 1) {
1239 # need to make the upstream subtree merge commit
1240 $new_upstream = make_commit \@upstream_merge_parents,
1241 [ "Combine upstreams for $new_upstream_version",
1242 ("[git-debrebase upstream-combine . ".
1243 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1248 # $new_upstream is either the single upstream commit, or the
1249 # combined commit we just made. Either way it will be the
1250 # "upstream" parent of the anchor merge.
1252 read_tree_subdir 'debian', "$old_bw:debian";
1254 # index now contains the anchor merge contents
1255 $new_bw = make_commit [ $old_bw, $new_upstream ],
1256 [ "Update to upstream $new_upstream_version",
1257 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1260 my $clogsignoff = cmdoutput qw(git show),
1261 '--pretty=format:%an <%ae> %aD',
1264 # Now we have to add a changelog stanza so the Debian version
1266 die if unlink "debian";
1267 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1268 unlink "debian/changelog" or $!==ENOENT or die $!;
1269 mkdir "debian" or die $!;
1270 open CN, ">", "debian/changelog" or die $!;
1271 my $oldclog = git_cat_file ":debian/changelog";
1272 $oldclog =~ m/^($package_re) \(\S+\) / or
1273 fail "cannot parse old changelog to get package name";
1275 print CN <<END, $oldclog or die $!;
1276 $p ($new_version) UNRELEASED; urgency=medium
1278 * Update to new upstream version $new_upstream_version.
1284 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1286 # Now we have the final new breakwater branch in the index
1287 $new_bw = make_commit [ $new_bw ],
1288 [ "Update changelog for new upstream $new_upstream_version",
1289 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1293 # we have constructed the new breakwater. we now need to commit to
1294 # the laundering output, because git-rebase can't easily be made
1295 # to make a replay list which is based on some other branch
1297 update_head_postlaunder $old_head, $old_laundered_tip,
1298 'launder for new upstream';
1300 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1302 # now it's for the user to sort out
1305 sub cmd_record_ffq_prev () {
1306 badusage "no arguments allowed" if @ARGV;
1307 my ($status, $msg) = record_ffq_prev_deferred();
1308 if ($status eq 'exists' && $opt_noop_ok) {
1309 print "Previous head already recorded\n" or die $!;
1310 } elsif ($status eq 'deferred') {
1311 run_deferred_updates 'record-ffq-prev';
1313 fail "Could not preserve: $msg";
1318 badusage "no arguments allowed" if @ARGV;
1319 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1320 print "$bw\n" or die $!;
1323 sub cmd_breakwater () {
1324 badusage "no arguments allowed" if @ARGV;
1325 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1326 print "$bw\n" or die $!;
1330 my $prose = 'stitch';
1331 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1332 badusage "no arguments allowed" if @ARGV;
1333 do_stitch $prose, 0;
1335 sub cmd_prepush () { cmd_stitch(); }
1338 badusage "no arguments allowed" if @ARGV;
1339 do_launder_head 'launder for git-debrebase quick';
1343 sub cmd_conclude () {
1344 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1345 if (!$ffq_prev_commitish) {
1346 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1349 my $dangling_head = get_head();
1351 badusage "no arguments allowed" if @ARGV;
1352 do_launder_head 'launder for git-debrebase quick';
1356 sub make_patches_staged ($) {
1358 # Produces the patches that would result from $head if it were
1360 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1363 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1364 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1365 runcmd qw(gbp pq export);
1366 runcmd @git, qw(add debian/patches);
1370 sub make_patches ($) {
1372 keycommits $head, 0, \&snag;
1373 make_patches_staged $head;
1376 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1377 runcmd @git, qw(read-tree), $head;
1378 read_tree_subdir 'debian/patches', $ptree;
1379 $out = make_commit [$head], [
1380 'Commit patch queue (exported by git-debrebase)',
1381 '[git-debrebase: export and commit patches]',
1384 my $d = get_differs $head, $out;
1386 return undef; # nothing to do
1387 } elsif ($d == D_PAT_ADD) {
1390 fail "Patch export produced patch amendments".
1391 " (abandoned output commit $out).".
1392 " Try laundering first.";
1396 sub cmd_make_patches () {
1397 badusage "no arguments allowed" if @ARGV;
1398 my $old_head = get_head();
1399 my $new = make_patches $old_head;
1402 fail "No (more) patches to export." unless $opt_noop_ok;
1405 update_head_checkout $old_head, $new, 'make-patches';
1408 sub cmd_convert_from_gbp () {
1409 badusage "needs 1 optional argument, the upstream git rev"
1411 my ($upstream_spec) = @ARGV;
1412 $upstream_spec //= 'refs/heads/upstream';
1413 my $upstream = git_rev_parse $upstream_spec;
1414 my $old_head = get_head();
1416 my $upsdiff = get_differs $upstream, $old_head;
1417 if ($upsdiff & D_UPS) {
1418 runcmd @git, qw(--no-pager diff),
1419 $upstream, $old_head,
1420 qw( -- :!/debian :/);
1421 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1424 if (!is_fast_fwd $upstream, $old_head) {
1425 snag 'upstream-not-ancestor',
1426 "upstream ($upstream) is not an ancestor of HEAD";
1428 my $wrong = cmdoutput
1429 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1430 qw(-- :/ :!/debian));
1431 if (length $wrong) {
1432 snag 'unexpected-upstream-changes',
1433 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1434 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1438 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1439 snag 'upstream-has-debian',
1440 "upstream ($upstream) contains debian/ directory";
1449 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1450 # make a branch out of the patch queue - we'll want this in a mo
1451 runcmd qw(gbp pq import);
1452 # strip the patches out
1453 runcmd @git, qw(checkout -q gdr-internal~0);
1454 rm_subdir_cached 'debian/patches';
1455 $work = make_commit ['HEAD'], [
1456 'git-debrebase convert-from-gbp: drop patches from tree',
1457 'Delete debian/patches, as part of converting to git-debrebase format.',
1458 '[git-debrebase convert-from-gbp: drop patches from tree]'
1460 # make the anchor merge
1461 # the tree is already exactly right
1462 $work = make_commit [$work, $upstream], [
1463 'git-debrebase import: declare upstream',
1464 'First breakwater merge.',
1465 '[git-debrebase anchor: declare upstream]'
1468 # rebase the patch queue onto the new breakwater
1469 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1470 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1471 $work = git_rev_parse 'HEAD';
1474 update_head_checkout $old_head, $work, 'convert-from-gbp';
1477 sub cmd_convert_to_gbp () {
1478 badusage "no arguments allowed" if @ARGV;
1479 my $head = get_head();
1480 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1481 keycommits $head, 0;
1483 make_patches_staged $head;
1485 $out = make_commit ['HEAD'], [
1486 'Commit patch queue (converted from git-debrebase format)',
1487 '[git-debrebase convert-to-gbp: commit patches]',
1491 push @deferred_updates, "delete $ffq";
1492 push @deferred_updates, "delete $gdrlast";
1495 update_head_checkout $head, $out, "convert to gbp (v0)";
1496 print <<END or die $!;
1497 git-debrebase: converted to git-buildpackage branch format
1498 git-debrebase: WARNING: do not now run "git-debrebase" any more
1499 git-debrebase: WARNING: doing so would drop all upstream patches!
1503 sub cmd_downstream_rebase_launder_v0 () {
1504 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1506 $base = git_rev_parse $base;
1507 my $old_head = get_head();
1508 my $current = $old_head;
1511 if ($current eq $base) {
1512 $topmost_keep //= $current;
1513 print " $current BASE stop\n";
1516 my $cl = classify $current;
1517 print " $current $cl->{Type}";
1519 my $p0 = $cl->{Parents}[0]{CommitId};
1521 if ($cl->{Type} eq 'Pseudomerge') {
1522 print " ^".($cl->{Contributor}{Ix}+1);
1523 $next = $cl->{Contributor}{CommitId};
1524 } elsif ($cl->{Type} eq 'AddPatches' or
1525 $cl->{Type} eq 'Changelog') {
1535 $topmost_keep //= $current;
1537 die "to-be stripped changes not on top of the branch\n"
1542 if ($topmost_keep eq $old_head) {
1543 print "unchanged\n";
1545 print "updating to $topmost_keep\n";
1546 update_head_checkout
1547 $old_head, $topmost_keep,
1548 'downstream-rebase-launder-v0';
1552 GetOptions("D+" => \$debuglevel,
1553 'noop-ok', => \$opt_noop_ok,
1554 'f=s' => \@snag_force_opts,
1555 'anchor=s' => \@opt_anchors,
1558 my ($opt,$val) = @_;
1559 badusage "git-debrebase: no cuddling to -i for git-rebase"
1561 die if $opt_defaultcmd_interactive; # should not happen
1562 $opt_defaultcmd_interactive = [ qw(-i) ];
1563 # This access to @ARGV is excessive familiarity with
1564 # Getopt::Long, but there isn't another sensible
1565 # approach. '-i=s{0,}' does not work with bundling.
1566 push @$opt_defaultcmd_interactive, @ARGV;
1568 }) or die badusage "bad options\n";
1569 initdebug('git-debrebase ');
1570 enabledebug if $debuglevel;
1572 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1573 chdir $toplevel or die "chdir $toplevel: $!";
1575 $rd = fresh_playground "$playprefix/misc";
1577 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1579 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1580 defaultcmd_rebase();
1582 my $cmd = shift @ARGV;
1585 $cmdfn = ${*::}{"cmd_$cmdfn"};
1587 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";