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/>.
23 use Debian::Dgit qw(:DEFAULT :playground);
30 use Getopt::Long qw(:config posix_default gnu_compat bundling);
32 use File::FnMatch qw(:fnmatch);
34 our ($opt_force, $opt_noop_ok, @opt_anchors);
35 our ($opt_defaultcmd_interactive);
37 our $us = qw(git-debrebase);
41 print STDERR "bad usage: $m\n";
46 my ($k, $optional) = @_;
48 my @cmd = qw(git config -z);
49 push @cmd, qw(--get-all) if wantarray;
51 my $out = cmdoutput_errok @cmd;
53 fail "missing required git config $k" unless $optional;
56 my @l = split /\0/, $out;
57 return wantarray ? @l : $l[0];
64 my $dd = new Data::Dumper [ $v ];
65 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
71 my $data = (git_cat_file $objid, 'commit');
72 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
76 sub D_UPS () { 0x02; } # upstream files
77 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
78 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
79 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
80 sub D_DEB_OTH () { 0x20; } # debian/changelog
81 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
83 our $playprefix = 'debrebase';
92 my $r = eval { $sub->(); };
93 { local $@; changedir $maindir; }
97 sub fresh_workarea () {
98 $workarea = fresh_playground "$playprefix/work";
99 in_workarea sub { playtree_setup };
105 our @deferred_updates;
106 our @deferred_update_messages;
108 sub run_deferred_updates ($) {
111 confess 'dangerous internal error' if
112 !$snags_checked || $snags_tripped || $snags_forced;
114 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
115 debugcmd '>|', @upd_cmd;
116 open U, "|-", @upd_cmd or die $!;
117 foreach (@deferred_updates) {
118 printdebug ">= ", $_, "\n";
119 print U $_, "\n" or die $!;
122 close U or failedcmd @upd_cmd;
124 print $_, "\n" foreach @deferred_update_messages;
126 @deferred_updates = ();
127 @deferred_update_messages = ();
130 sub get_differs ($$) {
132 # This resembles quiltify_trees_differ, in dgit, a bit.
133 # But we don't care about modes, or dpkg-source-unrepresentable
134 # changes, and we don't need the plethora of different modes.
135 # Conversely we need to distinguish different kinds of changes to
136 # debian/ and debian/patches/.
141 my ($opts, $limits, $fn) = @_;
142 my @cmd = (@git, qw(diff-tree -z --no-renames));
144 push @cmd, "$_:" foreach $x, $y;
145 push @cmd, '--', @$limits;
146 my $diffs = cmdoutput @cmd;
147 foreach (split /\0/, $diffs) { $fn->(); }
150 $rundiff->([qw(--name-only)], [], sub {
151 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
154 if ($differs & DS_DEB) {
156 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
158 m{^debian/patches/} ? D_PAT_OTH :
159 $_ eq 'debian/changelog' ? D_DEB_CLOG :
162 die "mysterious debian changes $x..$y"
163 unless $differs & (D_PAT_OTH|DS_DEB);
166 if ($differs & D_PAT_OTH) {
168 $differs &= ~D_PAT_OTH;
170 $differs |= D_PAT_OTH;
171 no warnings qw(exiting); last;
173 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
174 no warnings qw(exiting);
175 if (!defined $mode) {
178 die unless s{^debian/patches/}{};
180 if ($mode eq 'A' && !m/\.series$/s) {
182 } elsif ($mode eq 'M' && $_ eq 'series') {
183 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
184 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
185 chomp $x_s; $x_s .= "\n";
186 $ok = $x_s eq substr($y_s, 0, length $x_s);
191 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
193 die "mysterious debian/patches changes $x..$y"
194 unless $differs & (D_PAT_ADD|D_PAT_OTH);
197 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
202 sub commit_pr_info ($) {
204 return Data::Dumper->dump([$r], [qw(commit)]);
207 sub calculate_committer_authline () {
208 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
209 'DUMMY COMMIT (git-debrebase)', "HEAD:";
210 my ($h,$m) = get_commit $c;
211 $h =~ m/^committer .*$/m or confess "($h) ?";
215 sub rm_subdir_cached ($) {
217 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
220 sub read_tree_subdir ($$) {
221 my ($subdir, $new_tree_object) = @_;
222 rm_subdir_cached $subdir;
223 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
226 sub make_commit ($$) {
227 my ($parents, $message_paras) = @_;
228 my $tree = cmdoutput @git, qw(write-tree);
229 my @cmd = (@git, qw(commit-tree), $tree);
230 push @cmd, qw(-p), $_ foreach @$parents;
231 push @cmd, qw(-m), $_ foreach @$message_paras;
232 return cmdoutput @cmd;
235 our @snag_force_opts;
238 if (grep { $_ eq $tag } @snag_force_opts) {
240 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
243 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
247 sub snags_maybe_bail () {
251 "%s: snags: %d overriden by individual -f options\n",
255 if ($snags_tripped) {
258 "%s: snags: %d overriden by global --force\n",
263 "%s: snags: %d blockers (you could -f<tag>, or --force)",
269 return $snags_forced || $snags_tripped;
272 # classify returns an info hash like this
274 # Hdr => # commit headers, including 1 final newline
275 # Msg => # commit message (so one newline is dropped)
277 # Type => (see below)
279 # Ix => $index # ie 0, 1, 2, ...
281 # Differs => return value from get_differs
283 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
285 # NewMsg => # commit message, but with any [dgit import ...] edited
286 # # to say "[was: ...]"
296 # has additional entres in classification result
297 # Overwritten = [ subset of Parents ]
298 # Contributor = $the_remaining_Parent
300 # DgitImportUnpatched
301 # has additional entry in classification result
302 # OrigParents = [ subset of Parents ]
305 # has additional entry in classification result
306 # OrigParents = [ subset of Parents ] # singleton list
313 # has additional entry in classification result
316 sub parsecommit ($;$) {
317 my ($objid, $p_ref) = @_;
318 # => hash with CommitId Hdr Msg Tree Parents
319 # Parents entries have only Ix CommitId
320 # $p_ref, if provided, must be [] and is used as a base for Parents
325 my ($h,$m) = get_commit $objid;
327 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
328 my (@ph) = $h =~ m/^parent (\w+)$/mg;
338 foreach my $ph (@ph) {
340 Ix => scalar @$p_ref,
352 my $r = parsecommit($objid, \@p);
356 $p->{Differs} = (get_differs $p->{CommitId}, $t),
359 printdebug "classify $objid \$t=$t \@p",
360 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
364 my ($type, @rest) = @_;
365 $r = { %$r, Type => $type, @rest };
367 printdebug " = $type ".(dd $r)."\n";
373 $r = { %$r, Type => qw(Unknown), Why => $why };
374 printdebug " ** Unknown\n";
378 if (grep { $_ eq $objid } @opt_anchors) {
379 return $classify->('TreatAsAnchor');
382 my @identical = grep { !$_->{Differs} } @p;
383 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
384 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
386 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
387 # multi-orig upstreams are represented with an anchor merge
388 # from a single upstream commit which combines the orig tarballs
390 # Every anchor tagged this way must be a merge.
391 # We are relying on the
392 # [git-debrebase anchor: ...]
393 # commit message annotation in "declare" anchor merges (which
394 # do not have any upstream changes), to distinguish those
395 # anchor merges from ordinary pseudomerges (which we might
396 # just try to strip).
398 # However, the user is going to be doing git-rebase a lot. We
399 # really don't want them to rewrite an anchor commit.
400 # git-rebase trips up on merges, so that is a useful safety
403 # BreakwaterStart commits are also anchors in the terminology
404 # of git-debrebase(5), but they are untagged (and always
405 # manually generated).
407 # We cannot not tolerate any tagged linear commit (ie,
408 # BreakwaterStart commits tagged `[anchor:') because such a
409 # thing could result from an erroneous linearising raw git
410 # rebase of a merge anchor. That would represent a corruption
411 # of the branch. and we want to detect and reject the results
412 # of such corruption before it makes it out anywhere. If we
413 # reject it here then we avoid making the pseudomerge which
414 # would be needed to push it.
416 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
417 @p == 2 or return $badanchor->("has other than two parents");
418 $haspatches and return $badanchor->("contains debian/patches");
420 # How to decide about l/r ordering of anchors ? git
421 # --topo-order prefers to expand 2nd parent first. There's
422 # already an easy rune to look for debian/ history anyway (git log
423 # debian/) so debian breakwater branch should be 1st parent; that
424 # way also there's also an easy rune to look for the upstream
425 # patches (--topo-order).
427 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
428 $p[1]{Differs} & ~DS_DEB and
429 $badanchor->("upstream files differ from left parent");
430 $p[0]{Differs} & ~D_UPS and
431 $badanchor->("debian/ differs from right parent");
433 return $classify->(qw(Anchor),
434 OrigParents => [ $p[1] ]);
438 my $d = $r->{Parents}[0]{Differs};
439 if ($d == D_PAT_ADD) {
440 return $classify->(qw(AddPatches));
441 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
442 return $unknown->("edits debian/patches");
443 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
444 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
446 if ($d == D_DEB_CLOG) {
447 return $classify->(qw(Changelog));
449 return $classify->(qw(Packaging));
451 } elsif ($ty eq 'missing') {
452 return $classify->(qw(BreakwaterStart));
454 return $unknown->("parent's debian is not a directory");
456 } elsif ($d == D_UPS) {
457 return $classify->(qw(Upstream));
458 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
459 return $classify->(qw(Mixed));
461 return $unknown->("no changes");
463 confess "internal error $objid ?";
467 return $unknown->("origin commit");
470 if (@p == 2 && @identical == 1) {
471 my @overwritten = grep { $_->{Differs} } @p;
472 confess "internal error $objid ?" unless @overwritten==1;
473 return $classify->(qw(Pseudomerge),
474 Overwritten => [ $overwritten[0] ],
475 Contributor => $identical[0]);
477 if (@p == 2 && @identical == 2) {
479 my ($ph,$pm) = get_commit $_[0]{CommitId};
480 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
484 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
485 if ($order > 0) { # newer first
486 } elsif ($order < 0) {
487 @bytime = reverse @bytime;
489 # same age, default to order made by -s ours
490 # that is, commit was made by someone who preferred L
492 return $classify->(qw(Pseudomerge),
493 SubType => qw(Ambiguous),
494 Contributor => $bytime[0],
495 Overwritten => [ $bytime[1] ]);
498 my ($p_h, $p_m) = get_commit $p->{CommitId};
499 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
500 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
502 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
504 if (!(grep { !$_->{IsOrigin} } @p) and
505 (@orig_ps >= @p - 1) and
506 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
508 return $classify->(qw(DgitImportUnpatched),
509 OrigParents => \@orig_ps);
512 return $unknown->("complex merge");
515 sub keycommits ($;$$$) {
516 my ($head, $furniture, $unclean, $trouble) = @_;
517 # => ($anchor, $breakwater)
519 # $unclean->("unclean-$tagsfx", $msg)
520 # $furniture->("unclean-$tagsfx", $msg)
521 # $dgitimport->("unclean-$tagsfx", $msg)
522 # is callled for each situation or commit that
523 # wouldn't be found in a laundered branch
524 # $furniture is for furniture commits such as might be found on an
525 # interchange branch (pseudomerge, d/patches, changelog)
526 # $trouble is for things whnich prevent the return of
527 # anchor and breakwater information; if that is ignored,
528 # then keycommits returns (undef, undef) instead.
530 # If a callback is undef, fail is called instead.
531 # If a callback is defined but false, the situation is ignored.
533 # no warnings qw(exiting); last;
534 # if the answer is no longer wanted.
536 my ($anchor, $breakwater);
539 my ($cb, $tagsfx, $why) = @_;
540 my $m = "branch needs laundering (run git-debrebase): $why";
541 fail $m unless defined $cb;
543 $cb->("unclean-$tagsfx", $why);
546 my $cl = classify $head;
547 my $ty = $cl->{Type};
548 if ($ty eq 'Packaging') {
549 $breakwater //= $clogonly;
550 $breakwater //= $head;
551 } elsif ($ty eq 'Changelog') {
552 # this is going to count as the tip of the breakwater
553 # only if it has no upstream stuff before it
555 } elsif ($ty eq 'Anchor' or
556 $ty eq 'TreatAsAnchor' or
557 $ty eq 'BreakwaterStart') {
559 $breakwater //= $clogonly;
560 $breakwater //= $head;
562 } elsif ($ty eq 'Upstream') {
563 $x->($unclean, 'ordering',
564 "packaging change ($breakwater) follows upstream change (eg $head)")
565 if defined $breakwater;
568 } elsif ($ty eq 'Mixed') {
569 $x->($unclean, 'mixed',
570 "found mixed upstream/packaging commit ($head)");
573 } elsif ($ty eq 'Pseudomerge' or
574 $ty eq 'AddPatches') {
575 $x->($furniture, (lc $ty),
576 "found interchange bureaucracy commit ($ty, $head)");
577 } elsif ($ty eq 'DgitImportUnpatched') {
578 $x->($trouble, 'dgitimport',
579 "found dgit dsc import ($head)");
582 no warnings qw(exiting);
585 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
587 $head = $cl->{Parents}[0]{CommitId};
589 return ($anchor, $breakwater);
595 $nogenerate,$report) = @_;
596 # => ($tip, $breakwater_tip, $last_anchor)
597 # (or nothing, if $nogenerate)
599 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
601 # go through commits backwards
602 # we generate two lists of commits to apply:
603 # breakwater branch and upstream patches
604 my (@brw_cl, @upp_cl, @processed);
611 my ($prose, $info) = @_;
615 $ms .= "\n\n[git-debrebase$info: $prose]\n";
618 my $rewrite_from_here = sub {
620 my $sp_cl = { SpecialMethod => 'StartRewrite' };
622 push @processed, $sp_cl;
627 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
630 return unless $report;
631 print $report $prdelim, @_;
635 my $bomb = sub { # usage: return $bomb->();
636 print $report " Unprocessable" if $report;
637 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
640 return (undef,undef);
642 die "commit $cur: Cannot cope with this commit (d.".
643 (join ' ', map { sprintf "%#x", $_->{Differs} }
644 @{ $cl->{Parents} }).
645 (defined $cl->{Why} ? "; $cl->{Why}": '').
652 my $build_start = sub {
653 my ($msg, $parent) = @_;
656 no warnings qw(exiting); last;
663 my $ty = $cl->{Type};
664 my $st = $cl->{SubType};
665 $prline->("$cl->{CommitId} $cl->{Type}");
666 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
667 push @processed, $cl;
668 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
669 if ($ty eq 'AddPatches') {
671 $rewrite_from_here->(\@upp_cl);
673 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
677 } elsif ($ty eq 'BreakwaterStart') {
679 $build_start->('FirstPackaging', $cur);
680 } elsif ($ty eq 'Upstream') {
684 } elsif ($ty eq 'Mixed') {
687 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
690 $queue->(\@brw_cl, "debian");
691 $queue->(\@upp_cl, "upstream");
692 $rewrite_from_here->(\@brw_cl);
695 } elsif ($ty eq 'Pseudomerge') {
696 my $contrib = $cl->{Contributor}{CommitId};
697 print $report " Contributor=$contrib" if $report;
698 push @pseudomerges, $cl;
699 $rewrite_from_here->(\@upp_cl);
702 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
704 $build_start->("Anchor", $cur);
705 } elsif ($ty eq 'DgitImportUnpatched') {
706 my $pm = $pseudomerges[-1];
708 # To an extent, this is heuristic. Imports don't have
709 # a useful history of the debian/ branch. We assume
710 # that the first pseudomerge after an import has a
711 # useful history of debian/, and ignore the histories
712 # from later pseudomerges. Often the first pseudomerge
713 # will be the dgit import of the upload to the actual
714 # suite intended by the non-dgit NMUer, and later
715 # pseudomerges may represent in-archive copies.
716 my $ovwrs = $pm->{Overwritten};
717 printf $report " PM=%s \@Overwr:%d",
718 $pm->{CommitId}, (scalar @$ovwrs)
721 printdebug "*** WALK BOMB DgitImportUnpatched\n";
724 my $ovwr = $ovwrs->[0]{CommitId};
725 printf $report " Overwr=%s", $ovwr if $report;
726 # This import has a tree which is just like a
727 # breakwater tree, but it has the wrong history. It
728 # ought to have the previous breakwater (which the
729 # pseudomerge overwrote) as an ancestor. That will
730 # make the history of the debian/ files correct. As
731 # for the upstream version: either it's the same as
732 # was ovewritten (ie, same as the previous
733 # breakwater), in which case that history is precisely
734 # right; or, otherwise, it was a non-gitish upload of a
735 # new upstream version. We can tell these apart by
736 # looking at the tree of the supposed upstream.
739 SpecialMethod => 'DgitImportDebianUpdate',
740 $xmsg->("convert dgit import: debian changes")
743 SpecialMethod => 'DgitImportUpstreamUpdate',
744 $xmsg->("convert dgit import: upstream update",
747 $prline->(" Import");
748 $rewrite_from_here->(\@brw_cl);
749 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
753 # Everything is from this import. This kind of import
754 # is already in valid breakwater format, with the
755 # patches as commits.
756 printf $report " NoPM" if $report;
757 # last thing we processed will have been the first patch,
758 # if there is one; which is fine, so no need to rewrite
759 # on account of this import
760 $build_start->("ImportOrigin", $cur);
764 printdebug "*** WALK BOMB unrecognised\n";
770 printdebug "*** WALK prep done cur=$cur".
771 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
773 return if $nogenerate;
775 # Now we build it back up again
781 my $read_tree_debian = sub {
783 read_tree_subdir 'debian', "$treeish:debian";
784 rm_subdir_cached 'debian/patches';
786 my $read_tree_upstream = sub {
788 runcmd @git, qw(read-tree), $treeish;
789 $read_tree_debian->($build);
792 $#upp_cl = $upp_limit if defined $upp_limit;
794 my $committer_authline = calculate_committer_authline();
796 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
798 confess "internal error" unless $build eq (pop @processed)->{CommitId};
801 mkdir $rd or $!==EEXIST or die $!;
803 runcmd @git, qw(read-tree), $build;
804 foreach my $cl (qw(Debian), (reverse @brw_cl),
805 { SpecialMethod => 'RecordBreakwaterTip' },
806 qw(Upstream), (reverse @upp_cl)) {
808 $current_method = $cl;
811 my $method = $cl->{SpecialMethod} // $current_method;
812 my @parents = ($build);
813 my $cltree = $cl->{CommitId};
814 printdebug "WALK BUILD ".($cltree//'undef').
815 " $method (rewriting=$rewriting)\n";
816 if ($method eq 'Debian') {
817 $read_tree_debian->($cltree);
818 } elsif ($method eq 'Upstream') {
819 $read_tree_upstream->($cltree);
820 } elsif ($method eq 'StartRewrite') {
823 } elsif ($method eq 'RecordBreakwaterTip') {
824 $breakwater = $build;
826 } elsif ($method eq 'DgitImportDebianUpdate') {
827 $read_tree_debian->($cltree);
828 } elsif ($method eq 'DgitImportUpstreamUpdate') {
829 confess unless $rewriting;
830 my $differs = (get_differs $build, $cltree);
831 next unless $differs & D_UPS;
832 $read_tree_upstream->($cltree);
833 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
838 my $procd = (pop @processed) // 'UNDEF';
841 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
844 my $newtree = cmdoutput @git, qw(write-tree);
846 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
847 $ch =~ s{^parent .*\n}{}mg;
848 $ch =~ s{(?=^author)}{
849 join '', map { "parent $_\n" } @parents
850 }me or confess "$ch ?";
852 $ch =~ s{^committer .*$}{$committer_authline}m
855 my $cf = "$rd/m$rewriting";
856 open CD, ">", $cf or die $!;
857 print CD $ch, "\n", $cl->{Msg} or die $!;
859 my @cmd = (@git, qw(hash-object));
860 push @cmd, qw(-w) if $rewriting;
861 push @cmd, qw(-t commit), $cf;
862 my $newcommit = cmdoutput @cmd;
863 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
865 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
871 my $final_check = get_differs $build, $input;
872 die sprintf "internal error %#x %s %s", $final_check, $build, $input
873 if $final_check & ~D_PAT_ADD;
875 my @r = ($build, $breakwater, $last_anchor);
876 printdebug "*** WALK RETURN @r\n";
881 git_check_unmodified();
882 return git_rev_parse qw(HEAD);
885 sub update_head ($$$) {
886 my ($old, $new, $mrest) = @_;
887 push @deferred_updates, "update HEAD $new $old";
888 run_deferred_updates $mrest;
891 sub update_head_checkout ($$$) {
892 my ($old, $new, $mrest) = @_;
893 update_head $old, $new, $mrest;
894 runcmd @git, qw(reset --hard);
897 sub update_head_postlaunder ($$$) {
898 my ($old, $tip, $reflogmsg) = @_;
899 return if $tip eq $old;
900 print "git-debrebase: laundered (head was $old)\n";
901 update_head $old, $tip, $reflogmsg;
902 # no tree changes except debian/patches
903 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
906 sub do_launder_head ($) {
907 my ($reflogmsg) = @_;
908 my $old = get_head();
910 my ($tip,$breakwater) = walk $old;
912 update_head_postlaunder $old, $tip, $reflogmsg;
913 return ($tip,$breakwater);
916 sub cmd_launder_v0 () {
917 badusage "no arguments to launder-v0 allowed" if @ARGV;
918 my $old = get_head();
919 my ($tip,$breakwater,$last_anchor) = walk $old;
920 update_head_postlaunder $old, $tip, 'launder';
921 printf "# breakwater tip\n%s\n", $breakwater;
922 printf "# working tip\n%s\n", $tip;
923 printf "# last anchor\n%s\n", $last_anchor;
926 sub defaultcmd_rebase () {
927 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
928 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
929 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
933 die if ($ARGV[0]//'') =~ m/^-/;
934 badusage "too many arguments to analyse" if @ARGV>1;
937 $old = git_rev_parse $old;
939 $old = git_rev_parse 'HEAD';
941 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
942 STDOUT->error and die $!;
945 sub ffq_prev_branchinfo () {
946 # => ('status', "message", [$current, $ffq_prev, $gdrlast])
948 # branch message is undef
949 # weird-symref } no $current,
950 # notbranch } no $ffq_prev
951 my $current = git_get_symref();
952 return ('detached', 'detached HEAD') unless defined $current;
953 return ('weird-symref', 'HEAD symref is not to refs/')
954 unless $current =~ m{^refs/};
955 my $ffq_prev = "refs/$ffq_refprefix/$'";
956 my $gdrlast = "refs/$gdrlast_refprefix/$'";
957 printdebug "ffq_prev_branchinfo branch current $current\n";
958 return ('branch', undef, $current, $ffq_prev, $gdrlast);
961 sub record_ffq_prev_deferred () {
962 # => ('status', "message")
964 # deferred message is undef
969 # if not ff from some branch we should be ff from, is an snag
970 # if "deferred", will have added something about that to
971 # @deferred_update_messages, and also maybe printed (already)
972 # some messages about ff checks
973 my ($status, $message, $current, $ffq_prev, $gdrlast)
974 = ffq_prev_branchinfo();
975 return ($status, $message) unless $status eq 'branch';
977 my $currentval = get_head();
979 my $exists = git_get_ref $ffq_prev;
980 return ('exists',"$ffq_prev already exists") if $exists;
982 return ('not-branch', 'HEAD symref is not to refs/heads/')
983 unless $current =~ m{^refs/heads/};
986 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
989 printdebug "ffq check_specs @check_specs\n";
992 my ($lrref, $desc) = @_;
993 printdebug "ffq might check $lrref ($desc)\n";
995 for my $chk (@check_specs) {
997 $invert = $glob =~ s{^[!^]}{};
998 last if fnmatch $glob, $lrref;
1001 my $lrval = git_get_ref $lrref;
1002 return unless defined $lrval;
1004 if (is_fast_fwd $lrval, $currentval) {
1005 print "OK, you are ahead of $lrref\n" or die $!;
1006 $checked{$lrref} = 1;
1007 } elsif (is_fast_fwd $currentval, $lrval) {
1008 $checked{$lrref} = -1;
1009 snag 'behind', "you are behind $lrref, divergence risk";
1011 $checked{$lrref} = -1;
1012 snag 'diverged', "you have diverged from $lrref";
1016 my $merge = cfg "branch.$branch.merge",1;
1017 if (defined $merge and $merge =~ m{^refs/heads/}) {
1019 printdebug "ffq merge $rhs\n";
1020 my $check_remote = sub {
1021 my ($remote, $desc) = @_;
1022 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1023 return unless defined $remote;
1024 $check->("refs/remotes/$remote/$rhs", $desc);
1026 $check_remote->((scalar cfg "branch.$branch.remote",1),
1027 'remote fetch/merge branch');
1028 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1029 (scalar cfg "branch.$branch.pushDefault",1),
1030 'remote push branch');
1032 if ($branch =~ m{^dgit/}) {
1033 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1034 } elsif ($branch =~ m{^master$}) {
1035 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1040 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1041 push @deferred_updates, "delete $gdrlast";
1042 push @deferred_update_messages, "Recorded current head for preservation";
1043 return ('deferred', undef);
1046 sub record_ffq_auto () {
1047 my ($status, $message) = record_ffq_prev_deferred();
1048 if ($status eq 'deferred' || $status eq 'exists') {
1050 snag $status, "could not record ffq-prev: $message";
1055 sub ffq_prev_info () {
1056 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1057 my ($status, $message, $current, $ffq_prev, $gdrlast)
1058 = ffq_prev_branchinfo();
1059 if ($status ne 'branch') {
1060 snag $status, "could not check ffq-prev: $message";
1063 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1064 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1067 sub stitch ($$$$$) {
1068 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1070 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1072 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1073 my $differs = get_differs $old_head, $ffq_prev_commitish;
1074 unless ($differs & ~D_PAT_ADD) {
1075 # ffq-prev is ahead of us, and the only tree changes it has
1076 # are possibly addition of things in debian/patches/.
1077 # Just wind forwards rather than making a pointless pseudomerge.
1078 push @deferred_updates,
1079 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1080 update_head_checkout $old_head, $ffq_prev_commitish,
1081 "stitch (fast forward)";
1086 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1087 'Declare fast forward / record previous work',
1088 "[git-debrebase pseudomerge: $prose]",
1090 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1091 update_head $old_head, $new_head, "stitch: $prose";
1094 sub do_stitch ($;$) {
1095 my ($prose, $unclean) = @_;
1097 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1098 if (!$ffq_prev_commitish) {
1099 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1102 my $dangling_head = get_head();
1104 keycommits $dangling_head, $unclean,$unclean,$unclean;
1107 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1110 sub cmd_new_upstream_v0 () {
1111 # automatically and unconditionally launders before rebasing
1112 # if rebase --abort is used, laundering has still been done
1116 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1118 # parse args - low commitment
1119 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1120 my $new_upstream_version = $new_version->version();
1122 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1127 my ($n, @x) = @_; # may be ''
1128 my $pc = $pieces{$n} //= {
1130 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1132 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1137 my $newpiece = sub {
1138 my ($n, @x) = @_; # may be ''
1139 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1140 push @newpieces, $pc;
1145 New => $new_upstream,
1147 while (@ARGV && $ARGV[0] !~ m{^-}) {
1148 my $n = shift @ARGV;
1150 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1151 unless @ARGV && $ARGV[0] !~ m{^-};
1153 my $c = git_rev_parse shift @ARGV;
1154 die unless $n =~ m/^$extra_orig_namepart_re$/;
1155 $newpiece->($n, New => $c);
1158 # now we need to investigate the branch this generates the
1159 # laundered version but we don't switch to it yet
1160 my $old_head = get_head();
1161 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1163 my $old_bw_cl = classify $old_bw;
1164 my $old_anchor_cl = classify $old_anchor;
1166 if (!$old_anchor_cl->{OrigParents}) {
1167 snag 'anchor-treated',
1168 'old anchor is recognised due to --anchor, cannot check upstream';
1170 $old_upstream = parsecommit
1171 $old_anchor_cl->{OrigParents}[0]{CommitId};
1172 $piece->('', Old => $old_upstream->{CommitId});
1175 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1176 if ($old_upstream->{Msg} =~
1177 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1179 my @oldpieces = ('', split / /, $1);
1180 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1181 foreach my $i (0..$#oldpieces) {
1182 my $n = $oldpieces[$i];
1183 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1186 snag 'upstream-confusing',
1187 "previous upstream $old_upstream->{CommitId} is from".
1188 " git-debrebase but not an \`upstream-combine' commit";
1192 foreach my $pc (values %pieces) {
1193 if (!$old_upstream) {
1194 # we have complained already
1195 } elsif (!$pc->{Old}) {
1196 snag 'upstream-new-piece',
1197 "introducing upstream piece \`$pc->{Name}'";
1198 } elsif (!$pc->{New}) {
1199 snag 'upstream-rm-piece',
1200 "dropping upstream piece \`$pc->{Name}'";
1201 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1202 snag 'upstream-not-ff',
1203 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1207 printdebug "%pieces = ", (dd \%pieces), "\n";
1208 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1216 my @upstream_merge_parents;
1219 push @upstream_merge_parents, $old_upstream->{CommitId};
1222 foreach my $pc (@newpieces) { # always has '' first
1224 read_tree_subdir $pc->{Name}, $pc->{New};
1226 runcmd @git, qw(read-tree), $pc->{New};
1228 push @upstream_merge_parents, $pc->{New};
1231 # index now contains the new upstream
1233 if (@newpieces > 1) {
1234 # need to make the upstream subtree merge commit
1235 $new_upstream = make_commit \@upstream_merge_parents,
1236 [ "Combine upstreams for $new_upstream_version",
1237 ("[git-debrebase upstream-combine . ".
1238 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1243 # $new_upstream is either the single upstream commit, or the
1244 # combined commit we just made. Either way it will be the
1245 # "upstream" parent of the anchor merge.
1247 read_tree_subdir 'debian', "$old_bw:debian";
1249 # index now contains the anchor merge contents
1250 $new_bw = make_commit [ $old_bw, $new_upstream ],
1251 [ "Update to upstream $new_upstream_version",
1252 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1255 my $clogsignoff = cmdoutput qw(git show),
1256 '--pretty=format:%an <%ae> %aD',
1259 # Now we have to add a changelog stanza so the Debian version
1261 die if unlink "debian";
1262 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1263 unlink "debian/changelog" or $!==ENOENT or die $!;
1264 mkdir "debian" or die $!;
1265 open CN, ">", "debian/changelog" or die $!;
1266 my $oldclog = git_cat_file ":debian/changelog";
1267 $oldclog =~ m/^($package_re) \(\S+\) / or
1268 fail "cannot parse old changelog to get package name";
1270 print CN <<END, $oldclog or die $!;
1271 $p ($new_version) UNRELEASED; urgency=medium
1273 * Update to new upstream version $new_upstream_version.
1279 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1281 # Now we have the final new breakwater branch in the index
1282 $new_bw = make_commit [ $new_bw ],
1283 [ "Update changelog for new upstream $new_upstream_version",
1284 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1288 # we have constructed the new breakwater. we now need to commit to
1289 # the laundering output, because git-rebase can't easily be made
1290 # to make a replay list which is based on some other branch
1292 update_head_postlaunder $old_head, $old_laundered_tip,
1293 'launder for new upstream';
1295 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1297 # now it's for the user to sort out
1300 sub cmd_record_ffq_prev () {
1301 badusage "no arguments allowed" if @ARGV;
1302 my ($status, $msg) = record_ffq_prev_deferred();
1303 if ($status eq 'exists' && $opt_noop_ok) {
1304 print "Previous head already recorded\n" or die $!;
1305 } elsif ($status eq 'deferred') {
1306 run_deferred_updates 'record-ffq-prev';
1308 fail "Could not preserve: $msg";
1313 badusage "no arguments allowed" if @ARGV;
1314 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1315 print "$bw\n" or die $!;
1318 sub cmd_breakwater () {
1319 badusage "no arguments allowed" if @ARGV;
1320 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1321 print "$bw\n" or die $!;
1325 my $prose = 'stitch';
1326 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1327 badusage "no arguments allowed" if @ARGV;
1328 do_stitch $prose, 0;
1330 sub cmd_prepush () { cmd_stitch(); }
1333 badusage "no arguments allowed" if @ARGV;
1334 do_launder_head 'launder for git-debrebase quick';
1338 sub cmd_conclude () {
1339 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1340 if (!$ffq_prev_commitish) {
1341 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1344 my $dangling_head = get_head();
1346 badusage "no arguments allowed" if @ARGV;
1347 do_launder_head 'launder for git-debrebase quick';
1351 sub make_patches_staged ($) {
1353 # Produces the patches that would result from $head if it were
1355 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1358 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1359 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1360 runcmd qw(gbp pq export);
1361 runcmd @git, qw(add debian/patches);
1365 sub cmd_convert_from_gbp () {
1366 badusage "needs 1 optional argument, the upstream git rev"
1368 my ($upstream_spec) = @ARGV;
1369 $upstream_spec //= 'refs/heads/upstream';
1370 my $upstream = git_rev_parse $upstream_spec;
1371 my $old_head = get_head();
1373 my $upsdiff = get_differs $upstream, $old_head;
1374 if ($upsdiff & D_UPS) {
1375 runcmd @git, qw(--no-pager diff),
1376 $upstream, $old_head,
1377 qw( -- :!/debian :/);
1378 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1381 if (!is_fast_fwd $upstream, $old_head) {
1382 snag 'upstream-not-ancestor',
1383 "upstream ($upstream) is not an ancestor of HEAD";
1385 my $wrong = cmdoutput
1386 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1387 qw(-- :/ :!/debian));
1388 if (length $wrong) {
1389 snag 'unexpected-upstream-changes',
1390 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1391 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1395 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1396 snag 'upstream-has-debian',
1397 "upstream ($upstream) contains debian/ directory";
1406 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1407 # make a branch out of the patch queue - we'll want this in a mo
1408 runcmd qw(gbp pq import);
1409 # strip the patches out
1410 runcmd @git, qw(checkout -q gdr-internal~0);
1411 rm_subdir_cached 'debian/patches';
1412 $work = make_commit ['HEAD'], [
1413 'git-debrebase convert-from-gbp: drop patches from tree',
1414 'Delete debian/patches, as part of converting to git-debrebase format.',
1415 '[git-debrebase convert-from-gbp: drop patches from tree]'
1417 # make the anchor merge
1418 # the tree is already exactly right
1419 $work = make_commit [$work, $upstream], [
1420 'git-debrebase import: declare upstream',
1421 'First breakwater merge.',
1422 '[git-debrebase anchor: declare upstream]'
1425 # rebase the patch queue onto the new breakwater
1426 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1427 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1428 $work = git_rev_parse 'HEAD';
1431 update_head_checkout $old_head, $work, 'convert-from-gbp';
1434 sub cmd_convert_to_gbp () {
1435 badusage "no arguments allowed" if @ARGV;
1436 my $head = get_head();
1437 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1438 keycommits $head, 0;
1440 make_patches_staged $head;
1442 $out = make_commit ['HEAD'], [
1443 'Commit patch queue (converted from git-debrebase format)',
1444 '[git-debrebase convert-to-gbp: commit patches]',
1448 push @deferred_updates, "delete $ffq";
1449 push @deferred_updates, "delete $gdrlast";
1452 update_head_checkout $head, $out, "convert to gbp (v0)";
1453 print <<END or die $!;
1454 git-debrebase: converted to git-buildpackage branch format
1455 git-debrebase: WARNING: do not now run "git-debrebase" any more
1456 git-debrebase: WARNING: doing so would drop all upstream patches!
1460 sub cmd_downstream_rebase_launder_v0 () {
1461 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1463 $base = git_rev_parse $base;
1464 my $old_head = get_head();
1465 my $current = $old_head;
1468 if ($current eq $base) {
1469 $topmost_keep //= $current;
1470 print " $current BASE stop\n";
1473 my $cl = classify $current;
1474 print " $current $cl->{Type}";
1476 my $p0 = $cl->{Parents}[0]{CommitId};
1478 if ($cl->{Type} eq 'Pseudomerge') {
1479 print " ^".($cl->{Contributor}{Ix}+1);
1480 $next = $cl->{Contributor}{CommitId};
1481 } elsif ($cl->{Type} eq 'AddPatches' or
1482 $cl->{Type} eq 'Changelog') {
1492 $topmost_keep //= $current;
1494 die "to-be stripped changes not on top of the branch\n"
1499 if ($topmost_keep eq $old_head) {
1500 print "unchanged\n";
1502 print "updating to $topmost_keep\n";
1503 update_head_checkout
1504 $old_head, $topmost_keep,
1505 'downstream-rebase-launder-v0';
1509 GetOptions("D+" => \$debuglevel,
1510 'noop-ok', => \$opt_noop_ok,
1511 'f=s' => \@snag_force_opts,
1512 'anchor=s' => \@opt_anchors,
1515 my ($opt,$val) = @_;
1516 badusage "git-debrebase: no cuddling to -i for git-rebase"
1518 die if $opt_defaultcmd_interactive; # should not happen
1519 $opt_defaultcmd_interactive = [ qw(-i) ];
1520 # This access to @ARGV is excessive familiarity with
1521 # Getopt::Long, but there isn't another sensible
1522 # approach. '-i=s{0,}' does not work with bundling.
1523 push @$opt_defaultcmd_interactive, @ARGV;
1525 }) or die badusage "bad options\n";
1526 initdebug('git-debrebase ');
1527 enabledebug if $debuglevel;
1529 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1530 chdir $toplevel or die "chdir $toplevel: $!";
1532 $rd = fresh_playground "$playprefix/misc";
1534 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1536 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1537 defaultcmd_rebase();
1539 my $cmd = shift @ARGV;
1542 $cmdfn = ${*::}{"cmd_$cmdfn"};
1544 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";