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 = upstreamversion $version;
1192 if (!defined $new_upstream) {
1194 # todo: at some point maybe use git-deborig to do this
1195 foreach my $tagpfx ('', 'v', 'upstream/') {
1196 my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1197 $new_upstream = git_get_ref "refs/tags/$tag";
1198 last if length $new_upstream;
1201 if (!length $new_upstream) {
1202 fail "Could not determine appropriate upstream commitish.\n".
1203 " (Tried these tags: @tried)\n".
1204 " Check version, and specify upstream commitish explicitly.";
1207 $new_upstream = git_rev_parse $new_upstream;
1209 return ($new_upstream, $new_upstream_version);
1212 sub cmd_new_upstream () {
1213 # automatically and unconditionally launders before rebasing
1214 # if rebase --abort is used, laundering has still been done
1218 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1220 # parse args - low commitment
1221 my $spec_version = shift @ARGV;
1222 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1223 fail "bad version number \`$spec_version'" unless defined $new_version;
1224 if ($new_version->is_native()) {
1225 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1228 my $new_upstream = shift @ARGV;
1229 my $new_upstream_version;
1230 ($new_upstream, $new_upstream_version) =
1231 resolve_upstream_version $new_upstream, $new_version;
1236 my ($n, @x) = @_; # may be ''
1237 my $pc = $pieces{$n} //= {
1239 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1241 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1246 my $newpiece = sub {
1247 my ($n, @x) = @_; # may be ''
1248 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1249 push @newpieces, $pc;
1254 New => $new_upstream,
1256 while (@ARGV && $ARGV[0] !~ m{^-}) {
1257 my $n = shift @ARGV;
1259 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1260 unless @ARGV && $ARGV[0] !~ m{^-};
1262 my $c = git_rev_parse shift @ARGV;
1263 die unless $n =~ m/^$extra_orig_namepart_re$/;
1264 $newpiece->($n, New => $c);
1267 # now we need to investigate the branch this generates the
1268 # laundered version but we don't switch to it yet
1269 my $old_head = get_head();
1270 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1272 my $old_bw_cl = classify $old_bw;
1273 my $old_anchor_cl = classify $old_anchor;
1275 if (!$old_anchor_cl->{OrigParents}) {
1276 snag 'anchor-treated',
1277 'old anchor is recognised due to --anchor, cannot check upstream';
1279 $old_upstream = parsecommit
1280 $old_anchor_cl->{OrigParents}[0]{CommitId};
1281 $piece->('', Old => $old_upstream->{CommitId});
1284 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1285 if ($old_upstream->{Msg} =~
1286 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1288 my @oldpieces = (split / /, $1);
1289 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1290 if ($old_n_parents != @oldpieces &&
1291 $old_n_parents != @oldpieces + 1) {
1292 snag 'upstream-confusing', sprintf
1293 "previous upstream combine %s".
1294 " mentions %d pieces (each implying one parent)".
1295 " but has %d parents".
1296 " (one per piece plus maybe a previous combine)",
1297 $old_upstream->{CommitId},
1298 (scalar @oldpieces),
1300 } elsif ($oldpieces[0] ne '.') {
1301 snag 'upstream-confusing', sprintf
1302 "previous upstream combine %s".
1303 " first piece is not \`.'",
1307 foreach my $i (0..$#oldpieces) {
1308 my $n = $oldpieces[$i];
1309 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1310 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1314 snag 'upstream-confusing',
1315 "previous upstream $old_upstream->{CommitId} is from".
1316 " git-debrebase but not an \`upstream-combine' commit";
1320 foreach my $pc (values %pieces) {
1321 if (!$old_upstream) {
1322 # we have complained already
1323 } elsif (!$pc->{Old}) {
1324 snag 'upstream-new-piece',
1325 "introducing upstream piece \`$pc->{Name}'";
1326 } elsif (!$pc->{New}) {
1327 snag 'upstream-rm-piece',
1328 "dropping upstream piece \`$pc->{Name}'";
1329 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1330 snag 'upstream-not-ff',
1331 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1335 printdebug "%pieces = ", (dd \%pieces), "\n";
1336 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1344 my @upstream_merge_parents;
1347 push @upstream_merge_parents, $old_upstream->{CommitId};
1350 foreach my $pc (@newpieces) { # always has '' first
1352 read_tree_subdir $pc->{Name}, $pc->{New};
1354 runcmd @git, qw(read-tree), $pc->{New};
1356 push @upstream_merge_parents, $pc->{New};
1359 # index now contains the new upstream
1361 if (@newpieces > 1) {
1362 # need to make the upstream subtree merge commit
1363 $new_upstream = make_commit \@upstream_merge_parents,
1364 [ "Combine upstreams for $new_upstream_version",
1365 ("[git-debrebase upstream-combine . ".
1366 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1371 # $new_upstream is either the single upstream commit, or the
1372 # combined commit we just made. Either way it will be the
1373 # "upstream" parent of the anchor merge.
1375 read_tree_subdir 'debian', "$old_bw:debian";
1377 # index now contains the anchor merge contents
1378 $new_bw = make_commit [ $old_bw, $new_upstream ],
1379 [ "Update to upstream $new_upstream_version",
1380 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1383 my $clogsignoff = cmdoutput qw(git show),
1384 '--pretty=format:%an <%ae> %aD',
1387 # Now we have to add a changelog stanza so the Debian version
1389 die if unlink "debian";
1390 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1391 unlink "debian/changelog" or $!==ENOENT or die $!;
1392 mkdir "debian" or die $!;
1393 open CN, ">", "debian/changelog" or die $!;
1394 my $oldclog = git_cat_file ":debian/changelog";
1395 $oldclog =~ m/^($package_re) \(\S+\) / or
1396 fail "cannot parse old changelog to get package name";
1398 print CN <<END, $oldclog or die $!;
1399 $p ($new_version) UNRELEASED; urgency=medium
1401 * Update to new upstream version $new_upstream_version.
1407 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1409 # Now we have the final new breakwater branch in the index
1410 $new_bw = make_commit [ $new_bw ],
1411 [ "Update changelog for new upstream $new_upstream_version",
1412 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1416 # we have constructed the new breakwater. we now need to commit to
1417 # the laundering output, because git-rebase can't easily be made
1418 # to make a replay list which is based on some other branch
1420 update_head_postlaunder $old_head, $old_laundered_tip,
1421 'launder for new upstream';
1423 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1424 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1425 "debrebase new-upstream $new_version: rebase";
1427 # now it's for the user to sort out
1430 sub cmd_record_ffq_prev () {
1431 badusage "no arguments allowed" if @ARGV;
1432 my ($status, $msg) = record_ffq_prev_deferred();
1433 if ($status eq 'exists' && $opt_noop_ok) {
1434 print "Previous head already recorded\n" or die $!;
1435 } elsif ($status eq 'deferred') {
1436 run_deferred_updates 'record-ffq-prev';
1438 fail "Could not preserve: $msg";
1443 badusage "no arguments allowed" if @ARGV;
1444 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1445 print "$bw\n" or die $!;
1448 sub cmd_breakwater () {
1449 badusage "no arguments allowed" if @ARGV;
1450 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1451 print "$bw\n" or die $!;
1455 badusage "no arguments allowed" if @ARGV;
1457 # todo: gdr status should print divergence info
1458 # todo: gdr status should print upstream component(s) info
1459 # todo: gdr should leave/maintain some refs with this kind of info ?
1461 my $oldest = { Badness => 0 };
1464 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1465 if ($oldest->{Badness} < $badness) {
1466 $oldest = $newest = undef;
1469 Badness => $badness,
1470 CommitId => $cl->{CommitId},
1474 $newest //= $oldest;
1476 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1477 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1478 sub { $note->(2, 'branch is unlaundered', @_); },
1479 sub { $note->(3, 'branch needs laundering', @_); },
1480 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1482 my $prcommitinfo = sub {
1484 flush STDOUT or die $!;
1485 runcmd @git, qw(--no-pager log -n1),
1486 '--pretty=format: %h %s%n',
1490 print "current branch contents, in git-debrebase terms:\n";
1491 if (!$oldest->{Badness}) {
1492 print " branch is laundered\n";
1494 print " $oldest->{OurMsg}\n";
1496 foreach my $info ($oldest, $newest) {
1497 my $cid = $info->{CommitId};
1498 next if $cid eq $printed;
1500 print " $info->{KcMsg}\n";
1501 $prcommitinfo->($cid);
1506 my ($cid, $what) = @_;
1507 if (!defined $cid) {
1508 print " $what is not well-defined\n";
1511 $prcommitinfo->($cid);
1514 print "key git-debrebase commits:\n";
1515 $prab->($anchor, 'anchor');
1516 $prab->($bw, 'breakwater');
1518 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1519 ffq_prev_branchinfo();
1521 print "branch and ref status, in git-debrebase terms:\n";
1523 print " $ffq_msg\n";
1525 $ffq_prev = git_get_ref $ffq_prev;
1526 $gdrlast = git_get_ref $gdrlast;
1528 print " unstitched; previous tip was:\n";
1529 $prcommitinfo->($ffq_prev);
1530 } elsif (!$gdrlast) {
1531 print " stitched? (no record of git-debrebase work)\n";
1532 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1533 print " stitched\n";
1535 print " not git-debrebase (diverged since last stitch)\n"
1541 my $prose = 'stitch';
1542 getoptions("stitch",
1543 'prose=s', \$prose);
1544 badusage "no arguments allowed" if @ARGV;
1545 do_stitch $prose, 0;
1547 sub cmd_prepush () { cmd_stitch(); }
1550 badusage "no arguments allowed" if @ARGV;
1551 do_launder_head 'launder for git-debrebase quick';
1555 sub cmd_conclude () {
1556 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1557 if (!$ffq_prev_commitish) {
1558 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1561 my $dangling_head = get_head();
1563 badusage "no arguments allowed" if @ARGV;
1564 do_launder_head 'launder for git-debrebase quick';
1568 sub make_patches_staged ($) {
1570 # Produces the patches that would result from $head if it were
1572 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1575 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1576 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1577 my @gbp_cmd = (qw(gbp pq export));
1578 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1580 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1583 runcmd @git, qw(add -f debian/patches);
1587 sub make_patches ($) {
1589 keycommits $head, 0, \&snag;
1590 make_patches_staged $head;
1593 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1594 runcmd @git, qw(read-tree), $head;
1595 read_tree_subdir 'debian/patches', $ptree;
1596 $out = make_commit [$head], [
1597 'Commit patch queue (exported by git-debrebase)',
1598 '[git-debrebase: export and commit patches]',
1604 sub cmd_make_patches () {
1605 my $opt_quiet_would_amend;
1606 getoptions("make-patches",
1607 'quiet-would-amend!', \$opt_quiet_would_amend);
1608 badusage "no arguments allowed" if @ARGV;
1609 my $old_head = get_head();
1610 my $new = make_patches $old_head;
1611 my $d = get_differs $old_head, $new;
1613 fail "No (more) patches to export." unless $opt_noop_ok;
1615 } elsif ($d == D_PAT_ADD) {
1617 update_head_checkout $old_head, $new, 'make-patches';
1619 print STDERR failmsg
1620 "Patch export produced patch amendments".
1621 " (abandoned output commit $new).".
1622 " Try laundering first."
1623 unless $opt_quiet_would_amend;
1628 sub cmd_convert_from_gbp () {
1629 badusage "want only 1 optional argument, the upstream git commitish"
1632 my $clogp = parsechangelog();
1633 my $version = $clogp->{'Version'}
1634 // die "missing Version from changelog";
1636 my ($upstream_spec) = @ARGV;
1638 my ($upstream, $upstream_version) =
1639 resolve_upstream_version($upstream_spec, $version);
1641 my $old_head = get_head();
1643 my $upsdiff = get_differs $upstream, $old_head;
1644 if ($upsdiff & D_UPS) {
1645 runcmd @git, qw(--no-pager diff --stat),
1646 $upstream, $old_head,
1647 qw( -- :!/debian :/);
1649 upstream ($upstream_spec) and HEAD are not
1650 identical in upstream files. See diffstat above, or run
1651 git diff $upstream_spec HEAD -- :!/debian :/
1655 if (!is_fast_fwd $upstream, $old_head) {
1656 snag 'upstream-not-ancestor',
1657 "upstream ($upstream) is not an ancestor of HEAD";
1659 my $wrong = cmdoutput
1660 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1661 qw(-- :/ :!/debian));
1662 if (length $wrong) {
1663 snag 'unexpected-upstream-changes',
1664 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1665 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1669 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1670 snag 'upstream-has-debian',
1671 "upstream ($upstream) contains debian/ directory";
1674 my $previous_dgit_view = eval {
1675 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1677 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1678 my ($stz, $desc) = @_;
1679 no warnings qw(exiting);
1680 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1681 next unless $stz->{Date};
1682 next unless $stz->{Distribution} ne 'UNRELEASED';
1683 $lvsn = $stz->{Version};
1684 $suite = $stz->{Distribution};
1687 die "neither of the first two changelog entries are released\n"
1688 unless defined $lvsn;
1689 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1690 my $mtag_pat = debiantag_maintview $lvsn, '*';
1691 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1693 die "could not find suitable maintainer view tag $mtag_pat\n"
1694 unless $mtag_pat =~ m{/};
1695 is_fast_fwd $mtag, 'HEAD' or
1696 die "HEAD is not FF from maintainer tag $mtag!";
1697 my $dtag = "archive/$mtag";
1698 is_fast_fwd $mtag, $dtag or
1699 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1700 print "will stitch in dgit view, $dtag\n";
1701 git_rev_parse $dtag;
1703 if (!$previous_dgit_view) {
1706 print STDERR "cannot stitch in dgit view: $@\n";
1709 snags_maybe_bail_early();
1715 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1716 # make a branch out of the patch queue - we'll want this in a mo
1717 runcmd qw(gbp pq import);
1718 # strip the patches out
1719 runcmd @git, qw(checkout -q gdr-internal~0);
1720 rm_subdir_cached 'debian/patches';
1721 $work = make_commit ['HEAD'], [
1722 'git-debrebase convert-from-gbp: drop patches from tree',
1723 'Delete debian/patches, as part of converting to git-debrebase format.',
1724 '[git-debrebase convert-from-gbp: drop patches from tree]'
1726 # make the anchor merge
1727 # the tree is already exactly right
1728 $work = make_commit [$work, $upstream], [
1729 'git-debrebase import: declare upstream',
1730 'First breakwater merge.',
1731 '[git-debrebase anchor: declare upstream]'
1734 # rebase the patch queue onto the new breakwater
1735 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1736 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1737 $work = git_rev_parse 'HEAD';
1739 if ($previous_dgit_view) {
1740 $work = make_commit [$work, $previous_dgit_view], [
1741 'git-debrebase import: declare ff from dgit archive view',
1742 '[git-debrebase pseudomerge: import-from-gbp]',
1749 update_head_checkout $old_head, $work, 'convert-from-gbp';
1752 sub cmd_convert_to_gbp () {
1753 badusage "no arguments allowed" if @ARGV;
1754 my $head = get_head();
1755 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1756 keycommits $head, 0;
1758 make_patches_staged $head;
1760 $out = make_commit ['HEAD'], [
1761 'Commit patch queue (converted from git-debrebase format)',
1762 '[git-debrebase convert-to-gbp: commit patches]',
1766 push @deferred_updates, "delete $ffq";
1767 push @deferred_updates, "delete $gdrlast";
1770 update_head_checkout $head, $out, "convert to gbp (v0)";
1771 print <<END or die $!;
1772 git-debrebase: converted to git-buildpackage branch format
1773 git-debrebase: WARNING: do not now run "git-debrebase" any more
1774 git-debrebase: WARNING: doing so would drop all upstream patches!
1778 sub cmd_downstream_rebase_launder_v0 () {
1779 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1781 $base = git_rev_parse $base;
1782 my $old_head = get_head();
1783 my $current = $old_head;
1786 if ($current eq $base) {
1787 $topmost_keep //= $current;
1788 print " $current BASE stop\n";
1791 my $cl = classify $current;
1792 print " $current $cl->{Type}";
1794 my $p0 = $cl->{Parents}[0]{CommitId};
1796 if ($cl->{Type} eq 'Pseudomerge') {
1797 print " ^".($cl->{Contributor}{Ix}+1);
1798 $next = $cl->{Contributor}{CommitId};
1799 } elsif ($cl->{Type} eq 'AddPatches' or
1800 $cl->{Type} eq 'Changelog') {
1810 $topmost_keep //= $current;
1812 die "to-be stripped changes not on top of the branch\n"
1817 if ($topmost_keep eq $old_head) {
1818 print "unchanged\n";
1820 print "updating to $topmost_keep\n";
1821 update_head_checkout
1822 $old_head, $topmost_keep,
1823 'downstream-rebase-launder-v0';
1829 "D+" => \$debuglevel,
1830 'noop-ok', => \$opt_noop_ok,
1831 'f=s' => \@snag_force_opts,
1832 'anchor=s' => \@opt_anchors,
1835 my ($opt,$val) = @_;
1836 badusage "git-debrebase: no cuddling to -i for git-rebase"
1838 die if $opt_defaultcmd_interactive; # should not happen
1839 $opt_defaultcmd_interactive = [ qw(-i) ];
1840 # This access to @ARGV is excessive familiarity with
1841 # Getopt::Long, but there isn't another sensible
1842 # approach. '-i=s{0,}' does not work with bundling.
1843 push @$opt_defaultcmd_interactive, @ARGV;
1846 'help' => sub { print $usage_message or die $!; finish 0; },
1849 initdebug('git-debrebase ');
1850 enabledebug if $debuglevel;
1852 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1853 chdir $toplevel or die "chdir $toplevel: $!";
1855 $rd = fresh_playground "$playprefix/misc";
1857 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1859 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1860 defaultcmd_rebase();
1862 my $cmd = shift @ARGV;
1865 $cmdfn = ${*::}{"cmd_$cmdfn"};
1867 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";