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 };
102 our @deferred_updates;
103 our @deferred_update_messages;
105 sub run_deferred_updates ($) {
108 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
109 debugcmd '>|', @upd_cmd;
110 open U, "|-", @upd_cmd or die $!;
111 foreach (@deferred_updates) {
112 printdebug ">= ", $_, "\n";
113 print U $_, "\n" or die $!;
116 close U or failedcmd @upd_cmd;
118 print $_, "\n" foreach @deferred_update_messages;
120 @deferred_updates = ();
121 @deferred_update_messages = ();
124 sub get_differs ($$) {
126 # This resembles quiltify_trees_differ, in dgit, a bit.
127 # But we don't care about modes, or dpkg-source-unrepresentable
128 # changes, and we don't need the plethora of different modes.
129 # Conversely we need to distinguish different kinds of changes to
130 # debian/ and debian/patches/.
135 my ($opts, $limits, $fn) = @_;
136 my @cmd = (@git, qw(diff-tree -z --no-renames));
138 push @cmd, "$_:" foreach $x, $y;
139 push @cmd, '--', @$limits;
140 my $diffs = cmdoutput @cmd;
141 foreach (split /\0/, $diffs) { $fn->(); }
144 $rundiff->([qw(--name-only)], [], sub {
145 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
148 if ($differs & DS_DEB) {
150 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
152 m{^debian/patches/} ? D_PAT_OTH :
153 $_ eq 'debian/changelog' ? D_DEB_CLOG :
156 die "mysterious debian changes $x..$y"
157 unless $differs & (D_PAT_OTH|DS_DEB);
160 if ($differs & D_PAT_OTH) {
162 $differs &= ~D_PAT_OTH;
164 $differs |= D_PAT_OTH;
165 no warnings qw(exiting); last;
167 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
168 no warnings qw(exiting);
169 if (!defined $mode) {
172 die unless s{^debian/patches/}{};
174 if ($mode eq 'A' && !m/\.series$/s) {
176 } elsif ($mode eq 'M' && $_ eq 'series') {
177 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
178 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
179 chomp $x_s; $x_s .= "\n";
180 $ok = $x_s eq substr($y_s, 0, length $x_s);
185 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
187 die "mysterious debian/patches changes $x..$y"
188 unless $differs & (D_PAT_ADD|D_PAT_OTH);
191 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
196 sub commit_pr_info ($) {
198 return Data::Dumper->dump([$r], [qw(commit)]);
201 sub calculate_committer_authline () {
202 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
203 'DUMMY COMMIT (git-debrebase)', "HEAD:";
204 my ($h,$m) = get_commit $c;
205 $h =~ m/^committer .*$/m or confess "($h) ?";
209 sub rm_subdir_cached ($) {
211 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
214 sub read_tree_subdir ($$) {
215 my ($subdir, $new_tree_object) = @_;
216 rm_subdir_cached $subdir;
217 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
220 sub make_commit ($$) {
221 my ($parents, $message_paras) = @_;
222 my $tree = cmdoutput @git, qw(write-tree);
223 my @cmd = (@git, qw(commit-tree), $tree);
224 push @cmd, qw(-p), $_ foreach @$parents;
225 push @cmd, qw(-m), $_ foreach @$message_paras;
226 return cmdoutput @cmd;
229 our @snag_force_opts;
234 if (grep { $_ eq $tag } @snag_force_opts) {
236 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
239 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
243 sub snags_maybe_bail () {
246 "%s: snags: %d overriden by individual -f options\n",
249 if ($snags_tripped) {
252 "%s: snags: %d overriden by global --force\n",
256 "%s: snags: %d blockers (you could -f<tag>, or --force)",
262 return $snags_forced || $snags_tripped;
265 # classify returns an info hash like this
267 # Hdr => # commit headers, including 1 final newline
268 # Msg => # commit message (so one newline is dropped)
270 # Type => (see below)
272 # Ix => $index # ie 0, 1, 2, ...
274 # Differs => return value from get_differs
276 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
278 # NewMsg => # commit message, but with any [dgit import ...] edited
279 # # to say "[was: ...]"
289 # has additional entres in classification result
290 # Overwritten = [ subset of Parents ]
291 # Contributor = $the_remaining_Parent
293 # DgitImportUnpatched
294 # has additional entry in classification result
295 # OrigParents = [ subset of Parents ]
298 # has additional entry in classification result
299 # OrigParents = [ subset of Parents ] # singleton list
306 # has additional entry in classification result
309 sub parsecommit ($;$) {
310 my ($objid, $p_ref) = @_;
311 # => hash with CommitId Hdr Msg Tree Parents
312 # Parents entries have only Ix CommitId
313 # $p_ref, if provided, must be [] and is used as a base for Parents
318 my ($h,$m) = get_commit $objid;
320 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
321 my (@ph) = $h =~ m/^parent (\w+)$/mg;
331 foreach my $ph (@ph) {
333 Ix => scalar @$p_ref,
345 my $r = parsecommit($objid, \@p);
349 $p->{Differs} = (get_differs $p->{CommitId}, $t),
352 printdebug "classify $objid \$t=$t \@p",
353 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
357 my ($type, @rest) = @_;
358 $r = { %$r, Type => $type, @rest };
360 printdebug " = $type ".(dd $r)."\n";
366 $r = { %$r, Type => qw(Unknown), Why => $why };
367 printdebug " ** Unknown\n";
371 if (grep { $_ eq $objid } @opt_anchors) {
372 return $classify->('TreatAsAnchor');
375 my @identical = grep { !$_->{Differs} } @p;
376 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
377 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
379 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
380 # multi-orig upstreams are represented with an anchor merge
381 # from a single upstream commit which combines the orig tarballs
383 # Every anchor tagged this way must be a merge.
384 # We are relying on the
385 # [git-debrebase anchor: ...]
386 # commit message annotation in "declare" anchor merges (which
387 # do not have any upstream changes), to distinguish those
388 # anchor merges from ordinary pseudomerges (which we might
389 # just try to strip).
391 # However, the user is going to be doing git-rebase a lot. We
392 # really don't want them to rewrite an anchor commit.
393 # git-rebase trips up on merges, so that is a useful safety
396 # BreakwaterStart commits are also anchors in the terminology
397 # of git-debrebase(5), but they are untagged (and always
398 # manually generated).
400 # We cannot not tolerate any tagged linear commit (ie,
401 # BreakwaterStart commits tagged `[anchor:') because such a
402 # thing could result from an erroneous linearising raw git
403 # rebase of a merge anchor. That would represent a corruption
404 # of the branch. and we want to detect and reject the results
405 # of such corruption before it makes it out anywhere. If we
406 # reject it here then we avoid making the pseudomerge which
407 # would be needed to push it.
409 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
410 @p == 2 or return $badanchor->("has other than two parents");
411 $haspatches and return $badanchor->("contains debian/patches");
413 # How to decide about l/r ordering of anchors ? git
414 # --topo-order prefers to expand 2nd parent first. There's
415 # already an easy rune to look for debian/ history anyway (git log
416 # debian/) so debian breakwater branch should be 1st parent; that
417 # way also there's also an easy rune to look for the upstream
418 # patches (--topo-order).
420 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
421 $p[1]{Differs} & ~DS_DEB and
422 $badanchor->("upstream files differ from left parent");
423 $p[0]{Differs} & ~D_UPS and
424 $badanchor->("debian/ differs from right parent");
426 return $classify->(qw(Anchor),
427 OrigParents => [ $p[1] ]);
431 my $d = $r->{Parents}[0]{Differs};
432 if ($d == D_PAT_ADD) {
433 return $classify->(qw(AddPatches));
434 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
435 return $unknown->("edits debian/patches");
436 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
437 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
439 if ($d == D_DEB_CLOG) {
440 return $classify->(qw(Changelog));
442 return $classify->(qw(Packaging));
444 } elsif ($ty eq 'missing') {
445 return $classify->(qw(BreakwaterStart));
447 return $unknown->("parent's debian is not a directory");
449 } elsif ($d == D_UPS) {
450 return $classify->(qw(Upstream));
451 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
452 return $classify->(qw(Mixed));
454 return $unknown->("no changes");
456 confess "internal error $objid ?";
460 return $unknown->("origin commit");
463 if (@p == 2 && @identical == 1) {
464 my @overwritten = grep { $_->{Differs} } @p;
465 confess "internal error $objid ?" unless @overwritten==1;
466 return $classify->(qw(Pseudomerge),
467 Overwritten => [ $overwritten[0] ],
468 Contributor => $identical[0]);
470 if (@p == 2 && @identical == 2) {
472 my ($ph,$pm) = get_commit $_[0]{CommitId};
473 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
477 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
478 if ($order > 0) { # newer first
479 } elsif ($order < 0) {
480 @bytime = reverse @bytime;
482 # same age, default to order made by -s ours
483 # that is, commit was made by someone who preferred L
485 return $classify->(qw(Pseudomerge),
486 SubType => qw(Ambiguous),
487 Contributor => $bytime[0],
488 Overwritten => [ $bytime[1] ]);
491 my ($p_h, $p_m) = get_commit $p->{CommitId};
492 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
493 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
495 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
497 if (!(grep { !$_->{IsOrigin} } @p) and
498 (@orig_ps >= @p - 1) and
499 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
501 return $classify->(qw(DgitImportUnpatched),
502 OrigParents => \@orig_ps);
505 return $unknown->("complex merge");
508 sub keycommits ($;$$$) {
509 my ($head, $furniture, $unclean, $trouble) = @_;
510 # => ($anchor, $breakwater)
512 # $unclean->("unclean-$tagsfx", $msg)
513 # $furniture->("unclean-$tagsfx", $msg)
514 # $dgitimport->("unclean-$tagsfx", $msg)
515 # is callled for each situation or commit that
516 # wouldn't be found in a laundered branch
517 # $furniture is for furniture commits such as might be found on an
518 # interchange branch (pseudomerge, d/patches, changelog)
519 # $trouble is for things whnich prevent the return of
520 # anchor and breakwater information; if that is ignored,
521 # then keycommits returns (undef, undef) instead.
523 # If a callback is undef, fail is called instead.
524 # If a callback is defined but false, the situation is ignored.
526 # no warnings qw(exiting); last;
527 # if the answer is no longer wanted.
529 my ($anchor, $breakwater);
532 my ($cb, $tagsfx, $why) = @_;
533 my $m = "branch needs laundering (run git-debrebase): $why";
534 fail $m unless defined $cb;
536 $cb->("unclean-$tagsfx", $why);
539 my $cl = classify $head;
540 my $ty = $cl->{Type};
541 if ($ty eq 'Packaging') {
542 $breakwater //= $clogonly;
543 $breakwater //= $head;
544 } elsif ($ty eq 'Changelog') {
545 # this is going to count as the tip of the breakwater
546 # only if it has no upstream stuff before it
548 } elsif ($ty eq 'Anchor' or
549 $ty eq 'TreatAsAnchor' or
550 $ty eq 'BreakwaterStart') {
552 $breakwater //= $clogonly;
553 $breakwater //= $head;
555 } elsif ($ty eq 'Upstream') {
556 $x->($unclean, 'ordering',
557 "packaging change ($breakwater) follows upstream change (eg $head)")
558 if defined $breakwater;
561 } elsif ($ty eq 'Mixed') {
562 $x->($unclean, 'mixed',
563 'found mixed upstream/packaging commit ($head)');
566 } elsif ($ty eq 'Pseudomerge' or
567 $ty eq 'AddPatches') {
568 $x->($furniture, (lc $ty),
569 "found interchange bureaucracy commit ($ty, $head)");
570 } elsif ($ty eq 'DgitImportUnpatched') {
571 $x->($trouble, 'dgitimport',
572 "found dgit dsc import ($head)");
575 no warnings qw(exiting);
578 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
580 $head = $cl->{Parents}[0]{CommitId};
582 return ($anchor, $breakwater);
588 $nogenerate,$report) = @_;
589 # => ($tip, $breakwater_tip, $last_anchor)
590 # (or nothing, if $nogenerate)
592 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
594 # go through commits backwards
595 # we generate two lists of commits to apply:
596 # breakwater branch and upstream patches
597 my (@brw_cl, @upp_cl, @processed);
604 my ($prose, $info) = @_;
608 $ms .= "\n\n[git-debrebase$info: $prose]\n";
611 my $rewrite_from_here = sub {
613 my $sp_cl = { SpecialMethod => 'StartRewrite' };
615 push @processed, $sp_cl;
620 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
623 return unless $report;
624 print $report $prdelim, @_;
628 my $bomb = sub { # usage: return $bomb->();
629 print $report " Unprocessable" if $report;
630 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
633 return (undef,undef);
635 die "commit $cur: Cannot cope with this commit (d.".
636 (join ' ', map { sprintf "%#x", $_->{Differs} }
637 @{ $cl->{Parents} }).
638 (defined $cl->{Why} ? "; $cl->{Why}": '').
645 my $build_start = sub {
646 my ($msg, $parent) = @_;
649 no warnings qw(exiting); last;
656 my $ty = $cl->{Type};
657 my $st = $cl->{SubType};
658 $prline->("$cl->{CommitId} $cl->{Type}");
659 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
660 push @processed, $cl;
661 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
662 if ($ty eq 'AddPatches') {
664 $rewrite_from_here->(\@upp_cl);
666 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
670 } elsif ($ty eq 'BreakwaterStart') {
672 $build_start->('FirstPackaging', $cur);
673 } elsif ($ty eq 'Upstream') {
677 } elsif ($ty eq 'Mixed') {
680 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
683 $queue->(\@brw_cl, "debian");
684 $queue->(\@upp_cl, "upstream");
685 $rewrite_from_here->(\@brw_cl);
688 } elsif ($ty eq 'Pseudomerge') {
689 my $contrib = $cl->{Contributor}{CommitId};
690 print $report " Contributor=$contrib" if $report;
691 push @pseudomerges, $cl;
692 $rewrite_from_here->(\@upp_cl);
695 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
697 $build_start->("Anchor", $cur);
698 } elsif ($ty eq 'DgitImportUnpatched') {
699 my $pm = $pseudomerges[-1];
701 # To an extent, this is heuristic. Imports don't have
702 # a useful history of the debian/ branch. We assume
703 # that the first pseudomerge after an import has a
704 # useful history of debian/, and ignore the histories
705 # from later pseudomerges. Often the first pseudomerge
706 # will be the dgit import of the upload to the actual
707 # suite intended by the non-dgit NMUer, and later
708 # pseudomerges may represent in-archive copies.
709 my $ovwrs = $pm->{Overwritten};
710 printf $report " PM=%s \@Overwr:%d",
711 $pm->{CommitId}, (scalar @$ovwrs)
714 printdebug "*** WALK BOMB DgitImportUnpatched\n";
717 my $ovwr = $ovwrs->[0]{CommitId};
718 printf $report " Overwr=%s", $ovwr if $report;
719 # This import has a tree which is just like a
720 # breakwater tree, but it has the wrong history. It
721 # ought to have the previous breakwater (which the
722 # pseudomerge overwrote) as an ancestor. That will
723 # make the history of the debian/ files correct. As
724 # for the upstream version: either it's the same as
725 # was ovewritten (ie, same as the previous
726 # breakwater), in which case that history is precisely
727 # right; or, otherwise, it was a non-gitish upload of a
728 # new upstream version. We can tell these apart by
729 # looking at the tree of the supposed upstream.
732 SpecialMethod => 'DgitImportDebianUpdate',
733 $xmsg->("convert dgit import: debian changes")
736 SpecialMethod => 'DgitImportUpstreamUpdate',
737 $xmsg->("convert dgit import: upstream update",
740 $prline->(" Import");
741 $rewrite_from_here->(\@brw_cl);
742 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
746 # Everything is from this import. This kind of import
747 # is already in valid breakwater format, with the
748 # patches as commits.
749 printf $report " NoPM" if $report;
750 # last thing we processed will have been the first patch,
751 # if there is one; which is fine, so no need to rewrite
752 # on account of this import
753 $build_start->("ImportOrigin", $cur);
757 printdebug "*** WALK BOMB unrecognised\n";
763 printdebug "*** WALK prep done cur=$cur".
764 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
766 return if $nogenerate;
768 # Now we build it back up again
774 my $read_tree_debian = sub {
776 read_tree_subdir 'debian', "$treeish:debian";
777 rm_subdir_cached 'debian/patches';
779 my $read_tree_upstream = sub {
781 runcmd @git, qw(read-tree), $treeish;
782 $read_tree_debian->($build);
785 $#upp_cl = $upp_limit if defined $upp_limit;
787 my $committer_authline = calculate_committer_authline();
789 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
791 confess "internal error" unless $build eq (pop @processed)->{CommitId};
794 mkdir $rd or $!==EEXIST or die $!;
796 runcmd @git, qw(read-tree), $build;
797 foreach my $cl (qw(Debian), (reverse @brw_cl),
798 { SpecialMethod => 'RecordBreakwaterTip' },
799 qw(Upstream), (reverse @upp_cl)) {
801 $current_method = $cl;
804 my $method = $cl->{SpecialMethod} // $current_method;
805 my @parents = ($build);
806 my $cltree = $cl->{CommitId};
807 printdebug "WALK BUILD ".($cltree//'undef').
808 " $method (rewriting=$rewriting)\n";
809 if ($method eq 'Debian') {
810 $read_tree_debian->($cltree);
811 } elsif ($method eq 'Upstream') {
812 $read_tree_upstream->($cltree);
813 } elsif ($method eq 'StartRewrite') {
816 } elsif ($method eq 'RecordBreakwaterTip') {
817 $breakwater = $build;
819 } elsif ($method eq 'DgitImportDebianUpdate') {
820 $read_tree_debian->($cltree);
821 } elsif ($method eq 'DgitImportUpstreamUpdate') {
822 confess unless $rewriting;
823 my $differs = (get_differs $build, $cltree);
824 next unless $differs & D_UPS;
825 $read_tree_upstream->($cltree);
826 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
831 my $procd = (pop @processed) // 'UNDEF';
834 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
837 my $newtree = cmdoutput @git, qw(write-tree);
839 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
840 $ch =~ s{^parent .*\n}{}mg;
841 $ch =~ s{(?=^author)}{
842 join '', map { "parent $_\n" } @parents
843 }me or confess "$ch ?";
845 $ch =~ s{^committer .*$}{$committer_authline}m
848 my $cf = "$rd/m$rewriting";
849 open CD, ">", $cf or die $!;
850 print CD $ch, "\n", $cl->{Msg} or die $!;
852 my @cmd = (@git, qw(hash-object));
853 push @cmd, qw(-w) if $rewriting;
854 push @cmd, qw(-t commit), $cf;
855 my $newcommit = cmdoutput @cmd;
856 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
858 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
864 my $final_check = get_differs $build, $input;
865 die sprintf "internal error %#x %s %s", $final_check, $build, $input
866 if $final_check & ~D_PAT_ADD;
868 my @r = ($build, $breakwater, $last_anchor);
869 printdebug "*** WALK RETURN @r\n";
874 git_check_unmodified();
875 return git_rev_parse qw(HEAD);
878 sub update_head ($$$) {
879 my ($old, $new, $mrest) = @_;
880 push @deferred_updates, "update HEAD $new $old";
881 run_deferred_updates $mrest;
884 sub update_head_checkout ($$$) {
885 my ($old, $new, $mrest) = @_;
886 update_head $old, $new, $mrest;
887 runcmd @git, qw(reset --hard);
890 sub update_head_postlaunder ($$$) {
891 my ($old, $tip, $reflogmsg) = @_;
892 return if $tip eq $old;
893 print "git-debrebase: laundered (head was $old)\n";
894 update_head $old, $tip, $reflogmsg;
895 # no tree changes except debian/patches
896 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
899 sub do_launder_head ($) {
900 my ($reflogmsg) = @_;
901 my $old = get_head();
903 my ($tip,$breakwater) = walk $old;
904 update_head_postlaunder $old, $tip, $reflogmsg;
905 return ($tip,$breakwater);
908 sub cmd_launder_v0 () {
909 badusage "no arguments to launder-v0 allowed" if @ARGV;
910 my $old = get_head();
911 my ($tip,$breakwater,$last_anchor) = walk $old;
912 update_head_postlaunder $old, $tip, 'launder';
913 printf "# breakwater tip\n%s\n", $breakwater;
914 printf "# working tip\n%s\n", $tip;
915 printf "# last anchor\n%s\n", $last_anchor;
918 sub defaultcmd_rebase () {
919 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
920 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
921 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
925 die if ($ARGV[0]//'') =~ m/^-/;
926 badusage "too many arguments to analyse" if @ARGV>1;
929 $old = git_rev_parse $old;
931 $old = git_rev_parse 'HEAD';
933 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
934 STDOUT->error and die $!;
937 sub ffq_prev_branchinfo () {
938 # => ('status', "message", [$current, $ffq_prev, $gdrlast])
940 # branch message is undef
941 # weird-symref } no $current,
942 # notbranch } no $ffq_prev
943 my $current = git_get_symref();
944 return ('detached', 'detached HEAD') unless defined $current;
945 return ('weird-symref', 'HEAD symref is not to refs/')
946 unless $current =~ m{^refs/};
947 my $ffq_prev = "refs/$ffq_refprefix/$'";
948 my $gdrlast = "refs/$gdrlast_refprefix/$'";
949 printdebug "ffq_prev_branchinfo branch current $current\n";
950 return ('branch', undef, $current, $ffq_prev, $gdrlast);
953 sub record_ffq_prev_deferred () {
954 # => ('status', "message")
956 # deferred message is undef
961 # if not ff from some branch we should be ff from, is an snag
962 # if "deferred", will have added something about that to
963 # @deferred_update_messages, and also maybe printed (already)
964 # some messages about ff checks
965 my ($status, $message, $current, $ffq_prev, $gdrlast)
966 = ffq_prev_branchinfo();
967 return ($status, $message) unless $status eq 'branch';
969 my $currentval = get_head();
971 my $exists = git_get_ref $ffq_prev;
972 return ('exists',"$ffq_prev already exists") if $exists;
974 return ('not-branch', 'HEAD symref is not to refs/heads/')
975 unless $current =~ m{^refs/heads/};
978 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
981 printdebug "ffq check_specs @check_specs\n";
984 my ($lrref, $desc) = @_;
985 printdebug "ffq might check $lrref ($desc)\n";
987 for my $chk (@check_specs) {
989 $invert = $glob =~ s{^[!^]}{};
990 last if fnmatch $glob, $lrref;
993 my $lrval = git_get_ref $lrref;
994 return unless defined $lrval;
996 if (is_fast_fwd $lrval, $currentval) {
997 print "OK, you are ahead of $lrref\n" or die $!;
998 $checked{$lrref} = 1;
999 } elsif (is_fast_fwd $currentval, $lrval) {
1000 $checked{$lrref} = -1;
1001 snag 'behind', "you are behind $lrref, divergence risk";
1003 $checked{$lrref} = -1;
1004 snag 'diverged', "you have diverged from $lrref";
1008 my $merge = cfg "branch.$branch.merge",1;
1009 if (defined $merge and $merge =~ m{^refs/heads/}) {
1011 printdebug "ffq merge $rhs\n";
1012 my $check_remote = sub {
1013 my ($remote, $desc) = @_;
1014 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1015 return unless defined $remote;
1016 $check->("refs/remotes/$remote/$rhs", $desc);
1018 $check_remote->((scalar cfg "branch.$branch.remote",1),
1019 'remote fetch/merge branch');
1020 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1021 (scalar cfg "branch.$branch.pushDefault",1),
1022 'remote push branch');
1024 if ($branch =~ m{^dgit/}) {
1025 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1026 } elsif ($branch =~ m{^master$}) {
1027 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1032 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1033 push @deferred_updates, "delete $gdrlast";
1034 push @deferred_update_messages, "Recorded current head for preservation";
1035 return ('deferred', undef);
1038 sub record_ffq_auto () {
1039 my ($status, $message) = record_ffq_prev_deferred();
1040 if ($status eq 'deferred' || $status eq 'exists') {
1042 snag $status, "could not record ffq-prev: $message";
1047 sub ffq_prev_info () {
1048 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1049 my ($status, $message, $current, $ffq_prev, $gdrlast)
1050 = ffq_prev_branchinfo();
1051 if ($status ne 'branch') {
1052 snag $status, "could not check ffq-prev: $message";
1055 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1056 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1059 sub stitch ($$$$$) {
1060 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1062 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1064 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1065 my $differs = get_differs $old_head, $ffq_prev_commitish;
1066 unless ($differs & ~D_PAT_ADD) {
1067 # ffq-prev is ahead of us, and the only tree changes it has
1068 # are possibly addition of things in debian/patches/.
1069 # Just wind forwards rather than making a pointless pseudomerge.
1070 push @deferred_updates,
1071 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1072 update_head_checkout $old_head, $ffq_prev_commitish,
1073 "stitch (fast forward)";
1078 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1079 'Declare fast forward / record previous work',
1080 "[git-debrebase pseudomerge: $prose]",
1082 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1083 update_head $old_head, $new_head, "stitch: $prose";
1089 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1090 if (!$ffq_prev_commitish) {
1091 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1094 my $dangling_head = get_head();
1096 keycommits $dangling_head, \&snag, \&snag, \&snag;
1098 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1101 sub cmd_new_upstream_v0 () {
1102 # automatically and unconditionally launders before rebasing
1103 # if rebase --abort is used, laundering has still been done
1107 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1109 # parse args - low commitment
1110 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1111 my $new_upstream_version = $new_version->version();
1113 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1118 my ($n, @x) = @_; # may be ''
1119 my $pc = $pieces{$n} //= {
1121 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1123 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1128 my $newpiece = sub {
1129 my ($n, @x) = @_; # may be ''
1130 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1131 push @newpieces, $pc;
1136 New => $new_upstream,
1138 while (@ARGV && $ARGV[0] !~ m{^-}) {
1139 my $n = shift @ARGV;
1141 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1142 unless @ARGV && $ARGV[0] !~ m{^-};
1144 my $c = git_rev_parse shift @ARGV;
1145 die unless $n =~ m/^$extra_orig_namepart_re$/;
1146 $newpiece->($n, New => $c);
1149 # now we need to investigate the branch this generates the
1150 # laundered version but we don't switch to it yet
1151 my $old_head = get_head();
1152 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1154 my $old_bw_cl = classify $old_bw;
1155 my $old_anchor_cl = classify $old_anchor;
1157 if (!$old_anchor_cl->{OrigParents}) {
1158 snag 'anchor-treated',
1159 'old anchor is recognised due to --anchor, cannot check upstream';
1161 $old_upstream = parsecommit
1162 $old_anchor_cl->{OrigParents}[0]{CommitId};
1163 $piece->('', Old => $old_upstream->{CommitId});
1166 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1167 if ($old_upstream->{Msg} =~
1168 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1170 my @oldpieces = ('', split / /, $1);
1171 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1172 foreach my $i (0..$#oldpieces) {
1173 my $n = $oldpieces[$i];
1174 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1177 snag 'upstream-confusing',
1178 "previous upstream $old_upstream->{CommitId} is from".
1179 " git-debrebase but not an \`upstream-combine' commit";
1183 foreach my $pc (values %pieces) {
1184 if (!$old_upstream) {
1185 # we have complained already
1186 } elsif (!$pc->{Old}) {
1187 snag 'upstream-new-piece',
1188 "introducing upstream piece \`$pc->{Name}'";
1189 } elsif (!$pc->{New}) {
1190 snag 'upstream-rm-piece',
1191 "dropping upstream piece \`$pc->{Name}'";
1192 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1193 snag 'upstream-not-ff',
1194 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1198 printdebug "%pieces = ", (dd \%pieces), "\n";
1199 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1207 my @upstream_merge_parents;
1210 push @upstream_merge_parents, $old_upstream->{CommitId};
1213 foreach my $pc (@newpieces) { # always has '' first
1215 read_tree_subdir $pc->{Name}, $pc->{New};
1217 runcmd @git, qw(read-tree), $pc->{New};
1219 push @upstream_merge_parents, $pc->{New};
1222 # index now contains the new upstream
1224 if (@newpieces > 1) {
1225 # need to make the upstream subtree merge commit
1226 $new_upstream = make_commit \@upstream_merge_parents,
1227 [ "Combine upstreams for $new_upstream_version",
1228 ("[git-debrebase upstream-combine . ".
1229 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1234 # $new_upstream is either the single upstream commit, or the
1235 # combined commit we just made. Either way it will be the
1236 # "upstream" parent of the anchor merge.
1238 read_tree_subdir 'debian', "$old_bw:debian";
1240 # index now contains the anchor merge contents
1241 $new_bw = make_commit [ $old_bw, $new_upstream ],
1242 [ "Update to upstream $new_upstream_version",
1243 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1246 my $clogsignoff = cmdoutput qw(git show),
1247 '--pretty=format:%an <%ae> %aD',
1250 # Now we have to add a changelog stanza so the Debian version
1252 die if unlink "debian";
1253 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1254 unlink "debian/changelog" or $!==ENOENT or die $!;
1255 mkdir "debian" or die $!;
1256 open CN, ">", "debian/changelog" or die $!;
1257 my $oldclog = git_cat_file ":debian/changelog";
1258 $oldclog =~ m/^($package_re) \(\S+\) / or
1259 fail "cannot parse old changelog to get package name";
1261 print CN <<END, $oldclog or die $!;
1262 $p ($new_version) UNRELEASED; urgency=medium
1264 * Update to new upstream version $new_upstream_version.
1270 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1272 # Now we have the final new breakwater branch in the index
1273 $new_bw = make_commit [ $new_bw ],
1274 [ "Update changelog for new upstream $new_upstream_version",
1275 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1279 # we have constructed the new breakwater. we now need to commit to
1280 # the laundering output, because git-rebase can't easily be made
1281 # to make a replay list which is based on some other branch
1283 update_head_postlaunder $old_head, $old_laundered_tip,
1284 'launder for new upstream';
1286 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1288 # now it's for the user to sort out
1291 sub cmd_record_ffq_prev () {
1292 badusage "no arguments allowed" if @ARGV;
1293 my ($status, $msg) = record_ffq_prev_deferred();
1294 if ($status eq 'exists' && $opt_noop_ok) {
1295 print "Previous head already recorded\n" or die $!;
1296 } elsif ($status eq 'deferred') {
1297 run_deferred_updates 'record-ffq-prev';
1299 fail "Could not preserve: $msg";
1304 badusage "no arguments allowed" if @ARGV;
1305 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1306 print "$bw\n" or die $!;
1309 sub cmd_breakwater () {
1310 badusage "no arguments allowed" if @ARGV;
1311 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1312 print "$bw\n" or die $!;
1316 my $prose = 'stitch';
1317 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1318 badusage "no arguments allowed" if @ARGV;
1321 sub cmd_prepush () { cmd_stitch(); }
1324 badusage "no arguments allowed" if @ARGV;
1325 do_launder_head 'launder for git-debrebase quick';
1329 sub cmd_conclude () {
1330 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1331 if (!$ffq_prev_commitish) {
1332 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1335 my $dangling_head = get_head();
1337 badusage "no arguments allowed" if @ARGV;
1338 do_launder_head 'launder for git-debrebase quick';
1342 sub cmd_convert_from_gbp () {
1343 badusage "needs 1 optional argument, the upstream git rev"
1345 my ($upstream_spec) = @ARGV;
1346 $upstream_spec //= 'refs/heads/upstream';
1347 my $upstream = git_rev_parse $upstream_spec;
1348 my $old_head = get_head();
1350 my $upsdiff = get_differs $upstream, $old_head;
1351 if ($upsdiff & D_UPS) {
1352 runcmd @git, qw(--no-pager diff),
1353 $upstream, $old_head,
1354 qw( -- :!/debian :/);
1355 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1358 if (!is_fast_fwd $upstream, $old_head) {
1359 snag 'upstream-not-ancestor',
1360 "upstream ($upstream) is not an ancestor of HEAD";
1362 my $wrong = cmdoutput
1363 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1364 qw(-- :/ :!/debian));
1365 if (length $wrong) {
1366 snag 'unexpected-upstream-changes',
1367 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1368 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1372 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1373 snag 'upstream-has-debian',
1374 "upstream ($upstream) contains debian/ directory";
1383 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1384 # make a branch out of the patch queue - we'll want this in a mo
1385 runcmd qw(gbp pq import);
1386 # strip the patches out
1387 runcmd @git, qw(checkout -q gdr-internal~0);
1388 rm_subdir_cached 'debian/patches';
1389 $work = make_commit ['HEAD'], [
1390 'git-debrebase convert-from-gbp: drop patches from tree',
1391 'Delete debian/patches, as part of converting to git-debrebase format.',
1392 '[git-debrebase convert-from-gbp: drop patches from tree]'
1394 # make the anchor merge
1395 # the tree is already exactly right
1396 $work = make_commit [$work, $upstream], [
1397 'git-debrebase import: declare upstream',
1398 'First breakwater merge.',
1399 '[git-debrebase anchor: declare upstream]'
1402 # rebase the patch queue onto the new breakwater
1403 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1404 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1405 $work = git_rev_parse 'HEAD';
1408 update_head_checkout $old_head, $work, 'convert-from-gbp';
1411 sub cmd_convert_to_gbp () {
1412 badusage "no arguments allowed" if @ARGV;
1413 my $head = get_head();
1414 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1415 my ($anchor, $bw) = keycommits $head, 0;
1419 runcmd @git, qw(checkout -q -b bw), $bw;
1420 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1421 runcmd qw(gbp pq export);
1422 runcmd @git, qw(add debian/patches);
1423 $out = make_commit ['HEAD'], [
1424 'Commit patch queue (converted from git-debrebase format)',
1425 '[git-debrebase convert-to-gbp: commit patches]',
1429 push @deferred_updates, "delete $ffq";
1430 push @deferred_updates, "delete $gdrlast";
1432 update_head_checkout $head, $out, "convert to gbp (v0)";
1433 print <<END or die $!;
1434 git-debrebase: converted to git-buildpackage branch format
1435 git-debrebase: WARNING: do not now run "git-debrebase" any more
1436 git-debrebase: WARNING: doing so would drop all upstream patches!
1440 sub cmd_downstream_rebase_launder_v0 () {
1441 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1443 $base = git_rev_parse $base;
1444 my $old_head = get_head();
1445 my $current = $old_head;
1448 if ($current eq $base) {
1449 $topmost_keep //= $current;
1450 print " $current BASE stop\n";
1453 my $cl = classify $current;
1454 print " $current $cl->{Type}";
1456 my $p0 = $cl->{Parents}[0]{CommitId};
1458 if ($cl->{Type} eq 'Pseudomerge') {
1459 print " ^".($cl->{Contributor}{Ix}+1);
1460 $next = $cl->{Contributor}{CommitId};
1461 } elsif ($cl->{Type} eq 'AddPatches' or
1462 $cl->{Type} eq 'Changelog') {
1472 $topmost_keep //= $current;
1474 die "to-be stripped changes not on top of the branch\n"
1479 if ($topmost_keep eq $old_head) {
1480 print "unchanged\n";
1482 print "updating to $topmost_keep\n";
1483 update_head_checkout
1484 $old_head, $topmost_keep,
1485 'downstream-rebase-launder-v0';
1489 GetOptions("D+" => \$debuglevel,
1490 'noop-ok', => \$opt_noop_ok,
1491 'f=s' => \@snag_force_opts,
1492 'anchor=s' => \@opt_anchors,
1495 my ($opt,$val) = @_;
1496 badusage "git-debrebase: no cuddling to -i for git-rebase"
1498 die if $opt_defaultcmd_interactive; # should not happen
1499 $opt_defaultcmd_interactive = [ qw(-i) ];
1500 # This access to @ARGV is excessive familiarity with
1501 # Getopt::Long, but there isn't another sensible
1502 # approach. '-i=s{0,}' does not work with bundling.
1503 push @$opt_defaultcmd_interactive, @ARGV;
1505 }) or die badusage "bad options\n";
1506 initdebug('git-debrebase ');
1507 enabledebug if $debuglevel;
1509 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1510 chdir $toplevel or die "chdir $toplevel: $!";
1512 $rd = fresh_playground "$playprefix/misc";
1514 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1516 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1517 defaultcmd_rebase();
1519 my $cmd = shift @ARGV;
1522 $cmdfn = ${*::}{"cmd_$cmdfn"};
1524 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";