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>] new-upstream-v0 \
25 # <new-version> [<orig-commitish> \
26 # [<extra-orig-name> <extra-orig-commitish> ...] \
27 # [<git-rebase options>...]]
29 # git-debrebase [<options> --] [<git-rebase options...>]
30 # git-debrebase [<options>] analyse
31 # git-debrebase [<options>] breakwater # prints breakwater tip only
32 # git-debrebase [<options>] stitch [--prose=<for commit message>]
33 # git-debrebase [<options>] launder-v0 # prints breakwater tip etc.
34 # git-debrebase [<options>] downstream-rebase-launder-v0 # experimental
36 # git-debrebase [<options>] convert-from-gbp [<upstream-git-rev>]
37 # git-debrebase [<options>] convert-to-gbp
39 # problems / outstanding questions:
41 # * dgit push with a `3.0 (quilt)' package means doing quilt
42 # fixup. Usually this involves recommitting the whole patch
43 # series, one at a time, with dpkg-source --commit. This is
44 # terribly terribly slow. (Maybe this should be fixed in dgit.)
46 # * dgit push usually needs to (re)make a pseudomerge. The "first"
47 # git-debrebase stripped out the previous pseudomerge and could
48 # have remembeed the HEAD. But it's not quite clear what history
49 # ought to be preserved and what should be discarded. For now
50 # the user will have to tell dgit --overwrite.
52 # To fix this, do we need a new push hook for dgit ?
54 # * Workflow is currently clumsy. Lots of spurious runes to type.
55 # There's not even a guide.
57 # * There are no tests.
59 # * new-upstream-v0 has a terrible UI. You end up with giant
60 # runic command lines.
62 # One consequence of the lack of richness it can need --force in
63 # fairly sensible situations and there is no way to tell it what
64 # you are really trying to do, other than just --force. There
65 # should be an interface with some default branch names.
67 # * There should be a standard convention for the version number,
68 # and unfinalised or not changelog, after new-upstream.
70 # * Handing of multi-orig dgit new-upstream .dsc imports is known to
71 # be broken. They may be not recognised, improperly converted, or
72 # their conversion may be unrecognised.
74 # * Docs need writing and updating. Even README.git-debrebase
75 # describes a design but may not reflect the implementation.
77 # * We need to develop a plausible model that works for derivatives,
78 # who probably want to maintain their stack on top of Debian's.
79 # downstream-rebase-launder-v0 may be a starting point?
83 use Debian::Dgit qw(:DEFAULT :playground);
90 use Getopt::Long qw(:config posix_default gnu_compat bundling);
92 use File::FnMatch qw(:fnmatch);
94 our ($opt_force, $opt_noop_ok, @opt_anchors);
96 our $us = qw(git-debrebase);
100 die "bad usage: $m\n";
104 my ($k, $optional) = @_;
106 my @cmd = qw(git config -z);
107 push @cmd, qw(--get-all) if wantarray;
109 my $out = cmdoutput_errok @cmd;
111 fail "missing required git config $k" unless $optional;
114 my @l = split /\0/, $out;
115 return wantarray ? @l : $l[0];
122 my $dd = new Data::Dumper [ $v ];
123 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
129 my $data = (git_cat_file $objid, 'commit');
130 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
134 sub D_UPS () { 0x02; } # upstream files
135 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
136 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
137 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
138 sub D_DEB_OTH () { 0x20; } # debian/changelog
139 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
141 our $playprefix = 'debrebase';
147 sub in_workarea ($) {
150 my $r = eval { $sub->(); };
151 { local $@; changedir $maindir; }
155 sub fresh_workarea () {
156 $workarea = fresh_playground "$playprefix/work";
157 in_workarea sub { playtree_setup };
160 our @deferred_updates;
161 our @deferred_update_messages;
163 sub run_deferred_updates ($) {
166 my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
167 debugcmd '>|', @upd_cmd;
168 open U, "|-", @upd_cmd or die $!;
169 foreach (@deferred_updates) {
170 printdebug ">= ", $_, "\n";
171 print U $_, "\n" or die $!;
174 close U or failedcmd @upd_cmd;
176 print $_, "\n" foreach @deferred_update_messages;
178 @deferred_updates = ();
179 @deferred_update_messages = ();
182 sub get_differs ($$) {
184 # This resembles quiltify_trees_differ, in dgit, a bit.
185 # But we don't care about modes, or dpkg-source-unrepresentable
186 # changes, and we don't need the plethora of different modes.
187 # Conversely we need to distinguish different kinds of changes to
188 # debian/ and debian/patches/.
193 my ($opts, $limits, $fn) = @_;
194 my @cmd = (@git, qw(diff-tree -z --no-renames));
196 push @cmd, "$_:" foreach $x, $y;
197 push @cmd, '--', @$limits;
198 my $diffs = cmdoutput @cmd;
199 foreach (split /\0/, $diffs) { $fn->(); }
202 $rundiff->([qw(--name-only)], [], sub {
203 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
206 if ($differs & DS_DEB) {
208 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
210 m{^debian/patches/} ? D_PAT_OTH :
211 $_ eq 'debian/changelog' ? D_DEB_CLOG :
214 die "mysterious debian changes $x..$y"
215 unless $differs & (D_PAT_OTH|DS_DEB);
218 if ($differs & D_PAT_OTH) {
220 $differs &= ~D_PAT_OTH;
222 $differs |= D_PAT_OTH;
223 no warnings qw(exiting); last;
225 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
226 no warnings qw(exiting);
227 if (!defined $mode) {
230 die unless s{^debian/patches/}{};
232 if ($mode eq 'A' && !m/\.series$/s) {
234 } elsif ($mode eq 'M' && $_ eq 'series') {
235 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
236 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
237 chomp $x_s; $x_s .= "\n";
238 $ok = $x_s eq substr($y_s, 0, length $x_s);
243 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
245 die "mysterious debian/patches changes $x..$y"
246 unless $differs & (D_PAT_ADD|D_PAT_OTH);
249 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
254 sub commit_pr_info ($) {
256 return Data::Dumper->dump([$r], [qw(commit)]);
259 sub calculate_committer_authline () {
260 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
261 'DUMMY COMMIT (git-debrebase)', "HEAD:";
262 my ($h,$m) = get_commit $c;
263 $h =~ m/^committer .*$/m or confess "($h) ?";
267 sub rm_subdir_cached ($) {
269 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
272 sub read_tree_subdir ($$) {
273 my ($subdir, $new_tree_object) = @_;
274 rm_subdir_cached $subdir;
275 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
278 sub make_commit ($$) {
279 my ($parents, $message_paras) = @_;
280 my $tree = cmdoutput @git, qw(write-tree);
281 my @cmd = (@git, qw(commit-tree), $tree);
282 push @cmd, qw(-p), $_ foreach @$parents;
283 push @cmd, qw(-m), $_ foreach @$message_paras;
284 return cmdoutput @cmd;
287 our @fproblem_force_opts;
288 our $fproblems_forced;
289 our $fproblems_tripped;
292 if (grep { $_ eq $tag } @fproblem_force_opts) {
294 print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
296 $fproblems_tripped++;
297 print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
301 sub fproblems_maybe_bail () {
302 if ($fproblems_forced) {
304 "%s: safety catch trips: %d overriden by individual -f options\n",
305 $us, $fproblems_forced;
307 if ($fproblems_tripped) {
310 "%s: safety catch trips: %d overriden by global --force\n",
311 $us, $fproblems_tripped;
314 "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
315 $us, $fproblems_tripped;
319 sub any_fproblems () {
320 return $fproblems_forced || $fproblems_tripped;
323 # classify returns an info hash like this
325 # Hdr => # commit headers, including 1 final newline
326 # Msg => # commit message (so one newline is dropped)
328 # Type => (see below)
330 # Ix => $index # ie 0, 1, 2, ...
332 # Differs => return value from get_differs
334 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
336 # NewMsg => # commit message, but with any [dgit import ...] edited
337 # # to say "[was: ...]"
347 # has additional entres in classification result
348 # Overwritten = [ subset of Parents ]
349 # Contributor = $the_remaining_Parent
351 # DgitImportUnpatched
352 # has additional entry in classification result
353 # OrigParents = [ subset of Parents ]
356 # has additional entry in classification result
357 # OrigParents = [ subset of Parents ] # singleton list
364 # has additional entry in classification result
367 sub parsecommit ($;$) {
368 my ($objid, $p_ref) = @_;
369 # => hash with CommitId Hdr Msg Tree Parents
370 # Parents entries have only Ix CommitId
371 # $p_ref, if provided, must be [] and is used as a base for Parents
376 my ($h,$m) = get_commit $objid;
378 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
379 my (@ph) = $h =~ m/^parent (\w+)$/mg;
389 foreach my $ph (@ph) {
391 Ix => scalar @$p_ref,
403 my $r = parsecommit($objid, \@p);
407 $p->{Differs} = (get_differs $p->{CommitId}, $t),
410 printdebug "classify $objid \$t=$t \@p",
411 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
415 my ($type, @rest) = @_;
416 $r = { %$r, Type => $type, @rest };
418 printdebug " = $type ".(dd $r)."\n";
424 $r = { %$r, Type => qw(Unknown), Why => $why };
425 printdebug " ** Unknown\n";
429 if (grep { $_ eq $objid } @opt_anchors) {
430 return $classify->('TreatAsAnchor');
433 my @identical = grep { !$_->{Differs} } @p;
434 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
435 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
437 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
438 # multi-orig upstreams are represented with an anchor merge
439 # from a single upstream commit which combines the orig tarballs
441 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
442 @p == 2 or return $badanchor->("has other than two parents");
443 $haspatches and return $badanchor->("contains debian/patches");
445 # How to decide about l/r ordering of anchors ? git
446 # --topo-order prefers to expand 2nd parent first. There's
447 # already an easy rune to look for debian/ history anyway (git log
448 # debian/) so debian breakwater branch should be 1st parent; that
449 # way also there's also an easy rune to look for the upstream
450 # patches (--topo-order).
452 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
453 $p[1]{Differs} & ~DS_DEB and
454 $badanchor->("upstream files differ from left parent");
455 $p[0]{Differs} & ~D_UPS and
456 $badanchor->("debian/ differs from right parent");
458 return $classify->(qw(Anchor),
459 OrigParents => [ $p[1] ]);
463 my $d = $r->{Parents}[0]{Differs};
464 if ($d == D_PAT_ADD) {
465 return $classify->(qw(AddPatches));
466 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
467 return $unknown->("edits debian/patches");
468 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
469 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
471 if ($d == D_DEB_CLOG) {
472 return $classify->(qw(Changelog));
474 return $classify->(qw(Packaging));
476 } elsif ($ty eq 'missing') {
477 return $classify->(qw(BreakwaterStart));
479 return $unknown->("parent's debian is not a directory");
481 } elsif ($d == D_UPS) {
482 return $classify->(qw(Upstream));
483 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
484 return $classify->(qw(Mixed));
486 return $unknown->("no changes");
488 confess "internal error $objid ?";
492 return $unknown->("origin commit");
495 if (@p == 2 && @identical == 1) {
496 my @overwritten = grep { $_->{Differs} } @p;
497 confess "internal error $objid ?" unless @overwritten==1;
498 return $classify->(qw(Pseudomerge),
499 Overwritten => [ $overwritten[0] ],
500 Contributor => $identical[0]);
502 if (@p == 2 && @identical == 2) {
504 my ($ph,$pm) = get_commit $_[0]{CommitId};
505 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
509 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
510 if ($order > 0) { # newer first
511 } elsif ($order < 0) {
512 @bytime = reverse @bytime;
514 # same age, default to order made by -s ours
515 # that is, commit was made by someone who preferred L
517 return $classify->(qw(Pseudomerge),
518 SubType => qw(Ambiguous),
519 Contributor => $bytime[0],
520 Overwritten => [ $bytime[1] ]);
523 my ($p_h, $p_m) = get_commit $p->{CommitId};
524 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
525 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
527 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
529 if (!(grep { !$_->{IsOrigin} } @p) and
530 (@orig_ps >= @p - 1) and
531 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
533 return $classify->(qw(DgitImportUnpatched),
534 OrigParents => \@orig_ps);
537 return $unknown->("complex merge");
540 sub breakwater_of ($) {
541 my ($head) = @_; # must be laundered
545 fail "branch needs laundering (run git-debrebase): $why";
548 my $cl = classify $head;
549 my $ty = $cl->{Type};
550 if ($ty eq 'Packaging' or
551 $ty eq 'Changelog') {
552 $breakwater //= $head;
553 } elsif ($ty eq 'Anchor' or
554 $ty eq 'TreatAsAnchor' or
555 $ty eq 'BreakwaterStart') {
556 $breakwater //= $head;
558 } elsif ($ty eq 'Upstream') {
559 $unclean->("packaging change ($breakwater)".
560 " follows upstream change (eg $head)")
561 if defined $breakwater;
562 } elsif ($ty eq 'Mixed') {
563 $unclean->('found mixed upstream/packaging commit ($head)');
564 } elsif ($ty eq 'Pseudomerge' or
565 $ty eq 'AddPatches') {
566 $unclean->("found interchange conversion commit ($ty, $head)");
567 } elsif ($ty eq 'DgitImportUnpatched') {
568 $unclean->("found dgit dsc import ($head)");
570 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
572 $head = $cl->{Parents}[0]{CommitId};
580 $nogenerate,$report) = @_;
581 # => ($tip, $breakwater_tip, $last_anchor)
582 # (or nothing, if $nogenerate)
584 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
586 # go through commits backwards
587 # we generate two lists of commits to apply:
588 # breakwater branch and upstream patches
589 my (@brw_cl, @upp_cl, @processed);
596 my ($prose, $info) = @_;
600 $ms .= "\n\n[git-debrebase$info: $prose]\n";
603 my $rewrite_from_here = sub {
605 my $sp_cl = { SpecialMethod => 'StartRewrite' };
607 push @processed, $sp_cl;
612 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
615 return unless $report;
616 print $report $prdelim, @_;
620 my $bomb = sub { # usage: return $bomb->();
621 print $report " Unprocessable" if $report;
622 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
625 return (undef,undef);
627 die "commit $cur: Cannot cope with this commit (d.".
628 (join ' ', map { sprintf "%#x", $_->{Differs} }
629 @{ $cl->{Parents} }).
630 (defined $cl->{Why} ? "; $cl->{Why}": '').
637 my $build_start = sub {
638 my ($msg, $parent) = @_;
641 no warnings qw(exiting); last;
648 my $ty = $cl->{Type};
649 my $st = $cl->{SubType};
650 $prline->("$cl->{CommitId} $cl->{Type}");
651 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
652 push @processed, $cl;
653 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
654 if ($ty eq 'AddPatches') {
656 $rewrite_from_here->(\@upp_cl);
658 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
662 } elsif ($ty eq 'BreakwaterStart') {
664 $build_start->('FirstPackaging', $cur);
665 } elsif ($ty eq 'Upstream') {
669 } elsif ($ty eq 'Mixed') {
672 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
675 $queue->(\@brw_cl, "debian");
676 $queue->(\@upp_cl, "upstream");
677 $rewrite_from_here->(\@brw_cl);
680 } elsif ($ty eq 'Pseudomerge') {
681 my $contrib = $cl->{Contributor}{CommitId};
682 print $report " Contributor=$contrib" if $report;
683 push @pseudomerges, $cl;
684 $rewrite_from_here->(\@upp_cl);
687 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
689 $build_start->("Anchor", $cur);
690 } elsif ($ty eq 'DgitImportUnpatched') {
691 my $pm = $pseudomerges[-1];
693 # To an extent, this is heuristic. Imports don't have
694 # a useful history of the debian/ branch. We assume
695 # that the first pseudomerge after an import has a
696 # useful history of debian/, and ignore the histories
697 # from later pseudomerges. Often the first pseudomerge
698 # will be the dgit import of the upload to the actual
699 # suite intended by the non-dgit NMUer, and later
700 # pseudomerges may represent in-archive copies.
701 my $ovwrs = $pm->{Overwritten};
702 printf $report " PM=%s \@Overwr:%d",
703 $pm->{CommitId}, (scalar @$ovwrs)
706 printdebug "*** WALK BOMB DgitImportUnpatched\n";
709 my $ovwr = $ovwrs->[0]{CommitId};
710 printf $report " Overwr=%s", $ovwr if $report;
711 # This import has a tree which is just like a
712 # breakwater tree, but it has the wrong history. It
713 # ought to have the previous breakwater (which the
714 # pseudomerge overwrote) as an ancestor. That will
715 # make the history of the debian/ files correct. As
716 # for the upstream version: either it's the same as
717 # was ovewritten (ie, same as the previous
718 # breakwater), in which case that history is precisely
719 # right; or, otherwise, it was a non-gitish upload of a
720 # new upstream version. We can tell these apart by
721 # looking at the tree of the supposed upstream.
724 SpecialMethod => 'DgitImportDebianUpdate',
725 $xmsg->("convert dgit import: debian changes")
728 SpecialMethod => 'DgitImportUpstreamUpdate',
729 $xmsg->("convert dgit import: upstream update",
732 $prline->(" Import");
733 $rewrite_from_here->(\@brw_cl);
734 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
738 # Everything is from this import. This kind of import
739 # is already in valid breakwater format, with the
740 # patches as commits.
741 printf $report " NoPM" if $report;
742 # last thing we processed will have been the first patch,
743 # if there is one; which is fine, so no need to rewrite
744 # on account of this import
745 $build_start->("ImportOrigin", $cur);
749 printdebug "*** WALK BOMB unrecognised\n";
755 printdebug "*** WALK prep done cur=$cur".
756 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
758 return if $nogenerate;
760 # Now we build it back up again
766 my $read_tree_debian = sub {
768 read_tree_subdir 'debian', "$treeish:debian";
769 rm_subdir_cached 'debian/patches';
771 my $read_tree_upstream = sub {
773 runcmd @git, qw(read-tree), $treeish;
774 $read_tree_debian->($build);
777 $#upp_cl = $upp_limit if defined $upp_limit;
779 my $committer_authline = calculate_committer_authline();
781 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
783 confess "internal error" unless $build eq (pop @processed)->{CommitId};
786 mkdir $rd or $!==EEXIST or die $!;
788 runcmd @git, qw(read-tree), $build;
789 foreach my $cl (qw(Debian), (reverse @brw_cl),
790 { SpecialMethod => 'RecordBreakwaterTip' },
791 qw(Upstream), (reverse @upp_cl)) {
793 $current_method = $cl;
796 my $method = $cl->{SpecialMethod} // $current_method;
797 my @parents = ($build);
798 my $cltree = $cl->{CommitId};
799 printdebug "WALK BUILD ".($cltree//'undef').
800 " $method (rewriting=$rewriting)\n";
801 if ($method eq 'Debian') {
802 $read_tree_debian->($cltree);
803 } elsif ($method eq 'Upstream') {
804 $read_tree_upstream->($cltree);
805 } elsif ($method eq 'StartRewrite') {
808 } elsif ($method eq 'RecordBreakwaterTip') {
809 $breakwater = $build;
811 } elsif ($method eq 'DgitImportDebianUpdate') {
812 $read_tree_debian->($cltree);
813 } elsif ($method eq 'DgitImportUpstreamUpdate') {
814 confess unless $rewriting;
815 my $differs = (get_differs $build, $cltree);
816 next unless $differs & D_UPS;
817 $read_tree_upstream->($cltree);
818 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
823 my $procd = (pop @processed) // 'UNDEF';
826 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
829 my $newtree = cmdoutput @git, qw(write-tree);
831 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
832 $ch =~ s{^parent .*\n}{}mg;
833 $ch =~ s{(?=^author)}{
834 join '', map { "parent $_\n" } @parents
835 }me or confess "$ch ?";
837 $ch =~ s{^committer .*$}{$committer_authline}m
840 my $cf = "$rd/m$rewriting";
841 open CD, ">", $cf or die $!;
842 print CD $ch, "\n", $cl->{Msg} or die $!;
844 my @cmd = (@git, qw(hash-object));
845 push @cmd, qw(-w) if $rewriting;
846 push @cmd, qw(-t commit), $cf;
847 my $newcommit = cmdoutput @cmd;
848 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
850 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
856 my $final_check = get_differs $build, $input;
857 die sprintf "internal error %#x %s %s", $final_check, $build, $input
858 if $final_check & ~D_PAT_ADD;
860 my @r = ($build, $breakwater, $last_anchor);
861 printdebug "*** WALK RETURN @r\n";
866 git_check_unmodified();
867 return git_rev_parse qw(HEAD);
870 sub update_head ($$$) {
871 my ($old, $new, $mrest) = @_;
872 push @deferred_updates, "update HEAD $new $old";
873 run_deferred_updates $mrest;
876 sub update_head_checkout ($$$) {
877 my ($old, $new, $mrest) = @_;
878 update_head $old, $new, $mrest;
879 runcmd @git, qw(reset --hard);
882 sub update_head_postlaunder ($$$) {
883 my ($old, $tip, $reflogmsg) = @_;
884 return if $tip eq $old;
885 print "git-debrebase: laundered (head was $old)\n";
886 update_head $old, $tip, $reflogmsg;
887 # no tree changes except debian/patches
888 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
891 sub cmd_launder_v0 () {
892 badusage "no arguments to launder-v0 allowed" if @ARGV;
893 my $old = get_head();
894 my ($tip,$breakwater,$last_anchor) = walk $old;
895 update_head_postlaunder $old, $tip, 'launder';
896 printf "# breakwater tip\n%s\n", $breakwater;
897 printf "# working tip\n%s\n", $tip;
898 printf "# last anchor\n%s\n", $last_anchor;
901 sub defaultcmd_rebase () {
902 my $old = get_head();
904 my ($tip,$breakwater) = walk $old;
905 update_head_postlaunder $old, $tip, 'launder for rebase';
906 runcmd @git, qw(rebase), @ARGV, $breakwater;
910 die if ($ARGV[0]//'') =~ m/^-/;
911 badusage "too many arguments to analyse" if @ARGV>1;
914 $old = git_rev_parse $old;
916 $old = git_rev_parse 'HEAD';
918 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
919 STDOUT->error and die $!;
922 sub ffq_prev_branchinfo () {
923 # => ('status', "message", [$current, $ffq_prev])
925 # branch message is undef
926 # weird-symref } no $current,
927 # notbranch } no $ffq_prev
928 my $current = git_get_symref();
929 return ('detached', 'detached HEAD') unless defined $current;
930 return ('weird-symref', 'HEAD symref is not to refs/')
931 unless $current =~ m{^refs/};
932 my $ffq_prev = "refs/$ffq_refprefix/$'";
933 printdebug "ffq_prev_branchinfo branch current $current\n";
934 return ('branch', undef, $current, $ffq_prev);
937 sub record_ffq_prev_deferred () {
938 # => ('status', "message")
940 # deferred message is undef
945 # if not ff from some branch we should be ff from, is an fproblem
946 # if "deferred", will have added something about that to
947 # @deferred_update_messages, and also maybe printed (already)
948 # some messages about ff checks
949 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
950 return ($status, $message) unless $status eq 'branch';
952 my $currentval = get_head();
954 my $exists = git_get_ref $ffq_prev;
955 return ('exists',"$ffq_prev already exists") if $exists;
957 return ('not-branch', 'HEAD symref is not to refs/heads/')
958 unless $current =~ m{^refs/heads/};
961 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
964 printdebug "ffq check_specs @check_specs\n";
967 my ($lrref, $desc) = @_;
968 printdebug "ffq might check $lrref ($desc)\n";
970 for my $chk (@check_specs) {
972 $invert = $glob =~ s{^[!^]}{};
973 last if fnmatch $glob, $lrref;
976 my $lrval = git_get_ref $lrref;
977 return unless defined $lrval;
979 if (is_fast_fwd $lrval, $currentval) {
980 print "OK, you are ahead of $lrref\n" or die $!;
981 $checked{$lrref} = 1;
982 } elsif (is_fast_fwd $currentval, $lrval) {
983 $checked{$lrref} = -1;
984 fproblem 'behind', "you are behind $lrref, divergence risk";
986 $checked{$lrref} = -1;
987 fproblem 'diverged', "you have diverged from $lrref";
991 my $merge = cfg "branch.$branch.merge",1;
992 if (defined $merge and $merge =~ m{^refs/heads/}) {
994 printdebug "ffq merge $rhs\n";
995 my $check_remote = sub {
996 my ($remote, $desc) = @_;
997 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
998 return unless defined $remote;
999 $check->("refs/remotes/$remote/$rhs", $desc);
1001 $check_remote->((scalar cfg "branch.$branch.remote",1),
1002 'remote fetch/merge branch');
1003 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1004 (scalar cfg "branch.$branch.pushDefault",1),
1005 'remote push branch');
1007 if ($branch =~ m{^dgit/}) {
1008 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1009 } elsif ($branch =~ m{^master$}) {
1010 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1013 fproblems_maybe_bail();
1015 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1016 push @deferred_update_messages, "Recorded current head for preservation";
1017 return ('deferred', undef);
1020 sub record_ffq_auto () {
1021 my ($status, $message) = record_ffq_prev_deferred();
1022 if ($status eq 'deferred' || $status eq 'exists') {
1024 fproblem $status, "could not record ffq-prev: $message";
1025 fproblems_maybe_bail();
1029 sub cmd_new_upstream_v0 () {
1030 # automatically and unconditionally launders before rebasing
1031 # if rebase --abort is used, laundering has still been done
1035 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1037 # parse args - low commitment
1038 my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1039 my $new_upstream_version = $new_version->version();
1041 my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1046 my ($n, @x) = @_; # may be ''
1047 my $pc = $pieces{$n} //= {
1049 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1051 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1056 my $newpiece = sub {
1057 my ($n, @x) = @_; # may be ''
1058 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1059 push @newpieces, $pc;
1064 New => $new_upstream,
1066 while (@ARGV && $ARGV[0] !~ m{^-}) {
1067 my $n = shift @ARGV;
1069 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1070 unless @ARGV && $ARGV[0] !~ m{^-};
1072 my $c = git_rev_parse shift @ARGV;
1073 die unless $n =~ m/^$extra_orig_namepart_re$/;
1074 $newpiece->($n, New => $c);
1077 # now we need to investigate the branch this generates the
1078 # laundered version but we don't switch to it yet
1079 my $old_head = get_head();
1080 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1082 my $old_bw_cl = classify $old_bw;
1083 my $old_anchor_cl = classify $old_anchor;
1085 if (!$old_anchor_cl->{OrigParents}) {
1086 fproblem 'anchor-treated',
1087 'old anchor is recognised due to --anchor, cannot check upstream';
1089 $old_upstream = parsecommit
1090 $old_anchor_cl->{OrigParents}[0]{CommitId};
1091 $piece->('', Old => $old_upstream->{CommitId});
1094 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1095 if ($old_upstream->{Msg} =~
1096 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1098 my @oldpieces = ('', split / /, $1);
1099 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1100 foreach my $i (0..$#oldpieces) {
1101 my $n = $oldpieces[$i];
1102 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1105 fproblem 'upstream-confusing',
1106 "previous upstream $old_upstream->{CommitId} is from".
1107 " git-debrebase but not an \`upstream-combine' commit";
1111 foreach my $pc (values %pieces) {
1112 if (!$old_upstream) {
1113 # we have complained already
1114 } elsif (!$pc->{Old}) {
1115 fproblem 'upstream-new-piece',
1116 "introducing upstream piece \`$pc->{Name}'";
1117 } elsif (!$pc->{New}) {
1118 fproblem 'upstream-rm-piece',
1119 "dropping upstream piece \`$pc->{Name}'";
1120 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1121 fproblem 'upstream-not-ff',
1122 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1126 printdebug "%pieces = ", (dd \%pieces), "\n";
1127 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1129 fproblems_maybe_bail();
1135 my @upstream_merge_parents;
1137 if (!any_fproblems()) {
1138 push @upstream_merge_parents, $old_upstream->{CommitId};
1141 foreach my $pc (@newpieces) { # always has '' first
1143 read_tree_subdir $pc->{Name}, $pc->{New};
1145 runcmd @git, qw(read-tree), $pc->{New};
1147 push @upstream_merge_parents, $pc->{New};
1150 # index now contains the new upstream
1152 if (@newpieces > 1) {
1153 # need to make the upstream subtree merge commit
1154 $new_upstream = make_commit \@upstream_merge_parents,
1155 [ "Combine upstreams for $new_upstream_version",
1156 ("[git-debrebase upstream-combine . ".
1157 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1162 # $new_upstream is either the single upstream commit, or the
1163 # combined commit we just made. Either way it will be the
1164 # "upstream" parent of the anchor merge.
1166 read_tree_subdir 'debian', "$old_bw:debian";
1168 # index now contains the anchor merge contents
1169 $new_bw = make_commit [ $old_bw, $new_upstream ],
1170 [ "Update to upstream $new_upstream_version",
1171 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1174 # Now we have to add a changelog stanza so the Debian version
1176 die if unlink "debian";
1177 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1178 unlink "debian/changelog" or $!==ENOENT or die $!;
1179 mkdir "debian" or die $!;
1180 open CN, ">", "debian/changelog" or die $!;
1181 my $oldclog = git_cat_file ":debian/changelog";
1182 $oldclog =~ m/^($package_re) \(\S+\) / or
1183 fail "cannot parse old changelog to get package name";
1185 print CN <<END, $oldclog or die $!;
1186 $p ($new_version) UNRELEASED; urgency=medium
1188 * Update to new upstream version $new_upstream_version.
1194 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1196 # Now we have the final new breakwater branch in the index
1197 $new_bw = make_commit [ $new_bw ],
1198 [ "Update changelog for new upstream $new_upstream_version",
1199 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1203 # we have constructed the new breakwater. we now need to commit to
1204 # the laundering output, because git-rebase can't easily be made
1205 # to make a replay list which is based on some other branch
1207 update_head_postlaunder $old_head, $old_laundered_tip,
1208 'launder for new upstream';
1210 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1212 # now it's for the user to sort out
1215 sub cmd_record_ffq_prev () {
1216 badusage "no arguments allowed" if @ARGV;
1217 my ($status, $msg) = record_ffq_prev_deferred();
1218 if ($status eq 'exists' && $opt_noop_ok) {
1219 print "Previous head already recorded\n" or die $!;
1220 } elsif ($status eq 'deferred') {
1221 run_deferred_updates 'record-ffq-prev';
1223 fail "Could not preserve: $msg";
1227 sub cmd_breakwater () {
1228 badusage "no arguments allowed" if @ARGV;
1229 my $bw = breakwater_of git_rev_parse 'HEAD';
1230 print "$bw\n" or die $!;
1235 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1236 badusage "no arguments allowed" if @ARGV;
1237 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1238 if ($status ne 'branch') {
1239 fproblem $status, "could not check ffq-prev: $message";
1240 fproblems_maybe_bail();
1242 my $prev = $ffq_prev && git_get_ref $ffq_prev;
1244 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1246 push @deferred_updates, "delete $ffq_prev $prev";
1248 my $old_head = get_head();
1249 if (is_fast_fwd $old_head, $prev) {
1250 my $differs = get_differs $old_head, $prev;
1251 unless ($differs & ~D_PAT_ADD) {
1252 # ffq-prev is ahead of us, and the only tree changes it has
1253 # are possibly addition of things in debian/patches/.
1254 # Just wind forwards rather than making a pointless pseudomerge.
1255 update_head_checkout $old_head, $prev, "stitch (fast forward)";
1260 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1261 'Declare fast forward / record previous work',
1262 "[git-debrebase pseudomerge: stitch$prose]",
1264 update_head $old_head, $new_head, "stitch";
1267 sub cmd_convert_from_gbp () {
1268 badusage "needs 1 optional argument, the upstream git rev"
1270 my ($upstream_spec) = @ARGV;
1271 $upstream_spec //= 'refs/heads/upstream';
1272 my $upstream = git_rev_parse $upstream_spec;
1273 my $old_head = get_head();
1275 my $upsdiff = get_differs $upstream, $old_head;
1276 if ($upsdiff & D_UPS) {
1277 runcmd @git, qw(--no-pager diff),
1278 $upstream, $old_head,
1279 qw( -- :!/debian :/);
1280 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1283 if (!is_fast_fwd $upstream, $old_head) {
1284 fproblem 'upstream-not-ancestor',
1285 "upstream ($upstream) is not an ancestor of HEAD";
1287 my $wrong = cmdoutput
1288 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1289 qw(-- :/ :!/debian));
1290 if (length $wrong) {
1291 fproblem 'unexpected-upstream-changes',
1292 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1293 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1297 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1298 fproblem 'upstream-has-debian',
1299 "upstream ($upstream) contains debian/ directory";
1302 fproblems_maybe_bail();
1308 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1309 # make a branch out of the patch queue - we'll want this in a mo
1310 runcmd qw(gbp pq import);
1311 # strip the patches out
1312 runcmd @git, qw(checkout -q gdr-internal~0);
1313 rm_subdir_cached 'debian/patches';
1314 $work = make_commit ['HEAD'], [
1315 'git-debrebase convert-from-gbp: drop patches from tree',
1316 'Delete debian/patches, as part of converting to git-debrebase format.',
1317 '[git-debrebase convert-from-gbp: drop patches from tree]'
1319 # make the anchor merge
1320 # the tree is already exactly right
1321 $work = make_commit [$work, $upstream], [
1322 'git-debrebase import: declare upstream',
1323 'First breakwater merge.',
1324 '[git-debrebase anchor: declare upstream]'
1327 # rebase the patch queue onto the new breakwater
1328 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1329 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1330 $work = git_rev_parse 'HEAD';
1333 update_head_checkout $old_head, $work, 'convert-from-gbp';
1336 sub cmd_convert_to_gbp () {
1337 badusage "no arguments allowed" if @ARGV;
1338 my $head = get_head();
1339 my $ffq = (ffq_prev_branchinfo())[3];
1340 my $bw = breakwater_of $head;
1344 runcmd @git, qw(checkout -q -b bw), $bw;
1345 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1346 runcmd qw(gbp pq export);
1347 runcmd @git, qw(add debian/patches);
1348 $out = make_commit ['HEAD'], [
1349 'Commit patch queue (converted from git-debrebase format)',
1350 '[git-debrebase convert-to-gbp: commit patches]',
1354 push @deferred_updates, "delete $ffq";
1356 update_head_checkout $head, $out, "convert to gbp (v0)";
1357 print <<END or die $!;
1358 git-debrebase: converted to git-buildpackage branch format
1359 git-debrebase: WARNING: do not now run "git-debrebase" any more
1360 git-debrebase: WARNING: doing so would drop all upstream patches!
1364 sub cmd_downstream_rebase_launder_v0 () {
1365 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1367 $base = git_rev_parse $base;
1368 my $old_head = get_head();
1369 my $current = $old_head;
1372 if ($current eq $base) {
1373 $topmost_keep //= $current;
1374 print " $current BASE stop\n";
1377 my $cl = classify $current;
1378 print " $current $cl->{Type}";
1380 my $p0 = $cl->{Parents}[0]{CommitId};
1382 if ($cl->{Type} eq 'Pseudomerge') {
1383 print " ^".($cl->{Contributor}{Ix}+1);
1384 $next = $cl->{Contributor}{CommitId};
1385 } elsif ($cl->{Type} eq 'AddPatches' or
1386 $cl->{Type} eq 'Changelog') {
1396 $topmost_keep //= $current;
1398 die "to-be stripped changes not on top of the branch\n"
1403 if ($topmost_keep eq $old_head) {
1404 print "unchanged\n";
1406 print "updating to $topmost_keep\n";
1407 update_head_checkout
1408 $old_head, $topmost_keep,
1409 'downstream-rebase-launder-v0';
1413 GetOptions("D+" => \$debuglevel,
1414 'noop-ok', => \$opt_noop_ok,
1415 'f=s' => \@fproblem_force_opts,
1416 'anchor=s' => \@opt_anchors,
1417 'force!') or die badusage "bad options\n";
1418 initdebug('git-debrebase ');
1419 enabledebug if $debuglevel;
1421 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1422 chdir $toplevel or die "chdir $toplevel: $!";
1424 $rd = fresh_playground "$playprefix/misc";
1426 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1428 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1429 defaultcmd_rebase();
1431 my $cmd = shift @ARGV;
1434 $cmdfn = ${*::}{"cmd_$cmdfn"};
1436 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";