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 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
401 @p == 2 or return $badanchor->("has other than two parents");
402 $haspatches and return $badanchor->("contains debian/patches");
404 # How to decide about l/r ordering of anchors ? git
405 # --topo-order prefers to expand 2nd parent first. There's
406 # already an easy rune to look for debian/ history anyway (git log
407 # debian/) so debian breakwater branch should be 1st parent; that
408 # way also there's also an easy rune to look for the upstream
409 # patches (--topo-order).
411 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
412 $p[1]{Differs} & ~DS_DEB and
413 $badanchor->("upstream files differ from left parent");
414 $p[0]{Differs} & ~D_UPS and
415 $badanchor->("debian/ differs from right parent");
417 return $classify->(qw(Anchor),
418 OrigParents => [ $p[1] ]);
422 my $d = $r->{Parents}[0]{Differs};
423 if ($d == D_PAT_ADD) {
424 return $classify->(qw(AddPatches));
425 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
426 return $unknown->("edits debian/patches");
427 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
428 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
430 if ($d == D_DEB_CLOG) {
431 return $classify->(qw(Changelog));
433 return $classify->(qw(Packaging));
435 } elsif ($ty eq 'missing') {
436 return $classify->(qw(BreakwaterStart));
438 return $unknown->("parent's debian is not a directory");
440 } elsif ($d == D_UPS) {
441 return $classify->(qw(Upstream));
442 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
443 return $classify->(qw(Mixed));
445 return $unknown->("no changes");
447 confess "internal error $objid ?";
451 return $unknown->("origin commit");
454 if (@p == 2 && @identical == 1) {
455 my @overwritten = grep { $_->{Differs} } @p;
456 confess "internal error $objid ?" unless @overwritten==1;
457 return $classify->(qw(Pseudomerge),
458 Overwritten => [ $overwritten[0] ],
459 Contributor => $identical[0]);
461 if (@p == 2 && @identical == 2) {
463 my ($ph,$pm) = get_commit $_[0]{CommitId};
464 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
468 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
469 if ($order > 0) { # newer first
470 } elsif ($order < 0) {
471 @bytime = reverse @bytime;
473 # same age, default to order made by -s ours
474 # that is, commit was made by someone who preferred L
476 return $classify->(qw(Pseudomerge),
477 SubType => qw(Ambiguous),
478 Contributor => $bytime[0],
479 Overwritten => [ $bytime[1] ]);
482 my ($p_h, $p_m) = get_commit $p->{CommitId};
483 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
484 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
486 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
488 if (!(grep { !$_->{IsOrigin} } @p) and
489 (@orig_ps >= @p - 1) and
490 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
492 return $classify->(qw(DgitImportUnpatched),
493 OrigParents => \@orig_ps);
496 return $unknown->("complex merge");
499 sub keycommits ($;$$$) {
500 my ($head, $furniture, $unclean, $trouble) = @_;
501 # => ($anchor, $breakwater)
503 # $unclean->("unclean-$tagsfx", $msg)
504 # $furniture->("unclean-$tagsfx", $msg)
505 # $dgitimport->("unclean-$tagsfx", $msg)
506 # is callled for each situation or commit that
507 # wouldn't be found in a laundered branch
508 # $furniture is for furniture commits such as might be found on an
509 # interchange branch (pseudomerge, d/patches, changelog)
510 # $trouble is for things whnich prevent the return of
511 # anchor and breakwater information; if that is ignored,
512 # then keycommits returns (undef, undef) instead.
514 # If a callback is undef, fail is called instead.
515 # If a callback is defined but false, the situation is ignored.
517 # no warnings qw(exiting); last;
518 # if the answer is no longer wanted.
520 my ($anchor, $breakwater);
523 my ($cb, $tagsfx, $why) = @_;
524 my $m = "branch needs laundering (run git-debrebase): $why";
525 fail $m unless defined $cb;
527 $cb->("unclean-$tagsfx", $why);
530 my $cl = classify $head;
531 my $ty = $cl->{Type};
532 if ($ty eq 'Packaging') {
533 $breakwater //= $clogonly;
534 $breakwater //= $head;
535 } elsif ($ty eq 'Changelog') {
536 # this is going to count as the tip of the breakwater
537 # only if it has no upstream stuff before it
539 } elsif ($ty eq 'Anchor' or
540 $ty eq 'TreatAsAnchor' or
541 $ty eq 'BreakwaterStart') {
543 $breakwater //= $clogonly;
544 $breakwater //= $head;
546 } elsif ($ty eq 'Upstream') {
547 $x->($unclean, 'ordering',
548 "packaging change ($breakwater) follows upstream change (eg $head)")
549 if defined $breakwater;
552 } elsif ($ty eq 'Mixed') {
553 $x->($unclean, 'mixed',
554 'found mixed upstream/packaging commit ($head)');
557 } elsif ($ty eq 'Pseudomerge' or
558 $ty eq 'AddPatches') {
559 $x->($furniture, (lc $ty),
560 "found interchange bureaucracy commit ($ty, $head)");
561 } elsif ($ty eq 'DgitImportUnpatched') {
562 $x->($trouble, 'dgitimport',
563 "found dgit dsc import ($head)");
566 no warnings qw(exiting);
569 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
571 $head = $cl->{Parents}[0]{CommitId};
573 return ($anchor, $breakwater);
579 $nogenerate,$report) = @_;
580 # => ($tip, $breakwater_tip, $last_anchor)
581 # (or nothing, if $nogenerate)
583 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
585 # go through commits backwards
586 # we generate two lists of commits to apply:
587 # breakwater branch and upstream patches
588 my (@brw_cl, @upp_cl, @processed);
595 my ($prose, $info) = @_;
599 $ms .= "\n\n[git-debrebase$info: $prose]\n";
602 my $rewrite_from_here = sub {
604 my $sp_cl = { SpecialMethod => 'StartRewrite' };
606 push @processed, $sp_cl;
611 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
614 return unless $report;
615 print $report $prdelim, @_;
619 my $bomb = sub { # usage: return $bomb->();
620 print $report " Unprocessable" if $report;
621 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
624 return (undef,undef);
626 die "commit $cur: Cannot cope with this commit (d.".
627 (join ' ', map { sprintf "%#x", $_->{Differs} }
628 @{ $cl->{Parents} }).
629 (defined $cl->{Why} ? "; $cl->{Why}": '').
636 my $build_start = sub {
637 my ($msg, $parent) = @_;
640 no warnings qw(exiting); last;
647 my $ty = $cl->{Type};
648 my $st = $cl->{SubType};
649 $prline->("$cl->{CommitId} $cl->{Type}");
650 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
651 push @processed, $cl;
652 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
653 if ($ty eq 'AddPatches') {
655 $rewrite_from_here->(\@upp_cl);
657 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
661 } elsif ($ty eq 'BreakwaterStart') {
663 $build_start->('FirstPackaging', $cur);
664 } elsif ($ty eq 'Upstream') {
668 } elsif ($ty eq 'Mixed') {
671 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
674 $queue->(\@brw_cl, "debian");
675 $queue->(\@upp_cl, "upstream");
676 $rewrite_from_here->(\@brw_cl);
679 } elsif ($ty eq 'Pseudomerge') {
680 my $contrib = $cl->{Contributor}{CommitId};
681 print $report " Contributor=$contrib" if $report;
682 push @pseudomerges, $cl;
683 $rewrite_from_here->(\@upp_cl);
686 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
688 $build_start->("Anchor", $cur);
689 } elsif ($ty eq 'DgitImportUnpatched') {
690 my $pm = $pseudomerges[-1];
692 # To an extent, this is heuristic. Imports don't have
693 # a useful history of the debian/ branch. We assume
694 # that the first pseudomerge after an import has a
695 # useful history of debian/, and ignore the histories
696 # from later pseudomerges. Often the first pseudomerge
697 # will be the dgit import of the upload to the actual
698 # suite intended by the non-dgit NMUer, and later
699 # pseudomerges may represent in-archive copies.
700 my $ovwrs = $pm->{Overwritten};
701 printf $report " PM=%s \@Overwr:%d",
702 $pm->{CommitId}, (scalar @$ovwrs)
705 printdebug "*** WALK BOMB DgitImportUnpatched\n";
708 my $ovwr = $ovwrs->[0]{CommitId};
709 printf $report " Overwr=%s", $ovwr if $report;
710 # This import has a tree which is just like a
711 # breakwater tree, but it has the wrong history. It
712 # ought to have the previous breakwater (which the
713 # pseudomerge overwrote) as an ancestor. That will
714 # make the history of the debian/ files correct. As
715 # for the upstream version: either it's the same as
716 # was ovewritten (ie, same as the previous
717 # breakwater), in which case that history is precisely
718 # right; or, otherwise, it was a non-gitish upload of a
719 # new upstream version. We can tell these apart by
720 # looking at the tree of the supposed upstream.
723 SpecialMethod => 'DgitImportDebianUpdate',
724 $xmsg->("convert dgit import: debian changes")
727 SpecialMethod => 'DgitImportUpstreamUpdate',
728 $xmsg->("convert dgit import: upstream update",
731 $prline->(" Import");
732 $rewrite_from_here->(\@brw_cl);
733 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
737 # Everything is from this import. This kind of import
738 # is already in valid breakwater format, with the
739 # patches as commits.
740 printf $report " NoPM" if $report;
741 # last thing we processed will have been the first patch,
742 # if there is one; which is fine, so no need to rewrite
743 # on account of this import
744 $build_start->("ImportOrigin", $cur);
748 printdebug "*** WALK BOMB unrecognised\n";
754 printdebug "*** WALK prep done cur=$cur".
755 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
757 return if $nogenerate;
759 # Now we build it back up again
765 my $read_tree_debian = sub {
767 read_tree_subdir 'debian', "$treeish:debian";
768 rm_subdir_cached 'debian/patches';
770 my $read_tree_upstream = sub {
772 runcmd @git, qw(read-tree), $treeish;
773 $read_tree_debian->($build);
776 $#upp_cl = $upp_limit if defined $upp_limit;
778 my $committer_authline = calculate_committer_authline();
780 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
782 confess "internal error" unless $build eq (pop @processed)->{CommitId};
785 mkdir $rd or $!==EEXIST or die $!;
787 runcmd @git, qw(read-tree), $build;
788 foreach my $cl (qw(Debian), (reverse @brw_cl),
789 { SpecialMethod => 'RecordBreakwaterTip' },
790 qw(Upstream), (reverse @upp_cl)) {
792 $current_method = $cl;
795 my $method = $cl->{SpecialMethod} // $current_method;
796 my @parents = ($build);
797 my $cltree = $cl->{CommitId};
798 printdebug "WALK BUILD ".($cltree//'undef').
799 " $method (rewriting=$rewriting)\n";
800 if ($method eq 'Debian') {
801 $read_tree_debian->($cltree);
802 } elsif ($method eq 'Upstream') {
803 $read_tree_upstream->($cltree);
804 } elsif ($method eq 'StartRewrite') {
807 } elsif ($method eq 'RecordBreakwaterTip') {
808 $breakwater = $build;
810 } elsif ($method eq 'DgitImportDebianUpdate') {
811 $read_tree_debian->($cltree);
812 } elsif ($method eq 'DgitImportUpstreamUpdate') {
813 confess unless $rewriting;
814 my $differs = (get_differs $build, $cltree);
815 next unless $differs & D_UPS;
816 $read_tree_upstream->($cltree);
817 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
822 my $procd = (pop @processed) // 'UNDEF';
825 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
828 my $newtree = cmdoutput @git, qw(write-tree);
830 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
831 $ch =~ s{^parent .*\n}{}mg;
832 $ch =~ s{(?=^author)}{
833 join '', map { "parent $_\n" } @parents
834 }me or confess "$ch ?";
836 $ch =~ s{^committer .*$}{$committer_authline}m
839 my $cf = "$rd/m$rewriting";
840 open CD, ">", $cf or die $!;
841 print CD $ch, "\n", $cl->{Msg} or die $!;
843 my @cmd = (@git, qw(hash-object));
844 push @cmd, qw(-w) if $rewriting;
845 push @cmd, qw(-t commit), $cf;
846 my $newcommit = cmdoutput @cmd;
847 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
849 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
855 my $final_check = get_differs $build, $input;
856 die sprintf "internal error %#x %s %s", $final_check, $build, $input
857 if $final_check & ~D_PAT_ADD;
859 my @r = ($build, $breakwater, $last_anchor);
860 printdebug "*** WALK RETURN @r\n";
865 git_check_unmodified();
866 return git_rev_parse qw(HEAD);
869 sub update_head ($$$) {
870 my ($old, $new, $mrest) = @_;
871 push @deferred_updates, "update HEAD $new $old";
872 run_deferred_updates $mrest;
875 sub update_head_checkout ($$$) {
876 my ($old, $new, $mrest) = @_;
877 update_head $old, $new, $mrest;
878 runcmd @git, qw(reset --hard);
881 sub update_head_postlaunder ($$$) {
882 my ($old, $tip, $reflogmsg) = @_;
883 return if $tip eq $old;
884 print "git-debrebase: laundered (head was $old)\n";
885 update_head $old, $tip, $reflogmsg;
886 # no tree changes except debian/patches
887 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
890 sub do_launder_head ($) {
891 my ($reflogmsg) = @_;
892 my $old = get_head();
894 my ($tip,$breakwater) = walk $old;
895 update_head_postlaunder $old, $tip, $reflogmsg;
896 return ($tip,$breakwater);
899 sub cmd_launder_v0 () {
900 badusage "no arguments to launder-v0 allowed" if @ARGV;
901 my $old = get_head();
902 my ($tip,$breakwater,$last_anchor) = walk $old;
903 update_head_postlaunder $old, $tip, 'launder';
904 printf "# breakwater tip\n%s\n", $breakwater;
905 printf "# working tip\n%s\n", $tip;
906 printf "# last anchor\n%s\n", $last_anchor;
909 sub defaultcmd_rebase () {
910 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
911 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
912 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
916 die if ($ARGV[0]//'') =~ m/^-/;
917 badusage "too many arguments to analyse" if @ARGV>1;
920 $old = git_rev_parse $old;
922 $old = git_rev_parse 'HEAD';
924 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
925 STDOUT->error and die $!;
928 sub ffq_prev_branchinfo () {
929 # => ('status', "message", [$current, $ffq_prev, $gdrlast])
931 # branch message is undef
932 # weird-symref } no $current,
933 # notbranch } no $ffq_prev
934 my $current = git_get_symref();
935 return ('detached', 'detached HEAD') unless defined $current;
936 return ('weird-symref', 'HEAD symref is not to refs/')
937 unless $current =~ m{^refs/};
938 my $ffq_prev = "refs/$ffq_refprefix/$'";
939 my $gdrlast = "refs/$gdrlast_refprefix/$'";
940 printdebug "ffq_prev_branchinfo branch current $current\n";
941 return ('branch', undef, $current, $ffq_prev, $gdrlast);
944 sub record_ffq_prev_deferred () {
945 # => ('status', "message")
947 # deferred message is undef
952 # if not ff from some branch we should be ff from, is an snag
953 # if "deferred", will have added something about that to
954 # @deferred_update_messages, and also maybe printed (already)
955 # some messages about ff checks
956 my ($status, $message, $current, $ffq_prev, $gdrlast)
957 = ffq_prev_branchinfo();
958 return ($status, $message) unless $status eq 'branch';
960 my $currentval = get_head();
962 my $exists = git_get_ref $ffq_prev;
963 return ('exists',"$ffq_prev already exists") if $exists;
965 return ('not-branch', 'HEAD symref is not to refs/heads/')
966 unless $current =~ m{^refs/heads/};
969 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
972 printdebug "ffq check_specs @check_specs\n";
975 my ($lrref, $desc) = @_;
976 printdebug "ffq might check $lrref ($desc)\n";
978 for my $chk (@check_specs) {
980 $invert = $glob =~ s{^[!^]}{};
981 last if fnmatch $glob, $lrref;
984 my $lrval = git_get_ref $lrref;
985 return unless defined $lrval;
987 if (is_fast_fwd $lrval, $currentval) {
988 print "OK, you are ahead of $lrref\n" or die $!;
989 $checked{$lrref} = 1;
990 } elsif (is_fast_fwd $currentval, $lrval) {
991 $checked{$lrref} = -1;
992 snag 'behind', "you are behind $lrref, divergence risk";
994 $checked{$lrref} = -1;
995 snag 'diverged', "you have diverged from $lrref";
999 my $merge = cfg "branch.$branch.merge",1;
1000 if (defined $merge and $merge =~ m{^refs/heads/}) {
1002 printdebug "ffq merge $rhs\n";
1003 my $check_remote = sub {
1004 my ($remote, $desc) = @_;
1005 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1006 return unless defined $remote;
1007 $check->("refs/remotes/$remote/$rhs", $desc);
1009 $check_remote->((scalar cfg "branch.$branch.remote",1),
1010 'remote fetch/merge branch');
1011 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1012 (scalar cfg "branch.$branch.pushDefault",1),
1013 'remote push branch');
1015 if ($branch =~ m{^dgit/}) {
1016 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1017 } elsif ($branch =~ m{^master$}) {
1018 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1023 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1024 push @deferred_updates, "delete $gdrlast";
1025 push @deferred_update_messages, "Recorded current head for preservation";
1026 return ('deferred', undef);
1029 sub record_ffq_auto () {
1030 my ($status, $message) = record_ffq_prev_deferred();
1031 if ($status eq 'deferred' || $status eq 'exists') {
1033 snag $status, "could not record ffq-prev: $message";
1038 sub ffq_prev_info () {
1039 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1040 my ($status, $message, $current, $ffq_prev, $gdrlast)
1041 = ffq_prev_branchinfo();
1042 if ($status ne 'branch') {
1043 snag $status, "could not check ffq-prev: $message";
1046 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1047 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1050 sub stitch ($$$$$) {
1051 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1053 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1055 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1056 my $differs = get_differs $old_head, $ffq_prev_commitish;
1057 unless ($differs & ~D_PAT_ADD) {
1058 # ffq-prev is ahead of us, and the only tree changes it has
1059 # are possibly addition of things in debian/patches/.
1060 # Just wind forwards rather than making a pointless pseudomerge.
1061 push @deferred_updates,
1062 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1063 update_head_checkout $old_head, $ffq_prev_commitish,
1064 "stitch (fast forward)";
1069 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1070 'Declare fast forward / record previous work',
1071 "[git-debrebase pseudomerge: $prose]",
1073 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1074 update_head $old_head, $new_head, "stitch: $prose";
1080 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1081 if (!$ffq_prev_commitish) {
1082 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1085 my $dangling_head = get_head();
1087 keycommits $dangling_head, \&snag, \&snag, \&snag;
1089 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1092 sub cmd_new_upstream_v0 () {
1093 # automatically and unconditionally launders before rebasing
1094 # if rebase --abort is used, laundering has still been done
1098 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1100 # parse args - low commitment
1101 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1102 my $new_upstream_version = $new_version->version();
1104 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1109 my ($n, @x) = @_; # may be ''
1110 my $pc = $pieces{$n} //= {
1112 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1114 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1119 my $newpiece = sub {
1120 my ($n, @x) = @_; # may be ''
1121 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1122 push @newpieces, $pc;
1127 New => $new_upstream,
1129 while (@ARGV && $ARGV[0] !~ m{^-}) {
1130 my $n = shift @ARGV;
1132 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1133 unless @ARGV && $ARGV[0] !~ m{^-};
1135 my $c = git_rev_parse shift @ARGV;
1136 die unless $n =~ m/^$extra_orig_namepart_re$/;
1137 $newpiece->($n, New => $c);
1140 # now we need to investigate the branch this generates the
1141 # laundered version but we don't switch to it yet
1142 my $old_head = get_head();
1143 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1145 my $old_bw_cl = classify $old_bw;
1146 my $old_anchor_cl = classify $old_anchor;
1148 if (!$old_anchor_cl->{OrigParents}) {
1149 snag 'anchor-treated',
1150 'old anchor is recognised due to --anchor, cannot check upstream';
1152 $old_upstream = parsecommit
1153 $old_anchor_cl->{OrigParents}[0]{CommitId};
1154 $piece->('', Old => $old_upstream->{CommitId});
1157 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1158 if ($old_upstream->{Msg} =~
1159 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1161 my @oldpieces = ('', split / /, $1);
1162 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1163 foreach my $i (0..$#oldpieces) {
1164 my $n = $oldpieces[$i];
1165 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1168 snag 'upstream-confusing',
1169 "previous upstream $old_upstream->{CommitId} is from".
1170 " git-debrebase but not an \`upstream-combine' commit";
1174 foreach my $pc (values %pieces) {
1175 if (!$old_upstream) {
1176 # we have complained already
1177 } elsif (!$pc->{Old}) {
1178 snag 'upstream-new-piece',
1179 "introducing upstream piece \`$pc->{Name}'";
1180 } elsif (!$pc->{New}) {
1181 snag 'upstream-rm-piece',
1182 "dropping upstream piece \`$pc->{Name}'";
1183 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1184 snag 'upstream-not-ff',
1185 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1189 printdebug "%pieces = ", (dd \%pieces), "\n";
1190 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1198 my @upstream_merge_parents;
1201 push @upstream_merge_parents, $old_upstream->{CommitId};
1204 foreach my $pc (@newpieces) { # always has '' first
1206 read_tree_subdir $pc->{Name}, $pc->{New};
1208 runcmd @git, qw(read-tree), $pc->{New};
1210 push @upstream_merge_parents, $pc->{New};
1213 # index now contains the new upstream
1215 if (@newpieces > 1) {
1216 # need to make the upstream subtree merge commit
1217 $new_upstream = make_commit \@upstream_merge_parents,
1218 [ "Combine upstreams for $new_upstream_version",
1219 ("[git-debrebase upstream-combine . ".
1220 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1225 # $new_upstream is either the single upstream commit, or the
1226 # combined commit we just made. Either way it will be the
1227 # "upstream" parent of the anchor merge.
1229 read_tree_subdir 'debian', "$old_bw:debian";
1231 # index now contains the anchor merge contents
1232 $new_bw = make_commit [ $old_bw, $new_upstream ],
1233 [ "Update to upstream $new_upstream_version",
1234 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1237 my $clogsignoff = cmdoutput qw(git show),
1238 '--pretty=format:%an <%ae> %aD',
1241 # Now we have to add a changelog stanza so the Debian version
1243 die if unlink "debian";
1244 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1245 unlink "debian/changelog" or $!==ENOENT or die $!;
1246 mkdir "debian" or die $!;
1247 open CN, ">", "debian/changelog" or die $!;
1248 my $oldclog = git_cat_file ":debian/changelog";
1249 $oldclog =~ m/^($package_re) \(\S+\) / or
1250 fail "cannot parse old changelog to get package name";
1252 print CN <<END, $oldclog or die $!;
1253 $p ($new_version) UNRELEASED; urgency=medium
1255 * Update to new upstream version $new_upstream_version.
1261 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1263 # Now we have the final new breakwater branch in the index
1264 $new_bw = make_commit [ $new_bw ],
1265 [ "Update changelog for new upstream $new_upstream_version",
1266 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1270 # we have constructed the new breakwater. we now need to commit to
1271 # the laundering output, because git-rebase can't easily be made
1272 # to make a replay list which is based on some other branch
1274 update_head_postlaunder $old_head, $old_laundered_tip,
1275 'launder for new upstream';
1277 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1279 # now it's for the user to sort out
1282 sub cmd_record_ffq_prev () {
1283 badusage "no arguments allowed" if @ARGV;
1284 my ($status, $msg) = record_ffq_prev_deferred();
1285 if ($status eq 'exists' && $opt_noop_ok) {
1286 print "Previous head already recorded\n" or die $!;
1287 } elsif ($status eq 'deferred') {
1288 run_deferred_updates 'record-ffq-prev';
1290 fail "Could not preserve: $msg";
1295 badusage "no arguments allowed" if @ARGV;
1296 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1297 print "$bw\n" or die $!;
1300 sub cmd_breakwater () {
1301 badusage "no arguments allowed" if @ARGV;
1302 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1303 print "$bw\n" or die $!;
1307 my $prose = 'stitch';
1308 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1309 badusage "no arguments allowed" if @ARGV;
1313 sub cmd_conclude () {
1314 badusage "no arguments allowed" if @ARGV;
1315 do_launder_head 'launder for conclude';
1316 do_stitch 'conclude';
1319 sub cmd_convert_from_gbp () {
1320 badusage "needs 1 optional argument, the upstream git rev"
1322 my ($upstream_spec) = @ARGV;
1323 $upstream_spec //= 'refs/heads/upstream';
1324 my $upstream = git_rev_parse $upstream_spec;
1325 my $old_head = get_head();
1327 my $upsdiff = get_differs $upstream, $old_head;
1328 if ($upsdiff & D_UPS) {
1329 runcmd @git, qw(--no-pager diff),
1330 $upstream, $old_head,
1331 qw( -- :!/debian :/);
1332 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1335 if (!is_fast_fwd $upstream, $old_head) {
1336 snag 'upstream-not-ancestor',
1337 "upstream ($upstream) is not an ancestor of HEAD";
1339 my $wrong = cmdoutput
1340 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1341 qw(-- :/ :!/debian));
1342 if (length $wrong) {
1343 snag 'unexpected-upstream-changes',
1344 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1345 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1349 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1350 snag 'upstream-has-debian',
1351 "upstream ($upstream) contains debian/ directory";
1360 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1361 # make a branch out of the patch queue - we'll want this in a mo
1362 runcmd qw(gbp pq import);
1363 # strip the patches out
1364 runcmd @git, qw(checkout -q gdr-internal~0);
1365 rm_subdir_cached 'debian/patches';
1366 $work = make_commit ['HEAD'], [
1367 'git-debrebase convert-from-gbp: drop patches from tree',
1368 'Delete debian/patches, as part of converting to git-debrebase format.',
1369 '[git-debrebase convert-from-gbp: drop patches from tree]'
1371 # make the anchor merge
1372 # the tree is already exactly right
1373 $work = make_commit [$work, $upstream], [
1374 'git-debrebase import: declare upstream',
1375 'First breakwater merge.',
1376 '[git-debrebase anchor: declare upstream]'
1379 # rebase the patch queue onto the new breakwater
1380 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1381 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1382 $work = git_rev_parse 'HEAD';
1385 update_head_checkout $old_head, $work, 'convert-from-gbp';
1388 sub cmd_convert_to_gbp () {
1389 badusage "no arguments allowed" if @ARGV;
1390 my $head = get_head();
1391 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1392 my ($anchor, $bw) = keycommits $head, 0;
1396 runcmd @git, qw(checkout -q -b bw), $bw;
1397 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1398 runcmd qw(gbp pq export);
1399 runcmd @git, qw(add debian/patches);
1400 $out = make_commit ['HEAD'], [
1401 'Commit patch queue (converted from git-debrebase format)',
1402 '[git-debrebase convert-to-gbp: commit patches]',
1406 push @deferred_updates, "delete $ffq";
1407 push @deferred_updates, "delete $gdrlast";
1409 update_head_checkout $head, $out, "convert to gbp (v0)";
1410 print <<END or die $!;
1411 git-debrebase: converted to git-buildpackage branch format
1412 git-debrebase: WARNING: do not now run "git-debrebase" any more
1413 git-debrebase: WARNING: doing so would drop all upstream patches!
1417 sub cmd_downstream_rebase_launder_v0 () {
1418 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1420 $base = git_rev_parse $base;
1421 my $old_head = get_head();
1422 my $current = $old_head;
1425 if ($current eq $base) {
1426 $topmost_keep //= $current;
1427 print " $current BASE stop\n";
1430 my $cl = classify $current;
1431 print " $current $cl->{Type}";
1433 my $p0 = $cl->{Parents}[0]{CommitId};
1435 if ($cl->{Type} eq 'Pseudomerge') {
1436 print " ^".($cl->{Contributor}{Ix}+1);
1437 $next = $cl->{Contributor}{CommitId};
1438 } elsif ($cl->{Type} eq 'AddPatches' or
1439 $cl->{Type} eq 'Changelog') {
1449 $topmost_keep //= $current;
1451 die "to-be stripped changes not on top of the branch\n"
1456 if ($topmost_keep eq $old_head) {
1457 print "unchanged\n";
1459 print "updating to $topmost_keep\n";
1460 update_head_checkout
1461 $old_head, $topmost_keep,
1462 'downstream-rebase-launder-v0';
1466 GetOptions("D+" => \$debuglevel,
1467 'noop-ok', => \$opt_noop_ok,
1468 'f=s' => \@snag_force_opts,
1469 'anchor=s' => \@opt_anchors,
1472 my ($opt,$val) = @_;
1473 badusage "git-debrebase: no cuddling to -i for git-rebase"
1475 die if $opt_defaultcmd_interactive; # should not happen
1476 $opt_defaultcmd_interactive = [ qw(-i) ];
1477 # This access to @ARGV is excessive familiarity with
1478 # Getopt::Long, but there isn't another sensible
1479 # approach. '-i=s{0,}' does not work with bundling.
1480 push @$opt_defaultcmd_interactive, @ARGV;
1482 }) or die badusage "bad options\n";
1483 initdebug('git-debrebase ');
1484 enabledebug if $debuglevel;
1486 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1487 chdir $toplevel or die "chdir $toplevel: $!";
1489 $rd = fresh_playground "$playprefix/misc";
1491 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1493 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1494 defaultcmd_rebase();
1496 my $cmd = shift @ARGV;
1499 $cmdfn = ${*::}{"cmd_$cmdfn"};
1501 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";