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>] launder # prints breakwater tip etc.
33 # git-debrebase [<options>] stitch [--prose=<for commit message>]
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);
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 return split /\0/, $out;
121 my $dd = new Data::Dumper [ $v ];
122 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
128 my $data = (git_cat_file $objid, 'commit');
129 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
133 sub D_UPS () { 0x02; } # upstream files
134 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
135 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
136 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
137 sub D_DEB_OTH () { 0x20; } # debian/changelog
138 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
140 our $playprefix = 'debrebase';
146 sub in_workarea ($) {
149 my $r = eval { $sub->(); };
150 { local $@; changedir $maindir; }
154 sub fresh_workarea () {
155 $workarea = fresh_playground "$playprefix/work";
156 in_workarea sub { playtree_setup };
159 sub get_differs ($$) {
161 # This resembles quiltify_trees_differ, in dgit, a bit.
162 # But we don't care about modes, or dpkg-source-unrepresentable
163 # changes, and we don't need the plethora of different modes.
164 # Conversely we need to distinguish different kinds of changes to
165 # debian/ and debian/patches/.
170 my ($opts, $limits, $fn) = @_;
171 my @cmd = (@git, qw(diff-tree -z --no-renames));
173 push @cmd, "$_:" foreach $x, $y;
174 push @cmd, '--', @$limits;
175 my $diffs = cmdoutput @cmd;
176 foreach (split /\0/, $diffs) { $fn->(); }
179 $rundiff->([qw(--name-only)], [], sub {
180 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
183 if ($differs & DS_DEB) {
185 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
187 m{^debian/patches/} ? D_PAT_OTH :
188 $_ eq 'debian/changelog' ? D_DEB_CLOG :
191 die "mysterious debian changes $x..$y"
192 unless $differs & (D_PAT_OTH|DS_DEB);
195 if ($differs & D_PAT_OTH) {
197 $differs &= ~D_PAT_OTH;
199 $differs |= D_PAT_OTH;
200 no warnings qw(exiting); last;
202 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
203 no warnings qw(exiting);
204 if (!defined $mode) {
207 die unless s{^debian/patches/}{};
209 if ($mode eq 'A' && !m/\.series$/s) {
211 } elsif ($mode eq 'M' && $_ eq 'series') {
212 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
213 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
214 chomp $x_s; $x_s .= "\n";
215 $ok = $x_s eq substr($y_s, 0, length $x_s);
220 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
222 die "mysterious debian/patches changes $x..$y"
223 unless $differs & (D_PAT_ADD|D_PAT_OTH);
226 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
231 sub commit_pr_info ($) {
233 return Data::Dumper->dump([$r], [qw(commit)]);
236 sub calculate_committer_authline () {
237 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
238 'DUMMY COMMIT (git-debrebase)', "HEAD:";
239 my ($h,$m) = get_commit $c;
240 $h =~ m/^committer .*$/m or confess "($h) ?";
244 sub rm_subdir_cached ($) {
246 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
249 sub read_tree_subdir ($$) {
250 my ($subdir, $new_tree_object) = @_;
251 rm_subdir_cached $subdir;
252 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
255 sub make_commit ($$) {
256 my ($parents, $message_paras) = @_;
257 my $tree = cmdoutput @git, qw(write-tree);
258 my @cmd = (@git, qw(commit-tree), $tree);
259 push @cmd, qw(-p), $_ foreach @$parents;
260 push @cmd, qw(-m), $_ foreach @$message_paras;
261 return cmdoutput @cmd;
264 our @fproblem_force_opts;
265 our $fproblems_forced;
266 our $fproblems_tripped;
269 if (grep { $_ eq $tag } @fproblem_force_opts) {
271 print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
273 $fproblems_tripped++;
274 print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
278 sub fproblems_maybe_bail () {
279 if ($fproblems_forced) {
281 "%s: safety catch trips: %d overriden by individual -f options\n",
282 $us, $fproblems_forced;
284 if ($fproblems_tripped) {
287 "%s: safety catch trips: %d overriden by global --force\n",
288 $us, $fproblems_tripped;
291 "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
292 $us, $fproblems_tripped;
296 sub any_fproblems () {
297 return $fproblems_forced || $fproblems_tripped;
300 # classify returns an info hash like this
302 # Hdr => # commit headers, including 1 final newline
303 # Msg => # commit message (so one newline is dropped)
305 # Type => (see below)
307 # Ix => $index # ie 0, 1, 2, ...
309 # Differs => return value from get_differs
311 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
313 # NewMsg => # commit message, but with any [dgit import ...] edited
314 # # to say "[was: ...]"
324 # has additional entres in classification result
325 # Overwritten = [ subset of Parents ]
326 # Contributor = $the_remaining_Parent
328 # DgitImportUnpatched
329 # has additional entry in classification result
330 # OrigParents = [ subset of Parents ]
332 # BreakwaterUpstreamMerge
333 # has additional entry in classification result
334 # OrigParents = [ subset of Parents ] # singleton list
337 # has additional entry in classification result
340 sub parsecommit ($;$) {
341 my ($objid, $p_ref) = @_;
342 # => hash with CommitId Hdr Msg Tree Parents
343 # Parents entries have only Ix CommitId
344 # $p_ref, if provided, must be [] and is used as a base for Parents
349 my ($h,$m) = get_commit $objid;
351 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
352 my (@ph) = $h =~ m/^parent (\w+)$/mg;
362 foreach my $ph (@ph) {
364 Ix => scalar @$p_ref,
376 my $r = parsecommit($objid, \@p);
380 $p->{Differs} = (get_differs $p->{CommitId}, $t),
383 printdebug "classify $objid \$t=$t \@p",
384 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
388 my ($type, @rest) = @_;
389 $r = { %$r, Type => $type, @rest };
391 printdebug " = $type ".(dd $r)."\n";
397 $r = { %$r, Type => qw(Unknown), Why => $why };
398 printdebug " ** Unknown\n";
402 my $claims_to_be_breakwater =
403 $r->{Msg} =~ m{^\[git-debrebase breakwater.*\]$}m;
406 if ($claims_to_be_breakwater) {
407 return $unknown->("single-parent git-debrebase breakwater \`merge'");
409 my $d = $r->{Parents}[0]{Differs};
410 if ($d == D_PAT_ADD) {
411 return $classify->(qw(AddPatches));
412 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
413 return $unknown->("edits debian/patches");
414 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
415 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
417 if ($d == D_DEB_CLOG) {
418 return $classify->(qw(Changelog));
420 return $classify->(qw(Packaging));
422 } elsif ($ty eq 'missing') {
423 return $classify->(qw(BreakwaterStart));
425 return $unknown->("parent's debian is not a directory");
427 } elsif ($d == D_UPS) {
428 return $classify->(qw(Upstream));
429 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
430 return $classify->(qw(Mixed));
432 return $unknown->("no changes");
434 confess "internal error $objid ?";
438 return $unknown->("origin commit");
441 my @identical = grep { !$_->{Differs} } @p;
442 if (@p == 2 && @identical == 1 && !$claims_to_be_breakwater
443 # breakwater merges can look like pseudomerges, if they are
444 # "declare" commits (ie, there are no upstream changes)
446 my @overwritten = grep { $_->{Differs} } @p;
447 confess "internal error $objid ?" unless @overwritten==1;
448 return $classify->(qw(Pseudomerge),
449 Overwritten => [ $overwritten[0] ],
450 Contributor => $identical[0]);
452 if (@p == 2 && @identical == 2) {
454 my ($ph,$pm) = get_commit $_[0]{CommitId};
455 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
459 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
460 if ($order > 0) { # newer first
461 } elsif ($order < 0) {
462 @bytime = reverse @bytime;
464 return $unknown->('merge of two identical same-age parents');
466 return $classify->(qw(Pseudomerge),
467 SubType => qw(Ambiguous),
468 Contributor => $bytime[0],
469 Overwritten => [ $bytime[1] ]);
472 my ($p_h, $p_m) = get_commit $p->{CommitId};
473 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
474 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
476 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
478 if (!(grep { !$_->{IsOrigin} } @p) and
479 (@orig_ps >= @p - 1) and
480 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
482 return $classify->(qw(DgitImportUnpatched),
483 OrigParents => \@orig_ps);
486 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
487 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
489 # How to decide about l/r ordering of breakwater merges ? git
490 # --topo-order prefers to expand 2nd parent first. There's
491 # already an easy rune to look for debian/ history anyway (git log
492 # debian/) so debian breakwater branch should be 1st parent; that
493 # way also there's also an easy rune to look for the upstream
494 # patches (--topo-order).
496 # The above tells us which way *we* will generate them. But we
497 # might encounter ad-hoc breakwater merges generated manually,
498 # which might be the other way around. In principle, in some odd
499 # situations, a breakwater merge might have two identical parents.
500 # In that case we guess which way round it is (ie, which parent
501 # has the upstream history). The order of the 2-iteration loop
502 # controls which guess we make.
504 foreach my $prevbrw (qw(0 1)) {
507 !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
508 !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
509 !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
510 return $classify->(qw(BreakwaterUpstreamMerge),
511 OrigParents => [ $p[!$prevbrw] ]);
515 # multi-orig upstreams are represented with a breakwater merge
516 # from a single upstream commit which combines the orig tarballs
518 return $unknown->("complex merge");
521 sub breakwater_of ($) {
522 my ($head) = @_; # must be laundered
526 fail "branch needs laundering (run git-debrebase): $why";
529 my $cl = classify $head;
530 my $ty = $cl->{Type};
531 if ($ty eq 'Packaging' or
532 $ty eq 'Changelog') {
533 $breakwater //= $head;
534 } elsif ($ty eq 'BreakwaterUpstreamMerge' or
535 $ty eq 'BreakwaterStart') {
536 $breakwater //= $head;
538 } elsif ($ty eq 'Upstream') {
539 $unclean->("packaging change ($breakwater)".
540 " follows upstream change (eg $head)")
541 if defined $breakwater;
542 } elsif ($ty eq 'Mixed') {
543 $unclean->('found mixed upstream/packaging commit ($head)');
544 } elsif ($ty eq 'Pseudomerge' or
545 $ty eq 'AddPatches') {
546 $unclean->("found interchange conversion commit ($ty, $head)");
547 } elsif ($ty eq 'DgitImportUnpatched') {
548 $unclean->("found dgit dsc import ($head)");
550 fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
552 $head = $cl->{Parents}[0]{CommitId};
560 $nogenerate,$report) = @_;
561 # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
562 # (or nothing, if $nogenerate)
564 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
566 # go through commits backwards
567 # we generate two lists of commits to apply:
568 # breakwater branch and upstream patches
569 my (@brw_cl, @upp_cl, @processed);
576 my ($prose, $info) = @_;
580 $ms .= "\n\n[git-debrebase$info: $prose]\n";
583 my $rewrite_from_here = sub {
584 my $sp_cl = { SpecialMethod => 'StartRewrite' };
585 push @brw_cl, $sp_cl;
586 push @processed, $sp_cl;
591 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
594 return unless $report;
595 print $report $prdelim, @_;
599 my $bomb = sub { # usage: return $bomb->();
600 print $report " Unprocessable" if $report;
601 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
604 return (undef,undef);
606 die "commit $cur: Cannot cope with this commit (d.".
607 (join ' ', map { sprintf "%#x", $_->{Differs} }
608 @{ $cl->{Parents} }).
609 (defined $cl->{Why} ? "; $cl->{Why}": '').
616 my $build_start = sub {
617 my ($msg, $parent) = @_;
620 no warnings qw(exiting); last;
623 my $last_upstream_update;
627 my $ty = $cl->{Type};
628 my $st = $cl->{SubType};
629 $prline->("$cl->{CommitId} $cl->{Type}");
630 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
631 push @processed, $cl;
632 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
633 if ($ty eq 'AddPatches') {
635 $rewrite_from_here->();
637 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
641 } elsif ($ty eq 'BreakwaterStart') {
642 $last_upstream_update = $cur;
643 $build_start->('FirstPackaging', $cur);
644 } elsif ($ty eq 'Upstream') {
648 } elsif ($ty eq 'Mixed') {
651 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
654 $queue->(\@brw_cl, "debian");
655 $queue->(\@upp_cl, "upstream");
656 $rewrite_from_here->();
659 } elsif ($ty eq 'Pseudomerge') {
660 my $contrib = $cl->{Contributor}{CommitId};
661 print $report " Contributor=$contrib" if $report;
662 push @pseudomerges, $cl;
663 $rewrite_from_here->();
666 } elsif ($ty eq 'BreakwaterUpstreamMerge') {
667 $last_upstream_update = $cur;
668 $build_start->("PreviousBreakwater", $cur);
669 } elsif ($ty eq 'DgitImportUnpatched') {
670 my $pm = $pseudomerges[-1];
672 # To an extent, this is heuristic. Imports don't have
673 # a useful history of the debian/ branch. We assume
674 # that the first pseudomerge after an import has a
675 # useful history of debian/, and ignore the histories
676 # from later pseudomerges. Often the first pseudomerge
677 # will be the dgit import of the upload to the actual
678 # suite intended by the non-dgit NMUer, and later
679 # pseudomerges may represent in-archive copies.
680 my $ovwrs = $pm->{Overwritten};
681 printf $report " PM=%s \@Overwr:%d",
682 $pm->{CommitId}, (scalar @$ovwrs)
685 printdebug "*** WALK BOMB DgitImportUnpatched\n";
688 my $ovwr = $ovwrs->[0]{CommitId};
689 printf $report " Overwr=%s", $ovwr if $report;
690 # This import has a tree which is just like a
691 # breakwater tree, but it has the wrong history. It
692 # ought to have the previous breakwater (which the
693 # pseudomerge overwrote) as an ancestor. That will
694 # make the history of the debian/ files correct. As
695 # for the upstream version: either it's the same as
696 # was ovewritten (ie, same as the previous
697 # breakwater), in which case that history is precisely
698 # right; or, otherwise, it was a non-gitish upload of a
699 # new upstream version. We can tell these apart by
700 # looking at the tree of the supposed upstream.
703 SpecialMethod => 'DgitImportDebianUpdate',
704 $xmsg->("convert dgit import: debian changes")
707 SpecialMethod => 'DgitImportUpstreamUpdate',
708 $xmsg->("convert dgit import: upstream update",
711 $prline->(" Import");
712 $rewrite_from_here->();
713 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
717 # Everything is from this import. This kind of import
718 # is already in valid breakwater format, with the
719 # patches as commits.
720 printf $report " NoPM" if $report;
721 # last thing we processed will have been the first patch,
722 # if there is one; which is fine, so no need to rewrite
723 # on account of this import
724 $build_start->("ImportOrigin", $cur);
728 printdebug "*** WALK BOMB unrecognised\n";
734 printdebug "*** WALK prep done cur=$cur".
735 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
737 return if $nogenerate;
739 # Now we build it back up again
745 my $read_tree_debian = sub {
747 read_tree_subdir 'debian', "$treeish:debian";
748 rm_subdir_cached 'debian/patches';
750 my $read_tree_upstream = sub {
752 runcmd @git, qw(read-tree), $treeish;
753 $read_tree_debian->($build);
756 $#upp_cl = $upp_limit if defined $upp_limit;
758 my $committer_authline = calculate_committer_authline();
760 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
762 confess "internal error" unless $build eq (pop @processed)->{CommitId};
765 mkdir $rd or $!==EEXIST or die $!;
767 runcmd @git, qw(read-tree), $build;
768 foreach my $cl (qw(Debian), (reverse @brw_cl),
769 { SpecialMethod => 'RecordBreakwaterTip' },
770 qw(Upstream), (reverse @upp_cl)) {
772 $current_method = $cl;
775 my $method = $cl->{SpecialMethod} // $current_method;
776 my @parents = ($build);
777 my $cltree = $cl->{CommitId};
778 printdebug "WALK BUILD ".($cltree//'undef').
779 " $method (rewriting=$rewriting)\n";
780 if ($method eq 'Debian') {
781 $read_tree_debian->($cltree);
782 } elsif ($method eq 'Upstream') {
783 $read_tree_upstream->($cltree);
784 } elsif ($method eq 'StartRewrite') {
787 } elsif ($method eq 'RecordBreakwaterTip') {
788 $breakwater = $build;
790 } elsif ($method eq 'DgitImportDebianUpdate') {
791 $read_tree_debian->($cltree);
792 } elsif ($method eq 'DgitImportUpstreamUpdate') {
793 confess unless $rewriting;
794 my $differs = (get_differs $build, $cltree);
795 next unless $differs & D_UPS;
796 $read_tree_upstream->($cltree);
797 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
802 my $procd = (pop @processed) // 'UNDEF';
805 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
808 my $newtree = cmdoutput @git, qw(write-tree);
810 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
811 $ch =~ s{^parent .*\n}{}mg;
812 $ch =~ s{(?=^author)}{
813 join '', map { "parent $_\n" } @parents
814 }me or confess "$ch ?";
816 $ch =~ s{^committer .*$}{$committer_authline}m
819 my $cf = "$rd/m$rewriting";
820 open CD, ">", $cf or die $!;
821 print CD $ch, "\n", $cl->{Msg} or die $!;
823 my @cmd = (@git, qw(hash-object));
824 push @cmd, qw(-w) if $rewriting;
825 push @cmd, qw(-t commit), $cf;
826 my $newcommit = cmdoutput @cmd;
827 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
829 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
830 $last_upstream_update = $cur;
835 my $final_check = get_differs $build, $input;
836 die sprintf "internal error %#x %s %s", $final_check, $build, $input
837 if $final_check & ~D_PAT_ADD;
839 my @r = ($build, $breakwater, $last_upstream_update);
840 printdebug "*** WALK RETURN @r\n";
845 git_check_unmodified();
846 return git_rev_parse qw(HEAD);
849 sub update_head ($$$) {
850 my ($old, $new, $mrest) = @_;
851 runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
854 sub update_head_checkout ($$$) {
855 my ($old, $new, $mrest) = @_;
856 update_head $old, $new, $mrest;
857 runcmd @git, qw(reset --hard);
860 sub update_head_postlaunder ($$$) {
861 my ($old, $tip, $reflogmsg) = @_;
862 return if $tip eq $old;
863 print "git-debrebase: laundered (head was $old)\n";
864 update_head $old, $tip, $reflogmsg;
865 # no tree changes except debian/patches
866 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
870 badusage "no arguments to launder allowed" if @ARGV;
871 my $old = get_head();
872 my ($tip,$breakwater,$last_upstream_merge) = walk $old;
873 update_head_postlaunder $old, $tip, 'launder';
874 printf "# breakwater tip\n%s\n", $breakwater;
875 printf "# working tip\n%s\n", $tip;
876 printf "# last upstream merge\n%s\n", $last_upstream_merge;
879 sub defaultcmd_rebase () {
880 my $old = get_head();
881 my ($status, $message) = record_ffq_prev();
882 if ($status eq 'written' || $status eq 'exists') {
884 fproblem $status, "could not record ffq-prev: $message";
885 fproblems_maybe_bail();
887 my ($tip,$breakwater) = walk $old;
888 update_head_postlaunder $old, $tip, 'launder for rebase';
889 runcmd @git, qw(rebase), @ARGV, $breakwater;
893 die if ($ARGV[0]//'') =~ m/^-/;
894 badusage "too many arguments to analyse" if @ARGV>1;
897 $old = git_rev_parse $old;
899 $old = git_rev_parse 'HEAD';
901 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
902 STDOUT->error and die $!;
905 sub ffq_prev_branchinfo () {
906 # => ('status', "message", [$current, $ffq_prev])
908 # branch message is undef
909 # weird-symref } no $current,
910 # notbranch } no $ffq_prev
911 my $current = git_get_symref();
912 return ('detached', 'detached HEAD') unless defined $current;
913 return ('weird-symref', 'HEAD symref is not to refs/')
914 unless $current =~ m{^refs/};
915 my $ffq_prev = "refs/$ffq_refprefix/$'";
916 return ('branch', undef, $current, $ffq_prev);
919 sub record_ffq_prev () {
920 # => ('status', "message")
922 # written message is undef
927 # if not ff from some branch we should be ff from, is an fproblem
928 # if "written", will have printed something about that to stdout,
929 # and also some messages about ff checks
930 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
931 return ($status, $message) unless $status eq 'branch';
933 my $currentval = get_head();
935 my $exists = git_get_ref $ffq_prev;
936 return ('exists',"$ffq_prev already exists") if $exists;
938 return ('not-branch', 'HEAD symref is not to refs/heads/')
939 unless $current =~ m{^refs/heads/};
942 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
946 my ($lrref, $desc) = @_;
948 for my $chk (@check_specs) {
950 $invert = $glob =~ s{^[^!]}{};
951 last if fnmatch $glob, $lrref;
954 my $lrval = git_get_ref $lrref;
955 return unless defined $lrval;
957 if (is_fast_fwd $lrval, $currentval) {
958 print "OK, you are ahead of $lrref\n" or die $!;
959 $checked{$lrref} = 1;
960 } if (is_fast_fwd $currentval, $lrval) {
961 $checked{$lrref} = -1;
962 fproblem 'behind', "you are behind $lrref, divergence risk";
964 $checked{$lrref} = -1;
965 fproblem 'diverged', "you have diverged from $lrref";
969 my $merge = cfg "branch.$branch.merge",1;
970 if (defined $merge && $merge =~ m{^refs/heads/}) {
972 my $check_remote = sub {
973 my ($remote, $desc) = (@_);
974 return unless defined $remote;
975 $check->("refs/remotes/$remote/$rhs", $desc);
977 $check_remote->((cfg "branch.$branch.remote",1),
978 'remote fetch/merge branch');
979 $check_remote->((cfg "branch.$branch.pushRemote",1) //
980 (cfg "branch.$branch.pushDefault",1),
981 'remote push branch');
983 if ($branch =~ m{^dgit/}) {
984 $check->("remotes/dgit/$branch", 'remote dgit branch');
985 } elsif ($branch =~ m{^master$}) {
986 $check->("remotes/dgit/dgit/sid", 'remote dgit branch for sid');
989 fproblems_maybe_bail();
990 runcmd @git, qw(update-ref -m), "record current head for preservation",
991 $ffq_prev, $currentval, $git_null_obj;
992 print "Recorded current head for preservation\n" or die $!;
993 return ('written', undef);
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 >= 2;
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;
1011 my ($n, @x) = @_; # may be ''
1012 my $pc = $pieces{$n} //= {
1014 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1016 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1021 my $newpiece = sub {
1022 my ($n, @x) = @_; # may be ''
1023 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1024 push @newpieces, $pc;
1029 New => $new_upstream,
1031 while (@ARGV && $ARGV[0] !~ m{^-}) {
1032 my $n = shift @ARGV;
1034 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1035 unless @ARGV && $ARGV[0] !~ m{^-};
1037 my $c = git_rev_parse shift @ARGV;
1038 die unless $n =~ m/^$extra_orig_namepart_re$/;
1039 $newpiece->($n, New => $c);
1042 # now we need to investigate the branch this generates the
1043 # laundered version but we don't switch to it yet
1044 my $old_head = get_head();
1045 my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
1047 my $old_bw_cl = classify $old_bw;
1048 my $old_upstream_update_cl = classify $old_upstream_update;
1049 confess unless $old_upstream_update_cl->{OrigParents};
1050 my $old_upstream = parsecommit
1051 $old_upstream_update_cl->{OrigParents}[0]{CommitId};
1053 $piece->('', Old => $old_upstream->{CommitId});
1055 if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1056 if ($old_upstream->{Msg} =~
1057 m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1059 my @oldpieces = ('', split / /, $1);
1060 my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1061 foreach my $i (0..$#oldpieces) {
1062 my $n = $oldpieces[$i];
1063 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1066 fproblem 'upstream-confusing',
1067 "previous upstream $old_upstream->{CommitId} is from".
1068 " git-debrebase but not an \`upstream-combine' commit";
1072 foreach my $pc (values %pieces) {
1074 fproblem 'upstream-new-piece',
1075 "introducing upstream piece \`$pc->{Name}'";
1076 } elsif (!$pc->{New}) {
1077 fproblem 'upstream-rm-piece',
1078 "dropping upstream piece \`$pc->{Name}'";
1079 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1080 fproblem 'upstream-not-ff',
1081 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1085 printdebug "%pieces = ", (dd \%pieces), "\n";
1086 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1088 fproblems_maybe_bail();
1094 my @upstream_merge_parents;
1096 if (!any_fproblems()) {
1097 push @upstream_merge_parents, $old_upstream->{CommitId};
1100 foreach my $pc (@newpieces) { # always has '' first
1102 read_tree_subdir $pc->{Name}, $pc->{New};
1104 runcmd @git, qw(read-tree), $pc->{New};
1106 push @upstream_merge_parents, $pc->{New};
1109 # index now contains the new upstream
1111 if (@newpieces > 1) {
1112 # need to make the upstream subtree merge commit
1113 $new_upstream = make_commit \@upstream_merge_parents,
1114 [ "Combine upstreams for $new_upstream_version",
1115 ("[git-debrebase upstream-combine . ".
1116 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1121 # $new_upstream is either the single upstream commit, or the
1122 # combined commit we just made. Either way it will be the
1123 # "upstream" parent of the breakwater special merge.
1125 read_tree_subdir 'debian', "$old_bw:debian";
1127 # index now contains the breakwater merge contents
1128 $new_bw = make_commit [ $old_bw, $new_upstream ],
1129 [ "Update to upstream $new_upstream_version",
1130 "[git-debrebase breakwater: new upstream $new_upstream_version, merge]",
1133 # Now we have to add a changelog stanza so the Debian version
1135 die if unlink "debian";
1136 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1137 unlink "debian/changelog" or $!==ENOENT or die $!;
1138 mkdir "debian" or die $!;
1139 open CN, ">", "debian/changelog" or die $!;
1140 my $oldclog = git_cat_file ":debian/changelog";
1141 $oldclog =~ m/^($package_re) \(\S+\) / or
1142 fail "cannot parse old changelog to get package name";
1144 print CN <<END, $oldclog or die $!;
1145 $p ($new_version) UNRELEASED; urgency=medium
1147 * Update to new upstream version $new_upstream_version.
1153 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1155 # Now we have the final new breakwater branch in the index
1156 $new_bw = make_commit [ $new_bw ],
1157 [ "Update changelog for new upstream $new_upstream_version",
1158 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1162 # we have constructed the new breakwater. we now need to commit to
1163 # the laundering output, because git-rebase can't easily be made
1164 # to make a replay list which is based on some other branch
1166 update_head_postlaunder $old_head, $old_laundered_tip,
1167 'launder for new upstream';
1169 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1171 # now it's for the user to sort out
1174 sub cmd_record_ffq_prev () {
1175 badusage "no arguments allowed" if @ARGV;
1176 my ($status, $msg) = record_ffq_prev();
1177 if ($status eq 'exists' && $opt_noop_ok) {
1178 print "Previous head already recorded\n" or die $!;
1179 } elsif ($status eq 'written') {
1181 fail "Could not preserve: $msg";
1185 sub cmd_breakwater () {
1186 badusage "no arguments allowed" if @ARGV;
1187 my $bw = breakwater_of git_rev_parse 'HEAD';
1188 print "$bw\n" or die $!;
1193 GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1194 badusage "no arguments allowed" if @ARGV;
1195 my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1196 if ($status ne 'branch') {
1197 fproblem $status, "could not check ffq-prev: $message";
1198 fproblems_maybe_bail();
1200 my $prev = $ffq_prev && git_get_ref $ffq_prev;
1202 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1205 my $old_head = get_head();
1206 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1207 'Declare fast forward / record previous work',
1208 "[git-debrebase pseudomerge: stitch$prose]",
1210 my @upd_cmd = (@git, qw(update-ref --stdin));
1211 debugcmd '>|', @upd_cmd;
1212 open U, "|-", @upd_cmd or die $!;
1214 update HEAD $new_head $old_head
1215 delete $ffq_prev $prev
1217 printdebug ">= ", $_, "\n" foreach split /\n/, $u;
1220 close U or failedcmd @upd_cmd;
1223 sub cmd_convert_from_gbp () {
1224 badusage "needs 1 optional argument, the upstream git rev"
1226 my ($upstream_spec) = @ARGV;
1227 $upstream_spec //= 'refs/heads/upstream';
1228 my $upstream = git_rev_parse $upstream_spec;
1229 my $old_head = get_head();
1231 my $upsdiff = get_differs $upstream, $old_head;
1232 if ($upsdiff & D_UPS) {
1233 runcmd @git, qw(--no-pager diff),
1234 $upstream, $old_head,
1235 qw( -- :!/debian :/);
1236 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1239 if (!is_fast_fwd $upstream, $old_head) {
1240 fproblem 'upstream-not-ancestor',
1241 "upstream ($upstream) is not an ancestor of HEAD";
1243 my $wrong = cmdoutput
1244 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1245 qw(-- :/ :!/debian));
1246 if (length $wrong) {
1247 fproblem 'unexpected-upstream-changes',
1248 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1249 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1253 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1254 fproblem 'upstream-has-debian',
1255 "upstream ($upstream) contains debian/ directory";
1258 fproblems_maybe_bail();
1264 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1265 # make a branch out of the patch queue - we'll want this in a mo
1266 runcmd qw(gbp pq import);
1267 # strip the patches out
1268 runcmd @git, qw(checkout -q gdr-internal~0);
1269 rm_subdir_cached 'debian/patches';
1270 $work = make_commit ['HEAD'], [
1271 'git-debrebase convert-from-gbp: drop patches from tree',
1272 'Delete debian/patches, as part of converting to git-debrebase format.',
1273 '[git-debrebase convert-from-gbp: drop patches from tree]'
1275 # make the breakwater pseudomerge
1276 # the tree is already exactly right
1277 $work = make_commit [$work, $upstream], [
1278 'git-debrebase import: declare upstream',
1279 'First breakwater merge.',
1280 '[git-debrebase breakwater: declare upstream]'
1283 # rebase the patch queue onto the new breakwater
1284 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1285 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1286 $work = git_rev_parse 'HEAD';
1289 update_head_checkout $old_head, $work, 'convert-from-gbp';
1292 sub cmd_convert_to_gbp () {
1293 badusage "no arguments allowed" if @ARGV;
1294 my $head = get_head();
1295 my $ffq = (ffq_prev_branchinfo())[3];
1296 my $bw = breakwater_of $head;
1300 runcmd @git, qw(checkout -q -b bw), $bw;
1301 runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1302 runcmd qw(gbp pq export);
1303 runcmd @git, qw(add debian/patches);
1304 $out = make_commit ['HEAD'], [
1305 'Commit patch queue (converted from git-debrebase format)',
1306 '[git-debrebase convert-to-gbp: commit patches]',
1310 runcmd @git, qw(update-ref -m),
1311 "debrebase: converting corresponding main branch to gbp format",
1312 $ffq, $git_null_obj;
1314 update_head_checkout $head, $out, "convert to gbp (v0)";
1315 print <<END or die $!;
1316 git-debrebase: converted to git-buildpackage branch format
1317 git-debrebase: WARNING: do not now run "git-debrebase" any more
1318 git-debrebase: WARNING: doing so would drop all upstream patches!
1322 sub cmd_downstream_rebase_launder_v0 () {
1323 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1325 $base = git_rev_parse $base;
1326 my $old_head = get_head();
1327 my $current = $old_head;
1330 if ($current eq $base) {
1331 $topmost_keep //= $current;
1332 print " $current BASE stop\n";
1335 my $cl = classify $current;
1336 print " $current $cl->{Type}";
1338 my $p0 = $cl->{Parents}[0]{CommitId};
1340 if ($cl->{Type} eq 'Pseudomerge') {
1341 print " ^".($cl->{Contributor}{Ix}+1);
1342 $next = $cl->{Contributor}{CommitId};
1343 } elsif ($cl->{Type} eq 'AddPatches' or
1344 $cl->{Type} eq 'Changelog') {
1354 $topmost_keep //= $current;
1356 die "to-be stripped changes not on top of the branch\n"
1361 if ($topmost_keep eq $old_head) {
1362 print "unchanged\n";
1364 print "updating to $topmost_keep\n";
1365 update_head_checkout
1366 $old_head, $topmost_keep,
1367 'downstream-rebase-launder-v0';
1371 GetOptions("D+" => \$debuglevel,
1372 'noop-ok', => \$opt_noop_ok,
1373 'f=s' => \@fproblem_force_opts,
1374 'force!') or die badusage "bad options\n";
1375 initdebug('git-debrebase ');
1376 enabledebug if $debuglevel;
1378 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1379 chdir $toplevel or die "chdir $toplevel: $!";
1381 $rd = fresh_playground "$playprefix/misc";
1383 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1384 defaultcmd_rebase();
1386 my $cmd = shift @ARGV;
1389 $cmdfn = ${*::}{"cmd_$cmdfn"};
1391 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";