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/>.
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::GDR;
23 use Debian::Dgit::ExitStatus;
27 use Debian::Dgit qw(:DEFAULT :playground);
34 use Getopt::Long qw(:config posix_default gnu_compat bundling);
36 use File::FnMatch qw(:fnmatch);
39 our ($usage_message) = <<'END';
41 git-debrebase [<options>] [--|-i <git rebase options...>]
42 git-debrebase [<options>] status
43 git-debrebase [<options>] prepush [--prose=...]
44 git-debrebase [<options>] quick|conclude
45 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
46 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
48 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
51 our ($opt_force, $opt_noop_ok, @opt_anchors);
52 our ($opt_defaultcmd_interactive);
54 our $us = qw(git-debrebase);
60 print STDERR "$us: bad usage: $m\n";
66 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
67 GetOptions @_ or badusage $m;
71 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
75 my ($k, $optional) = @_;
77 my @cmd = qw(git config -z);
78 push @cmd, qw(--get-all) if wantarray;
80 my $out = cmdoutput_errok @cmd;
82 fail "missing required git config $k" unless $optional;
85 my @l = split /\0/, $out;
86 return wantarray ? @l : $l[0];
93 my $dd = new Data::Dumper [ $v ];
94 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
100 my $data = (git_cat_file $objid, 'commit');
101 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
105 sub D_UPS () { 0x02; } # upstream files
106 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
107 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
108 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
109 sub D_DEB_OTH () { 0x20; } # debian/changelog
110 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
112 our $playprefix = 'debrebase';
117 our @dgit = qw(dgit);
119 sub in_workarea ($) {
122 my $r = eval { $sub->(); };
123 { local $@; changedir $maindir; }
127 sub fresh_workarea () {
128 $workarea = fresh_playground "$playprefix/work";
129 in_workarea sub { playtree_setup };
132 our $snags_forced = 0;
133 our $snags_tripped = 0;
134 our $snags_summarised = 0;
135 our @deferred_updates;
136 our @deferred_update_messages;
138 sub all_snags_summarised () {
139 $snags_forced + $snags_tripped == $snags_summarised;
141 sub run_deferred_updates ($) {
144 confess 'dangerous internal error' unless all_snags_summarised();
146 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
147 debugcmd '>|', @upd_cmd;
148 open U, "|-", @upd_cmd or die $!;
149 foreach (@deferred_updates) {
150 printdebug ">= ", $_, "\n";
151 print U $_, "\n" or die $!;
154 close U or failedcmd @upd_cmd;
156 print $_, "\n" foreach @deferred_update_messages;
158 @deferred_updates = ();
159 @deferred_update_messages = ();
162 sub get_differs ($$) {
164 # This resembles quiltify_trees_differ, in dgit, a bit.
165 # But we don't care about modes, or dpkg-source-unrepresentable
166 # changes, and we don't need the plethora of different modes.
167 # Conversely we need to distinguish different kinds of changes to
168 # debian/ and debian/patches/.
173 my ($opts, $limits, $fn) = @_;
174 my @cmd = (@git, qw(diff-tree -z --no-renames));
176 push @cmd, "$_:" foreach $x, $y;
177 push @cmd, '--', @$limits;
178 my $diffs = cmdoutput @cmd;
179 foreach (split /\0/, $diffs) { $fn->(); }
182 $rundiff->([qw(--name-only)], [], sub {
183 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
186 if ($differs & DS_DEB) {
188 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
190 m{^debian/patches/} ? D_PAT_OTH :
191 $_ eq 'debian/changelog' ? D_DEB_CLOG :
194 die "mysterious debian changes $x..$y"
195 unless $differs & (D_PAT_OTH|DS_DEB);
198 if ($differs & D_PAT_OTH) {
200 $differs &= ~D_PAT_OTH;
202 $differs |= D_PAT_OTH;
203 no warnings qw(exiting); last;
205 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
206 no warnings qw(exiting);
207 if (!defined $mode) {
210 die unless s{^debian/patches/}{};
212 if ($mode eq 'A' && !m/\.series$/s) {
214 } elsif ($mode eq 'M' && $_ eq 'series') {
215 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
216 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
217 chomp $x_s; $x_s .= "\n";
218 $ok = $x_s eq substr($y_s, 0, length $x_s);
223 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
225 die "mysterious debian/patches changes $x..$y"
226 unless $differs & (D_PAT_ADD|D_PAT_OTH);
229 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
234 sub commit_pr_info ($) {
236 return Data::Dumper->dump([$r], [qw(commit)]);
239 sub calculate_committer_authline () {
240 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
241 'DUMMY COMMIT (git-debrebase)', "HEAD:";
242 my ($h,$m) = get_commit $c;
243 $h =~ m/^committer .*$/m or confess "($h) ?";
247 sub rm_subdir_cached ($) {
249 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
252 sub read_tree_subdir ($$) {
253 my ($subdir, $new_tree_object) = @_;
254 rm_subdir_cached $subdir;
255 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
258 sub make_commit ($$) {
259 my ($parents, $message_paras) = @_;
260 my $tree = cmdoutput @git, qw(write-tree);
261 my @cmd = (@git, qw(commit-tree), $tree);
262 push @cmd, qw(-p), $_ foreach @$parents;
263 push @cmd, qw(-m), $_ foreach @$message_paras;
264 return cmdoutput @cmd;
267 our @snag_force_opts;
269 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
270 if (grep { $_ eq $tag } @snag_force_opts) {
272 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
275 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
279 # Important: all mainline code must call snags_maybe_bail after
280 # any point where snag might be called, but before making changes
281 # (eg before any call to run_deferred_updates). snags_maybe_bail
282 # may be called more than once if necessary (but this is not ideal
283 # because then the messages about number of snags may be confusing).
284 sub snags_maybe_bail () {
285 return if all_snags_summarised();
288 "%s: snags: %d overriden by individual -f options\n",
291 if ($snags_tripped) {
294 "%s: snags: %d overriden by global --force\n",
298 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
302 $snags_summarised = $snags_forced + $snags_tripped;
304 sub snags_maybe_bail_early () {
305 # useful to bail out early without doing a lot of work;
306 # not a substitute for snags_maybe_bail.
307 snags_maybe_bail() if $snags_tripped && !$opt_force;
310 return $snags_forced || $snags_tripped;
313 # classify returns an info hash like this
315 # Hdr => # commit headers, including 1 final newline
316 # Msg => # commit message (so one newline is dropped)
318 # Type => (see below)
320 # Ix => $index # ie 0, 1, 2, ...
322 # Differs => return value from get_differs
324 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
326 # NewMsg => # commit message, but with any [dgit import ...] edited
327 # # to say "[was: ...]"
337 # has additional entres in classification result
338 # Overwritten = [ subset of Parents ]
339 # Contributor = $the_remaining_Parent
341 # DgitImportUnpatched
342 # has additional entry in classification result
343 # OrigParents = [ subset of Parents ]
346 # has additional entry in classification result
347 # OrigParents = [ subset of Parents ] # singleton list
354 # has additional entry in classification result
357 sub parsecommit ($;$) {
358 my ($objid, $p_ref) = @_;
359 # => hash with CommitId Hdr Msg Tree Parents
360 # Parents entries have only Ix CommitId
361 # $p_ref, if provided, must be [] and is used as a base for Parents
366 my ($h,$m) = get_commit $objid;
368 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
369 my (@ph) = $h =~ m/^parent (\w+)$/mg;
379 foreach my $ph (@ph) {
381 Ix => scalar @$p_ref,
393 my $r = parsecommit($objid, \@p);
397 $p->{Differs} = (get_differs $p->{CommitId}, $t),
400 printdebug "classify $objid \$t=$t \@p",
401 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
405 my ($type, @rest) = @_;
406 $r = { %$r, Type => $type, @rest };
408 printdebug " = $type ".(dd $r)."\n";
414 $r = { %$r, Type => qw(Unknown), Why => $why };
415 printdebug " ** Unknown\n";
419 if (grep { $_ eq $objid } @opt_anchors) {
420 return $classify->('TreatAsAnchor');
423 my @identical = grep { !$_->{Differs} } @p;
424 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
425 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
427 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
428 # multi-orig upstreams are represented with an anchor merge
429 # from a single upstream commit which combines the orig tarballs
431 # Every anchor tagged this way must be a merge.
432 # We are relying on the
433 # [git-debrebase anchor: ...]
434 # commit message annotation in "declare" anchor merges (which
435 # do not have any upstream changes), to distinguish those
436 # anchor merges from ordinary pseudomerges (which we might
437 # just try to strip).
439 # However, the user is going to be doing git-rebase a lot. We
440 # really don't want them to rewrite an anchor commit.
441 # git-rebase trips up on merges, so that is a useful safety
444 # BreakwaterStart commits are also anchors in the terminology
445 # of git-debrebase(5), but they are untagged (and always
446 # manually generated).
448 # We cannot not tolerate any tagged linear commit (ie,
449 # BreakwaterStart commits tagged `[anchor:') because such a
450 # thing could result from an erroneous linearising raw git
451 # rebase of a merge anchor. That would represent a corruption
452 # of the branch. and we want to detect and reject the results
453 # of such corruption before it makes it out anywhere. If we
454 # reject it here then we avoid making the pseudomerge which
455 # would be needed to push it.
457 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
458 @p == 2 or return $badanchor->("has other than two parents");
459 $haspatches and return $badanchor->("contains debian/patches");
461 # How to decide about l/r ordering of anchors ? git
462 # --topo-order prefers to expand 2nd parent first. There's
463 # already an easy rune to look for debian/ history anyway (git log
464 # debian/) so debian breakwater branch should be 1st parent; that
465 # way also there's also an easy rune to look for the upstream
466 # patches (--topo-order).
468 # Also this makes --first-parent be slightly more likely to
469 # be useful - it makes it provide a linearised breakwater history.
471 # Of course one can say somthing like
472 # gitk -- ':/' ':!/debian'
473 # to get _just_ the commits touching upstream files, and by
474 # the TREESAME logic in git-rev-list this will leave the
475 # breakwater into upstream at the first anchor. But that
476 # doesn't report debian/ changes at all.
478 # Other observations about gitk: by default, gitk seems to
479 # produce output in a different order to git-rev-list. I
480 # can't seem to find this documented anywhere. gitk
481 # --date-order DTRT. But, gitk always seems to put the
482 # parents from left to right, in order, so it's easy to see
483 # which way round a pseudomerge is.
485 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
486 $p[1]{Differs} & ~DS_DEB and
487 $badanchor->("upstream files differ from left parent");
488 $p[0]{Differs} & ~D_UPS and
489 $badanchor->("debian/ differs from right parent");
491 return $classify->(qw(Anchor),
492 OrigParents => [ $p[1] ]);
496 my $d = $r->{Parents}[0]{Differs};
497 if ($d == D_PAT_ADD) {
498 return $classify->(qw(AddPatches));
499 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
500 return $unknown->("edits debian/patches");
501 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
502 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
504 if ($d == D_DEB_CLOG) {
505 return $classify->(qw(Changelog));
507 return $classify->(qw(Packaging));
509 } elsif ($ty eq 'missing') {
510 return $classify->(qw(BreakwaterStart));
512 return $unknown->("parent's debian is not a directory");
514 } elsif ($d == D_UPS) {
515 return $classify->(qw(Upstream));
516 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
517 return $classify->(qw(Mixed));
519 return $unknown->("no changes");
521 confess "internal error $objid ?";
525 return $unknown->("origin commit");
528 if (@p == 2 && @identical == 1) {
529 my @overwritten = grep { $_->{Differs} } @p;
530 confess "internal error $objid ?" unless @overwritten==1;
531 return $classify->(qw(Pseudomerge),
532 Overwritten => [ $overwritten[0] ],
533 Contributor => $identical[0]);
535 if (@p == 2 && @identical == 2) {
537 my ($ph,$pm) = get_commit $_[0]{CommitId};
538 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
542 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
543 if ($order > 0) { # newer first
544 } elsif ($order < 0) {
545 @bytime = reverse @bytime;
547 # same age, default to order made by -s ours
548 # that is, commit was made by someone who preferred L
550 return $classify->(qw(Pseudomerge),
551 SubType => qw(Ambiguous),
552 Contributor => $bytime[0],
553 Overwritten => [ $bytime[1] ]);
556 my ($p_h, $p_m) = get_commit $p->{CommitId};
557 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
558 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
560 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
562 if (!(grep { !$_->{IsOrigin} } @p) and
563 (@orig_ps >= @p - 1) and
564 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
566 return $classify->(qw(DgitImportUnpatched),
567 OrigParents => \@orig_ps);
570 return $unknown->("complex merge");
573 sub keycommits ($;$$$$) {
574 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
575 # => ($anchor, $breakwater)
577 # $unclean->("unclean-$tagsfx", $msg, $cl)
578 # $furniture->("unclean-$tagsfx", $msg, $cl)
579 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
580 # is callled for each situation or commit that
581 # wouldn't be found in a laundered branch
582 # $furniture is for furniture commits such as might be found on an
583 # interchange branch (pseudomerge, d/patches, changelog)
584 # $trouble is for things whnich prevent the return of
585 # anchor and breakwater information; if that is ignored,
586 # then keycommits returns (undef, undef) instead.
587 # $fatal is for unprocessable commits, and should normally cause
588 # a failure. If ignored, agaion, (undef, undef) is returned.
590 # If a callback is undef, fail is called instead.
591 # If a callback is defined but false, the situation is ignored.
593 # no warnings qw(exiting); last;
594 # if the answer is no longer wanted.
596 my ($anchor, $breakwater);
600 $fatal //= sub { fail $_[1]; };
602 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
603 my $why = $mainwhy.$xwhy;
604 my $m = "branch needs laundering (run git-debrebase): $why";
605 fail $m unless defined $cb;
607 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
610 $cl = classify $head;
611 my $ty = $cl->{Type};
612 if ($ty eq 'Packaging') {
613 $breakwater //= $clogonly;
614 $breakwater //= $head;
615 } elsif ($ty eq 'Changelog') {
616 # this is going to count as the tip of the breakwater
617 # only if it has no upstream stuff before it
619 } elsif ($ty eq 'Anchor' or
620 $ty eq 'TreatAsAnchor' or
621 $ty eq 'BreakwaterStart') {
623 $breakwater //= $clogonly;
624 $breakwater //= $head;
626 } elsif ($ty eq 'Upstream') {
627 $x->($unclean, 'ordering',
628 "packaging change ($breakwater) follows upstream change"," (eg $head)")
629 if defined $breakwater;
632 } elsif ($ty eq 'Mixed') {
633 $x->($unclean, 'mixed',
634 "found mixed upstream/packaging commit"," ($head)");
637 } elsif ($ty eq 'Pseudomerge' or
638 $ty eq 'AddPatches') {
640 $x->($furniture, (lc $ty),
641 "found interchange bureaucracy commit ($ty)"," ($head)");
642 } elsif ($ty eq 'DgitImportUnpatched') {
644 $x->($trouble, 'dgitimport',
645 "found dgit dsc import"," ($head)");
646 return (undef,undef);
648 $x->($fatal, 'unprocessable',
649 "found bare dgit dsc import with no prior history",
651 return (undef,undef);
654 $x->($fatal, 'unprocessable',
655 "found unprocessable commit, cannot cope: $cl->{Why}",
657 return (undef,undef);
659 $head = $cl->{Parents}[0]{CommitId};
661 return ($anchor, $breakwater);
667 $nogenerate,$report) = @_;
668 # => ($tip, $breakwater_tip, $last_anchor)
669 # (or nothing, if $nogenerate)
671 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
673 # go through commits backwards
674 # we generate two lists of commits to apply:
675 # breakwater branch and upstream patches
676 my (@brw_cl, @upp_cl, @processed);
683 my ($prose, $info) = @_;
687 $ms .= "\n\n[git-debrebase$info: $prose]\n";
690 my $rewrite_from_here = sub {
692 my $sp_cl = { SpecialMethod => 'StartRewrite' };
694 push @processed, $sp_cl;
699 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
702 return unless $report;
703 print $report $prdelim, @_;
707 my $bomb = sub { # usage: return $bomb->();
708 print $report " Unprocessable" if $report;
709 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
712 return (undef,undef);
714 fail "found unprocessable commit, cannot cope".
715 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
716 " (commit $cur) (d.".
717 (join ' ', map { sprintf "%#x", $_->{Differs} }
718 @{ $cl->{Parents} }).
725 my $build_start = sub {
726 my ($msg, $parent) = @_;
729 no warnings qw(exiting); last;
736 my $ty = $cl->{Type};
737 my $st = $cl->{SubType};
738 $prline->("$cl->{CommitId} $cl->{Type}");
739 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
740 push @processed, $cl;
741 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
742 if ($ty eq 'AddPatches') {
744 $rewrite_from_here->(\@upp_cl);
746 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
750 } elsif ($ty eq 'BreakwaterStart') {
752 $build_start->('FirstPackaging', $cur);
753 } elsif ($ty eq 'Upstream') {
757 } elsif ($ty eq 'Mixed') {
760 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
763 $queue->(\@brw_cl, "debian");
764 $queue->(\@upp_cl, "upstream");
765 $rewrite_from_here->(\@brw_cl);
768 } elsif ($ty eq 'Pseudomerge') {
769 my $contrib = $cl->{Contributor}{CommitId};
770 print $report " Contributor=$contrib" if $report;
771 push @pseudomerges, $cl;
772 $rewrite_from_here->(\@upp_cl);
775 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
777 $build_start->("Anchor", $cur);
778 } elsif ($ty eq 'DgitImportUnpatched') {
779 my $pm = $pseudomerges[-1];
781 # To an extent, this is heuristic. Imports don't have
782 # a useful history of the debian/ branch. We assume
783 # that the first pseudomerge after an import has a
784 # useful history of debian/, and ignore the histories
785 # from later pseudomerges. Often the first pseudomerge
786 # will be the dgit import of the upload to the actual
787 # suite intended by the non-dgit NMUer, and later
788 # pseudomerges may represent in-archive copies.
789 my $ovwrs = $pm->{Overwritten};
790 printf $report " PM=%s \@Overwr:%d",
791 $pm->{CommitId}, (scalar @$ovwrs)
794 printdebug "*** WALK BOMB DgitImportUnpatched\n";
797 my $ovwr = $ovwrs->[0]{CommitId};
798 printf $report " Overwr=%s", $ovwr if $report;
799 # This import has a tree which is just like a
800 # breakwater tree, but it has the wrong history. It
801 # ought to have the previous breakwater (which the
802 # pseudomerge overwrote) as an ancestor. That will
803 # make the history of the debian/ files correct. As
804 # for the upstream version: either it's the same as
805 # was ovewritten (ie, same as the previous
806 # breakwater), in which case that history is precisely
807 # right; or, otherwise, it was a non-gitish upload of a
808 # new upstream version. We can tell these apart by
809 # looking at the tree of the supposed upstream.
812 SpecialMethod => 'DgitImportDebianUpdate',
813 $xmsg->("convert dgit import: debian changes")
816 SpecialMethod => 'DgitImportUpstreamUpdate',
817 $xmsg->("convert dgit import: upstream update",
820 $prline->(" Import");
821 $rewrite_from_here->(\@brw_cl);
822 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
826 # Everything is from this import. This kind of import
827 # is already nearly in valid breakwater format, with the
828 # patches as commits. Unfortunately it contains
830 printdebug "*** WALK BOMB bare dgit import\n";
831 $cl->{Why} = "bare dgit dsc import";
836 printdebug "*** WALK BOMB unrecognised\n";
842 printdebug "*** WALK prep done cur=$cur".
843 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
845 return if $nogenerate;
847 # Now we build it back up again
853 my $read_tree_debian = sub {
855 read_tree_subdir 'debian', "$treeish:debian";
856 rm_subdir_cached 'debian/patches';
858 my $read_tree_upstream = sub {
860 runcmd @git, qw(read-tree), $treeish;
861 $read_tree_debian->($build);
864 $#upp_cl = $upp_limit if defined $upp_limit;
866 my $committer_authline = calculate_committer_authline();
868 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
870 confess "internal error" unless $build eq (pop @processed)->{CommitId};
873 mkdir $rd or $!==EEXIST or die $!;
875 runcmd @git, qw(read-tree), $build;
876 foreach my $cl (qw(Debian), (reverse @brw_cl),
877 { SpecialMethod => 'RecordBreakwaterTip' },
878 qw(Upstream), (reverse @upp_cl)) {
880 $current_method = $cl;
883 my $method = $cl->{SpecialMethod} // $current_method;
884 my @parents = ($build);
885 my $cltree = $cl->{CommitId};
886 printdebug "WALK BUILD ".($cltree//'undef').
887 " $method (rewriting=$rewriting)\n";
888 if ($method eq 'Debian') {
889 $read_tree_debian->($cltree);
890 } elsif ($method eq 'Upstream') {
891 $read_tree_upstream->($cltree);
892 } elsif ($method eq 'StartRewrite') {
895 } elsif ($method eq 'RecordBreakwaterTip') {
896 $breakwater = $build;
898 } elsif ($method eq 'DgitImportDebianUpdate') {
899 $read_tree_debian->($cltree);
900 } elsif ($method eq 'DgitImportUpstreamUpdate') {
901 confess unless $rewriting;
902 my $differs = (get_differs $build, $cltree);
903 next unless $differs & D_UPS;
904 $read_tree_upstream->($cltree);
905 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
910 my $procd = (pop @processed) // 'UNDEF';
913 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
916 my $newtree = cmdoutput @git, qw(write-tree);
918 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
919 $ch =~ s{^parent .*\n}{}mg;
920 $ch =~ s{(?=^author)}{
921 join '', map { "parent $_\n" } @parents
922 }me or confess "$ch ?";
924 $ch =~ s{^committer .*$}{$committer_authline}m
927 my $cf = "$rd/m$rewriting";
928 open CD, ">", $cf or die $!;
929 print CD $ch, "\n", $cl->{Msg} or die $!;
931 my @cmd = (@git, qw(hash-object));
932 push @cmd, qw(-w) if $rewriting;
933 push @cmd, qw(-t commit), $cf;
934 my $newcommit = cmdoutput @cmd;
935 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
937 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
943 my $final_check = get_differs $build, $input;
944 die sprintf "internal error %#x %s %s", $final_check, $build, $input
945 if $final_check & ~D_PAT_ADD;
947 my @r = ($build, $breakwater, $last_anchor);
948 printdebug "*** WALK RETURN @r\n";
953 git_check_unmodified();
954 return git_rev_parse qw(HEAD);
957 sub update_head ($$$) {
958 my ($old, $new, $mrest) = @_;
959 push @deferred_updates, "update HEAD $new $old";
960 run_deferred_updates $mrest;
963 sub update_head_checkout ($$$) {
964 my ($old, $new, $mrest) = @_;
965 update_head $old, $new, $mrest;
966 runcmd @git, qw(reset --hard);
969 sub update_head_postlaunder ($$$) {
970 my ($old, $tip, $reflogmsg) = @_;
971 return if $tip eq $old;
972 print "git-debrebase: laundered (head was $old)\n";
973 update_head $old, $tip, $reflogmsg;
974 # no tree changes except debian/patches
975 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
978 sub do_launder_head ($) {
979 my ($reflogmsg) = @_;
980 my $old = get_head();
982 my ($tip,$breakwater) = walk $old;
984 update_head_postlaunder $old, $tip, $reflogmsg;
985 return ($tip,$breakwater);
988 sub cmd_launder_v0 () {
989 badusage "no arguments to launder-v0 allowed" if @ARGV;
990 my $old = get_head();
991 my ($tip,$breakwater,$last_anchor) = walk $old;
992 update_head_postlaunder $old, $tip, 'launder';
993 printf "# breakwater tip\n%s\n", $breakwater;
994 printf "# working tip\n%s\n", $tip;
995 printf "# last anchor\n%s\n", $last_anchor;
998 sub defaultcmd_rebase () {
999 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1000 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1001 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1004 sub cmd_analyse () {
1005 badusage "analyse does not support any options"
1006 if @ARGV and $ARGV[0] =~ m/^-/;
1007 badusage "too many arguments to analyse" if @ARGV>1;
1010 $old = git_rev_parse $old;
1012 $old = git_rev_parse 'HEAD';
1014 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1015 STDOUT->error and die $!;
1018 sub ffq_prev_branchinfo () {
1019 my $current = git_get_symref();
1020 return gdr_ffq_prev_branchinfo($current);
1023 sub ffq_check ($;$$) {
1024 # calls $ff and/or $notff zero or more times
1025 # then returns either (status,message) where status is
1030 # or (undef,undef, $ffq_prev,$gdrlast)
1031 # $ff and $notff are called like this:
1032 # $ff->("message for stdout\n");
1033 # $notff->('snag-name', $message);
1034 # normally $currentval should be HEAD
1035 my ($currentval, $ff, $notff) =@_;
1037 $ff //= sub { print $_[0] or die $!; };
1040 my ($status, $message, $current, $ffq_prev, $gdrlast)
1041 = ffq_prev_branchinfo();
1042 return ($status, $message) unless $status eq 'branch';
1044 my $exists = git_get_ref $ffq_prev;
1045 return ('exists',"$ffq_prev already exists") if $exists;
1047 return ('not-branch', 'HEAD symref is not to refs/heads/')
1048 unless $current =~ m{^refs/heads/};
1051 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1054 printdebug "ffq check_specs @check_specs\n";
1057 my ($lrref, $desc) = @_;
1058 printdebug "ffq might check $lrref ($desc)\n";
1060 for my $chk (@check_specs) {
1062 $invert = $glob =~ s{^[!^]}{};
1063 last if fnmatch $glob, $lrref;
1066 my $lrval = git_get_ref $lrref;
1067 return unless length $lrval;
1069 if (is_fast_fwd $lrval, $currentval) {
1070 $ff->("OK, you are ahead of $lrref\n");
1071 $checked{$lrref} = 1;
1072 } elsif (is_fast_fwd $currentval, $lrval) {
1073 $checked{$lrref} = -1;
1074 $notff->('behind', "you are behind $lrref, divergence risk");
1076 $checked{$lrref} = -1;
1077 $notff->('diverged', "you have diverged from $lrref");
1081 my $merge = cfg "branch.$branch.merge",1;
1082 if (defined $merge and $merge =~ m{^refs/heads/}) {
1084 printdebug "ffq merge $rhs\n";
1085 my $check_remote = sub {
1086 my ($remote, $desc) = @_;
1087 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1088 return unless defined $remote;
1089 $check->("refs/remotes/$remote/$rhs", $desc);
1091 $check_remote->((scalar cfg "branch.$branch.remote",1),
1092 'remote fetch/merge branch');
1093 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1094 (scalar cfg "branch.$branch.pushDefault",1),
1095 'remote push branch');
1097 if ($branch =~ m{^dgit/}) {
1098 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1099 } elsif ($branch =~ m{^master$}) {
1100 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1102 return (undef, undef, $ffq_prev, $gdrlast);
1105 sub record_ffq_prev_deferred () {
1106 # => ('status', "message")
1108 # deferred message is undef
1113 # if not ff from some branch we should be ff from, is an snag
1114 # if "deferred", will have added something about that to
1115 # @deferred_update_messages, and also maybe printed (already)
1116 # some messages about ff checks
1117 my $currentval = get_head();
1119 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1120 return ($status,$message) if defined $status;
1124 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1125 push @deferred_updates, "delete $gdrlast";
1126 push @deferred_update_messages, "Recorded current head for preservation";
1127 return ('deferred', undef);
1130 sub record_ffq_auto () {
1131 my ($status, $message) = record_ffq_prev_deferred();
1132 if ($status eq 'deferred' || $status eq 'exists') {
1134 snag $status, "could not record ffq-prev: $message";
1139 sub ffq_prev_info () {
1140 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1141 my ($status, $message, $current, $ffq_prev, $gdrlast)
1142 = ffq_prev_branchinfo();
1143 if ($status ne 'branch') {
1144 snag $status, "could not check ffq-prev: $message";
1147 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1148 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1151 sub stitch ($$$$$) {
1152 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1154 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1156 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1157 my $differs = get_differs $old_head, $ffq_prev_commitish;
1158 unless ($differs & ~D_PAT_ADD) {
1159 # ffq-prev is ahead of us, and the only tree changes it has
1160 # are possibly addition of things in debian/patches/.
1161 # Just wind forwards rather than making a pointless pseudomerge.
1162 push @deferred_updates,
1163 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1164 update_head_checkout $old_head, $ffq_prev_commitish,
1165 "stitch (fast forward)";
1170 # We make pseudomerges with L as the contributing parent.
1171 # This makes git rev-list --first-parent work properly.
1172 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1173 'Declare fast forward / record previous work',
1174 "[git-debrebase pseudomerge: $prose]",
1176 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1177 update_head $old_head, $new_head, "stitch: $prose";
1180 sub do_stitch ($;$) {
1181 my ($prose, $unclean) = @_;
1183 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1184 if (!$ffq_prev_commitish) {
1185 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1188 my $dangling_head = get_head();
1190 keycommits $dangling_head, $unclean,$unclean,$unclean;
1193 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1196 sub upstream_commitish_search ($$) {
1197 my ($upstream_version, $tried) = @_;
1198 # todo: at some point maybe use git-deborig to do this
1199 foreach my $tagpfx ('', 'v', 'upstream/') {
1200 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1201 my $new_upstream = git_get_ref "refs/tags/$tag";
1203 return $new_upstream if length $new_upstream;
1207 sub resolve_upstream_version ($$) {
1208 my ($new_upstream, $upstream_version) = @_;
1210 if (!defined $new_upstream) {
1212 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1213 if (!length $new_upstream) {
1214 fail "Could not determine appropriate upstream commitish.\n".
1215 " (Tried these tags: @tried)\n".
1216 " Check version, and specify upstream commitish explicitly.";
1219 $new_upstream = git_rev_parse $new_upstream;
1221 return $new_upstream;
1224 sub cmd_new_upstream () {
1225 # automatically and unconditionally launders before rebasing
1226 # if rebase --abort is used, laundering has still been done
1230 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1232 # parse args - low commitment
1233 my $spec_version = shift @ARGV;
1234 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1235 fail "bad version number \`$spec_version'" unless defined $new_version;
1236 if ($new_version->is_native()) {
1237 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1240 my $new_upstream = shift @ARGV;
1241 my $new_upstream_version = upstreamversion $new_version;
1243 resolve_upstream_version $new_upstream, $new_upstream_version;
1248 my ($n, @x) = @_; # may be ''
1249 my $pc = $pieces{$n} //= {
1251 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1253 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1258 my $newpiece = sub {
1259 my ($n, @x) = @_; # may be ''
1260 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1261 push @newpieces, $pc;
1266 New => $new_upstream,
1268 while (@ARGV && $ARGV[0] !~ m{^-}) {
1269 my $n = shift @ARGV;
1271 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1272 unless @ARGV && $ARGV[0] !~ m{^-};
1274 my $c = git_rev_parse shift @ARGV;
1275 die unless $n =~ m/^$extra_orig_namepart_re$/;
1276 $newpiece->($n, New => $c);
1279 # now we need to investigate the branch this generates the
1280 # laundered version but we don't switch to it yet
1281 my $old_head = get_head();
1282 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1284 my $old_bw_cl = classify $old_bw;
1285 my $old_anchor_cl = classify $old_anchor;
1287 if (!$old_anchor_cl->{OrigParents}) {
1288 snag 'anchor-treated',
1289 'old anchor is recognised due to --anchor, cannot check upstream';
1291 $old_upstream = parsecommit
1292 $old_anchor_cl->{OrigParents}[0]{CommitId};
1293 $piece->('', Old => $old_upstream->{CommitId});
1296 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1297 if ($old_upstream->{Msg} =~
1298 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1300 my @oldpieces = (split / /, $1);
1301 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1302 if ($old_n_parents != @oldpieces &&
1303 $old_n_parents != @oldpieces + 1) {
1304 snag 'upstream-confusing', sprintf
1305 "previous upstream combine %s".
1306 " mentions %d pieces (each implying one parent)".
1307 " but has %d parents".
1308 " (one per piece plus maybe a previous combine)",
1309 $old_upstream->{CommitId},
1310 (scalar @oldpieces),
1312 } elsif ($oldpieces[0] ne '.') {
1313 snag 'upstream-confusing', sprintf
1314 "previous upstream combine %s".
1315 " first piece is not \`.'",
1319 foreach my $i (0..$#oldpieces) {
1320 my $n = $oldpieces[$i];
1321 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1322 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1326 snag 'upstream-confusing',
1327 "previous upstream $old_upstream->{CommitId} is from".
1328 " git-debrebase but not an \`upstream-combine' commit";
1332 foreach my $pc (values %pieces) {
1333 if (!$old_upstream) {
1334 # we have complained already
1335 } elsif (!$pc->{Old}) {
1336 snag 'upstream-new-piece',
1337 "introducing upstream piece \`$pc->{Name}'";
1338 } elsif (!$pc->{New}) {
1339 snag 'upstream-rm-piece',
1340 "dropping upstream piece \`$pc->{Name}'";
1341 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1342 snag 'upstream-not-ff',
1343 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1347 printdebug "%pieces = ", (dd \%pieces), "\n";
1348 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1356 my @upstream_merge_parents;
1359 push @upstream_merge_parents, $old_upstream->{CommitId};
1362 foreach my $pc (@newpieces) { # always has '' first
1364 read_tree_subdir $pc->{Name}, $pc->{New};
1366 runcmd @git, qw(read-tree), $pc->{New};
1368 push @upstream_merge_parents, $pc->{New};
1371 # index now contains the new upstream
1373 if (@newpieces > 1) {
1374 # need to make the upstream subtree merge commit
1375 $new_upstream = make_commit \@upstream_merge_parents,
1376 [ "Combine upstreams for $new_upstream_version",
1377 ("[git-debrebase upstream-combine . ".
1378 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1383 # $new_upstream is either the single upstream commit, or the
1384 # combined commit we just made. Either way it will be the
1385 # "upstream" parent of the anchor merge.
1387 read_tree_subdir 'debian', "$old_bw:debian";
1389 # index now contains the anchor merge contents
1390 $new_bw = make_commit [ $old_bw, $new_upstream ],
1391 [ "Update to upstream $new_upstream_version",
1392 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1395 my $clogsignoff = cmdoutput qw(git show),
1396 '--pretty=format:%an <%ae> %aD',
1399 # Now we have to add a changelog stanza so the Debian version
1401 die if unlink "debian";
1402 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1403 unlink "debian/changelog" or $!==ENOENT or die $!;
1404 mkdir "debian" or die $!;
1405 open CN, ">", "debian/changelog" or die $!;
1406 my $oldclog = git_cat_file ":debian/changelog";
1407 $oldclog =~ m/^($package_re) \(\S+\) / or
1408 fail "cannot parse old changelog to get package name";
1410 print CN <<END, $oldclog or die $!;
1411 $p ($new_version) UNRELEASED; urgency=medium
1413 * Update to new upstream version $new_upstream_version.
1419 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1421 # Now we have the final new breakwater branch in the index
1422 $new_bw = make_commit [ $new_bw ],
1423 [ "Update changelog for new upstream $new_upstream_version",
1424 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1428 # we have constructed the new breakwater. we now need to commit to
1429 # the laundering output, because git-rebase can't easily be made
1430 # to make a replay list which is based on some other branch
1432 update_head_postlaunder $old_head, $old_laundered_tip,
1433 'launder for new upstream';
1435 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1436 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1437 "debrebase new-upstream $new_version: rebase";
1439 # now it's for the user to sort out
1442 sub cmd_record_ffq_prev () {
1443 badusage "no arguments allowed" if @ARGV;
1444 my ($status, $msg) = record_ffq_prev_deferred();
1445 if ($status eq 'exists' && $opt_noop_ok) {
1446 print "Previous head already recorded\n" or die $!;
1447 } elsif ($status eq 'deferred') {
1448 run_deferred_updates 'record-ffq-prev';
1450 fail "Could not preserve: $msg";
1455 badusage "no arguments allowed" if @ARGV;
1456 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1457 print "$bw\n" or die $!;
1460 sub cmd_breakwater () {
1461 badusage "no arguments allowed" if @ARGV;
1462 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1463 print "$bw\n" or die $!;
1467 badusage "no arguments allowed" if @ARGV;
1469 # todo: gdr status should print divergence info
1470 # todo: gdr status should print upstream component(s) info
1471 # todo: gdr should leave/maintain some refs with this kind of info ?
1473 my $oldest = { Badness => 0 };
1476 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1477 if ($oldest->{Badness} < $badness) {
1478 $oldest = $newest = undef;
1481 Badness => $badness,
1482 CommitId => $cl->{CommitId},
1486 $newest //= $oldest;
1488 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1489 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1490 sub { $note->(2, 'branch is unlaundered', @_); },
1491 sub { $note->(3, 'branch needs laundering', @_); },
1492 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1494 my $prcommitinfo = sub {
1496 flush STDOUT or die $!;
1497 runcmd @git, qw(--no-pager log -n1),
1498 '--pretty=format: %h %s%n',
1502 print "current branch contents, in git-debrebase terms:\n";
1503 if (!$oldest->{Badness}) {
1504 print " branch is laundered\n";
1506 print " $oldest->{OurMsg}\n";
1508 foreach my $info ($oldest, $newest) {
1509 my $cid = $info->{CommitId};
1510 next if $cid eq $printed;
1512 print " $info->{KcMsg}\n";
1513 $prcommitinfo->($cid);
1518 my ($cid, $what) = @_;
1519 if (!defined $cid) {
1520 print " $what is not well-defined\n";
1523 $prcommitinfo->($cid);
1526 print "key git-debrebase commits:\n";
1527 $prab->($anchor, 'anchor');
1528 $prab->($bw, 'breakwater');
1530 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1531 ffq_prev_branchinfo();
1533 print "branch and ref status, in git-debrebase terms:\n";
1535 print " $ffq_msg\n";
1537 $ffq_prev = git_get_ref $ffq_prev;
1538 $gdrlast = git_get_ref $gdrlast;
1540 print " unstitched; previous tip was:\n";
1541 $prcommitinfo->($ffq_prev);
1542 } elsif (!$gdrlast) {
1543 print " stitched? (no record of git-debrebase work)\n";
1544 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1545 print " stitched\n";
1547 print " not git-debrebase (diverged since last stitch)\n"
1553 my $prose = 'stitch';
1554 getoptions("stitch",
1555 'prose=s', \$prose);
1556 badusage "no arguments allowed" if @ARGV;
1557 do_stitch $prose, 0;
1559 sub cmd_prepush () { cmd_stitch(); }
1562 badusage "no arguments allowed" if @ARGV;
1563 do_launder_head 'launder for git-debrebase quick';
1567 sub cmd_conclude () {
1568 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1569 if (!$ffq_prev_commitish) {
1570 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1573 my $dangling_head = get_head();
1575 badusage "no arguments allowed" if @ARGV;
1576 do_launder_head 'launder for git-debrebase quick';
1581 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1582 if (!$ffq_prev_commitish) {
1583 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1586 my $scrapping_head = get_head();
1587 badusage "no arguments allowed" if @ARGV;
1588 push @deferred_updates,
1589 "update $gdrlast $ffq_prev_commitish $git_null_obj",
1590 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
1592 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
1595 sub make_patches_staged ($) {
1597 # Produces the patches that would result from $head if it were
1599 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1602 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1603 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1604 my @gbp_cmd = (qw(gbp pq export));
1605 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1607 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1610 runcmd @git, qw(add -f debian/patches);
1614 sub make_patches ($) {
1616 keycommits $head, 0, \&snag;
1617 make_patches_staged $head;
1620 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1621 runcmd @git, qw(read-tree), $head;
1622 read_tree_subdir 'debian/patches', $ptree;
1623 $out = make_commit [$head], [
1624 'Commit patch queue (exported by git-debrebase)',
1625 '[git-debrebase: export and commit patches]',
1631 sub cmd_make_patches () {
1632 my $opt_quiet_would_amend;
1633 getoptions("make-patches",
1634 'quiet-would-amend!', \$opt_quiet_would_amend);
1635 badusage "no arguments allowed" if @ARGV;
1636 my $old_head = get_head();
1637 my $new = make_patches $old_head;
1638 my $d = get_differs $old_head, $new;
1640 fail "No (more) patches to export." unless $opt_noop_ok;
1642 } elsif ($d == D_PAT_ADD) {
1644 update_head_checkout $old_head, $new, 'make-patches';
1646 print STDERR failmsg
1647 "Patch export produced patch amendments".
1648 " (abandoned output commit $new).".
1649 " Try laundering first."
1650 unless $opt_quiet_would_amend;
1655 sub cmd_convert_from_gbp () {
1656 badusage "want only 1 optional argument, the upstream git commitish"
1659 my $clogp = parsechangelog();
1660 my $version = $clogp->{'Version'}
1661 // die "missing Version from changelog";
1663 my ($upstream_spec) = @ARGV;
1665 my $upstream_version = upstreamversion $version;
1667 resolve_upstream_version($upstream_spec, $upstream_version);
1669 my $old_head = get_head();
1671 my $upsdiff = get_differs $upstream, $old_head;
1672 if ($upsdiff & D_UPS) {
1673 runcmd @git, qw(--no-pager diff --stat),
1674 $upstream, $old_head,
1675 qw( -- :!/debian :/);
1677 upstream ($upstream_spec) and HEAD are not
1678 identical in upstream files. See diffstat above, or run
1679 git diff $upstream_spec HEAD -- :!/debian :/
1683 if (!is_fast_fwd $upstream, $old_head) {
1684 snag 'upstream-not-ancestor',
1685 "upstream ($upstream) is not an ancestor of HEAD";
1687 my $wrong = cmdoutput
1688 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1689 qw(-- :/ :!/debian));
1690 if (length $wrong) {
1691 snag 'unexpected-upstream-changes',
1692 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1693 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1697 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1698 snag 'upstream-has-debian',
1699 "upstream ($upstream) contains debian/ directory";
1702 my $previous_dgit_view = eval {
1703 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1705 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1706 my ($stz, $desc) = @_;
1707 no warnings qw(exiting);
1708 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1709 next unless $stz->{Date};
1710 next unless $stz->{Distribution} ne 'UNRELEASED';
1711 $lvsn = $stz->{Version};
1712 $suite = $stz->{Distribution};
1715 die "neither of the first two changelog entries are released\n"
1716 unless defined $lvsn;
1717 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1718 my $mtag_pat = debiantag_maintview $lvsn, '*';
1719 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1721 die "could not find suitable maintainer view tag $mtag_pat\n"
1722 unless $mtag_pat =~ m{/};
1723 is_fast_fwd $mtag, 'HEAD' or
1724 die "HEAD is not FF from maintainer tag $mtag!";
1725 my $dtag = "archive/$mtag";
1726 is_fast_fwd $mtag, $dtag or
1727 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1728 print "will stitch in dgit view, $dtag\n";
1729 git_rev_parse $dtag;
1731 if (!$previous_dgit_view) {
1734 print STDERR "cannot stitch in dgit view: $@\n";
1737 snags_maybe_bail_early();
1743 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1744 # make a branch out of the patch queue - we'll want this in a mo
1745 runcmd qw(gbp pq import);
1746 # strip the patches out
1747 runcmd @git, qw(checkout -q gdr-internal~0);
1748 rm_subdir_cached 'debian/patches';
1749 $work = make_commit ['HEAD'], [
1750 'git-debrebase convert-from-gbp: drop patches from tree',
1751 'Delete debian/patches, as part of converting to git-debrebase format.',
1752 '[git-debrebase convert-from-gbp: drop patches from tree]'
1754 # make the anchor merge
1755 # the tree is already exactly right
1756 $work = make_commit [$work, $upstream], [
1757 'git-debrebase import: declare upstream',
1758 'First breakwater merge.',
1759 '[git-debrebase anchor: declare upstream]'
1762 # rebase the patch queue onto the new breakwater
1763 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1764 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1765 $work = git_rev_parse 'HEAD';
1767 if ($previous_dgit_view) {
1768 $work = make_commit [$work, $previous_dgit_view], [
1769 'git-debrebase import: declare ff from dgit archive view',
1770 '[git-debrebase pseudomerge: import-from-gbp]',
1777 update_head_checkout $old_head, $work, 'convert-from-gbp';
1780 sub cmd_convert_to_gbp () {
1781 badusage "no arguments allowed" if @ARGV;
1782 my $head = get_head();
1783 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1784 keycommits $head, 0;
1786 make_patches_staged $head;
1788 $out = make_commit ['HEAD'], [
1789 'Commit patch queue (converted from git-debrebase format)',
1790 '[git-debrebase convert-to-gbp: commit patches]',
1794 push @deferred_updates, "delete $ffq";
1795 push @deferred_updates, "delete $gdrlast";
1798 update_head_checkout $head, $out, "convert to gbp (v0)";
1799 print <<END or die $!;
1800 git-debrebase: converted to git-buildpackage branch format
1801 git-debrebase: WARNING: do not now run "git-debrebase" any more
1802 git-debrebase: WARNING: doing so would drop all upstream patches!
1806 sub cmd_convert_from_dgit_view () {
1807 my $clogp = parsechangelog();
1809 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
1815 getoptions("convert-from-dgit-view",
1816 'diagnose!', \$diagnose,
1817 'build-products-dir:s', \$bpd,
1818 'origs!', \$do_origs,
1820 'always-convert-anyway!', \$always);
1821 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
1826 my $spec = shift @ARGV;
1827 my $commit = git_rev_parse "$spec^{commit}";
1828 push @upstreams, { Commit => $commit,
1829 Source => "$ARGV[0], from command line",
1834 my $head = get_head();
1838 my $trouble = sub { $troubles++; };
1839 keycommits $head, sub{}, sub{}, $trouble, $trouble;
1840 printdebug "troubles=$troubles\n";
1843 $us: Branch already seems to be in git-debrebase format!
1844 $us: --always-convert-anyway would do the conversion operation anyway
1845 $us: but is probably a bad idea. Probably, you wanted to do nothing.
1847 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
1852 snags_maybe_bail_early();
1854 my $version = upstreamversion $clogp->{Version};
1855 print STDERR "Considering possible commits corresponding to upstream:\n";
1860 my $ups_tag = upstream_commitish_search $version, \@tried;
1862 my $this = "git tag $tried[-1]";
1863 push @upstreams, { Commit => $ups_tag,
1868 " git tag: no suitable tag found (tried %s)\n",
1873 my $p = $clogp->{'Source'};
1874 # we do a quick check to see if there are plausible origs
1876 if (!opendir BPD, $bpd) {
1877 die "$bpd: opendir: $!" unless $!==ENOENT;
1879 while ($!=0, my $f = readdir BPD) {
1880 next unless is_orig_file_of_p_v $f, $p, $version;
1882 " orig: found what looks like a .orig, %s\n",
1887 die "read $bpd: $!" if $!;
1891 my $tree = cmdoutput
1892 @dgit, qw(--build-products-dir), $bpd,
1893 qw(print-unapplied-treeish);
1896 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
1897 rm_subdir_cached 'debian';
1898 $tree = cmdoutput @git, qw(write-tree);
1899 my $ups_synth = make_commit [], [ <<END, <<END,
1900 Import effective orig tree for upstream version $version
1902 This includes the contents of the .orig(s), minus any debian/ directory.
1904 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
1907 push @upstreams, { Commit => $ups_synth,
1908 Source => "orig(s) imported via dgit",
1913 " orig: no suitable origs found (looked for %s in %s)\n",
1914 "${p}_".(stripeoch $version)."...", $bpd;
1919 my $some_patches = stat_exists 'debian/patches/series';
1921 print STDERR "Evaluating possible commits corresponding to upstream:\n";
1924 foreach my $u (@upstreams) {
1928 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
1929 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
1930 runcmd @git, qw(clean -xdff);
1931 runcmd @git, qw(checkout), $head, qw(-- debian);
1932 if ($some_patches) {
1933 rm_subdir_cached 'debian/patches';
1934 $work = make_commit [ $work ], [
1935 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
1936 "Drop upstream changes, and delete debian/patches, as part of converting\n".
1937 "to git-debrebase format. Upstream changes will appear as commits.",
1938 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
1941 $work = make_commit [ $work, $u->{Commit} ], [
1942 'git-debrebase convert-from-dgit-view: declare upstream',
1943 '(Re)constructed breakwater merge.',
1944 '[git-debrebase anchor: declare upstream]'
1946 runcmd @git, qw(checkout --quiet -b mk), $work;
1947 if ($some_patches) {
1948 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
1949 runcmd @git, qw(reset --quiet);
1950 my @gbp_cmd = (qw(gbp pq import));
1952 my $gbp_err = "../gbp-pq-err";
1953 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
1955 my $r = system @gbp_cmd;
1958 " %s: couldn't apply patches: gbp pq %s",
1959 $u->{Source}, waitstatusmsg();
1963 my $work = git_rev_parse qw(HEAD);
1964 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
1965 if (length $diffout) {
1967 " $u->{Source}: applying patches gives different tree\n";
1968 print STDERR $diffout if $diagnose;
1972 $u->{Result} = $work;
1980 Could not find or construct a suitable upstream commit.
1981 Rerun adding --diagnose after convert-from-dgit-view, or pass a
1982 upstream commmit explicitly or provide suitable origs.
1986 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
1988 ffq_check $result->{Result};
1990 update_head_checkout $head, $result->{Result},
1991 'convert-from-dgit-view';
1994 sub cmd_downstream_rebase_launder_v0 () {
1995 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1997 $base = git_rev_parse $base;
1998 my $old_head = get_head();
1999 my $current = $old_head;
2002 if ($current eq $base) {
2003 $topmost_keep //= $current;
2004 print " $current BASE stop\n";
2007 my $cl = classify $current;
2008 print " $current $cl->{Type}";
2010 my $p0 = $cl->{Parents}[0]{CommitId};
2012 if ($cl->{Type} eq 'Pseudomerge') {
2013 print " ^".($cl->{Contributor}{Ix}+1);
2014 $next = $cl->{Contributor}{CommitId};
2015 } elsif ($cl->{Type} eq 'AddPatches' or
2016 $cl->{Type} eq 'Changelog') {
2026 $topmost_keep //= $current;
2028 die "to-be stripped changes not on top of the branch\n"
2033 if ($topmost_keep eq $old_head) {
2034 print "unchanged\n";
2036 print "updating to $topmost_keep\n";
2037 update_head_checkout
2038 $old_head, $topmost_keep,
2039 'downstream-rebase-launder-v0';
2045 "D+" => \$debuglevel,
2046 'noop-ok', => \$opt_noop_ok,
2047 'f=s' => \@snag_force_opts,
2048 'anchor=s' => \@opt_anchors,
2049 '--dgit=s' => \($dgit[0]),
2052 my ($opt,$val) = @_;
2053 badusage "git-debrebase: no cuddling to -i for git-rebase"
2055 die if $opt_defaultcmd_interactive; # should not happen
2056 $opt_defaultcmd_interactive = [ qw(-i) ];
2057 # This access to @ARGV is excessive familiarity with
2058 # Getopt::Long, but there isn't another sensible
2059 # approach. '-i=s{0,}' does not work with bundling.
2060 push @$opt_defaultcmd_interactive, @ARGV;
2063 'help' => sub { print $usage_message or die $!; finish 0; },
2066 initdebug('git-debrebase ');
2067 enabledebug if $debuglevel;
2069 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2070 chdir $toplevel or die "chdir $toplevel: $!";
2072 $rd = fresh_playground "$playprefix/misc";
2074 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2076 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2077 defaultcmd_rebase();
2079 my $cmd = shift @ARGV;
2082 $cmdfn = ${*::}{"cmd_$cmdfn"};
2084 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";