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 die "bad usage: $m\n";
44 my ($k, $optional) = @_;
46 my @cmd = qw(git config -z);
47 push @cmd, qw(--get-all) if wantarray;
49 my $out = cmdoutput_errok @cmd;
51 fail "missing required git config $k" unless $optional;
54 my @l = split /\0/, $out;
55 return wantarray ? @l : $l[0];
62 my $dd = new Data::Dumper [ $v ];
63 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
69 my $data = (git_cat_file $objid, 'commit');
70 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
74 sub D_UPS () { 0x02; } # upstream files
75 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
76 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
77 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
78 sub D_DEB_OTH () { 0x20; } # debian/changelog
79 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
81 our $playprefix = 'debrebase';
90 my $r = eval { $sub->(); };
91 { local $@; changedir $maindir; }
95 sub fresh_workarea () {
96 $workarea = fresh_playground "$playprefix/work";
97 in_workarea sub { playtree_setup };
100 our @deferred_updates;
101 our @deferred_update_messages;
103 sub run_deferred_updates ($) {
106 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
107 debugcmd '>|', @upd_cmd;
108 open U, "|-", @upd_cmd or die $!;
109 foreach (@deferred_updates) {
110 printdebug ">= ", $_, "\n";
111 print U $_, "\n" or die $!;
114 close U or failedcmd @upd_cmd;
116 print $_, "\n" foreach @deferred_update_messages;
118 @deferred_updates = ();
119 @deferred_update_messages = ();
122 sub get_differs ($$) {
124 # This resembles quiltify_trees_differ, in dgit, a bit.
125 # But we don't care about modes, or dpkg-source-unrepresentable
126 # changes, and we don't need the plethora of different modes.
127 # Conversely we need to distinguish different kinds of changes to
128 # debian/ and debian/patches/.
133 my ($opts, $limits, $fn) = @_;
134 my @cmd = (@git, qw(diff-tree -z --no-renames));
136 push @cmd, "$_:" foreach $x, $y;
137 push @cmd, '--', @$limits;
138 my $diffs = cmdoutput @cmd;
139 foreach (split /\0/, $diffs) { $fn->(); }
142 $rundiff->([qw(--name-only)], [], sub {
143 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
146 if ($differs & DS_DEB) {
148 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
150 m{^debian/patches/} ? D_PAT_OTH :
151 $_ eq 'debian/changelog' ? D_DEB_CLOG :
154 die "mysterious debian changes $x..$y"
155 unless $differs & (D_PAT_OTH|DS_DEB);
158 if ($differs & D_PAT_OTH) {
160 $differs &= ~D_PAT_OTH;
162 $differs |= D_PAT_OTH;
163 no warnings qw(exiting); last;
165 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
166 no warnings qw(exiting);
167 if (!defined $mode) {
170 die unless s{^debian/patches/}{};
172 if ($mode eq 'A' && !m/\.series$/s) {
174 } elsif ($mode eq 'M' && $_ eq 'series') {
175 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
176 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
177 chomp $x_s; $x_s .= "\n";
178 $ok = $x_s eq substr($y_s, 0, length $x_s);
183 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
185 die "mysterious debian/patches changes $x..$y"
186 unless $differs & (D_PAT_ADD|D_PAT_OTH);
189 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
194 sub commit_pr_info ($) {
196 return Data::Dumper->dump([$r], [qw(commit)]);
199 sub calculate_committer_authline () {
200 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
201 'DUMMY COMMIT (git-debrebase)', "HEAD:";
202 my ($h,$m) = get_commit $c;
203 $h =~ m/^committer .*$/m or confess "($h) ?";
207 sub rm_subdir_cached ($) {
209 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
212 sub read_tree_subdir ($$) {
213 my ($subdir, $new_tree_object) = @_;
214 rm_subdir_cached $subdir;
215 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
218 sub make_commit ($$) {
219 my ($parents, $message_paras) = @_;
220 my $tree = cmdoutput @git, qw(write-tree);
221 my @cmd = (@git, qw(commit-tree), $tree);
222 push @cmd, qw(-p), $_ foreach @$parents;
223 push @cmd, qw(-m), $_ foreach @$message_paras;
224 return cmdoutput @cmd;
227 our @fproblem_force_opts;
228 our $fproblems_forced;
229 our $fproblems_tripped;
232 if (grep { $_ eq $tag } @fproblem_force_opts) {
234 print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
236 $fproblems_tripped++;
237 print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
241 sub fproblems_maybe_bail () {
242 if ($fproblems_forced) {
244 "%s: safety catch trips: %d overriden by individual -f options\n",
245 $us, $fproblems_forced;
247 if ($fproblems_tripped) {
250 "%s: safety catch trips: %d overriden by global --force\n",
251 $us, $fproblems_tripped;
254 "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
255 $us, $fproblems_tripped;
259 sub any_fproblems () {
260 return $fproblems_forced || $fproblems_tripped;
263 # classify returns an info hash like this
265 # Hdr => # commit headers, including 1 final newline
266 # Msg => # commit message (so one newline is dropped)
268 # Type => (see below)
270 # Ix => $index # ie 0, 1, 2, ...
272 # Differs => return value from get_differs
274 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
276 # NewMsg => # commit message, but with any [dgit import ...] edited
277 # # to say "[was: ...]"
287 # has additional entres in classification result
288 # Overwritten = [ subset of Parents ]
289 # Contributor = $the_remaining_Parent
291 # DgitImportUnpatched
292 # has additional entry in classification result
293 # OrigParents = [ subset of Parents ]
296 # has additional entry in classification result
297 # OrigParents = [ subset of Parents ] # singleton list
304 # has additional entry in classification result
307 sub parsecommit ($;$) {
308 my ($objid, $p_ref) = @_;
309 # => hash with CommitId Hdr Msg Tree Parents
310 # Parents entries have only Ix CommitId
311 # $p_ref, if provided, must be [] and is used as a base for Parents
316 my ($h,$m) = get_commit $objid;
318 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
319 my (@ph) = $h =~ m/^parent (\w+)$/mg;
329 foreach my $ph (@ph) {
331 Ix => scalar @$p_ref,
343 my $r = parsecommit($objid, \@p);
347 $p->{Differs} = (get_differs $p->{CommitId}, $t),
350 printdebug "classify $objid \$t=$t \@p",
351 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
355 my ($type, @rest) = @_;
356 $r = { %$r, Type => $type, @rest };
358 printdebug " = $type ".(dd $r)."\n";
364 $r = { %$r, Type => qw(Unknown), Why => $why };
365 printdebug " ** Unknown\n";
369 if (grep { $_ eq $objid } @opt_anchors) {
370 return $classify->('TreatAsAnchor');
373 my @identical = grep { !$_->{Differs} } @p;
374 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
375 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
377 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
378 # multi-orig upstreams are represented with an anchor merge
379 # from a single upstream commit which combines the orig tarballs
381 # Every anchor tagged this way must be a merge.
382 # We are relying on the
383 # [git-debrebase anchor: ...]
384 # commit message annotation in "declare" anchor merges (which
385 # do not have any upstream changes), to distinguish those
386 # anchor merges from ordinary pseudomerges (which we might
387 # just try to strip).
389 # However, the user is going to be doing git-rebase a lot. We
390 # really don't want them to rewrite an anchor commit.
391 # git-rebase trips up on merges, so that is a useful safety
394 # BreakwaterStart commits are also anchors in the terminology
395 # of git-debrebase(5), but they are untagged (and always
396 # manually generated).
398 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
399 @p == 2 or return $badanchor->("has other than two parents");
400 $haspatches and return $badanchor->("contains debian/patches");
402 # How to decide about l/r ordering of anchors ? git
403 # --topo-order prefers to expand 2nd parent first. There's
404 # already an easy rune to look for debian/ history anyway (git log
405 # debian/) so debian breakwater branch should be 1st parent; that
406 # way also there's also an easy rune to look for the upstream
407 # patches (--topo-order).
409 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
410 $p[1]{Differs} & ~DS_DEB and
411 $badanchor->("upstream files differ from left parent");
412 $p[0]{Differs} & ~D_UPS and
413 $badanchor->("debian/ differs from right parent");
415 return $classify->(qw(Anchor),
416 OrigParents => [ $p[1] ]);
420 my $d = $r->{Parents}[0]{Differs};
421 if ($d == D_PAT_ADD) {
422 return $classify->(qw(AddPatches));
423 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
424 return $unknown->("edits debian/patches");
425 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
426 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
428 if ($d == D_DEB_CLOG) {
429 return $classify->(qw(Changelog));
431 return $classify->(qw(Packaging));
433 } elsif ($ty eq 'missing') {
434 return $classify->(qw(BreakwaterStart));
436 return $unknown->("parent's debian is not a directory");
438 } elsif ($d == D_UPS) {
439 return $classify->(qw(Upstream));
440 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
441 return $classify->(qw(Mixed));
443 return $unknown->("no changes");
445 confess "internal error $objid ?";
449 return $unknown->("origin commit");
452 if (@p == 2 && @identical == 1) {
453 my @overwritten = grep { $_->{Differs} } @p;
454 confess "internal error $objid ?" unless @overwritten==1;
455 return $classify->(qw(Pseudomerge),
456 Overwritten => [ $overwritten[0] ],
457 Contributor => $identical[0]);
459 if (@p == 2 && @identical == 2) {
461 my ($ph,$pm) = get_commit $_[0]{CommitId};
462 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
466 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
467 if ($order > 0) { # newer first
468 } elsif ($order < 0) {
469 @bytime = reverse @bytime;
471 # same age, default to order made by -s ours
472 # that is, commit was made by someone who preferred L
474 return $classify->(qw(Pseudomerge),
475 SubType => qw(Ambiguous),
476 Contributor => $bytime[0],
477 Overwritten => [ $bytime[1] ]);
480 my ($p_h, $p_m) = get_commit $p->{CommitId};
481 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
482 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
484 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
486 if (!(grep { !$_->{IsOrigin} } @p) and
487 (@orig_ps >= @p - 1) and
488 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
490 return $classify->(qw(DgitImportUnpatched),
491 OrigParents => \@orig_ps);
494 return $unknown->("complex merge");
497 sub breakwater_of ($;$) {
498 my ($head, $unclean_fproblem_tag) = @_;
499 # $head should be laundered; if not, $unclean_fproblem_tag controls:
500 # if falseish, calls fail; otherwise, calls fproblem and returns undef
504 my $m = "branch needs laundering (run git-debrebase): $why";
505 fail $m unless $unclean_fproblem_tag;
506 fproblem $unclean_fproblem_tag, $m;
508 no warnings qw(exiting);
512 my $cl = classify $head;
513 my $ty = $cl->{Type};
514 if ($ty eq 'Packaging' or
515 $ty eq 'Changelog') {
516 $breakwater //= $head;
517 } elsif ($ty eq 'Anchor' or
518 $ty eq 'TreatAsAnchor' or
519 $ty eq 'BreakwaterStart') {
520 $breakwater //= $head;
522 } elsif ($ty eq 'Upstream') {
523 $unclean->("packaging change ($breakwater)".
524 " follows upstream change (eg $head)")
525 if defined $breakwater;
526 } elsif ($ty eq 'Mixed') {
527 $unclean->('found mixed upstream/packaging commit ($head)');
528 } elsif ($ty eq 'Pseudomerge' or
529 $ty eq 'AddPatches') {
530 $unclean->("found interchange conversion commit ($ty, $head)");
531 } elsif ($ty eq 'DgitImportUnpatched') {
532 $unclean->("found dgit dsc import ($head)");
534 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
536 $head = $cl->{Parents}[0]{CommitId};
544 $nogenerate,$report) = @_;
545 # => ($tip, $breakwater_tip, $last_anchor)
546 # (or nothing, if $nogenerate)
548 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
550 # go through commits backwards
551 # we generate two lists of commits to apply:
552 # breakwater branch and upstream patches
553 my (@brw_cl, @upp_cl, @processed);
560 my ($prose, $info) = @_;
564 $ms .= "\n\n[git-debrebase$info: $prose]\n";
567 my $rewrite_from_here = sub {
569 my $sp_cl = { SpecialMethod => 'StartRewrite' };
571 push @processed, $sp_cl;
576 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
579 return unless $report;
580 print $report $prdelim, @_;
584 my $bomb = sub { # usage: return $bomb->();
585 print $report " Unprocessable" if $report;
586 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
589 return (undef,undef);
591 die "commit $cur: Cannot cope with this commit (d.".
592 (join ' ', map { sprintf "%#x", $_->{Differs} }
593 @{ $cl->{Parents} }).
594 (defined $cl->{Why} ? "; $cl->{Why}": '').
601 my $build_start = sub {
602 my ($msg, $parent) = @_;
605 no warnings qw(exiting); last;
612 my $ty = $cl->{Type};
613 my $st = $cl->{SubType};
614 $prline->("$cl->{CommitId} $cl->{Type}");
615 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
616 push @processed, $cl;
617 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
618 if ($ty eq 'AddPatches') {
620 $rewrite_from_here->(\@upp_cl);
622 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
626 } elsif ($ty eq 'BreakwaterStart') {
628 $build_start->('FirstPackaging', $cur);
629 } elsif ($ty eq 'Upstream') {
633 } elsif ($ty eq 'Mixed') {
636 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
639 $queue->(\@brw_cl, "debian");
640 $queue->(\@upp_cl, "upstream");
641 $rewrite_from_here->(\@brw_cl);
644 } elsif ($ty eq 'Pseudomerge') {
645 my $contrib = $cl->{Contributor}{CommitId};
646 print $report " Contributor=$contrib" if $report;
647 push @pseudomerges, $cl;
648 $rewrite_from_here->(\@upp_cl);
651 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
653 $build_start->("Anchor", $cur);
654 } elsif ($ty eq 'DgitImportUnpatched') {
655 my $pm = $pseudomerges[-1];
657 # To an extent, this is heuristic. Imports don't have
658 # a useful history of the debian/ branch. We assume
659 # that the first pseudomerge after an import has a
660 # useful history of debian/, and ignore the histories
661 # from later pseudomerges. Often the first pseudomerge
662 # will be the dgit import of the upload to the actual
663 # suite intended by the non-dgit NMUer, and later
664 # pseudomerges may represent in-archive copies.
665 my $ovwrs = $pm->{Overwritten};
666 printf $report " PM=%s \@Overwr:%d",
667 $pm->{CommitId}, (scalar @$ovwrs)
670 printdebug "*** WALK BOMB DgitImportUnpatched\n";
673 my $ovwr = $ovwrs->[0]{CommitId};
674 printf $report " Overwr=%s", $ovwr if $report;
675 # This import has a tree which is just like a
676 # breakwater tree, but it has the wrong history. It
677 # ought to have the previous breakwater (which the
678 # pseudomerge overwrote) as an ancestor. That will
679 # make the history of the debian/ files correct. As
680 # for the upstream version: either it's the same as
681 # was ovewritten (ie, same as the previous
682 # breakwater), in which case that history is precisely
683 # right; or, otherwise, it was a non-gitish upload of a
684 # new upstream version. We can tell these apart by
685 # looking at the tree of the supposed upstream.
688 SpecialMethod => 'DgitImportDebianUpdate',
689 $xmsg->("convert dgit import: debian changes")
692 SpecialMethod => 'DgitImportUpstreamUpdate',
693 $xmsg->("convert dgit import: upstream update",
696 $prline->(" Import");
697 $rewrite_from_here->(\@brw_cl);
698 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
702 # Everything is from this import. This kind of import
703 # is already in valid breakwater format, with the
704 # patches as commits.
705 printf $report " NoPM" if $report;
706 # last thing we processed will have been the first patch,
707 # if there is one; which is fine, so no need to rewrite
708 # on account of this import
709 $build_start->("ImportOrigin", $cur);
713 printdebug "*** WALK BOMB unrecognised\n";
719 printdebug "*** WALK prep done cur=$cur".
720 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
722 return if $nogenerate;
724 # Now we build it back up again
730 my $read_tree_debian = sub {
732 read_tree_subdir 'debian', "$treeish:debian";
733 rm_subdir_cached 'debian/patches';
735 my $read_tree_upstream = sub {
737 runcmd @git, qw(read-tree), $treeish;
738 $read_tree_debian->($build);
741 $#upp_cl = $upp_limit if defined $upp_limit;
743 my $committer_authline = calculate_committer_authline();
745 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
747 confess "internal error" unless $build eq (pop @processed)->{CommitId};
750 mkdir $rd or $!==EEXIST or die $!;
752 runcmd @git, qw(read-tree), $build;
753 foreach my $cl (qw(Debian), (reverse @brw_cl),
754 { SpecialMethod => 'RecordBreakwaterTip' },
755 qw(Upstream), (reverse @upp_cl)) {
757 $current_method = $cl;
760 my $method = $cl->{SpecialMethod} // $current_method;
761 my @parents = ($build);
762 my $cltree = $cl->{CommitId};
763 printdebug "WALK BUILD ".($cltree//'undef').
764 " $method (rewriting=$rewriting)\n";
765 if ($method eq 'Debian') {
766 $read_tree_debian->($cltree);
767 } elsif ($method eq 'Upstream') {
768 $read_tree_upstream->($cltree);
769 } elsif ($method eq 'StartRewrite') {
772 } elsif ($method eq 'RecordBreakwaterTip') {
773 $breakwater = $build;
775 } elsif ($method eq 'DgitImportDebianUpdate') {
776 $read_tree_debian->($cltree);
777 } elsif ($method eq 'DgitImportUpstreamUpdate') {
778 confess unless $rewriting;
779 my $differs = (get_differs $build, $cltree);
780 next unless $differs & D_UPS;
781 $read_tree_upstream->($cltree);
782 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
787 my $procd = (pop @processed) // 'UNDEF';
790 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
793 my $newtree = cmdoutput @git, qw(write-tree);
795 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
796 $ch =~ s{^parent .*\n}{}mg;
797 $ch =~ s{(?=^author)}{
798 join '', map { "parent $_\n" } @parents
799 }me or confess "$ch ?";
801 $ch =~ s{^committer .*$}{$committer_authline}m
804 my $cf = "$rd/m$rewriting";
805 open CD, ">", $cf or die $!;
806 print CD $ch, "\n", $cl->{Msg} or die $!;
808 my @cmd = (@git, qw(hash-object));
809 push @cmd, qw(-w) if $rewriting;
810 push @cmd, qw(-t commit), $cf;
811 my $newcommit = cmdoutput @cmd;
812 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
814 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
820 my $final_check = get_differs $build, $input;
821 die sprintf "internal error %#x %s %s", $final_check, $build, $input
822 if $final_check & ~D_PAT_ADD;
824 my @r = ($build, $breakwater, $last_anchor);
825 printdebug "*** WALK RETURN @r\n";
830 git_check_unmodified();
831 return git_rev_parse qw(HEAD);
834 sub update_head ($$$) {
835 my ($old, $new, $mrest) = @_;
836 push @deferred_updates, "update HEAD $new $old";
837 run_deferred_updates $mrest;
840 sub update_head_checkout ($$$) {
841 my ($old, $new, $mrest) = @_;
842 update_head $old, $new, $mrest;
843 runcmd @git, qw(reset --hard);
846 sub update_head_postlaunder ($$$) {
847 my ($old, $tip, $reflogmsg) = @_;
848 return if $tip eq $old;
849 print "git-debrebase: laundered (head was $old)\n";
850 update_head $old, $tip, $reflogmsg;
851 # no tree changes except debian/patches
852 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
855 sub cmd_launder_v0 () {
856 badusage "no arguments to launder-v0 allowed" if @ARGV;
857 my $old = get_head();
858 my ($tip,$breakwater,$last_anchor) = walk $old;
859 update_head_postlaunder $old, $tip, 'launder';
860 printf "# breakwater tip\n%s\n", $breakwater;
861 printf "# working tip\n%s\n", $tip;
862 printf "# last anchor\n%s\n", $last_anchor;
865 sub defaultcmd_rebase () {
866 my $old = get_head();
868 my ($tip,$breakwater) = walk $old;
869 update_head_postlaunder $old, $tip, 'launder for rebase';
870 runcmd @git, qw(rebase), @ARGV, $breakwater;
874 die if ($ARGV[0]//'') =~ m/^-/;
875 badusage "too many arguments to analyse" if @ARGV>1;
878 $old = git_rev_parse $old;
880 $old = git_rev_parse 'HEAD';
882 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
883 STDOUT->error and die $!;
886 sub ffq_prev_branchinfo () {
887 # => ('status', "message", [$current, $ffq_prev, $drlast])
889 # branch message is undef
890 # weird-symref } no $current,
891 # notbranch } no $ffq_prev
892 my $current = git_get_symref();
893 return ('detached', 'detached HEAD') unless defined $current;
894 return ('weird-symref', 'HEAD symref is not to refs/')
895 unless $current =~ m{^refs/};
896 my $ffq_prev = "refs/$ffq_refprefix/$'";
897 my $drlast = "refs/$gdrlast_refprefix/$'";
898 printdebug "ffq_prev_branchinfo branch current $current\n";
899 return ('branch', undef, $current, $ffq_prev, $drlast);
902 sub record_ffq_prev_deferred () {
903 # => ('status', "message")
905 # deferred message is undef
910 # if not ff from some branch we should be ff from, is an fproblem
911 # if "deferred", will have added something about that to
912 # @deferred_update_messages, and also maybe printed (already)
913 # some messages about ff checks
914 my ($status, $message, $current, $ffq_prev, $drlast)
915 = ffq_prev_branchinfo();
916 return ($status, $message) unless $status eq 'branch';
918 my $currentval = get_head();
920 my $exists = git_get_ref $ffq_prev;
921 return ('exists',"$ffq_prev already exists") if $exists;
923 return ('not-branch', 'HEAD symref is not to refs/heads/')
924 unless $current =~ m{^refs/heads/};
927 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
930 printdebug "ffq check_specs @check_specs\n";
933 my ($lrref, $desc) = @_;
934 printdebug "ffq might check $lrref ($desc)\n";
936 for my $chk (@check_specs) {
938 $invert = $glob =~ s{^[!^]}{};
939 last if fnmatch $glob, $lrref;
942 my $lrval = git_get_ref $lrref;
943 return unless defined $lrval;
945 if (is_fast_fwd $lrval, $currentval) {
946 print "OK, you are ahead of $lrref\n" or die $!;
947 $checked{$lrref} = 1;
948 } elsif (is_fast_fwd $currentval, $lrval) {
949 $checked{$lrref} = -1;
950 fproblem 'behind', "you are behind $lrref, divergence risk";
952 $checked{$lrref} = -1;
953 fproblem 'diverged', "you have diverged from $lrref";
957 my $merge = cfg "branch.$branch.merge",1;
958 if (defined $merge and $merge =~ m{^refs/heads/}) {
960 printdebug "ffq merge $rhs\n";
961 my $check_remote = sub {
962 my ($remote, $desc) = @_;
963 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
964 return unless defined $remote;
965 $check->("refs/remotes/$remote/$rhs", $desc);
967 $check_remote->((scalar cfg "branch.$branch.remote",1),
968 'remote fetch/merge branch');
969 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
970 (scalar cfg "branch.$branch.pushDefault",1),
971 'remote push branch');
973 if ($branch =~ m{^dgit/}) {
974 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
975 } elsif ($branch =~ m{^master$}) {
976 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
979 fproblems_maybe_bail();
981 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
982 push @deferred_updates, "delete $drlast";
983 push @deferred_update_messages, "Recorded current head for preservation";
984 return ('deferred', undef);
987 sub record_ffq_auto () {
988 my ($status, $message) = record_ffq_prev_deferred();
989 if ($status eq 'deferred' || $status eq 'exists') {
991 fproblem $status, "could not record ffq-prev: $message";
992 fproblems_maybe_bail();
996 sub cmd_new_upstream_v0 () {
997 # automatically and unconditionally launders before rebasing
998 # if rebase --abort is used, laundering has still been done
1002 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1004 # parse args - low commitment
1005 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1006 my $new_upstream_version = $new_version->version();
1008 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1013 my ($n, @x) = @_; # may be ''
1014 my $pc = $pieces{$n} //= {
1016 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1018 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1023 my $newpiece = sub {
1024 my ($n, @x) = @_; # may be ''
1025 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1026 push @newpieces, $pc;
1031 New => $new_upstream,
1033 while (@ARGV && $ARGV[0] !~ m{^-}) {
1034 my $n = shift @ARGV;
1036 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1037 unless @ARGV && $ARGV[0] !~ m{^-};
1039 my $c = git_rev_parse shift @ARGV;
1040 die unless $n =~ m/^$extra_orig_namepart_re$/;
1041 $newpiece->($n, New => $c);
1044 # now we need to investigate the branch this generates the
1045 # laundered version but we don't switch to it yet
1046 my $old_head = get_head();
1047 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1049 my $old_bw_cl = classify $old_bw;
1050 my $old_anchor_cl = classify $old_anchor;
1052 if (!$old_anchor_cl->{OrigParents}) {
1053 fproblem 'anchor-treated',
1054 'old anchor is recognised due to --anchor, cannot check upstream';
1056 $old_upstream = parsecommit
1057 $old_anchor_cl->{OrigParents}[0]{CommitId};
1058 $piece->('', Old => $old_upstream->{CommitId});
1061 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1062 if ($old_upstream->{Msg} =~
1063 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1065 my @oldpieces = ('', split / /, $1);
1066 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1067 foreach my $i (0..$#oldpieces) {
1068 my $n = $oldpieces[$i];
1069 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1072 fproblem 'upstream-confusing',
1073 "previous upstream $old_upstream->{CommitId} is from".
1074 " git-debrebase but not an \`upstream-combine' commit";
1078 foreach my $pc (values %pieces) {
1079 if (!$old_upstream) {
1080 # we have complained already
1081 } elsif (!$pc->{Old}) {
1082 fproblem 'upstream-new-piece',
1083 "introducing upstream piece \`$pc->{Name}'";
1084 } elsif (!$pc->{New}) {
1085 fproblem 'upstream-rm-piece',
1086 "dropping upstream piece \`$pc->{Name}'";
1087 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1088 fproblem 'upstream-not-ff',
1089 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1093 printdebug "%pieces = ", (dd \%pieces), "\n";
1094 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1096 fproblems_maybe_bail();
1102 my @upstream_merge_parents;
1104 if (!any_fproblems()) {
1105 push @upstream_merge_parents, $old_upstream->{CommitId};
1108 foreach my $pc (@newpieces) { # always has '' first
1110 read_tree_subdir $pc->{Name}, $pc->{New};
1112 runcmd @git, qw(read-tree), $pc->{New};
1114 push @upstream_merge_parents, $pc->{New};
1117 # index now contains the new upstream
1119 if (@newpieces > 1) {
1120 # need to make the upstream subtree merge commit
1121 $new_upstream = make_commit \@upstream_merge_parents,
1122 [ "Combine upstreams for $new_upstream_version",
1123 ("[git-debrebase upstream-combine . ".
1124 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1129 # $new_upstream is either the single upstream commit, or the
1130 # combined commit we just made. Either way it will be the
1131 # "upstream" parent of the anchor merge.
1133 read_tree_subdir 'debian', "$old_bw:debian";
1135 # index now contains the anchor merge contents
1136 $new_bw = make_commit [ $old_bw, $new_upstream ],
1137 [ "Update to upstream $new_upstream_version",
1138 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1141 # Now we have to add a changelog stanza so the Debian version
1143 die if unlink "debian";
1144 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1145 unlink "debian/changelog" or $!==ENOENT or die $!;
1146 mkdir "debian" or die $!;
1147 open CN, ">", "debian/changelog" or die $!;
1148 my $oldclog = git_cat_file ":debian/changelog";
1149 $oldclog =~ m/^($package_re) \(\S+\) / or
1150 fail "cannot parse old changelog to get package name";
1152 print CN <<END, $oldclog or die $!;
1153 $p ($new_version) UNRELEASED; urgency=medium
1155 * Update to new upstream version $new_upstream_version.
1161 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1163 # Now we have the final new breakwater branch in the index
1164 $new_bw = make_commit [ $new_bw ],
1165 [ "Update changelog for new upstream $new_upstream_version",
1166 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1170 # we have constructed the new breakwater. we now need to commit to
1171 # the laundering output, because git-rebase can't easily be made
1172 # to make a replay list which is based on some other branch
1174 update_head_postlaunder $old_head, $old_laundered_tip,
1175 'launder for new upstream';
1177 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1179 # now it's for the user to sort out
1182 sub cmd_record_ffq_prev () {
1183 badusage "no arguments allowed" if @ARGV;
1184 my ($status, $msg) = record_ffq_prev_deferred();
1185 if ($status eq 'exists' && $opt_noop_ok) {
1186 print "Previous head already recorded\n" or die $!;
1187 } elsif ($status eq 'deferred') {
1188 run_deferred_updates 'record-ffq-prev';
1190 fail "Could not preserve: $msg";
1194 sub cmd_breakwater () {
1195 badusage "no arguments allowed" if @ARGV;
1196 my $bw = breakwater_of git_rev_parse 'HEAD';
1197 print "$bw\n" or die $!;
1202 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1203 badusage "no arguments allowed" if @ARGV;
1204 my ($status, $message, $current, $ffq_prev, $drlast)
1205 = ffq_prev_branchinfo();
1206 if ($status ne 'branch') {
1207 fproblem $status, "could not check ffq-prev: $message";
1208 fproblems_maybe_bail();
1210 my $prev = $ffq_prev && git_get_ref $ffq_prev;
1212 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1214 my $old_head = get_head();
1216 breakwater_of $old_head, 'unclean-stitch';
1218 push @deferred_updates, "delete $ffq_prev $prev";
1220 if (is_fast_fwd $old_head, $prev) {
1221 my $differs = get_differs $old_head, $prev;
1222 unless ($differs & ~D_PAT_ADD) {
1223 # ffq-prev is ahead of us, and the only tree changes it has
1224 # are possibly addition of things in debian/patches/.
1225 # Just wind forwards rather than making a pointless pseudomerge.
1226 push @deferred_updates, "update $drlast $prev $git_null_obj";
1227 update_head_checkout $old_head, $prev, "stitch (fast forward)";
1232 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1233 'Declare fast forward / record previous work',
1234 "[git-debrebase pseudomerge: stitch$prose]",
1236 push @deferred_updates, "update $drlast $new_head $git_null_obj";
1237 update_head $old_head, $new_head, "stitch";
1240 sub cmd_convert_from_gbp () {
1241 badusage "needs 1 optional argument, the upstream git rev"
1243 my ($upstream_spec) = @ARGV;
1244 $upstream_spec //= 'refs/heads/upstream';
1245 my $upstream = git_rev_parse $upstream_spec;
1246 my $old_head = get_head();
1248 my $upsdiff = get_differs $upstream, $old_head;
1249 if ($upsdiff & D_UPS) {
1250 runcmd @git, qw(--no-pager diff),
1251 $upstream, $old_head,
1252 qw( -- :!/debian :/);
1253 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1256 if (!is_fast_fwd $upstream, $old_head) {
1257 fproblem 'upstream-not-ancestor',
1258 "upstream ($upstream) is not an ancestor of HEAD";
1260 my $wrong = cmdoutput
1261 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1262 qw(-- :/ :!/debian));
1263 if (length $wrong) {
1264 fproblem 'unexpected-upstream-changes',
1265 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1266 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1270 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1271 fproblem 'upstream-has-debian',
1272 "upstream ($upstream) contains debian/ directory";
1275 fproblems_maybe_bail();
1281 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1282 # make a branch out of the patch queue - we'll want this in a mo
1283 runcmd qw(gbp pq import);
1284 # strip the patches out
1285 runcmd @git, qw(checkout -q gdr-internal~0);
1286 rm_subdir_cached 'debian/patches';
1287 $work = make_commit ['HEAD'], [
1288 'git-debrebase convert-from-gbp: drop patches from tree',
1289 'Delete debian/patches, as part of converting to git-debrebase format.',
1290 '[git-debrebase convert-from-gbp: drop patches from tree]'
1292 # make the anchor merge
1293 # the tree is already exactly right
1294 $work = make_commit [$work, $upstream], [
1295 'git-debrebase import: declare upstream',
1296 'First breakwater merge.',
1297 '[git-debrebase anchor: declare upstream]'
1300 # rebase the patch queue onto the new breakwater
1301 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1302 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1303 $work = git_rev_parse 'HEAD';
1306 update_head_checkout $old_head, $work, 'convert-from-gbp';
1309 sub cmd_convert_to_gbp () {
1310 badusage "no arguments allowed" if @ARGV;
1311 my $head = get_head();
1312 my (undef, undef, undef, $ffq, $drlast) = ffq_prev_branchinfo();
1313 my $bw = breakwater_of $head;
1317 runcmd @git, qw(checkout -q -b bw), $bw;
1318 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1319 runcmd qw(gbp pq export);
1320 runcmd @git, qw(add debian/patches);
1321 $out = make_commit ['HEAD'], [
1322 'Commit patch queue (converted from git-debrebase format)',
1323 '[git-debrebase convert-to-gbp: commit patches]',
1327 push @deferred_updates, "delete $ffq";
1328 push @deferred_updates, "delete $drlast";
1330 update_head_checkout $head, $out, "convert to gbp (v0)";
1331 print <<END or die $!;
1332 git-debrebase: converted to git-buildpackage branch format
1333 git-debrebase: WARNING: do not now run "git-debrebase" any more
1334 git-debrebase: WARNING: doing so would drop all upstream patches!
1338 sub cmd_downstream_rebase_launder_v0 () {
1339 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1341 $base = git_rev_parse $base;
1342 my $old_head = get_head();
1343 my $current = $old_head;
1346 if ($current eq $base) {
1347 $topmost_keep //= $current;
1348 print " $current BASE stop\n";
1351 my $cl = classify $current;
1352 print " $current $cl->{Type}";
1354 my $p0 = $cl->{Parents}[0]{CommitId};
1356 if ($cl->{Type} eq 'Pseudomerge') {
1357 print " ^".($cl->{Contributor}{Ix}+1);
1358 $next = $cl->{Contributor}{CommitId};
1359 } elsif ($cl->{Type} eq 'AddPatches' or
1360 $cl->{Type} eq 'Changelog') {
1370 $topmost_keep //= $current;
1372 die "to-be stripped changes not on top of the branch\n"
1377 if ($topmost_keep eq $old_head) {
1378 print "unchanged\n";
1380 print "updating to $topmost_keep\n";
1381 update_head_checkout
1382 $old_head, $topmost_keep,
1383 'downstream-rebase-launder-v0';
1387 GetOptions("D+" => \$debuglevel,
1388 'noop-ok', => \$opt_noop_ok,
1389 'f=s' => \@fproblem_force_opts,
1390 'anchor=s' => \@opt_anchors,
1391 'force!') or die badusage "bad options\n";
1392 initdebug('git-debrebase ');
1393 enabledebug if $debuglevel;
1395 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1396 chdir $toplevel or die "chdir $toplevel: $!";
1398 $rd = fresh_playground "$playprefix/misc";
1400 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1402 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1403 defaultcmd_rebase();
1405 my $cmd = shift @ARGV;
1408 $cmdfn = ${*::}{"cmd_$cmdfn"};
1410 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";