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);
36 our $us = qw(git-debrebase);
40 print STDERR "bad usage: $m\n";
45 my ($k, $optional) = @_;
47 my @cmd = qw(git config -z);
48 push @cmd, qw(--get-all) if wantarray;
50 my $out = cmdoutput_errok @cmd;
52 fail "missing required git config $k" unless $optional;
55 my @l = split /\0/, $out;
56 return wantarray ? @l : $l[0];
63 my $dd = new Data::Dumper [ $v ];
64 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
70 my $data = (git_cat_file $objid, 'commit');
71 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
75 sub D_UPS () { 0x02; } # upstream files
76 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
77 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
78 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
79 sub D_DEB_OTH () { 0x20; } # debian/changelog
80 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
82 our $playprefix = 'debrebase';
91 my $r = eval { $sub->(); };
92 { local $@; changedir $maindir; }
96 sub fresh_workarea () {
97 $workarea = fresh_playground "$playprefix/work";
98 in_workarea sub { playtree_setup };
101 our @deferred_updates;
102 our @deferred_update_messages;
104 sub run_deferred_updates ($) {
107 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
108 debugcmd '>|', @upd_cmd;
109 open U, "|-", @upd_cmd or die $!;
110 foreach (@deferred_updates) {
111 printdebug ">= ", $_, "\n";
112 print U $_, "\n" or die $!;
115 close U or failedcmd @upd_cmd;
117 print $_, "\n" foreach @deferred_update_messages;
119 @deferred_updates = ();
120 @deferred_update_messages = ();
123 sub get_differs ($$) {
125 # This resembles quiltify_trees_differ, in dgit, a bit.
126 # But we don't care about modes, or dpkg-source-unrepresentable
127 # changes, and we don't need the plethora of different modes.
128 # Conversely we need to distinguish different kinds of changes to
129 # debian/ and debian/patches/.
134 my ($opts, $limits, $fn) = @_;
135 my @cmd = (@git, qw(diff-tree -z --no-renames));
137 push @cmd, "$_:" foreach $x, $y;
138 push @cmd, '--', @$limits;
139 my $diffs = cmdoutput @cmd;
140 foreach (split /\0/, $diffs) { $fn->(); }
143 $rundiff->([qw(--name-only)], [], sub {
144 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
147 if ($differs & DS_DEB) {
149 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
151 m{^debian/patches/} ? D_PAT_OTH :
152 $_ eq 'debian/changelog' ? D_DEB_CLOG :
155 die "mysterious debian changes $x..$y"
156 unless $differs & (D_PAT_OTH|DS_DEB);
159 if ($differs & D_PAT_OTH) {
161 $differs &= ~D_PAT_OTH;
163 $differs |= D_PAT_OTH;
164 no warnings qw(exiting); last;
166 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
167 no warnings qw(exiting);
168 if (!defined $mode) {
171 die unless s{^debian/patches/}{};
173 if ($mode eq 'A' && !m/\.series$/s) {
175 } elsif ($mode eq 'M' && $_ eq 'series') {
176 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
177 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
178 chomp $x_s; $x_s .= "\n";
179 $ok = $x_s eq substr($y_s, 0, length $x_s);
184 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
186 die "mysterious debian/patches changes $x..$y"
187 unless $differs & (D_PAT_ADD|D_PAT_OTH);
190 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
195 sub commit_pr_info ($) {
197 return Data::Dumper->dump([$r], [qw(commit)]);
200 sub calculate_committer_authline () {
201 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
202 'DUMMY COMMIT (git-debrebase)', "HEAD:";
203 my ($h,$m) = get_commit $c;
204 $h =~ m/^committer .*$/m or confess "($h) ?";
208 sub rm_subdir_cached ($) {
210 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
213 sub read_tree_subdir ($$) {
214 my ($subdir, $new_tree_object) = @_;
215 rm_subdir_cached $subdir;
216 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
219 sub make_commit ($$) {
220 my ($parents, $message_paras) = @_;
221 my $tree = cmdoutput @git, qw(write-tree);
222 my @cmd = (@git, qw(commit-tree), $tree);
223 push @cmd, qw(-p), $_ foreach @$parents;
224 push @cmd, qw(-m), $_ foreach @$message_paras;
225 return cmdoutput @cmd;
228 our @snag_force_opts;
233 if (grep { $_ eq $tag } @snag_force_opts) {
235 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
238 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
242 sub snags_maybe_bail () {
245 "%s: snags: %d overriden by individual -f options\n",
248 if ($snags_tripped) {
251 "%s: snags: %d overriden by global --force\n",
255 "%s: snags: %d blockers (you could -f<tag>, or --force)",
261 return $snags_forced || $snags_tripped;
264 # classify returns an info hash like this
266 # Hdr => # commit headers, including 1 final newline
267 # Msg => # commit message (so one newline is dropped)
269 # Type => (see below)
271 # Ix => $index # ie 0, 1, 2, ...
273 # Differs => return value from get_differs
275 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
277 # NewMsg => # commit message, but with any [dgit import ...] edited
278 # # to say "[was: ...]"
288 # has additional entres in classification result
289 # Overwritten = [ subset of Parents ]
290 # Contributor = $the_remaining_Parent
292 # DgitImportUnpatched
293 # has additional entry in classification result
294 # OrigParents = [ subset of Parents ]
297 # has additional entry in classification result
298 # OrigParents = [ subset of Parents ] # singleton list
305 # has additional entry in classification result
308 sub parsecommit ($;$) {
309 my ($objid, $p_ref) = @_;
310 # => hash with CommitId Hdr Msg Tree Parents
311 # Parents entries have only Ix CommitId
312 # $p_ref, if provided, must be [] and is used as a base for Parents
317 my ($h,$m) = get_commit $objid;
319 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
320 my (@ph) = $h =~ m/^parent (\w+)$/mg;
330 foreach my $ph (@ph) {
332 Ix => scalar @$p_ref,
344 my $r = parsecommit($objid, \@p);
348 $p->{Differs} = (get_differs $p->{CommitId}, $t),
351 printdebug "classify $objid \$t=$t \@p",
352 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
356 my ($type, @rest) = @_;
357 $r = { %$r, Type => $type, @rest };
359 printdebug " = $type ".(dd $r)."\n";
365 $r = { %$r, Type => qw(Unknown), Why => $why };
366 printdebug " ** Unknown\n";
370 if (grep { $_ eq $objid } @opt_anchors) {
371 return $classify->('TreatAsAnchor');
374 my @identical = grep { !$_->{Differs} } @p;
375 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
376 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
378 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
379 # multi-orig upstreams are represented with an anchor merge
380 # from a single upstream commit which combines the orig tarballs
382 # Every anchor tagged this way must be a merge.
383 # We are relying on the
384 # [git-debrebase anchor: ...]
385 # commit message annotation in "declare" anchor merges (which
386 # do not have any upstream changes), to distinguish those
387 # anchor merges from ordinary pseudomerges (which we might
388 # just try to strip).
390 # However, the user is going to be doing git-rebase a lot. We
391 # really don't want them to rewrite an anchor commit.
392 # git-rebase trips up on merges, so that is a useful safety
395 # BreakwaterStart commits are also anchors in the terminology
396 # of git-debrebase(5), but they are untagged (and always
397 # manually generated).
399 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
400 @p == 2 or return $badanchor->("has other than two parents");
401 $haspatches and return $badanchor->("contains debian/patches");
403 # How to decide about l/r ordering of anchors ? git
404 # --topo-order prefers to expand 2nd parent first. There's
405 # already an easy rune to look for debian/ history anyway (git log
406 # debian/) so debian breakwater branch should be 1st parent; that
407 # way also there's also an easy rune to look for the upstream
408 # patches (--topo-order).
410 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
411 $p[1]{Differs} & ~DS_DEB and
412 $badanchor->("upstream files differ from left parent");
413 $p[0]{Differs} & ~D_UPS and
414 $badanchor->("debian/ differs from right parent");
416 return $classify->(qw(Anchor),
417 OrigParents => [ $p[1] ]);
421 my $d = $r->{Parents}[0]{Differs};
422 if ($d == D_PAT_ADD) {
423 return $classify->(qw(AddPatches));
424 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
425 return $unknown->("edits debian/patches");
426 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
427 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
429 if ($d == D_DEB_CLOG) {
430 return $classify->(qw(Changelog));
432 return $classify->(qw(Packaging));
434 } elsif ($ty eq 'missing') {
435 return $classify->(qw(BreakwaterStart));
437 return $unknown->("parent's debian is not a directory");
439 } elsif ($d == D_UPS) {
440 return $classify->(qw(Upstream));
441 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
442 return $classify->(qw(Mixed));
444 return $unknown->("no changes");
446 confess "internal error $objid ?";
450 return $unknown->("origin commit");
453 if (@p == 2 && @identical == 1) {
454 my @overwritten = grep { $_->{Differs} } @p;
455 confess "internal error $objid ?" unless @overwritten==1;
456 return $classify->(qw(Pseudomerge),
457 Overwritten => [ $overwritten[0] ],
458 Contributor => $identical[0]);
460 if (@p == 2 && @identical == 2) {
462 my ($ph,$pm) = get_commit $_[0]{CommitId};
463 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
467 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
468 if ($order > 0) { # newer first
469 } elsif ($order < 0) {
470 @bytime = reverse @bytime;
472 # same age, default to order made by -s ours
473 # that is, commit was made by someone who preferred L
475 return $classify->(qw(Pseudomerge),
476 SubType => qw(Ambiguous),
477 Contributor => $bytime[0],
478 Overwritten => [ $bytime[1] ]);
481 my ($p_h, $p_m) = get_commit $p->{CommitId};
482 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
483 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
485 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
487 if (!(grep { !$_->{IsOrigin} } @p) and
488 (@orig_ps >= @p - 1) and
489 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
491 return $classify->(qw(DgitImportUnpatched),
492 OrigParents => \@orig_ps);
495 return $unknown->("complex merge");
498 sub keycommits ($;$$$) {
499 my ($head, $furniture, $unclean, $trouble) = @_;
500 # => ($anchor, $breakwater)
502 # $unclean->("unclean-$tagsfx", $msg)
503 # $furniture->("unclean-$tagsfx", $msg)
504 # $dgitimport->("unclean-$tagsfx", $msg)
505 # is callled for each situation or commit that
506 # wouldn't be found in a laundered branch
507 # $furniture is for furniture commits such as might be found on an
508 # interchange branch (pseudomerge, d/patches, changelog)
509 # $trouble is for things whnich prevent the return of
510 # anchor and breakwater information; if that is ignored,
511 # then keycommits returns (undef, undef) instead.
513 # If a callback is undef, fail is called instead.
514 # If a callback is defined but false, the situation is ignored.
516 # no warnings qw(exiting); last;
517 # if the answer is no longer wanted.
519 my ($anchor, $breakwater);
522 my ($cb, $tagsfx, $why) = @_;
523 my $m = "branch needs laundering (run git-debrebase): $why";
524 fail $m unless defined $cb;
526 $cb->("unclean-$tagsfx", $why);
529 my $cl = classify $head;
530 my $ty = $cl->{Type};
531 if ($ty eq 'Packaging') {
532 $breakwater //= $clogonly;
533 $breakwater //= $head;
534 } elsif ($ty eq 'Changelog') {
535 # this is going to count as the tip of the breakwater
536 # only if it has no upstream stuff before it
538 } elsif ($ty eq 'Anchor' or
539 $ty eq 'TreatAsAnchor' or
540 $ty eq 'BreakwaterStart') {
542 $breakwater //= $clogonly;
543 $breakwater //= $head;
545 } elsif ($ty eq 'Upstream') {
546 $x->($unclean, 'ordering',
547 "packaging change ($breakwater) follows upstream change (eg $head)")
548 if defined $breakwater;
551 } elsif ($ty eq 'Mixed') {
552 $x->($unclean, 'mixed',
553 'found mixed upstream/packaging commit ($head)');
556 } elsif ($ty eq 'Pseudomerge' or
557 $ty eq 'AddPatches') {
558 $x->($furniture, (lc $ty),
559 "found interchange bureaucracy commit ($ty, $head)");
560 } elsif ($ty eq 'DgitImportUnpatched') {
561 $x->($trouble, 'dgitimport',
562 "found dgit dsc import ($head)");
565 no warnings qw(exiting);
568 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
570 $head = $cl->{Parents}[0]{CommitId};
572 return ($anchor, $breakwater);
578 $nogenerate,$report) = @_;
579 # => ($tip, $breakwater_tip, $last_anchor)
580 # (or nothing, if $nogenerate)
582 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
584 # go through commits backwards
585 # we generate two lists of commits to apply:
586 # breakwater branch and upstream patches
587 my (@brw_cl, @upp_cl, @processed);
594 my ($prose, $info) = @_;
598 $ms .= "\n\n[git-debrebase$info: $prose]\n";
601 my $rewrite_from_here = sub {
603 my $sp_cl = { SpecialMethod => 'StartRewrite' };
605 push @processed, $sp_cl;
610 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
613 return unless $report;
614 print $report $prdelim, @_;
618 my $bomb = sub { # usage: return $bomb->();
619 print $report " Unprocessable" if $report;
620 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
623 return (undef,undef);
625 die "commit $cur: Cannot cope with this commit (d.".
626 (join ' ', map { sprintf "%#x", $_->{Differs} }
627 @{ $cl->{Parents} }).
628 (defined $cl->{Why} ? "; $cl->{Why}": '').
635 my $build_start = sub {
636 my ($msg, $parent) = @_;
639 no warnings qw(exiting); last;
646 my $ty = $cl->{Type};
647 my $st = $cl->{SubType};
648 $prline->("$cl->{CommitId} $cl->{Type}");
649 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
650 push @processed, $cl;
651 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
652 if ($ty eq 'AddPatches') {
654 $rewrite_from_here->(\@upp_cl);
656 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
660 } elsif ($ty eq 'BreakwaterStart') {
662 $build_start->('FirstPackaging', $cur);
663 } elsif ($ty eq 'Upstream') {
667 } elsif ($ty eq 'Mixed') {
670 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
673 $queue->(\@brw_cl, "debian");
674 $queue->(\@upp_cl, "upstream");
675 $rewrite_from_here->(\@brw_cl);
678 } elsif ($ty eq 'Pseudomerge') {
679 my $contrib = $cl->{Contributor}{CommitId};
680 print $report " Contributor=$contrib" if $report;
681 push @pseudomerges, $cl;
682 $rewrite_from_here->(\@upp_cl);
685 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
687 $build_start->("Anchor", $cur);
688 } elsif ($ty eq 'DgitImportUnpatched') {
689 my $pm = $pseudomerges[-1];
691 # To an extent, this is heuristic. Imports don't have
692 # a useful history of the debian/ branch. We assume
693 # that the first pseudomerge after an import has a
694 # useful history of debian/, and ignore the histories
695 # from later pseudomerges. Often the first pseudomerge
696 # will be the dgit import of the upload to the actual
697 # suite intended by the non-dgit NMUer, and later
698 # pseudomerges may represent in-archive copies.
699 my $ovwrs = $pm->{Overwritten};
700 printf $report " PM=%s \@Overwr:%d",
701 $pm->{CommitId}, (scalar @$ovwrs)
704 printdebug "*** WALK BOMB DgitImportUnpatched\n";
707 my $ovwr = $ovwrs->[0]{CommitId};
708 printf $report " Overwr=%s", $ovwr if $report;
709 # This import has a tree which is just like a
710 # breakwater tree, but it has the wrong history. It
711 # ought to have the previous breakwater (which the
712 # pseudomerge overwrote) as an ancestor. That will
713 # make the history of the debian/ files correct. As
714 # for the upstream version: either it's the same as
715 # was ovewritten (ie, same as the previous
716 # breakwater), in which case that history is precisely
717 # right; or, otherwise, it was a non-gitish upload of a
718 # new upstream version. We can tell these apart by
719 # looking at the tree of the supposed upstream.
722 SpecialMethod => 'DgitImportDebianUpdate',
723 $xmsg->("convert dgit import: debian changes")
726 SpecialMethod => 'DgitImportUpstreamUpdate',
727 $xmsg->("convert dgit import: upstream update",
730 $prline->(" Import");
731 $rewrite_from_here->(\@brw_cl);
732 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
736 # Everything is from this import. This kind of import
737 # is already in valid breakwater format, with the
738 # patches as commits.
739 printf $report " NoPM" if $report;
740 # last thing we processed will have been the first patch,
741 # if there is one; which is fine, so no need to rewrite
742 # on account of this import
743 $build_start->("ImportOrigin", $cur);
747 printdebug "*** WALK BOMB unrecognised\n";
753 printdebug "*** WALK prep done cur=$cur".
754 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
756 return if $nogenerate;
758 # Now we build it back up again
764 my $read_tree_debian = sub {
766 read_tree_subdir 'debian', "$treeish:debian";
767 rm_subdir_cached 'debian/patches';
769 my $read_tree_upstream = sub {
771 runcmd @git, qw(read-tree), $treeish;
772 $read_tree_debian->($build);
775 $#upp_cl = $upp_limit if defined $upp_limit;
777 my $committer_authline = calculate_committer_authline();
779 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
781 confess "internal error" unless $build eq (pop @processed)->{CommitId};
784 mkdir $rd or $!==EEXIST or die $!;
786 runcmd @git, qw(read-tree), $build;
787 foreach my $cl (qw(Debian), (reverse @brw_cl),
788 { SpecialMethod => 'RecordBreakwaterTip' },
789 qw(Upstream), (reverse @upp_cl)) {
791 $current_method = $cl;
794 my $method = $cl->{SpecialMethod} // $current_method;
795 my @parents = ($build);
796 my $cltree = $cl->{CommitId};
797 printdebug "WALK BUILD ".($cltree//'undef').
798 " $method (rewriting=$rewriting)\n";
799 if ($method eq 'Debian') {
800 $read_tree_debian->($cltree);
801 } elsif ($method eq 'Upstream') {
802 $read_tree_upstream->($cltree);
803 } elsif ($method eq 'StartRewrite') {
806 } elsif ($method eq 'RecordBreakwaterTip') {
807 $breakwater = $build;
809 } elsif ($method eq 'DgitImportDebianUpdate') {
810 $read_tree_debian->($cltree);
811 } elsif ($method eq 'DgitImportUpstreamUpdate') {
812 confess unless $rewriting;
813 my $differs = (get_differs $build, $cltree);
814 next unless $differs & D_UPS;
815 $read_tree_upstream->($cltree);
816 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
821 my $procd = (pop @processed) // 'UNDEF';
824 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
827 my $newtree = cmdoutput @git, qw(write-tree);
829 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
830 $ch =~ s{^parent .*\n}{}mg;
831 $ch =~ s{(?=^author)}{
832 join '', map { "parent $_\n" } @parents
833 }me or confess "$ch ?";
835 $ch =~ s{^committer .*$}{$committer_authline}m
838 my $cf = "$rd/m$rewriting";
839 open CD, ">", $cf or die $!;
840 print CD $ch, "\n", $cl->{Msg} or die $!;
842 my @cmd = (@git, qw(hash-object));
843 push @cmd, qw(-w) if $rewriting;
844 push @cmd, qw(-t commit), $cf;
845 my $newcommit = cmdoutput @cmd;
846 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
848 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
854 my $final_check = get_differs $build, $input;
855 die sprintf "internal error %#x %s %s", $final_check, $build, $input
856 if $final_check & ~D_PAT_ADD;
858 my @r = ($build, $breakwater, $last_anchor);
859 printdebug "*** WALK RETURN @r\n";
864 git_check_unmodified();
865 return git_rev_parse qw(HEAD);
868 sub update_head ($$$) {
869 my ($old, $new, $mrest) = @_;
870 push @deferred_updates, "update HEAD $new $old";
871 run_deferred_updates $mrest;
874 sub update_head_checkout ($$$) {
875 my ($old, $new, $mrest) = @_;
876 update_head $old, $new, $mrest;
877 runcmd @git, qw(reset --hard);
880 sub update_head_postlaunder ($$$) {
881 my ($old, $tip, $reflogmsg) = @_;
882 return if $tip eq $old;
883 print "git-debrebase: laundered (head was $old)\n";
884 update_head $old, $tip, $reflogmsg;
885 # no tree changes except debian/patches
886 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
889 sub do_launder_head ($) {
890 my ($reflogmsg) = @_;
891 my $old = get_head();
893 my ($tip,$breakwater) = walk $old;
894 update_head_postlaunder $old, $tip, $reflogmsg;
895 return ($tip,$breakwater);
898 sub cmd_launder_v0 () {
899 badusage "no arguments to launder-v0 allowed" if @ARGV;
900 my $old = get_head();
901 my ($tip,$breakwater,$last_anchor) = walk $old;
902 update_head_postlaunder $old, $tip, 'launder';
903 printf "# breakwater tip\n%s\n", $breakwater;
904 printf "# working tip\n%s\n", $tip;
905 printf "# last anchor\n%s\n", $last_anchor;
908 sub defaultcmd_rebase () {
909 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
910 runcmd @git, qw(rebase), @ARGV, $breakwater;
914 die if ($ARGV[0]//'') =~ m/^-/;
915 badusage "too many arguments to analyse" if @ARGV>1;
918 $old = git_rev_parse $old;
920 $old = git_rev_parse 'HEAD';
922 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
923 STDOUT->error and die $!;
926 sub ffq_prev_branchinfo () {
927 # => ('status', "message", [$current, $ffq_prev, $gdrlast])
929 # branch message is undef
930 # weird-symref } no $current,
931 # notbranch } no $ffq_prev
932 my $current = git_get_symref();
933 return ('detached', 'detached HEAD') unless defined $current;
934 return ('weird-symref', 'HEAD symref is not to refs/')
935 unless $current =~ m{^refs/};
936 my $ffq_prev = "refs/$ffq_refprefix/$'";
937 my $gdrlast = "refs/$gdrlast_refprefix/$'";
938 printdebug "ffq_prev_branchinfo branch current $current\n";
939 return ('branch', undef, $current, $ffq_prev, $gdrlast);
942 sub record_ffq_prev_deferred () {
943 # => ('status', "message")
945 # deferred message is undef
950 # if not ff from some branch we should be ff from, is an snag
951 # if "deferred", will have added something about that to
952 # @deferred_update_messages, and also maybe printed (already)
953 # some messages about ff checks
954 my ($status, $message, $current, $ffq_prev, $gdrlast)
955 = ffq_prev_branchinfo();
956 return ($status, $message) unless $status eq 'branch';
958 my $currentval = get_head();
960 my $exists = git_get_ref $ffq_prev;
961 return ('exists',"$ffq_prev already exists") if $exists;
963 return ('not-branch', 'HEAD symref is not to refs/heads/')
964 unless $current =~ m{^refs/heads/};
967 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
970 printdebug "ffq check_specs @check_specs\n";
973 my ($lrref, $desc) = @_;
974 printdebug "ffq might check $lrref ($desc)\n";
976 for my $chk (@check_specs) {
978 $invert = $glob =~ s{^[!^]}{};
979 last if fnmatch $glob, $lrref;
982 my $lrval = git_get_ref $lrref;
983 return unless defined $lrval;
985 if (is_fast_fwd $lrval, $currentval) {
986 print "OK, you are ahead of $lrref\n" or die $!;
987 $checked{$lrref} = 1;
988 } elsif (is_fast_fwd $currentval, $lrval) {
989 $checked{$lrref} = -1;
990 snag 'behind', "you are behind $lrref, divergence risk";
992 $checked{$lrref} = -1;
993 snag 'diverged', "you have diverged from $lrref";
997 my $merge = cfg "branch.$branch.merge",1;
998 if (defined $merge and $merge =~ m{^refs/heads/}) {
1000 printdebug "ffq merge $rhs\n";
1001 my $check_remote = sub {
1002 my ($remote, $desc) = @_;
1003 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1004 return unless defined $remote;
1005 $check->("refs/remotes/$remote/$rhs", $desc);
1007 $check_remote->((scalar cfg "branch.$branch.remote",1),
1008 'remote fetch/merge branch');
1009 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1010 (scalar cfg "branch.$branch.pushDefault",1),
1011 'remote push branch');
1013 if ($branch =~ m{^dgit/}) {
1014 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1015 } elsif ($branch =~ m{^master$}) {
1016 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1021 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1022 push @deferred_updates, "delete $gdrlast";
1023 push @deferred_update_messages, "Recorded current head for preservation";
1024 return ('deferred', undef);
1027 sub record_ffq_auto () {
1028 my ($status, $message) = record_ffq_prev_deferred();
1029 if ($status eq 'deferred' || $status eq 'exists') {
1031 snag $status, "could not record ffq-prev: $message";
1036 sub ffq_prev_info () {
1037 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1038 my ($status, $message, $current, $ffq_prev, $gdrlast)
1039 = ffq_prev_branchinfo();
1040 if ($status ne 'branch') {
1041 snag $status, "could not check ffq-prev: $message";
1044 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1045 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1048 sub stitch ($$$$$) {
1049 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1051 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1053 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1054 my $differs = get_differs $old_head, $ffq_prev_commitish;
1055 unless ($differs & ~D_PAT_ADD) {
1056 # ffq-prev is ahead of us, and the only tree changes it has
1057 # are possibly addition of things in debian/patches/.
1058 # Just wind forwards rather than making a pointless pseudomerge.
1059 push @deferred_updates,
1060 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1061 update_head_checkout $old_head, $ffq_prev_commitish,
1062 "stitch (fast forward)";
1067 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1068 'Declare fast forward / record previous work',
1069 "[git-debrebase pseudomerge: $prose]",
1071 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1072 update_head $old_head, $new_head, "stitch: $prose";
1078 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1079 if (!$ffq_prev_commitish) {
1080 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1083 my $dangling_head = get_head();
1085 keycommits $dangling_head, \&snag, \&snag, \&snag;
1087 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1090 sub cmd_new_upstream_v0 () {
1091 # automatically and unconditionally launders before rebasing
1092 # if rebase --abort is used, laundering has still been done
1096 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1098 # parse args - low commitment
1099 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1100 my $new_upstream_version = $new_version->version();
1102 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1107 my ($n, @x) = @_; # may be ''
1108 my $pc = $pieces{$n} //= {
1110 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1112 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1117 my $newpiece = sub {
1118 my ($n, @x) = @_; # may be ''
1119 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1120 push @newpieces, $pc;
1125 New => $new_upstream,
1127 while (@ARGV && $ARGV[0] !~ m{^-}) {
1128 my $n = shift @ARGV;
1130 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1131 unless @ARGV && $ARGV[0] !~ m{^-};
1133 my $c = git_rev_parse shift @ARGV;
1134 die unless $n =~ m/^$extra_orig_namepart_re$/;
1135 $newpiece->($n, New => $c);
1138 # now we need to investigate the branch this generates the
1139 # laundered version but we don't switch to it yet
1140 my $old_head = get_head();
1141 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1143 my $old_bw_cl = classify $old_bw;
1144 my $old_anchor_cl = classify $old_anchor;
1146 if (!$old_anchor_cl->{OrigParents}) {
1147 snag 'anchor-treated',
1148 'old anchor is recognised due to --anchor, cannot check upstream';
1150 $old_upstream = parsecommit
1151 $old_anchor_cl->{OrigParents}[0]{CommitId};
1152 $piece->('', Old => $old_upstream->{CommitId});
1155 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1156 if ($old_upstream->{Msg} =~
1157 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1159 my @oldpieces = ('', split / /, $1);
1160 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1161 foreach my $i (0..$#oldpieces) {
1162 my $n = $oldpieces[$i];
1163 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1166 snag 'upstream-confusing',
1167 "previous upstream $old_upstream->{CommitId} is from".
1168 " git-debrebase but not an \`upstream-combine' commit";
1172 foreach my $pc (values %pieces) {
1173 if (!$old_upstream) {
1174 # we have complained already
1175 } elsif (!$pc->{Old}) {
1176 snag 'upstream-new-piece',
1177 "introducing upstream piece \`$pc->{Name}'";
1178 } elsif (!$pc->{New}) {
1179 snag 'upstream-rm-piece',
1180 "dropping upstream piece \`$pc->{Name}'";
1181 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1182 snag 'upstream-not-ff',
1183 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1187 printdebug "%pieces = ", (dd \%pieces), "\n";
1188 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1196 my @upstream_merge_parents;
1199 push @upstream_merge_parents, $old_upstream->{CommitId};
1202 foreach my $pc (@newpieces) { # always has '' first
1204 read_tree_subdir $pc->{Name}, $pc->{New};
1206 runcmd @git, qw(read-tree), $pc->{New};
1208 push @upstream_merge_parents, $pc->{New};
1211 # index now contains the new upstream
1213 if (@newpieces > 1) {
1214 # need to make the upstream subtree merge commit
1215 $new_upstream = make_commit \@upstream_merge_parents,
1216 [ "Combine upstreams for $new_upstream_version",
1217 ("[git-debrebase upstream-combine . ".
1218 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1223 # $new_upstream is either the single upstream commit, or the
1224 # combined commit we just made. Either way it will be the
1225 # "upstream" parent of the anchor merge.
1227 read_tree_subdir 'debian', "$old_bw:debian";
1229 # index now contains the anchor merge contents
1230 $new_bw = make_commit [ $old_bw, $new_upstream ],
1231 [ "Update to upstream $new_upstream_version",
1232 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1235 # Now we have to add a changelog stanza so the Debian version
1237 die if unlink "debian";
1238 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1239 unlink "debian/changelog" or $!==ENOENT or die $!;
1240 mkdir "debian" or die $!;
1241 open CN, ">", "debian/changelog" or die $!;
1242 my $oldclog = git_cat_file ":debian/changelog";
1243 $oldclog =~ m/^($package_re) \(\S+\) / or
1244 fail "cannot parse old changelog to get package name";
1246 print CN <<END, $oldclog or die $!;
1247 $p ($new_version) UNRELEASED; urgency=medium
1249 * Update to new upstream version $new_upstream_version.
1255 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1257 # Now we have the final new breakwater branch in the index
1258 $new_bw = make_commit [ $new_bw ],
1259 [ "Update changelog for new upstream $new_upstream_version",
1260 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1264 # we have constructed the new breakwater. we now need to commit to
1265 # the laundering output, because git-rebase can't easily be made
1266 # to make a replay list which is based on some other branch
1268 update_head_postlaunder $old_head, $old_laundered_tip,
1269 'launder for new upstream';
1271 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1273 # now it's for the user to sort out
1276 sub cmd_record_ffq_prev () {
1277 badusage "no arguments allowed" if @ARGV;
1278 my ($status, $msg) = record_ffq_prev_deferred();
1279 if ($status eq 'exists' && $opt_noop_ok) {
1280 print "Previous head already recorded\n" or die $!;
1281 } elsif ($status eq 'deferred') {
1282 run_deferred_updates 'record-ffq-prev';
1284 fail "Could not preserve: $msg";
1289 badusage "no arguments allowed" if @ARGV;
1290 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1291 print "$bw\n" or die $!;
1294 sub cmd_breakwater () {
1295 badusage "no arguments allowed" if @ARGV;
1296 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1297 print "$bw\n" or die $!;
1301 my $prose = 'stitch';
1302 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1303 badusage "no arguments allowed" if @ARGV;
1307 sub cmd_conclude () {
1308 badusage "no arguments allowed" if @ARGV;
1309 do_launder_head 'launder for conclude';
1310 do_stitch 'conclude';
1313 sub cmd_convert_from_gbp () {
1314 badusage "needs 1 optional argument, the upstream git rev"
1316 my ($upstream_spec) = @ARGV;
1317 $upstream_spec //= 'refs/heads/upstream';
1318 my $upstream = git_rev_parse $upstream_spec;
1319 my $old_head = get_head();
1321 my $upsdiff = get_differs $upstream, $old_head;
1322 if ($upsdiff & D_UPS) {
1323 runcmd @git, qw(--no-pager diff),
1324 $upstream, $old_head,
1325 qw( -- :!/debian :/);
1326 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1329 if (!is_fast_fwd $upstream, $old_head) {
1330 snag 'upstream-not-ancestor',
1331 "upstream ($upstream) is not an ancestor of HEAD";
1333 my $wrong = cmdoutput
1334 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1335 qw(-- :/ :!/debian));
1336 if (length $wrong) {
1337 snag 'unexpected-upstream-changes',
1338 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1339 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1343 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1344 snag 'upstream-has-debian',
1345 "upstream ($upstream) contains debian/ directory";
1354 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1355 # make a branch out of the patch queue - we'll want this in a mo
1356 runcmd qw(gbp pq import);
1357 # strip the patches out
1358 runcmd @git, qw(checkout -q gdr-internal~0);
1359 rm_subdir_cached 'debian/patches';
1360 $work = make_commit ['HEAD'], [
1361 'git-debrebase convert-from-gbp: drop patches from tree',
1362 'Delete debian/patches, as part of converting to git-debrebase format.',
1363 '[git-debrebase convert-from-gbp: drop patches from tree]'
1365 # make the anchor merge
1366 # the tree is already exactly right
1367 $work = make_commit [$work, $upstream], [
1368 'git-debrebase import: declare upstream',
1369 'First breakwater merge.',
1370 '[git-debrebase anchor: declare upstream]'
1373 # rebase the patch queue onto the new breakwater
1374 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1375 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1376 $work = git_rev_parse 'HEAD';
1379 update_head_checkout $old_head, $work, 'convert-from-gbp';
1382 sub cmd_convert_to_gbp () {
1383 badusage "no arguments allowed" if @ARGV;
1384 my $head = get_head();
1385 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1386 my ($anchor, $bw) = keycommits $head, 0;
1390 runcmd @git, qw(checkout -q -b bw), $bw;
1391 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1392 runcmd qw(gbp pq export);
1393 runcmd @git, qw(add debian/patches);
1394 $out = make_commit ['HEAD'], [
1395 'Commit patch queue (converted from git-debrebase format)',
1396 '[git-debrebase convert-to-gbp: commit patches]',
1400 push @deferred_updates, "delete $ffq";
1401 push @deferred_updates, "delete $gdrlast";
1403 update_head_checkout $head, $out, "convert to gbp (v0)";
1404 print <<END or die $!;
1405 git-debrebase: converted to git-buildpackage branch format
1406 git-debrebase: WARNING: do not now run "git-debrebase" any more
1407 git-debrebase: WARNING: doing so would drop all upstream patches!
1411 sub cmd_downstream_rebase_launder_v0 () {
1412 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1414 $base = git_rev_parse $base;
1415 my $old_head = get_head();
1416 my $current = $old_head;
1419 if ($current eq $base) {
1420 $topmost_keep //= $current;
1421 print " $current BASE stop\n";
1424 my $cl = classify $current;
1425 print " $current $cl->{Type}";
1427 my $p0 = $cl->{Parents}[0]{CommitId};
1429 if ($cl->{Type} eq 'Pseudomerge') {
1430 print " ^".($cl->{Contributor}{Ix}+1);
1431 $next = $cl->{Contributor}{CommitId};
1432 } elsif ($cl->{Type} eq 'AddPatches' or
1433 $cl->{Type} eq 'Changelog') {
1443 $topmost_keep //= $current;
1445 die "to-be stripped changes not on top of the branch\n"
1450 if ($topmost_keep eq $old_head) {
1451 print "unchanged\n";
1453 print "updating to $topmost_keep\n";
1454 update_head_checkout
1455 $old_head, $topmost_keep,
1456 'downstream-rebase-launder-v0';
1460 GetOptions("D+" => \$debuglevel,
1461 'noop-ok', => \$opt_noop_ok,
1462 'f=s' => \@snag_force_opts,
1463 'anchor=s' => \@opt_anchors,
1464 'force!') or die badusage "bad options\n";
1465 initdebug('git-debrebase ');
1466 enabledebug if $debuglevel;
1468 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1469 chdir $toplevel or die "chdir $toplevel: $!";
1471 $rd = fresh_playground "$playprefix/misc";
1473 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1475 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1476 defaultcmd_rebase();
1478 my $cmd = shift @ARGV;
1481 $cmdfn = ${*::}{"cmd_$cmdfn"};
1483 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";