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';
118 sub in_workarea ($) {
121 my $r = eval { $sub->(); };
122 { local $@; changedir $maindir; }
126 sub fresh_workarea () {
127 $workarea = fresh_playground "$playprefix/work";
128 in_workarea sub { playtree_setup };
131 our $snags_forced = 0;
132 our $snags_tripped = 0;
133 our $snags_summarised = 0;
134 our @deferred_updates;
135 our @deferred_update_messages;
137 sub all_snags_summarised () {
138 $snags_forced + $snags_tripped == $snags_summarised;
140 sub run_deferred_updates ($) {
143 confess 'dangerous internal error' unless all_snags_summarised();
145 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
146 debugcmd '>|', @upd_cmd;
147 open U, "|-", @upd_cmd or die $!;
148 foreach (@deferred_updates) {
149 printdebug ">= ", $_, "\n";
150 print U $_, "\n" or die $!;
153 close U or failedcmd @upd_cmd;
155 print $_, "\n" foreach @deferred_update_messages;
157 @deferred_updates = ();
158 @deferred_update_messages = ();
161 sub get_differs ($$) {
163 # This resembles quiltify_trees_differ, in dgit, a bit.
164 # But we don't care about modes, or dpkg-source-unrepresentable
165 # changes, and we don't need the plethora of different modes.
166 # Conversely we need to distinguish different kinds of changes to
167 # debian/ and debian/patches/.
172 my ($opts, $limits, $fn) = @_;
173 my @cmd = (@git, qw(diff-tree -z --no-renames));
175 push @cmd, "$_:" foreach $x, $y;
176 push @cmd, '--', @$limits;
177 my $diffs = cmdoutput @cmd;
178 foreach (split /\0/, $diffs) { $fn->(); }
181 $rundiff->([qw(--name-only)], [], sub {
182 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
185 if ($differs & DS_DEB) {
187 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
189 m{^debian/patches/} ? D_PAT_OTH :
190 $_ eq 'debian/changelog' ? D_DEB_CLOG :
193 die "mysterious debian changes $x..$y"
194 unless $differs & (D_PAT_OTH|DS_DEB);
197 if ($differs & D_PAT_OTH) {
199 $differs &= ~D_PAT_OTH;
201 $differs |= D_PAT_OTH;
202 no warnings qw(exiting); last;
204 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
205 no warnings qw(exiting);
206 if (!defined $mode) {
209 die unless s{^debian/patches/}{};
211 if ($mode eq 'A' && !m/\.series$/s) {
213 } elsif ($mode eq 'M' && $_ eq 'series') {
214 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
215 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
216 chomp $x_s; $x_s .= "\n";
217 $ok = $x_s eq substr($y_s, 0, length $x_s);
222 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
224 die "mysterious debian/patches changes $x..$y"
225 unless $differs & (D_PAT_ADD|D_PAT_OTH);
228 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
233 sub commit_pr_info ($) {
235 return Data::Dumper->dump([$r], [qw(commit)]);
238 sub calculate_committer_authline () {
239 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
240 'DUMMY COMMIT (git-debrebase)', "HEAD:";
241 my ($h,$m) = get_commit $c;
242 $h =~ m/^committer .*$/m or confess "($h) ?";
246 sub rm_subdir_cached ($) {
248 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
251 sub read_tree_subdir ($$) {
252 my ($subdir, $new_tree_object) = @_;
253 rm_subdir_cached $subdir;
254 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
257 sub make_commit ($$) {
258 my ($parents, $message_paras) = @_;
259 my $tree = cmdoutput @git, qw(write-tree);
260 my @cmd = (@git, qw(commit-tree), $tree);
261 push @cmd, qw(-p), $_ foreach @$parents;
262 push @cmd, qw(-m), $_ foreach @$message_paras;
263 return cmdoutput @cmd;
266 our @snag_force_opts;
268 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
269 if (grep { $_ eq $tag } @snag_force_opts) {
271 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
274 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
278 # Important: all mainline code must call snags_maybe_bail after
279 # any point where snag might be called, but before making changes
280 # (eg before any call to run_deferred_updates). snags_maybe_bail
281 # may be called more than once if necessary (but this is not ideal
282 # because then the messages about number of snags may be confusing).
283 sub snags_maybe_bail () {
284 return if all_snags_summarised();
287 "%s: snags: %d overriden by individual -f options\n",
290 if ($snags_tripped) {
293 "%s: snags: %d overriden by global --force\n",
297 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
301 $snags_summarised = $snags_forced + $snags_tripped;
303 sub snags_maybe_bail_early () {
304 # useful to bail out early without doing a lot of work;
305 # not a substitute for snags_maybe_bail.
306 snags_maybe_bail() if $snags_tripped && !$opt_force;
309 return $snags_forced || $snags_tripped;
312 # classify returns an info hash like this
314 # Hdr => # commit headers, including 1 final newline
315 # Msg => # commit message (so one newline is dropped)
317 # Type => (see below)
319 # Ix => $index # ie 0, 1, 2, ...
321 # Differs => return value from get_differs
323 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
325 # NewMsg => # commit message, but with any [dgit import ...] edited
326 # # to say "[was: ...]"
336 # has additional entres in classification result
337 # Overwritten = [ subset of Parents ]
338 # Contributor = $the_remaining_Parent
340 # DgitImportUnpatched
341 # has additional entry in classification result
342 # OrigParents = [ subset of Parents ]
345 # has additional entry in classification result
346 # OrigParents = [ subset of Parents ] # singleton list
353 # has additional entry in classification result
356 sub parsecommit ($;$) {
357 my ($objid, $p_ref) = @_;
358 # => hash with CommitId Hdr Msg Tree Parents
359 # Parents entries have only Ix CommitId
360 # $p_ref, if provided, must be [] and is used as a base for Parents
365 my ($h,$m) = get_commit $objid;
367 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
368 my (@ph) = $h =~ m/^parent (\w+)$/mg;
378 foreach my $ph (@ph) {
380 Ix => scalar @$p_ref,
392 my $r = parsecommit($objid, \@p);
396 $p->{Differs} = (get_differs $p->{CommitId}, $t),
399 printdebug "classify $objid \$t=$t \@p",
400 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
404 my ($type, @rest) = @_;
405 $r = { %$r, Type => $type, @rest };
407 printdebug " = $type ".(dd $r)."\n";
413 $r = { %$r, Type => qw(Unknown), Why => $why };
414 printdebug " ** Unknown\n";
418 if (grep { $_ eq $objid } @opt_anchors) {
419 return $classify->('TreatAsAnchor');
422 my @identical = grep { !$_->{Differs} } @p;
423 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
424 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
426 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
427 # multi-orig upstreams are represented with an anchor merge
428 # from a single upstream commit which combines the orig tarballs
430 # Every anchor tagged this way must be a merge.
431 # We are relying on the
432 # [git-debrebase anchor: ...]
433 # commit message annotation in "declare" anchor merges (which
434 # do not have any upstream changes), to distinguish those
435 # anchor merges from ordinary pseudomerges (which we might
436 # just try to strip).
438 # However, the user is going to be doing git-rebase a lot. We
439 # really don't want them to rewrite an anchor commit.
440 # git-rebase trips up on merges, so that is a useful safety
443 # BreakwaterStart commits are also anchors in the terminology
444 # of git-debrebase(5), but they are untagged (and always
445 # manually generated).
447 # We cannot not tolerate any tagged linear commit (ie,
448 # BreakwaterStart commits tagged `[anchor:') because such a
449 # thing could result from an erroneous linearising raw git
450 # rebase of a merge anchor. That would represent a corruption
451 # of the branch. and we want to detect and reject the results
452 # of such corruption before it makes it out anywhere. If we
453 # reject it here then we avoid making the pseudomerge which
454 # would be needed to push it.
456 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
457 @p == 2 or return $badanchor->("has other than two parents");
458 $haspatches and return $badanchor->("contains debian/patches");
460 # How to decide about l/r ordering of anchors ? git
461 # --topo-order prefers to expand 2nd parent first. There's
462 # already an easy rune to look for debian/ history anyway (git log
463 # debian/) so debian breakwater branch should be 1st parent; that
464 # way also there's also an easy rune to look for the upstream
465 # patches (--topo-order).
467 # Also this makes --first-parent be slightly more likely to
468 # be useful - it makes it provide a linearised breakwater history.
470 # Of course one can say somthing like
471 # gitk -- ':/' ':!/debian'
472 # to get _just_ the commits touching upstream files, and by
473 # the TREESAME logic in git-rev-list this will leave the
474 # breakwater into upstream at the first anchor. But that
475 # doesn't report debian/ changes at all.
477 # Other observations about gitk: by default, gitk seems to
478 # produce output in a different order to git-rev-list. I
479 # can't seem to find this documented anywhere. gitk
480 # --date-order DTRT. But, gitk always seems to put the
481 # parents from left to right, in order, so it's easy to see
482 # which way round a pseudomerge is.
484 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
485 $p[1]{Differs} & ~DS_DEB and
486 $badanchor->("upstream files differ from left parent");
487 $p[0]{Differs} & ~D_UPS and
488 $badanchor->("debian/ differs from right parent");
490 return $classify->(qw(Anchor),
491 OrigParents => [ $p[1] ]);
495 my $d = $r->{Parents}[0]{Differs};
496 if ($d == D_PAT_ADD) {
497 return $classify->(qw(AddPatches));
498 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
499 return $unknown->("edits debian/patches");
500 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
501 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
503 if ($d == D_DEB_CLOG) {
504 return $classify->(qw(Changelog));
506 return $classify->(qw(Packaging));
508 } elsif ($ty eq 'missing') {
509 return $classify->(qw(BreakwaterStart));
511 return $unknown->("parent's debian is not a directory");
513 } elsif ($d == D_UPS) {
514 return $classify->(qw(Upstream));
515 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
516 return $classify->(qw(Mixed));
518 return $unknown->("no changes");
520 confess "internal error $objid ?";
524 return $unknown->("origin commit");
527 if (@p == 2 && @identical == 1) {
528 my @overwritten = grep { $_->{Differs} } @p;
529 confess "internal error $objid ?" unless @overwritten==1;
530 return $classify->(qw(Pseudomerge),
531 Overwritten => [ $overwritten[0] ],
532 Contributor => $identical[0]);
534 if (@p == 2 && @identical == 2) {
536 my ($ph,$pm) = get_commit $_[0]{CommitId};
537 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
541 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
542 if ($order > 0) { # newer first
543 } elsif ($order < 0) {
544 @bytime = reverse @bytime;
546 # same age, default to order made by -s ours
547 # that is, commit was made by someone who preferred L
549 return $classify->(qw(Pseudomerge),
550 SubType => qw(Ambiguous),
551 Contributor => $bytime[0],
552 Overwritten => [ $bytime[1] ]);
555 my ($p_h, $p_m) = get_commit $p->{CommitId};
556 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
557 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
559 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
561 if (!(grep { !$_->{IsOrigin} } @p) and
562 (@orig_ps >= @p - 1) and
563 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
565 return $classify->(qw(DgitImportUnpatched),
566 OrigParents => \@orig_ps);
569 return $unknown->("complex merge");
572 sub keycommits ($;$$$$) {
573 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
574 # => ($anchor, $breakwater)
576 # $unclean->("unclean-$tagsfx", $msg, $cl)
577 # $furniture->("unclean-$tagsfx", $msg, $cl)
578 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
579 # is callled for each situation or commit that
580 # wouldn't be found in a laundered branch
581 # $furniture is for furniture commits such as might be found on an
582 # interchange branch (pseudomerge, d/patches, changelog)
583 # $trouble is for things whnich prevent the return of
584 # anchor and breakwater information; if that is ignored,
585 # then keycommits returns (undef, undef) instead.
586 # $fatal is for unprocessable commits, and should normally cause
587 # a failure. If ignored, agaion, (undef, undef) is returned.
589 # If a callback is undef, fail is called instead.
590 # If a callback is defined but false, the situation is ignored.
592 # no warnings qw(exiting); last;
593 # if the answer is no longer wanted.
595 my ($anchor, $breakwater);
598 $fatal //= sub { fail $_[1]; };
600 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
601 my $why = $mainwhy.$xwhy;
602 my $m = "branch needs laundering (run git-debrebase): $why";
603 fail $m unless defined $cb;
605 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
608 $cl = classify $head;
609 my $ty = $cl->{Type};
610 if ($ty eq 'Packaging') {
611 $breakwater //= $clogonly;
612 $breakwater //= $head;
613 } elsif ($ty eq 'Changelog') {
614 # this is going to count as the tip of the breakwater
615 # only if it has no upstream stuff before it
617 } elsif ($ty eq 'Anchor' or
618 $ty eq 'TreatAsAnchor' or
619 $ty eq 'BreakwaterStart') {
621 $breakwater //= $clogonly;
622 $breakwater //= $head;
624 } elsif ($ty eq 'Upstream') {
625 $x->($unclean, 'ordering',
626 "packaging change ($breakwater) follows upstream change"," (eg $head)")
627 if defined $breakwater;
630 } elsif ($ty eq 'Mixed') {
631 $x->($unclean, 'mixed',
632 "found mixed upstream/packaging commit"," ($head)");
635 } elsif ($ty eq 'Pseudomerge' or
636 $ty eq 'AddPatches') {
637 $x->($furniture, (lc $ty),
638 "found interchange bureaucracy commit ($ty)"," ($head)");
639 } elsif ($ty eq 'DgitImportUnpatched') {
640 $x->($trouble, 'dgitimport',
641 "found dgit dsc import ($head)");
642 return (undef,undef);
644 $x->($fatal, 'unprocessable',
645 "found unprocessable commit, cannot cope: $cl->{Why}",
647 return (undef,undef);
649 $head = $cl->{Parents}[0]{CommitId};
651 return ($anchor, $breakwater);
657 $nogenerate,$report) = @_;
658 # => ($tip, $breakwater_tip, $last_anchor)
659 # (or nothing, if $nogenerate)
661 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
663 # go through commits backwards
664 # we generate two lists of commits to apply:
665 # breakwater branch and upstream patches
666 my (@brw_cl, @upp_cl, @processed);
673 my ($prose, $info) = @_;
677 $ms .= "\n\n[git-debrebase$info: $prose]\n";
680 my $rewrite_from_here = sub {
682 my $sp_cl = { SpecialMethod => 'StartRewrite' };
684 push @processed, $sp_cl;
689 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
692 return unless $report;
693 print $report $prdelim, @_;
697 my $bomb = sub { # usage: return $bomb->();
698 print $report " Unprocessable" if $report;
699 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
702 return (undef,undef);
704 fail "found unprocessable commit, cannot cope:".
705 (defined $cl->{Why} ? "; $cl->{Why}": '').
706 " (commit $cur) (d.".
707 (join ' ', map { sprintf "%#x", $_->{Differs} }
708 @{ $cl->{Parents} }).
715 my $build_start = sub {
716 my ($msg, $parent) = @_;
719 no warnings qw(exiting); last;
726 my $ty = $cl->{Type};
727 my $st = $cl->{SubType};
728 $prline->("$cl->{CommitId} $cl->{Type}");
729 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
730 push @processed, $cl;
731 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
732 if ($ty eq 'AddPatches') {
734 $rewrite_from_here->(\@upp_cl);
736 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
740 } elsif ($ty eq 'BreakwaterStart') {
742 $build_start->('FirstPackaging', $cur);
743 } elsif ($ty eq 'Upstream') {
747 } elsif ($ty eq 'Mixed') {
750 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
753 $queue->(\@brw_cl, "debian");
754 $queue->(\@upp_cl, "upstream");
755 $rewrite_from_here->(\@brw_cl);
758 } elsif ($ty eq 'Pseudomerge') {
759 my $contrib = $cl->{Contributor}{CommitId};
760 print $report " Contributor=$contrib" if $report;
761 push @pseudomerges, $cl;
762 $rewrite_from_here->(\@upp_cl);
765 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
767 $build_start->("Anchor", $cur);
768 } elsif ($ty eq 'DgitImportUnpatched') {
769 my $pm = $pseudomerges[-1];
771 # To an extent, this is heuristic. Imports don't have
772 # a useful history of the debian/ branch. We assume
773 # that the first pseudomerge after an import has a
774 # useful history of debian/, and ignore the histories
775 # from later pseudomerges. Often the first pseudomerge
776 # will be the dgit import of the upload to the actual
777 # suite intended by the non-dgit NMUer, and later
778 # pseudomerges may represent in-archive copies.
779 my $ovwrs = $pm->{Overwritten};
780 printf $report " PM=%s \@Overwr:%d",
781 $pm->{CommitId}, (scalar @$ovwrs)
784 printdebug "*** WALK BOMB DgitImportUnpatched\n";
787 my $ovwr = $ovwrs->[0]{CommitId};
788 printf $report " Overwr=%s", $ovwr if $report;
789 # This import has a tree which is just like a
790 # breakwater tree, but it has the wrong history. It
791 # ought to have the previous breakwater (which the
792 # pseudomerge overwrote) as an ancestor. That will
793 # make the history of the debian/ files correct. As
794 # for the upstream version: either it's the same as
795 # was ovewritten (ie, same as the previous
796 # breakwater), in which case that history is precisely
797 # right; or, otherwise, it was a non-gitish upload of a
798 # new upstream version. We can tell these apart by
799 # looking at the tree of the supposed upstream.
802 SpecialMethod => 'DgitImportDebianUpdate',
803 $xmsg->("convert dgit import: debian changes")
806 SpecialMethod => 'DgitImportUpstreamUpdate',
807 $xmsg->("convert dgit import: upstream update",
810 $prline->(" Import");
811 $rewrite_from_here->(\@brw_cl);
812 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
816 # Everything is from this import. This kind of import
817 # is already in valid breakwater format, with the
818 # patches as commits.
819 printf $report " NoPM" if $report;
820 # last thing we processed will have been the first patch,
821 # if there is one; which is fine, so no need to rewrite
822 # on account of this import
823 $build_start->("ImportOrigin", $cur);
827 printdebug "*** WALK BOMB unrecognised\n";
833 printdebug "*** WALK prep done cur=$cur".
834 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
836 return if $nogenerate;
838 # Now we build it back up again
844 my $read_tree_debian = sub {
846 read_tree_subdir 'debian', "$treeish:debian";
847 rm_subdir_cached 'debian/patches';
849 my $read_tree_upstream = sub {
851 runcmd @git, qw(read-tree), $treeish;
852 $read_tree_debian->($build);
855 $#upp_cl = $upp_limit if defined $upp_limit;
857 my $committer_authline = calculate_committer_authline();
859 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
861 confess "internal error" unless $build eq (pop @processed)->{CommitId};
864 mkdir $rd or $!==EEXIST or die $!;
866 runcmd @git, qw(read-tree), $build;
867 foreach my $cl (qw(Debian), (reverse @brw_cl),
868 { SpecialMethod => 'RecordBreakwaterTip' },
869 qw(Upstream), (reverse @upp_cl)) {
871 $current_method = $cl;
874 my $method = $cl->{SpecialMethod} // $current_method;
875 my @parents = ($build);
876 my $cltree = $cl->{CommitId};
877 printdebug "WALK BUILD ".($cltree//'undef').
878 " $method (rewriting=$rewriting)\n";
879 if ($method eq 'Debian') {
880 $read_tree_debian->($cltree);
881 } elsif ($method eq 'Upstream') {
882 $read_tree_upstream->($cltree);
883 } elsif ($method eq 'StartRewrite') {
886 } elsif ($method eq 'RecordBreakwaterTip') {
887 $breakwater = $build;
889 } elsif ($method eq 'DgitImportDebianUpdate') {
890 $read_tree_debian->($cltree);
891 } elsif ($method eq 'DgitImportUpstreamUpdate') {
892 confess unless $rewriting;
893 my $differs = (get_differs $build, $cltree);
894 next unless $differs & D_UPS;
895 $read_tree_upstream->($cltree);
896 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
901 my $procd = (pop @processed) // 'UNDEF';
904 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
907 my $newtree = cmdoutput @git, qw(write-tree);
909 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
910 $ch =~ s{^parent .*\n}{}mg;
911 $ch =~ s{(?=^author)}{
912 join '', map { "parent $_\n" } @parents
913 }me or confess "$ch ?";
915 $ch =~ s{^committer .*$}{$committer_authline}m
918 my $cf = "$rd/m$rewriting";
919 open CD, ">", $cf or die $!;
920 print CD $ch, "\n", $cl->{Msg} or die $!;
922 my @cmd = (@git, qw(hash-object));
923 push @cmd, qw(-w) if $rewriting;
924 push @cmd, qw(-t commit), $cf;
925 my $newcommit = cmdoutput @cmd;
926 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
928 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
934 my $final_check = get_differs $build, $input;
935 die sprintf "internal error %#x %s %s", $final_check, $build, $input
936 if $final_check & ~D_PAT_ADD;
938 my @r = ($build, $breakwater, $last_anchor);
939 printdebug "*** WALK RETURN @r\n";
944 git_check_unmodified();
945 return git_rev_parse qw(HEAD);
948 sub update_head ($$$) {
949 my ($old, $new, $mrest) = @_;
950 push @deferred_updates, "update HEAD $new $old";
951 run_deferred_updates $mrest;
954 sub update_head_checkout ($$$) {
955 my ($old, $new, $mrest) = @_;
956 update_head $old, $new, $mrest;
957 runcmd @git, qw(reset --hard);
960 sub update_head_postlaunder ($$$) {
961 my ($old, $tip, $reflogmsg) = @_;
962 return if $tip eq $old;
963 print "git-debrebase: laundered (head was $old)\n";
964 update_head $old, $tip, $reflogmsg;
965 # no tree changes except debian/patches
966 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
969 sub do_launder_head ($) {
970 my ($reflogmsg) = @_;
971 my $old = get_head();
973 my ($tip,$breakwater) = walk $old;
975 update_head_postlaunder $old, $tip, $reflogmsg;
976 return ($tip,$breakwater);
979 sub cmd_launder_v0 () {
980 badusage "no arguments to launder-v0 allowed" if @ARGV;
981 my $old = get_head();
982 my ($tip,$breakwater,$last_anchor) = walk $old;
983 update_head_postlaunder $old, $tip, 'launder';
984 printf "# breakwater tip\n%s\n", $breakwater;
985 printf "# working tip\n%s\n", $tip;
986 printf "# last anchor\n%s\n", $last_anchor;
989 sub defaultcmd_rebase () {
990 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
991 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
992 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
996 badusage "analyse does not support any options"
997 if @ARGV and $ARGV[0] =~ m/^-/;
998 badusage "too many arguments to analyse" if @ARGV>1;
1001 $old = git_rev_parse $old;
1003 $old = git_rev_parse 'HEAD';
1005 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1006 STDOUT->error and die $!;
1009 sub ffq_prev_branchinfo () {
1010 my $current = git_get_symref();
1011 return gdr_ffq_prev_branchinfo($current);
1014 sub ffq_check ($;$$) {
1015 # calls $ff and/or $notff zero or more times
1016 # then returns either (status,message) where status is
1021 # or (undef,undef, $ffq_prev,$gdrlast)
1022 # $ff and $notff are called like this:
1023 # $ff->("message for stdout\n");
1024 # $notff->('snag-name', $message);
1025 # normally $currentval should be HEAD
1026 my ($currentval, $ff, $notff) =@_;
1028 $ff //= sub { print $_[0] or die $!; };
1031 my ($status, $message, $current, $ffq_prev, $gdrlast)
1032 = ffq_prev_branchinfo();
1033 return ($status, $message) unless $status eq 'branch';
1035 my $exists = git_get_ref $ffq_prev;
1036 return ('exists',"$ffq_prev already exists") if $exists;
1038 return ('not-branch', 'HEAD symref is not to refs/heads/')
1039 unless $current =~ m{^refs/heads/};
1042 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1045 printdebug "ffq check_specs @check_specs\n";
1048 my ($lrref, $desc) = @_;
1049 printdebug "ffq might check $lrref ($desc)\n";
1051 for my $chk (@check_specs) {
1053 $invert = $glob =~ s{^[!^]}{};
1054 last if fnmatch $glob, $lrref;
1057 my $lrval = git_get_ref $lrref;
1058 return unless length $lrval;
1060 if (is_fast_fwd $lrval, $currentval) {
1061 $ff->("OK, you are ahead of $lrref\n");
1062 $checked{$lrref} = 1;
1063 } elsif (is_fast_fwd $currentval, $lrval) {
1064 $checked{$lrref} = -1;
1065 $notff->('behind', "you are behind $lrref, divergence risk");
1067 $checked{$lrref} = -1;
1068 $notff->('diverged', "you have diverged from $lrref");
1072 my $merge = cfg "branch.$branch.merge",1;
1073 if (defined $merge and $merge =~ m{^refs/heads/}) {
1075 printdebug "ffq merge $rhs\n";
1076 my $check_remote = sub {
1077 my ($remote, $desc) = @_;
1078 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1079 return unless defined $remote;
1080 $check->("refs/remotes/$remote/$rhs", $desc);
1082 $check_remote->((scalar cfg "branch.$branch.remote",1),
1083 'remote fetch/merge branch');
1084 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1085 (scalar cfg "branch.$branch.pushDefault",1),
1086 'remote push branch');
1088 if ($branch =~ m{^dgit/}) {
1089 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1090 } elsif ($branch =~ m{^master$}) {
1091 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1093 return (undef, undef, $ffq_prev, $gdrlast);
1096 sub record_ffq_prev_deferred () {
1097 # => ('status', "message")
1099 # deferred message is undef
1104 # if not ff from some branch we should be ff from, is an snag
1105 # if "deferred", will have added something about that to
1106 # @deferred_update_messages, and also maybe printed (already)
1107 # some messages about ff checks
1108 my $currentval = get_head();
1110 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1111 return ($status,$message) if defined $status;
1115 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1116 push @deferred_updates, "delete $gdrlast";
1117 push @deferred_update_messages, "Recorded current head for preservation";
1118 return ('deferred', undef);
1121 sub record_ffq_auto () {
1122 my ($status, $message) = record_ffq_prev_deferred();
1123 if ($status eq 'deferred' || $status eq 'exists') {
1125 snag $status, "could not record ffq-prev: $message";
1130 sub ffq_prev_info () {
1131 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1132 my ($status, $message, $current, $ffq_prev, $gdrlast)
1133 = ffq_prev_branchinfo();
1134 if ($status ne 'branch') {
1135 snag $status, "could not check ffq-prev: $message";
1138 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1139 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1142 sub stitch ($$$$$) {
1143 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1145 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1147 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1148 my $differs = get_differs $old_head, $ffq_prev_commitish;
1149 unless ($differs & ~D_PAT_ADD) {
1150 # ffq-prev is ahead of us, and the only tree changes it has
1151 # are possibly addition of things in debian/patches/.
1152 # Just wind forwards rather than making a pointless pseudomerge.
1153 push @deferred_updates,
1154 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1155 update_head_checkout $old_head, $ffq_prev_commitish,
1156 "stitch (fast forward)";
1161 # We make pseudomerges with L as the contributing parent.
1162 # This makes git rev-list --first-parent work properly.
1163 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1164 'Declare fast forward / record previous work',
1165 "[git-debrebase pseudomerge: $prose]",
1167 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1168 update_head $old_head, $new_head, "stitch: $prose";
1171 sub do_stitch ($;$) {
1172 my ($prose, $unclean) = @_;
1174 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1175 if (!$ffq_prev_commitish) {
1176 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1179 my $dangling_head = get_head();
1181 keycommits $dangling_head, $unclean,$unclean,$unclean;
1184 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1187 sub resolve_upstream_version ($$) {
1188 my ($new_upstream, $version) = @_;
1190 my $new_upstream_version = "$version";
1191 $new_upstream_version =~ s/-.*?$//;;
1193 if (!defined $new_upstream) {
1195 # todo: at some point maybe use git-deborig to do this
1196 foreach my $tagpfx ('', 'v', 'upstream/') {
1197 my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1198 $new_upstream = git_get_ref "refs/tags/$tag";
1199 last if length $new_upstream;
1202 if (!length $new_upstream) {
1203 fail "Could not determine appropriate upstream commitish.\n".
1204 " (Tried these tags: @tried)\n".
1205 " Check version, and specify upstream commitish explicitly.";
1208 $new_upstream = git_rev_parse $new_upstream;
1210 return ($new_upstream, $new_upstream_version);
1213 sub cmd_new_upstream () {
1214 # automatically and unconditionally launders before rebasing
1215 # if rebase --abort is used, laundering has still been done
1219 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1221 # parse args - low commitment
1222 my $spec_version = shift @ARGV;
1223 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1224 fail "bad version number \`$spec_version'" unless defined $new_version;
1225 if ($new_version->is_native()) {
1226 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1229 my $new_upstream = shift @ARGV;
1230 my $new_upstream_version;
1231 ($new_upstream, $new_upstream_version) =
1232 resolve_upstream_version $new_upstream, $new_version;
1237 my ($n, @x) = @_; # may be ''
1238 my $pc = $pieces{$n} //= {
1240 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1242 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1247 my $newpiece = sub {
1248 my ($n, @x) = @_; # may be ''
1249 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1250 push @newpieces, $pc;
1255 New => $new_upstream,
1257 while (@ARGV && $ARGV[0] !~ m{^-}) {
1258 my $n = shift @ARGV;
1260 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1261 unless @ARGV && $ARGV[0] !~ m{^-};
1263 my $c = git_rev_parse shift @ARGV;
1264 die unless $n =~ m/^$extra_orig_namepart_re$/;
1265 $newpiece->($n, New => $c);
1268 # now we need to investigate the branch this generates the
1269 # laundered version but we don't switch to it yet
1270 my $old_head = get_head();
1271 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1273 my $old_bw_cl = classify $old_bw;
1274 my $old_anchor_cl = classify $old_anchor;
1276 if (!$old_anchor_cl->{OrigParents}) {
1277 snag 'anchor-treated',
1278 'old anchor is recognised due to --anchor, cannot check upstream';
1280 $old_upstream = parsecommit
1281 $old_anchor_cl->{OrigParents}[0]{CommitId};
1282 $piece->('', Old => $old_upstream->{CommitId});
1285 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1286 if ($old_upstream->{Msg} =~
1287 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1289 my @oldpieces = (split / /, $1);
1290 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1291 if ($old_n_parents != @oldpieces &&
1292 $old_n_parents != @oldpieces + 1) {
1293 snag 'upstream-confusing', sprintf
1294 "previous upstream combine %s".
1295 " mentions %d pieces (each implying one parent)".
1296 " but has %d parents".
1297 " (one per piece plus maybe a previous combine)",
1298 $old_upstream->{CommitId},
1299 (scalar @oldpieces),
1301 } elsif ($oldpieces[0] ne '.') {
1302 snag 'upstream-confusing', sprintf
1303 "previous upstream combine %s".
1304 " first piece is not \`.'",
1308 foreach my $i (0..$#oldpieces) {
1309 my $n = $oldpieces[$i];
1310 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1311 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1315 snag 'upstream-confusing',
1316 "previous upstream $old_upstream->{CommitId} is from".
1317 " git-debrebase but not an \`upstream-combine' commit";
1321 foreach my $pc (values %pieces) {
1322 if (!$old_upstream) {
1323 # we have complained already
1324 } elsif (!$pc->{Old}) {
1325 snag 'upstream-new-piece',
1326 "introducing upstream piece \`$pc->{Name}'";
1327 } elsif (!$pc->{New}) {
1328 snag 'upstream-rm-piece',
1329 "dropping upstream piece \`$pc->{Name}'";
1330 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1331 snag 'upstream-not-ff',
1332 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1336 printdebug "%pieces = ", (dd \%pieces), "\n";
1337 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1345 my @upstream_merge_parents;
1348 push @upstream_merge_parents, $old_upstream->{CommitId};
1351 foreach my $pc (@newpieces) { # always has '' first
1353 read_tree_subdir $pc->{Name}, $pc->{New};
1355 runcmd @git, qw(read-tree), $pc->{New};
1357 push @upstream_merge_parents, $pc->{New};
1360 # index now contains the new upstream
1362 if (@newpieces > 1) {
1363 # need to make the upstream subtree merge commit
1364 $new_upstream = make_commit \@upstream_merge_parents,
1365 [ "Combine upstreams for $new_upstream_version",
1366 ("[git-debrebase upstream-combine . ".
1367 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1372 # $new_upstream is either the single upstream commit, or the
1373 # combined commit we just made. Either way it will be the
1374 # "upstream" parent of the anchor merge.
1376 read_tree_subdir 'debian', "$old_bw:debian";
1378 # index now contains the anchor merge contents
1379 $new_bw = make_commit [ $old_bw, $new_upstream ],
1380 [ "Update to upstream $new_upstream_version",
1381 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1384 my $clogsignoff = cmdoutput qw(git show),
1385 '--pretty=format:%an <%ae> %aD',
1388 # Now we have to add a changelog stanza so the Debian version
1390 die if unlink "debian";
1391 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1392 unlink "debian/changelog" or $!==ENOENT or die $!;
1393 mkdir "debian" or die $!;
1394 open CN, ">", "debian/changelog" or die $!;
1395 my $oldclog = git_cat_file ":debian/changelog";
1396 $oldclog =~ m/^($package_re) \(\S+\) / or
1397 fail "cannot parse old changelog to get package name";
1399 print CN <<END, $oldclog or die $!;
1400 $p ($new_version) UNRELEASED; urgency=medium
1402 * Update to new upstream version $new_upstream_version.
1408 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1410 # Now we have the final new breakwater branch in the index
1411 $new_bw = make_commit [ $new_bw ],
1412 [ "Update changelog for new upstream $new_upstream_version",
1413 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1417 # we have constructed the new breakwater. we now need to commit to
1418 # the laundering output, because git-rebase can't easily be made
1419 # to make a replay list which is based on some other branch
1421 update_head_postlaunder $old_head, $old_laundered_tip,
1422 'launder for new upstream';
1424 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1425 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1426 "debrebase new-upstream $new_version: rebase";
1428 # now it's for the user to sort out
1431 sub cmd_record_ffq_prev () {
1432 badusage "no arguments allowed" if @ARGV;
1433 my ($status, $msg) = record_ffq_prev_deferred();
1434 if ($status eq 'exists' && $opt_noop_ok) {
1435 print "Previous head already recorded\n" or die $!;
1436 } elsif ($status eq 'deferred') {
1437 run_deferred_updates 'record-ffq-prev';
1439 fail "Could not preserve: $msg";
1444 badusage "no arguments allowed" if @ARGV;
1445 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1446 print "$bw\n" or die $!;
1449 sub cmd_breakwater () {
1450 badusage "no arguments allowed" if @ARGV;
1451 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1452 print "$bw\n" or die $!;
1456 badusage "no arguments allowed" if @ARGV;
1458 # todo: gdr status should print divergence info
1459 # todo: gdr status should print upstream component(s) info
1460 # todo: gdr should leave/maintain some refs with this kind of info ?
1462 my $oldest = { Badness => 0 };
1465 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1466 if ($oldest->{Badness} < $badness) {
1467 $oldest = $newest = undef;
1470 Badness => $badness,
1471 CommitId => $cl->{CommitId},
1475 $newest //= $oldest;
1477 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1478 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1479 sub { $note->(2, 'branch is unlaundered', @_); },
1480 sub { $note->(3, 'branch needs laundering', @_); },
1481 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1483 my $prcommitinfo = sub {
1485 flush STDOUT or die $!;
1486 runcmd @git, qw(--no-pager log -n1),
1487 '--pretty=format: %h %s%n',
1491 print "current branch contents, in git-debrebase terms:\n";
1492 if (!$oldest->{Badness}) {
1493 print " branch is laundered\n";
1495 print " $oldest->{OurMsg}\n";
1497 foreach my $info ($oldest, $newest) {
1498 my $cid = $info->{CommitId};
1499 next if $cid eq $printed;
1501 print " $info->{KcMsg}\n";
1502 $prcommitinfo->($cid);
1507 my ($cid, $what) = @_;
1508 if (!defined $cid) {
1509 print " $what is not well-defined\n";
1512 $prcommitinfo->($cid);
1515 print "key git-debrebase commits:\n";
1516 $prab->($anchor, 'anchor');
1517 $prab->($bw, 'breakwater');
1519 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1520 ffq_prev_branchinfo();
1522 print "branch and ref status, in git-debrebase terms:\n";
1524 print " $ffq_msg\n";
1526 $ffq_prev = git_get_ref $ffq_prev;
1527 $gdrlast = git_get_ref $gdrlast;
1529 print " unstitched; previous tip was:\n";
1530 $prcommitinfo->($ffq_prev);
1531 } elsif (!$gdrlast) {
1532 print " stitched? (no record of git-debrebase work)\n";
1533 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1534 print " stitched\n";
1536 print " not git-debrebase (diverged since last stitch)\n"
1542 my $prose = 'stitch';
1543 getoptions("stitch",
1544 'prose=s', \$prose);
1545 badusage "no arguments allowed" if @ARGV;
1546 do_stitch $prose, 0;
1548 sub cmd_prepush () { cmd_stitch(); }
1551 badusage "no arguments allowed" if @ARGV;
1552 do_launder_head 'launder for git-debrebase quick';
1556 sub cmd_conclude () {
1557 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1558 if (!$ffq_prev_commitish) {
1559 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1562 my $dangling_head = get_head();
1564 badusage "no arguments allowed" if @ARGV;
1565 do_launder_head 'launder for git-debrebase quick';
1569 sub make_patches_staged ($) {
1571 # Produces the patches that would result from $head if it were
1573 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1576 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1577 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1578 my @gbp_cmd = (qw(gbp pq export));
1579 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1581 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1584 runcmd @git, qw(add -f debian/patches);
1588 sub make_patches ($) {
1590 keycommits $head, 0, \&snag;
1591 make_patches_staged $head;
1594 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1595 runcmd @git, qw(read-tree), $head;
1596 read_tree_subdir 'debian/patches', $ptree;
1597 $out = make_commit [$head], [
1598 'Commit patch queue (exported by git-debrebase)',
1599 '[git-debrebase: export and commit patches]',
1605 sub cmd_make_patches () {
1606 my $opt_quiet_would_amend;
1607 getoptions("make-patches",
1608 'quiet-would-amend!', \$opt_quiet_would_amend);
1609 badusage "no arguments allowed" if @ARGV;
1610 my $old_head = get_head();
1611 my $new = make_patches $old_head;
1612 my $d = get_differs $old_head, $new;
1614 fail "No (more) patches to export." unless $opt_noop_ok;
1616 } elsif ($d == D_PAT_ADD) {
1618 update_head_checkout $old_head, $new, 'make-patches';
1620 print STDERR failmsg
1621 "Patch export produced patch amendments".
1622 " (abandoned output commit $new).".
1623 " Try laundering first."
1624 unless $opt_quiet_would_amend;
1629 sub cmd_convert_from_gbp () {
1630 badusage "want only 1 optional argument, the upstream git commitish"
1633 my $clogp = parsechangelog();
1634 my $version = $clogp->{'Version'}
1635 // die "missing Version from changelog";
1637 my ($upstream_spec) = @ARGV;
1639 my ($upstream, $upstream_version) =
1640 resolve_upstream_version($upstream_spec, $version);
1642 my $old_head = get_head();
1644 my $upsdiff = get_differs $upstream, $old_head;
1645 if ($upsdiff & D_UPS) {
1646 runcmd @git, qw(--no-pager diff --stat),
1647 $upstream, $old_head,
1648 qw( -- :!/debian :/);
1650 upstream ($upstream_spec) and HEAD are not
1651 identical in upstream files. See diffstat above, or run
1652 git diff $upstream_spec HEAD -- :!/debian :/
1656 if (!is_fast_fwd $upstream, $old_head) {
1657 snag 'upstream-not-ancestor',
1658 "upstream ($upstream) is not an ancestor of HEAD";
1660 my $wrong = cmdoutput
1661 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1662 qw(-- :/ :!/debian));
1663 if (length $wrong) {
1664 snag 'unexpected-upstream-changes',
1665 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1666 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1670 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1671 snag 'upstream-has-debian',
1672 "upstream ($upstream) contains debian/ directory";
1675 my $previous_dgit_view = eval {
1676 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1678 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1679 my ($stz, $desc) = @_;
1680 no warnings qw(exiting);
1681 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1682 next unless $stz->{Date};
1683 next unless $stz->{Distribution} ne 'UNRELEASED';
1684 $lvsn = $stz->{Version};
1685 $suite = $stz->{Distribution};
1688 die "neither of the first two changelog entries are released\n"
1689 unless defined $lvsn;
1690 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1691 my $mtag_pat = debiantag_maintview $lvsn, '*';
1692 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1694 die "could not find suitable maintainer view tag $mtag_pat\n"
1695 unless $mtag_pat =~ m{/};
1696 is_fast_fwd $mtag, 'HEAD' or
1697 die "HEAD is not FF from maintainer tag $mtag!";
1698 my $dtag = "archive/$mtag";
1699 is_fast_fwd $mtag, $dtag or
1700 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1701 print "will stitch in dgit view, $dtag\n";
1702 git_rev_parse $dtag;
1704 if (!$previous_dgit_view) {
1707 print STDERR "cannot stitch in dgit view: $@\n";
1710 snags_maybe_bail_early();
1716 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1717 # make a branch out of the patch queue - we'll want this in a mo
1718 runcmd qw(gbp pq import);
1719 # strip the patches out
1720 runcmd @git, qw(checkout -q gdr-internal~0);
1721 rm_subdir_cached 'debian/patches';
1722 $work = make_commit ['HEAD'], [
1723 'git-debrebase convert-from-gbp: drop patches from tree',
1724 'Delete debian/patches, as part of converting to git-debrebase format.',
1725 '[git-debrebase convert-from-gbp: drop patches from tree]'
1727 # make the anchor merge
1728 # the tree is already exactly right
1729 $work = make_commit [$work, $upstream], [
1730 'git-debrebase import: declare upstream',
1731 'First breakwater merge.',
1732 '[git-debrebase anchor: declare upstream]'
1735 # rebase the patch queue onto the new breakwater
1736 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1737 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1738 $work = git_rev_parse 'HEAD';
1740 if ($previous_dgit_view) {
1741 $work = make_commit [$work, $previous_dgit_view], [
1742 'git-debrebase import: declare ff from dgit archive view',
1743 '[git-debrebase pseudomerge: import-from-gbp]',
1750 update_head_checkout $old_head, $work, 'convert-from-gbp';
1753 sub cmd_convert_to_gbp () {
1754 badusage "no arguments allowed" if @ARGV;
1755 my $head = get_head();
1756 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1757 keycommits $head, 0;
1759 make_patches_staged $head;
1761 $out = make_commit ['HEAD'], [
1762 'Commit patch queue (converted from git-debrebase format)',
1763 '[git-debrebase convert-to-gbp: commit patches]',
1767 push @deferred_updates, "delete $ffq";
1768 push @deferred_updates, "delete $gdrlast";
1771 update_head_checkout $head, $out, "convert to gbp (v0)";
1772 print <<END or die $!;
1773 git-debrebase: converted to git-buildpackage branch format
1774 git-debrebase: WARNING: do not now run "git-debrebase" any more
1775 git-debrebase: WARNING: doing so would drop all upstream patches!
1779 sub cmd_downstream_rebase_launder_v0 () {
1780 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1782 $base = git_rev_parse $base;
1783 my $old_head = get_head();
1784 my $current = $old_head;
1787 if ($current eq $base) {
1788 $topmost_keep //= $current;
1789 print " $current BASE stop\n";
1792 my $cl = classify $current;
1793 print " $current $cl->{Type}";
1795 my $p0 = $cl->{Parents}[0]{CommitId};
1797 if ($cl->{Type} eq 'Pseudomerge') {
1798 print " ^".($cl->{Contributor}{Ix}+1);
1799 $next = $cl->{Contributor}{CommitId};
1800 } elsif ($cl->{Type} eq 'AddPatches' or
1801 $cl->{Type} eq 'Changelog') {
1811 $topmost_keep //= $current;
1813 die "to-be stripped changes not on top of the branch\n"
1818 if ($topmost_keep eq $old_head) {
1819 print "unchanged\n";
1821 print "updating to $topmost_keep\n";
1822 update_head_checkout
1823 $old_head, $topmost_keep,
1824 'downstream-rebase-launder-v0';
1830 "D+" => \$debuglevel,
1831 'noop-ok', => \$opt_noop_ok,
1832 'f=s' => \@snag_force_opts,
1833 'anchor=s' => \@opt_anchors,
1836 my ($opt,$val) = @_;
1837 badusage "git-debrebase: no cuddling to -i for git-rebase"
1839 die if $opt_defaultcmd_interactive; # should not happen
1840 $opt_defaultcmd_interactive = [ qw(-i) ];
1841 # This access to @ARGV is excessive familiarity with
1842 # Getopt::Long, but there isn't another sensible
1843 # approach. '-i=s{0,}' does not work with bundling.
1844 push @$opt_defaultcmd_interactive, @ARGV;
1847 'help' => sub { print $usage_message or die $!; finish 0; },
1850 initdebug('git-debrebase ');
1851 enabledebug if $debuglevel;
1853 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1854 chdir $toplevel or die "chdir $toplevel: $!";
1856 $rd = fresh_playground "$playprefix/misc";
1858 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1860 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1861 defaultcmd_rebase();
1863 my $cmd = shift @ARGV;
1866 $cmdfn = ${*::}{"cmd_$cmdfn"};
1868 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";