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/>.
24 # git-debrebase [<options>] analyse
25 # git-debrebase [<options>] launder-v0 # prints breakwater tip etc.
26 # git-debrebase [<options>] downstream-rebase-launder-v0 # experimental
28 # problems / outstanding questions:
30 # * dgit push with a `3.0 (quilt)' package means doing quilt
31 # fixup. Usually this involves recommitting the whole patch
32 # series, one at a time, with dpkg-source --commit. This is
33 # terribly terribly slow. (Maybe this should be fixed in dgit.)
35 # * dgit push usually needs to (re)make a pseudomerge. The "first"
36 # git-debrebase stripped out the previous pseudomerge and could
37 # have remembeed the HEAD. But it's not quite clear what history
38 # ought to be preserved and what should be discarded. For now
39 # the user will have to tell dgit --overwrite.
41 # To fix this, do we need a new push hook for dgit ?
43 # * Workflow is currently clumsy. Lots of spurious runes to type.
44 # There's not even a guide.
46 # * There are no tests.
48 # * new-upstream-v0 has a terrible UI. You end up with giant
49 # runic command lines.
51 # One consequence of the lack of richness it can need --force in
52 # fairly sensible situations and there is no way to tell it what
53 # you are really trying to do, other than just --force. There
54 # should be an interface with some default branch names.
56 # * There should be a standard convention for the version number,
57 # and unfinalised or not changelog, after new-upstream.
59 # * Handing of multi-orig dgit new-upstream .dsc imports is known to
60 # be broken. They may be not recognised, improperly converted, or
61 # their conversion may be unrecognised.
63 # * Docs need writing and updating. Even README.git-debrebase
64 # describes a design but may not reflect the implementation.
66 # * We need to develop a plausible model that works for derivatives,
67 # who probably want to maintain their stack on top of Debian's.
68 # downstream-rebase-launder-v0 may be a starting point?
72 use Debian::Dgit qw(:DEFAULT :playground);
79 use Getopt::Long qw(:config posix_default gnu_compat bundling);
81 use File::FnMatch qw(:fnmatch);
83 our ($opt_force, $opt_noop_ok, @opt_anchors);
85 our $us = qw(git-debrebase);
89 die "bad usage: $m\n";
93 my ($k, $optional) = @_;
95 my @cmd = qw(git config -z);
96 push @cmd, qw(--get-all) if wantarray;
98 my $out = cmdoutput_errok @cmd;
100 fail "missing required git config $k" unless $optional;
103 my @l = split /\0/, $out;
104 return wantarray ? @l : $l[0];
111 my $dd = new Data::Dumper [ $v ];
112 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
118 my $data = (git_cat_file $objid, 'commit');
119 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
123 sub D_UPS () { 0x02; } # upstream files
124 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
125 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
126 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
127 sub D_DEB_OTH () { 0x20; } # debian/changelog
128 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
130 our $playprefix = 'debrebase';
136 sub in_workarea ($) {
139 my $r = eval { $sub->(); };
140 { local $@; changedir $maindir; }
144 sub fresh_workarea () {
145 $workarea = fresh_playground "$playprefix/work";
146 in_workarea sub { playtree_setup };
149 our @deferred_updates;
150 our @deferred_update_messages;
152 sub run_deferred_updates ($) {
155 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
156 debugcmd '>|', @upd_cmd;
157 open U, "|-", @upd_cmd or die $!;
158 foreach (@deferred_updates) {
159 printdebug ">= ", $_, "\n";
160 print U $_, "\n" or die $!;
163 close U or failedcmd @upd_cmd;
165 print $_, "\n" foreach @deferred_update_messages;
167 @deferred_updates = ();
168 @deferred_update_messages = ();
171 sub get_differs ($$) {
173 # This resembles quiltify_trees_differ, in dgit, a bit.
174 # But we don't care about modes, or dpkg-source-unrepresentable
175 # changes, and we don't need the plethora of different modes.
176 # Conversely we need to distinguish different kinds of changes to
177 # debian/ and debian/patches/.
182 my ($opts, $limits, $fn) = @_;
183 my @cmd = (@git, qw(diff-tree -z --no-renames));
185 push @cmd, "$_:" foreach $x, $y;
186 push @cmd, '--', @$limits;
187 my $diffs = cmdoutput @cmd;
188 foreach (split /\0/, $diffs) { $fn->(); }
191 $rundiff->([qw(--name-only)], [], sub {
192 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
195 if ($differs & DS_DEB) {
197 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
199 m{^debian/patches/} ? D_PAT_OTH :
200 $_ eq 'debian/changelog' ? D_DEB_CLOG :
203 die "mysterious debian changes $x..$y"
204 unless $differs & (D_PAT_OTH|DS_DEB);
207 if ($differs & D_PAT_OTH) {
209 $differs &= ~D_PAT_OTH;
211 $differs |= D_PAT_OTH;
212 no warnings qw(exiting); last;
214 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
215 no warnings qw(exiting);
216 if (!defined $mode) {
219 die unless s{^debian/patches/}{};
221 if ($mode eq 'A' && !m/\.series$/s) {
223 } elsif ($mode eq 'M' && $_ eq 'series') {
224 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
225 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
226 chomp $x_s; $x_s .= "\n";
227 $ok = $x_s eq substr($y_s, 0, length $x_s);
232 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
234 die "mysterious debian/patches changes $x..$y"
235 unless $differs & (D_PAT_ADD|D_PAT_OTH);
238 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
243 sub commit_pr_info ($) {
245 return Data::Dumper->dump([$r], [qw(commit)]);
248 sub calculate_committer_authline () {
249 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
250 'DUMMY COMMIT (git-debrebase)', "HEAD:";
251 my ($h,$m) = get_commit $c;
252 $h =~ m/^committer .*$/m or confess "($h) ?";
256 sub rm_subdir_cached ($) {
258 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
261 sub read_tree_subdir ($$) {
262 my ($subdir, $new_tree_object) = @_;
263 rm_subdir_cached $subdir;
264 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
267 sub make_commit ($$) {
268 my ($parents, $message_paras) = @_;
269 my $tree = cmdoutput @git, qw(write-tree);
270 my @cmd = (@git, qw(commit-tree), $tree);
271 push @cmd, qw(-p), $_ foreach @$parents;
272 push @cmd, qw(-m), $_ foreach @$message_paras;
273 return cmdoutput @cmd;
276 our @fproblem_force_opts;
277 our $fproblems_forced;
278 our $fproblems_tripped;
281 if (grep { $_ eq $tag } @fproblem_force_opts) {
283 print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
285 $fproblems_tripped++;
286 print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
290 sub fproblems_maybe_bail () {
291 if ($fproblems_forced) {
293 "%s: safety catch trips: %d overriden by individual -f options\n",
294 $us, $fproblems_forced;
296 if ($fproblems_tripped) {
299 "%s: safety catch trips: %d overriden by global --force\n",
300 $us, $fproblems_tripped;
303 "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
304 $us, $fproblems_tripped;
308 sub any_fproblems () {
309 return $fproblems_forced || $fproblems_tripped;
312 # classify returns an info hash like this
314 # Hdr => # commit headers, including 1 final newline
315 # Msg => # commit message (so one newline is dropped)
317 # Type => (see below)
319 # Ix => $index # ie 0, 1, 2, ...
321 # Differs => return value from get_differs
323 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
325 # NewMsg => # commit message, but with any [dgit import ...] edited
326 # # to say "[was: ...]"
336 # has additional entres in classification result
337 # Overwritten = [ subset of Parents ]
338 # Contributor = $the_remaining_Parent
340 # DgitImportUnpatched
341 # has additional entry in classification result
342 # OrigParents = [ subset of Parents ]
345 # has additional entry in classification result
346 # OrigParents = [ subset of Parents ] # singleton list
353 # has additional entry in classification result
356 sub parsecommit ($;$) {
357 my ($objid, $p_ref) = @_;
358 # => hash with CommitId Hdr Msg Tree Parents
359 # Parents entries have only Ix CommitId
360 # $p_ref, if provided, must be [] and is used as a base for Parents
365 my ($h,$m) = get_commit $objid;
367 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
368 my (@ph) = $h =~ m/^parent (\w+)$/mg;
378 foreach my $ph (@ph) {
380 Ix => scalar @$p_ref,
392 my $r = parsecommit($objid, \@p);
396 $p->{Differs} = (get_differs $p->{CommitId}, $t),
399 printdebug "classify $objid \$t=$t \@p",
400 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
404 my ($type, @rest) = @_;
405 $r = { %$r, Type => $type, @rest };
407 printdebug " = $type ".(dd $r)."\n";
413 $r = { %$r, Type => qw(Unknown), Why => $why };
414 printdebug " ** Unknown\n";
418 if (grep { $_ eq $objid } @opt_anchors) {
419 return $classify->('TreatAsAnchor');
422 my @identical = grep { !$_->{Differs} } @p;
423 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
424 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
426 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
427 # multi-orig upstreams are represented with an anchor merge
428 # from a single upstream commit which combines the orig tarballs
430 # Every anchor tagged this way must be a merge.
431 # We are relying on the
432 # [git-debrebase anchor: ...]
433 # commit message annotation in "declare" anchor merges (which
434 # do not have any upstream changes), to distinguish those
435 # anchor merges from ordinary pseudomerges (which we might
436 # just try to strip).
438 # However, the user is going to be doing git-rebase a lot. We
439 # really don't want them to rewrite an anchor commit.
440 # git-rebase trips up on merges, so that is a useful safety
443 # BreakwaterStart commits are also anchors in the terminology
444 # of git-debrebase(5), but they are untagged (and always
445 # manually generated).
447 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
448 @p == 2 or return $badanchor->("has other than two parents");
449 $haspatches and return $badanchor->("contains debian/patches");
451 # How to decide about l/r ordering of anchors ? git
452 # --topo-order prefers to expand 2nd parent first. There's
453 # already an easy rune to look for debian/ history anyway (git log
454 # debian/) so debian breakwater branch should be 1st parent; that
455 # way also there's also an easy rune to look for the upstream
456 # patches (--topo-order).
458 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
459 $p[1]{Differs} & ~DS_DEB and
460 $badanchor->("upstream files differ from left parent");
461 $p[0]{Differs} & ~D_UPS and
462 $badanchor->("debian/ differs from right parent");
464 return $classify->(qw(Anchor),
465 OrigParents => [ $p[1] ]);
469 my $d = $r->{Parents}[0]{Differs};
470 if ($d == D_PAT_ADD) {
471 return $classify->(qw(AddPatches));
472 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
473 return $unknown->("edits debian/patches");
474 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
475 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
477 if ($d == D_DEB_CLOG) {
478 return $classify->(qw(Changelog));
480 return $classify->(qw(Packaging));
482 } elsif ($ty eq 'missing') {
483 return $classify->(qw(BreakwaterStart));
485 return $unknown->("parent's debian is not a directory");
487 } elsif ($d == D_UPS) {
488 return $classify->(qw(Upstream));
489 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
490 return $classify->(qw(Mixed));
492 return $unknown->("no changes");
494 confess "internal error $objid ?";
498 return $unknown->("origin commit");
501 if (@p == 2 && @identical == 1) {
502 my @overwritten = grep { $_->{Differs} } @p;
503 confess "internal error $objid ?" unless @overwritten==1;
504 return $classify->(qw(Pseudomerge),
505 Overwritten => [ $overwritten[0] ],
506 Contributor => $identical[0]);
508 if (@p == 2 && @identical == 2) {
510 my ($ph,$pm) = get_commit $_[0]{CommitId};
511 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
515 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
516 if ($order > 0) { # newer first
517 } elsif ($order < 0) {
518 @bytime = reverse @bytime;
520 # same age, default to order made by -s ours
521 # that is, commit was made by someone who preferred L
523 return $classify->(qw(Pseudomerge),
524 SubType => qw(Ambiguous),
525 Contributor => $bytime[0],
526 Overwritten => [ $bytime[1] ]);
529 my ($p_h, $p_m) = get_commit $p->{CommitId};
530 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
531 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
533 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
535 if (!(grep { !$_->{IsOrigin} } @p) and
536 (@orig_ps >= @p - 1) and
537 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
539 return $classify->(qw(DgitImportUnpatched),
540 OrigParents => \@orig_ps);
543 return $unknown->("complex merge");
546 sub breakwater_of ($) {
547 my ($head) = @_; # must be laundered
551 fail "branch needs laundering (run git-debrebase): $why";
554 my $cl = classify $head;
555 my $ty = $cl->{Type};
556 if ($ty eq 'Packaging' or
557 $ty eq 'Changelog') {
558 $breakwater //= $head;
559 } elsif ($ty eq 'Anchor' or
560 $ty eq 'TreatAsAnchor' or
561 $ty eq 'BreakwaterStart') {
562 $breakwater //= $head;
564 } elsif ($ty eq 'Upstream') {
565 $unclean->("packaging change ($breakwater)".
566 " follows upstream change (eg $head)")
567 if defined $breakwater;
568 } elsif ($ty eq 'Mixed') {
569 $unclean->('found mixed upstream/packaging commit ($head)');
570 } elsif ($ty eq 'Pseudomerge' or
571 $ty eq 'AddPatches') {
572 $unclean->("found interchange conversion commit ($ty, $head)");
573 } elsif ($ty eq 'DgitImportUnpatched') {
574 $unclean->("found dgit dsc import ($head)");
576 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
578 $head = $cl->{Parents}[0]{CommitId};
586 $nogenerate,$report) = @_;
587 # => ($tip, $breakwater_tip, $last_anchor)
588 # (or nothing, if $nogenerate)
590 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
592 # go through commits backwards
593 # we generate two lists of commits to apply:
594 # breakwater branch and upstream patches
595 my (@brw_cl, @upp_cl, @processed);
602 my ($prose, $info) = @_;
606 $ms .= "\n\n[git-debrebase$info: $prose]\n";
609 my $rewrite_from_here = sub {
611 my $sp_cl = { SpecialMethod => 'StartRewrite' };
613 push @processed, $sp_cl;
618 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
621 return unless $report;
622 print $report $prdelim, @_;
626 my $bomb = sub { # usage: return $bomb->();
627 print $report " Unprocessable" if $report;
628 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
631 return (undef,undef);
633 die "commit $cur: Cannot cope with this commit (d.".
634 (join ' ', map { sprintf "%#x", $_->{Differs} }
635 @{ $cl->{Parents} }).
636 (defined $cl->{Why} ? "; $cl->{Why}": '').
643 my $build_start = sub {
644 my ($msg, $parent) = @_;
647 no warnings qw(exiting); last;
654 my $ty = $cl->{Type};
655 my $st = $cl->{SubType};
656 $prline->("$cl->{CommitId} $cl->{Type}");
657 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
658 push @processed, $cl;
659 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
660 if ($ty eq 'AddPatches') {
662 $rewrite_from_here->(\@upp_cl);
664 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
668 } elsif ($ty eq 'BreakwaterStart') {
670 $build_start->('FirstPackaging', $cur);
671 } elsif ($ty eq 'Upstream') {
675 } elsif ($ty eq 'Mixed') {
678 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
681 $queue->(\@brw_cl, "debian");
682 $queue->(\@upp_cl, "upstream");
683 $rewrite_from_here->(\@brw_cl);
686 } elsif ($ty eq 'Pseudomerge') {
687 my $contrib = $cl->{Contributor}{CommitId};
688 print $report " Contributor=$contrib" if $report;
689 push @pseudomerges, $cl;
690 $rewrite_from_here->(\@upp_cl);
693 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
695 $build_start->("Anchor", $cur);
696 } elsif ($ty eq 'DgitImportUnpatched') {
697 my $pm = $pseudomerges[-1];
699 # To an extent, this is heuristic. Imports don't have
700 # a useful history of the debian/ branch. We assume
701 # that the first pseudomerge after an import has a
702 # useful history of debian/, and ignore the histories
703 # from later pseudomerges. Often the first pseudomerge
704 # will be the dgit import of the upload to the actual
705 # suite intended by the non-dgit NMUer, and later
706 # pseudomerges may represent in-archive copies.
707 my $ovwrs = $pm->{Overwritten};
708 printf $report " PM=%s \@Overwr:%d",
709 $pm->{CommitId}, (scalar @$ovwrs)
712 printdebug "*** WALK BOMB DgitImportUnpatched\n";
715 my $ovwr = $ovwrs->[0]{CommitId};
716 printf $report " Overwr=%s", $ovwr if $report;
717 # This import has a tree which is just like a
718 # breakwater tree, but it has the wrong history. It
719 # ought to have the previous breakwater (which the
720 # pseudomerge overwrote) as an ancestor. That will
721 # make the history of the debian/ files correct. As
722 # for the upstream version: either it's the same as
723 # was ovewritten (ie, same as the previous
724 # breakwater), in which case that history is precisely
725 # right; or, otherwise, it was a non-gitish upload of a
726 # new upstream version. We can tell these apart by
727 # looking at the tree of the supposed upstream.
730 SpecialMethod => 'DgitImportDebianUpdate',
731 $xmsg->("convert dgit import: debian changes")
734 SpecialMethod => 'DgitImportUpstreamUpdate',
735 $xmsg->("convert dgit import: upstream update",
738 $prline->(" Import");
739 $rewrite_from_here->(\@brw_cl);
740 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
744 # Everything is from this import. This kind of import
745 # is already in valid breakwater format, with the
746 # patches as commits.
747 printf $report " NoPM" if $report;
748 # last thing we processed will have been the first patch,
749 # if there is one; which is fine, so no need to rewrite
750 # on account of this import
751 $build_start->("ImportOrigin", $cur);
755 printdebug "*** WALK BOMB unrecognised\n";
761 printdebug "*** WALK prep done cur=$cur".
762 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
764 return if $nogenerate;
766 # Now we build it back up again
772 my $read_tree_debian = sub {
774 read_tree_subdir 'debian', "$treeish:debian";
775 rm_subdir_cached 'debian/patches';
777 my $read_tree_upstream = sub {
779 runcmd @git, qw(read-tree), $treeish;
780 $read_tree_debian->($build);
783 $#upp_cl = $upp_limit if defined $upp_limit;
785 my $committer_authline = calculate_committer_authline();
787 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
789 confess "internal error" unless $build eq (pop @processed)->{CommitId};
792 mkdir $rd or $!==EEXIST or die $!;
794 runcmd @git, qw(read-tree), $build;
795 foreach my $cl (qw(Debian), (reverse @brw_cl),
796 { SpecialMethod => 'RecordBreakwaterTip' },
797 qw(Upstream), (reverse @upp_cl)) {
799 $current_method = $cl;
802 my $method = $cl->{SpecialMethod} // $current_method;
803 my @parents = ($build);
804 my $cltree = $cl->{CommitId};
805 printdebug "WALK BUILD ".($cltree//'undef').
806 " $method (rewriting=$rewriting)\n";
807 if ($method eq 'Debian') {
808 $read_tree_debian->($cltree);
809 } elsif ($method eq 'Upstream') {
810 $read_tree_upstream->($cltree);
811 } elsif ($method eq 'StartRewrite') {
814 } elsif ($method eq 'RecordBreakwaterTip') {
815 $breakwater = $build;
817 } elsif ($method eq 'DgitImportDebianUpdate') {
818 $read_tree_debian->($cltree);
819 } elsif ($method eq 'DgitImportUpstreamUpdate') {
820 confess unless $rewriting;
821 my $differs = (get_differs $build, $cltree);
822 next unless $differs & D_UPS;
823 $read_tree_upstream->($cltree);
824 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
829 my $procd = (pop @processed) // 'UNDEF';
832 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
835 my $newtree = cmdoutput @git, qw(write-tree);
837 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
838 $ch =~ s{^parent .*\n}{}mg;
839 $ch =~ s{(?=^author)}{
840 join '', map { "parent $_\n" } @parents
841 }me or confess "$ch ?";
843 $ch =~ s{^committer .*$}{$committer_authline}m
846 my $cf = "$rd/m$rewriting";
847 open CD, ">", $cf or die $!;
848 print CD $ch, "\n", $cl->{Msg} or die $!;
850 my @cmd = (@git, qw(hash-object));
851 push @cmd, qw(-w) if $rewriting;
852 push @cmd, qw(-t commit), $cf;
853 my $newcommit = cmdoutput @cmd;
854 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
856 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
862 my $final_check = get_differs $build, $input;
863 die sprintf "internal error %#x %s %s", $final_check, $build, $input
864 if $final_check & ~D_PAT_ADD;
866 my @r = ($build, $breakwater, $last_anchor);
867 printdebug "*** WALK RETURN @r\n";
872 git_check_unmodified();
873 return git_rev_parse qw(HEAD);
876 sub update_head ($$$) {
877 my ($old, $new, $mrest) = @_;
878 push @deferred_updates, "update HEAD $new $old";
879 run_deferred_updates $mrest;
882 sub update_head_checkout ($$$) {
883 my ($old, $new, $mrest) = @_;
884 update_head $old, $new, $mrest;
885 runcmd @git, qw(reset --hard);
888 sub update_head_postlaunder ($$$) {
889 my ($old, $tip, $reflogmsg) = @_;
890 return if $tip eq $old;
891 print "git-debrebase: laundered (head was $old)\n";
892 update_head $old, $tip, $reflogmsg;
893 # no tree changes except debian/patches
894 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
897 sub cmd_launder_v0 () {
898 badusage "no arguments to launder-v0 allowed" if @ARGV;
899 my $old = get_head();
900 my ($tip,$breakwater,$last_anchor) = walk $old;
901 update_head_postlaunder $old, $tip, 'launder';
902 printf "# breakwater tip\n%s\n", $breakwater;
903 printf "# working tip\n%s\n", $tip;
904 printf "# last anchor\n%s\n", $last_anchor;
907 sub defaultcmd_rebase () {
908 my $old = get_head();
910 my ($tip,$breakwater) = walk $old;
911 update_head_postlaunder $old, $tip, 'launder for rebase';
912 runcmd @git, qw(rebase), @ARGV, $breakwater;
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])
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 printdebug "ffq_prev_branchinfo branch current $current\n";
940 return ('branch', undef, $current, $ffq_prev);
943 sub record_ffq_prev_deferred () {
944 # => ('status', "message")
946 # deferred message is undef
951 # if not ff from some branch we should be ff from, is an fproblem
952 # if "deferred", will have added something about that to
953 # @deferred_update_messages, and also maybe printed (already)
954 # some messages about ff checks
955 my ($status, $message, $current, $ffq_prev) = 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 fproblem 'behind', "you are behind $lrref, divergence risk";
992 $checked{$lrref} = -1;
993 fproblem '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');
1019 fproblems_maybe_bail();
1021 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1022 push @deferred_update_messages, "Recorded current head for preservation";
1023 return ('deferred', undef);
1026 sub record_ffq_auto () {
1027 my ($status, $message) = record_ffq_prev_deferred();
1028 if ($status eq 'deferred' || $status eq 'exists') {
1030 fproblem $status, "could not record ffq-prev: $message";
1031 fproblems_maybe_bail();
1035 sub cmd_new_upstream_v0 () {
1036 # automatically and unconditionally launders before rebasing
1037 # if rebase --abort is used, laundering has still been done
1041 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1043 # parse args - low commitment
1044 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1045 my $new_upstream_version = $new_version->version();
1047 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1052 my ($n, @x) = @_; # may be ''
1053 my $pc = $pieces{$n} //= {
1055 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1057 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1062 my $newpiece = sub {
1063 my ($n, @x) = @_; # may be ''
1064 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1065 push @newpieces, $pc;
1070 New => $new_upstream,
1072 while (@ARGV && $ARGV[0] !~ m{^-}) {
1073 my $n = shift @ARGV;
1075 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1076 unless @ARGV && $ARGV[0] !~ m{^-};
1078 my $c = git_rev_parse shift @ARGV;
1079 die unless $n =~ m/^$extra_orig_namepart_re$/;
1080 $newpiece->($n, New => $c);
1083 # now we need to investigate the branch this generates the
1084 # laundered version but we don't switch to it yet
1085 my $old_head = get_head();
1086 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1088 my $old_bw_cl = classify $old_bw;
1089 my $old_anchor_cl = classify $old_anchor;
1091 if (!$old_anchor_cl->{OrigParents}) {
1092 fproblem 'anchor-treated',
1093 'old anchor is recognised due to --anchor, cannot check upstream';
1095 $old_upstream = parsecommit
1096 $old_anchor_cl->{OrigParents}[0]{CommitId};
1097 $piece->('', Old => $old_upstream->{CommitId});
1100 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1101 if ($old_upstream->{Msg} =~
1102 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1104 my @oldpieces = ('', split / /, $1);
1105 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1106 foreach my $i (0..$#oldpieces) {
1107 my $n = $oldpieces[$i];
1108 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1111 fproblem 'upstream-confusing',
1112 "previous upstream $old_upstream->{CommitId} is from".
1113 " git-debrebase but not an \`upstream-combine' commit";
1117 foreach my $pc (values %pieces) {
1118 if (!$old_upstream) {
1119 # we have complained already
1120 } elsif (!$pc->{Old}) {
1121 fproblem 'upstream-new-piece',
1122 "introducing upstream piece \`$pc->{Name}'";
1123 } elsif (!$pc->{New}) {
1124 fproblem 'upstream-rm-piece',
1125 "dropping upstream piece \`$pc->{Name}'";
1126 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1127 fproblem 'upstream-not-ff',
1128 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1132 printdebug "%pieces = ", (dd \%pieces), "\n";
1133 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1135 fproblems_maybe_bail();
1141 my @upstream_merge_parents;
1143 if (!any_fproblems()) {
1144 push @upstream_merge_parents, $old_upstream->{CommitId};
1147 foreach my $pc (@newpieces) { # always has '' first
1149 read_tree_subdir $pc->{Name}, $pc->{New};
1151 runcmd @git, qw(read-tree), $pc->{New};
1153 push @upstream_merge_parents, $pc->{New};
1156 # index now contains the new upstream
1158 if (@newpieces > 1) {
1159 # need to make the upstream subtree merge commit
1160 $new_upstream = make_commit \@upstream_merge_parents,
1161 [ "Combine upstreams for $new_upstream_version",
1162 ("[git-debrebase upstream-combine . ".
1163 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1168 # $new_upstream is either the single upstream commit, or the
1169 # combined commit we just made. Either way it will be the
1170 # "upstream" parent of the anchor merge.
1172 read_tree_subdir 'debian', "$old_bw:debian";
1174 # index now contains the anchor merge contents
1175 $new_bw = make_commit [ $old_bw, $new_upstream ],
1176 [ "Update to upstream $new_upstream_version",
1177 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1180 # Now we have to add a changelog stanza so the Debian version
1182 die if unlink "debian";
1183 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1184 unlink "debian/changelog" or $!==ENOENT or die $!;
1185 mkdir "debian" or die $!;
1186 open CN, ">", "debian/changelog" or die $!;
1187 my $oldclog = git_cat_file ":debian/changelog";
1188 $oldclog =~ m/^($package_re) \(\S+\) / or
1189 fail "cannot parse old changelog to get package name";
1191 print CN <<END, $oldclog or die $!;
1192 $p ($new_version) UNRELEASED; urgency=medium
1194 * Update to new upstream version $new_upstream_version.
1200 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1202 # Now we have the final new breakwater branch in the index
1203 $new_bw = make_commit [ $new_bw ],
1204 [ "Update changelog for new upstream $new_upstream_version",
1205 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1209 # we have constructed the new breakwater. we now need to commit to
1210 # the laundering output, because git-rebase can't easily be made
1211 # to make a replay list which is based on some other branch
1213 update_head_postlaunder $old_head, $old_laundered_tip,
1214 'launder for new upstream';
1216 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1218 # now it's for the user to sort out
1221 sub cmd_record_ffq_prev () {
1222 badusage "no arguments allowed" if @ARGV;
1223 my ($status, $msg) = record_ffq_prev_deferred();
1224 if ($status eq 'exists' && $opt_noop_ok) {
1225 print "Previous head already recorded\n" or die $!;
1226 } elsif ($status eq 'deferred') {
1227 run_deferred_updates 'record-ffq-prev';
1229 fail "Could not preserve: $msg";
1233 sub cmd_breakwater () {
1234 badusage "no arguments allowed" if @ARGV;
1235 my $bw = breakwater_of git_rev_parse 'HEAD';
1236 print "$bw\n" or die $!;
1241 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1242 badusage "no arguments allowed" if @ARGV;
1243 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1244 if ($status ne 'branch') {
1245 fproblem $status, "could not check ffq-prev: $message";
1246 fproblems_maybe_bail();
1248 my $prev = $ffq_prev && git_get_ref $ffq_prev;
1250 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1252 push @deferred_updates, "delete $ffq_prev $prev";
1254 my $old_head = get_head();
1255 if (is_fast_fwd $old_head, $prev) {
1256 my $differs = get_differs $old_head, $prev;
1257 unless ($differs & ~D_PAT_ADD) {
1258 # ffq-prev is ahead of us, and the only tree changes it has
1259 # are possibly addition of things in debian/patches/.
1260 # Just wind forwards rather than making a pointless pseudomerge.
1261 update_head_checkout $old_head, $prev, "stitch (fast forward)";
1266 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1267 'Declare fast forward / record previous work',
1268 "[git-debrebase pseudomerge: stitch$prose]",
1270 update_head $old_head, $new_head, "stitch";
1273 sub cmd_convert_from_gbp () {
1274 badusage "needs 1 optional argument, the upstream git rev"
1276 my ($upstream_spec) = @ARGV;
1277 $upstream_spec //= 'refs/heads/upstream';
1278 my $upstream = git_rev_parse $upstream_spec;
1279 my $old_head = get_head();
1281 my $upsdiff = get_differs $upstream, $old_head;
1282 if ($upsdiff & D_UPS) {
1283 runcmd @git, qw(--no-pager diff),
1284 $upstream, $old_head,
1285 qw( -- :!/debian :/);
1286 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1289 if (!is_fast_fwd $upstream, $old_head) {
1290 fproblem 'upstream-not-ancestor',
1291 "upstream ($upstream) is not an ancestor of HEAD";
1293 my $wrong = cmdoutput
1294 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1295 qw(-- :/ :!/debian));
1296 if (length $wrong) {
1297 fproblem 'unexpected-upstream-changes',
1298 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1299 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1303 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1304 fproblem 'upstream-has-debian',
1305 "upstream ($upstream) contains debian/ directory";
1308 fproblems_maybe_bail();
1314 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1315 # make a branch out of the patch queue - we'll want this in a mo
1316 runcmd qw(gbp pq import);
1317 # strip the patches out
1318 runcmd @git, qw(checkout -q gdr-internal~0);
1319 rm_subdir_cached 'debian/patches';
1320 $work = make_commit ['HEAD'], [
1321 'git-debrebase convert-from-gbp: drop patches from tree',
1322 'Delete debian/patches, as part of converting to git-debrebase format.',
1323 '[git-debrebase convert-from-gbp: drop patches from tree]'
1325 # make the anchor merge
1326 # the tree is already exactly right
1327 $work = make_commit [$work, $upstream], [
1328 'git-debrebase import: declare upstream',
1329 'First breakwater merge.',
1330 '[git-debrebase anchor: declare upstream]'
1333 # rebase the patch queue onto the new breakwater
1334 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1335 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1336 $work = git_rev_parse 'HEAD';
1339 update_head_checkout $old_head, $work, 'convert-from-gbp';
1342 sub cmd_convert_to_gbp () {
1343 badusage "no arguments allowed" if @ARGV;
1344 my $head = get_head();
1345 my $ffq = (ffq_prev_branchinfo())[3];
1346 my $bw = breakwater_of $head;
1350 runcmd @git, qw(checkout -q -b bw), $bw;
1351 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1352 runcmd qw(gbp pq export);
1353 runcmd @git, qw(add debian/patches);
1354 $out = make_commit ['HEAD'], [
1355 'Commit patch queue (converted from git-debrebase format)',
1356 '[git-debrebase convert-to-gbp: commit patches]',
1360 push @deferred_updates, "delete $ffq";
1362 update_head_checkout $head, $out, "convert to gbp (v0)";
1363 print <<END or die $!;
1364 git-debrebase: converted to git-buildpackage branch format
1365 git-debrebase: WARNING: do not now run "git-debrebase" any more
1366 git-debrebase: WARNING: doing so would drop all upstream patches!
1370 sub cmd_downstream_rebase_launder_v0 () {
1371 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1373 $base = git_rev_parse $base;
1374 my $old_head = get_head();
1375 my $current = $old_head;
1378 if ($current eq $base) {
1379 $topmost_keep //= $current;
1380 print " $current BASE stop\n";
1383 my $cl = classify $current;
1384 print " $current $cl->{Type}";
1386 my $p0 = $cl->{Parents}[0]{CommitId};
1388 if ($cl->{Type} eq 'Pseudomerge') {
1389 print " ^".($cl->{Contributor}{Ix}+1);
1390 $next = $cl->{Contributor}{CommitId};
1391 } elsif ($cl->{Type} eq 'AddPatches' or
1392 $cl->{Type} eq 'Changelog') {
1402 $topmost_keep //= $current;
1404 die "to-be stripped changes not on top of the branch\n"
1409 if ($topmost_keep eq $old_head) {
1410 print "unchanged\n";
1412 print "updating to $topmost_keep\n";
1413 update_head_checkout
1414 $old_head, $topmost_keep,
1415 'downstream-rebase-launder-v0';
1419 GetOptions("D+" => \$debuglevel,
1420 'noop-ok', => \$opt_noop_ok,
1421 'f=s' => \@fproblem_force_opts,
1422 'anchor=s' => \@opt_anchors,
1423 'force!') or die badusage "bad options\n";
1424 initdebug('git-debrebase ');
1425 enabledebug if $debuglevel;
1427 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1428 chdir $toplevel or die "chdir $toplevel: $!";
1430 $rd = fresh_playground "$playprefix/misc";
1432 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1434 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1435 defaultcmd_rebase();
1437 my $cmd = shift @ARGV;
1440 $cmdfn = ${*::}{"cmd_$cmdfn"};
1442 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";