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 ($opt_force, $opt_noop_ok, @opt_anchors);
40 our ($opt_defaultcmd_interactive);
42 our $us = qw(git-debrebase);
48 print STDERR "bad usage: $m\n";
53 my ($k, $optional) = @_;
55 my @cmd = qw(git config -z);
56 push @cmd, qw(--get-all) if wantarray;
58 my $out = cmdoutput_errok @cmd;
60 fail "missing required git config $k" unless $optional;
63 my @l = split /\0/, $out;
64 return wantarray ? @l : $l[0];
71 my $dd = new Data::Dumper [ $v ];
72 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
78 my $data = (git_cat_file $objid, 'commit');
79 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
83 sub D_UPS () { 0x02; } # upstream files
84 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
85 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
86 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
87 sub D_DEB_OTH () { 0x20; } # debian/changelog
88 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
90 our $playprefix = 'debrebase';
99 my $r = eval { $sub->(); };
100 { local $@; changedir $maindir; }
104 sub fresh_workarea () {
105 $workarea = fresh_playground "$playprefix/work";
106 in_workarea sub { playtree_setup };
109 our $snags_forced = 0;
110 our $snags_tripped = 0;
111 our $snags_summarised = 0;
112 our @deferred_updates;
113 our @deferred_update_messages;
115 sub all_snags_summarised () {
116 $snags_forced + $snags_tripped == $snags_summarised;
118 sub run_deferred_updates ($) {
121 confess 'dangerous internal error' unless all_snags_summarised();
123 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
124 debugcmd '>|', @upd_cmd;
125 open U, "|-", @upd_cmd or die $!;
126 foreach (@deferred_updates) {
127 printdebug ">= ", $_, "\n";
128 print U $_, "\n" or die $!;
131 close U or failedcmd @upd_cmd;
133 print $_, "\n" foreach @deferred_update_messages;
135 @deferred_updates = ();
136 @deferred_update_messages = ();
139 sub get_differs ($$) {
141 # This resembles quiltify_trees_differ, in dgit, a bit.
142 # But we don't care about modes, or dpkg-source-unrepresentable
143 # changes, and we don't need the plethora of different modes.
144 # Conversely we need to distinguish different kinds of changes to
145 # debian/ and debian/patches/.
150 my ($opts, $limits, $fn) = @_;
151 my @cmd = (@git, qw(diff-tree -z --no-renames));
153 push @cmd, "$_:" foreach $x, $y;
154 push @cmd, '--', @$limits;
155 my $diffs = cmdoutput @cmd;
156 foreach (split /\0/, $diffs) { $fn->(); }
159 $rundiff->([qw(--name-only)], [], sub {
160 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
163 if ($differs & DS_DEB) {
165 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
167 m{^debian/patches/} ? D_PAT_OTH :
168 $_ eq 'debian/changelog' ? D_DEB_CLOG :
171 die "mysterious debian changes $x..$y"
172 unless $differs & (D_PAT_OTH|DS_DEB);
175 if ($differs & D_PAT_OTH) {
177 $differs &= ~D_PAT_OTH;
179 $differs |= D_PAT_OTH;
180 no warnings qw(exiting); last;
182 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
183 no warnings qw(exiting);
184 if (!defined $mode) {
187 die unless s{^debian/patches/}{};
189 if ($mode eq 'A' && !m/\.series$/s) {
191 } elsif ($mode eq 'M' && $_ eq 'series') {
192 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
193 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
194 chomp $x_s; $x_s .= "\n";
195 $ok = $x_s eq substr($y_s, 0, length $x_s);
200 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
202 die "mysterious debian/patches changes $x..$y"
203 unless $differs & (D_PAT_ADD|D_PAT_OTH);
206 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
211 sub commit_pr_info ($) {
213 return Data::Dumper->dump([$r], [qw(commit)]);
216 sub calculate_committer_authline () {
217 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
218 'DUMMY COMMIT (git-debrebase)', "HEAD:";
219 my ($h,$m) = get_commit $c;
220 $h =~ m/^committer .*$/m or confess "($h) ?";
224 sub rm_subdir_cached ($) {
226 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
229 sub read_tree_subdir ($$) {
230 my ($subdir, $new_tree_object) = @_;
231 rm_subdir_cached $subdir;
232 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
235 sub make_commit ($$) {
236 my ($parents, $message_paras) = @_;
237 my $tree = cmdoutput @git, qw(write-tree);
238 my @cmd = (@git, qw(commit-tree), $tree);
239 push @cmd, qw(-p), $_ foreach @$parents;
240 push @cmd, qw(-m), $_ foreach @$message_paras;
241 return cmdoutput @cmd;
244 our @snag_force_opts;
246 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
247 if (grep { $_ eq $tag } @snag_force_opts) {
249 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
252 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
256 # Important: all mainline code must call snags_maybe_bail after
257 # any point where snag might be called, but before making changes
258 # (eg before any call to run_deferred_updates). snags_maybe_bail
259 # may be called more than once if necessary (but this is not ideal
260 # because then the messages about number of snags may be confusing).
261 sub snags_maybe_bail () {
262 return if all_snags_summarised();
265 "%s: snags: %d overriden by individual -f options\n",
268 if ($snags_tripped) {
271 "%s: snags: %d overriden by global --force\n",
275 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
279 $snags_summarised = $snags_forced + $snags_tripped;
281 sub snags_maybe_bail_early () {
282 # useful to bail out early without doing a lot of work;
283 # not a substitute for snags_maybe_bail.
284 snags_maybe_bail() if $snags_tripped && !$opt_force;
287 return $snags_forced || $snags_tripped;
290 # classify returns an info hash like this
292 # Hdr => # commit headers, including 1 final newline
293 # Msg => # commit message (so one newline is dropped)
295 # Type => (see below)
297 # Ix => $index # ie 0, 1, 2, ...
299 # Differs => return value from get_differs
301 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
303 # NewMsg => # commit message, but with any [dgit import ...] edited
304 # # to say "[was: ...]"
314 # has additional entres in classification result
315 # Overwritten = [ subset of Parents ]
316 # Contributor = $the_remaining_Parent
318 # DgitImportUnpatched
319 # has additional entry in classification result
320 # OrigParents = [ subset of Parents ]
323 # has additional entry in classification result
324 # OrigParents = [ subset of Parents ] # singleton list
331 # has additional entry in classification result
334 sub parsecommit ($;$) {
335 my ($objid, $p_ref) = @_;
336 # => hash with CommitId Hdr Msg Tree Parents
337 # Parents entries have only Ix CommitId
338 # $p_ref, if provided, must be [] and is used as a base for Parents
343 my ($h,$m) = get_commit $objid;
345 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
346 my (@ph) = $h =~ m/^parent (\w+)$/mg;
356 foreach my $ph (@ph) {
358 Ix => scalar @$p_ref,
370 my $r = parsecommit($objid, \@p);
374 $p->{Differs} = (get_differs $p->{CommitId}, $t),
377 printdebug "classify $objid \$t=$t \@p",
378 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
382 my ($type, @rest) = @_;
383 $r = { %$r, Type => $type, @rest };
385 printdebug " = $type ".(dd $r)."\n";
391 $r = { %$r, Type => qw(Unknown), Why => $why };
392 printdebug " ** Unknown\n";
396 if (grep { $_ eq $objid } @opt_anchors) {
397 return $classify->('TreatAsAnchor');
400 my @identical = grep { !$_->{Differs} } @p;
401 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
402 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
404 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
405 # multi-orig upstreams are represented with an anchor merge
406 # from a single upstream commit which combines the orig tarballs
408 # Every anchor tagged this way must be a merge.
409 # We are relying on the
410 # [git-debrebase anchor: ...]
411 # commit message annotation in "declare" anchor merges (which
412 # do not have any upstream changes), to distinguish those
413 # anchor merges from ordinary pseudomerges (which we might
414 # just try to strip).
416 # However, the user is going to be doing git-rebase a lot. We
417 # really don't want them to rewrite an anchor commit.
418 # git-rebase trips up on merges, so that is a useful safety
421 # BreakwaterStart commits are also anchors in the terminology
422 # of git-debrebase(5), but they are untagged (and always
423 # manually generated).
425 # We cannot not tolerate any tagged linear commit (ie,
426 # BreakwaterStart commits tagged `[anchor:') because such a
427 # thing could result from an erroneous linearising raw git
428 # rebase of a merge anchor. That would represent a corruption
429 # of the branch. and we want to detect and reject the results
430 # of such corruption before it makes it out anywhere. If we
431 # reject it here then we avoid making the pseudomerge which
432 # would be needed to push it.
434 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
435 @p == 2 or return $badanchor->("has other than two parents");
436 $haspatches and return $badanchor->("contains debian/patches");
438 # How to decide about l/r ordering of anchors ? git
439 # --topo-order prefers to expand 2nd parent first. There's
440 # already an easy rune to look for debian/ history anyway (git log
441 # debian/) so debian breakwater branch should be 1st parent; that
442 # way also there's also an easy rune to look for the upstream
443 # patches (--topo-order).
445 # Also this makes --first-parent be slightly more likely to
446 # be useful - it makes it provide a linearised breakwater history.
448 # Of course one can say somthing like
449 # gitk -- ':/' ':!/debian'
450 # to get _just_ the commits touching upstream files, and by
451 # the TREESAME logic in git-rev-list this will leave the
452 # breakwater into upstream at the first anchor. But that
453 # doesn't report debian/ changes at all.
455 # Other observations about gitk: by default, gitk seems to
456 # produce output in a different order to git-rev-list. I
457 # can't seem to find this documented anywhere. gitk
458 # --date-order DTRT. But, gitk always seems to put the
459 # parents from left to right, in order, so it's easy to see
460 # which way round a pseudomerge is.
462 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
463 $p[1]{Differs} & ~DS_DEB and
464 $badanchor->("upstream files differ from left parent");
465 $p[0]{Differs} & ~D_UPS and
466 $badanchor->("debian/ differs from right parent");
468 return $classify->(qw(Anchor),
469 OrigParents => [ $p[1] ]);
473 my $d = $r->{Parents}[0]{Differs};
474 if ($d == D_PAT_ADD) {
475 return $classify->(qw(AddPatches));
476 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
477 return $unknown->("edits debian/patches");
478 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
479 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
481 if ($d == D_DEB_CLOG) {
482 return $classify->(qw(Changelog));
484 return $classify->(qw(Packaging));
486 } elsif ($ty eq 'missing') {
487 return $classify->(qw(BreakwaterStart));
489 return $unknown->("parent's debian is not a directory");
491 } elsif ($d == D_UPS) {
492 return $classify->(qw(Upstream));
493 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
494 return $classify->(qw(Mixed));
496 return $unknown->("no changes");
498 confess "internal error $objid ?";
502 return $unknown->("origin commit");
505 if (@p == 2 && @identical == 1) {
506 my @overwritten = grep { $_->{Differs} } @p;
507 confess "internal error $objid ?" unless @overwritten==1;
508 return $classify->(qw(Pseudomerge),
509 Overwritten => [ $overwritten[0] ],
510 Contributor => $identical[0]);
512 if (@p == 2 && @identical == 2) {
514 my ($ph,$pm) = get_commit $_[0]{CommitId};
515 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
519 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
520 if ($order > 0) { # newer first
521 } elsif ($order < 0) {
522 @bytime = reverse @bytime;
524 # same age, default to order made by -s ours
525 # that is, commit was made by someone who preferred L
527 return $classify->(qw(Pseudomerge),
528 SubType => qw(Ambiguous),
529 Contributor => $bytime[0],
530 Overwritten => [ $bytime[1] ]);
533 my ($p_h, $p_m) = get_commit $p->{CommitId};
534 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
535 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
537 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
539 if (!(grep { !$_->{IsOrigin} } @p) and
540 (@orig_ps >= @p - 1) and
541 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
543 return $classify->(qw(DgitImportUnpatched),
544 OrigParents => \@orig_ps);
547 return $unknown->("complex merge");
550 sub keycommits ($;$$$$) {
551 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
552 # => ($anchor, $breakwater)
554 # $unclean->("unclean-$tagsfx", $msg, $cl)
555 # $furniture->("unclean-$tagsfx", $msg, $cl)
556 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
557 # is callled for each situation or commit that
558 # wouldn't be found in a laundered branch
559 # $furniture is for furniture commits such as might be found on an
560 # interchange branch (pseudomerge, d/patches, changelog)
561 # $trouble is for things whnich prevent the return of
562 # anchor and breakwater information; if that is ignored,
563 # then keycommits returns (undef, undef) instead.
564 # $fatal is for unprocessable commits, and should normally cause
565 # a failure. If ignored, agaion, (undef, undef) is returned.
567 # If a callback is undef, fail is called instead.
568 # If a callback is defined but false, the situation is ignored.
570 # no warnings qw(exiting); last;
571 # if the answer is no longer wanted.
573 my ($anchor, $breakwater);
576 $fatal //= sub { fail $_[1]; };
578 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
579 my $why = $mainwhy.$xwhy;
580 my $m = "branch needs laundering (run git-debrebase): $why";
581 fail $m unless defined $cb;
583 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
586 $cl = classify $head;
587 my $ty = $cl->{Type};
588 if ($ty eq 'Packaging') {
589 $breakwater //= $clogonly;
590 $breakwater //= $head;
591 } elsif ($ty eq 'Changelog') {
592 # this is going to count as the tip of the breakwater
593 # only if it has no upstream stuff before it
595 } elsif ($ty eq 'Anchor' or
596 $ty eq 'TreatAsAnchor' or
597 $ty eq 'BreakwaterStart') {
599 $breakwater //= $clogonly;
600 $breakwater //= $head;
602 } elsif ($ty eq 'Upstream') {
603 $x->($unclean, 'ordering',
604 "packaging change ($breakwater) follows upstream change"," (eg $head)")
605 if defined $breakwater;
608 } elsif ($ty eq 'Mixed') {
609 $x->($unclean, 'mixed',
610 "found mixed upstream/packaging commit"," ($head)");
613 } elsif ($ty eq 'Pseudomerge' or
614 $ty eq 'AddPatches') {
615 $x->($furniture, (lc $ty),
616 "found interchange bureaucracy commit ($ty)"," ($head)");
617 } elsif ($ty eq 'DgitImportUnpatched') {
618 $x->($trouble, 'dgitimport',
619 "found dgit dsc import ($head)");
620 return (undef,undef);
622 $x->($fatal, 'unprocessable',
623 "found unprocessable commit, cannot cope: $cl->{Why}",
625 return (undef,undef);
627 $head = $cl->{Parents}[0]{CommitId};
629 return ($anchor, $breakwater);
635 $nogenerate,$report) = @_;
636 # => ($tip, $breakwater_tip, $last_anchor)
637 # (or nothing, if $nogenerate)
639 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
641 # go through commits backwards
642 # we generate two lists of commits to apply:
643 # breakwater branch and upstream patches
644 my (@brw_cl, @upp_cl, @processed);
651 my ($prose, $info) = @_;
655 $ms .= "\n\n[git-debrebase$info: $prose]\n";
658 my $rewrite_from_here = sub {
660 my $sp_cl = { SpecialMethod => 'StartRewrite' };
662 push @processed, $sp_cl;
667 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
670 return unless $report;
671 print $report $prdelim, @_;
675 my $bomb = sub { # usage: return $bomb->();
676 print $report " Unprocessable" if $report;
677 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
680 return (undef,undef);
682 fail "found unprocessable commit, cannot cope:".
683 (defined $cl->{Why} ? "; $cl->{Why}": '').
684 " (commit $cur) (d.".
685 (join ' ', map { sprintf "%#x", $_->{Differs} }
686 @{ $cl->{Parents} }).
693 my $build_start = sub {
694 my ($msg, $parent) = @_;
697 no warnings qw(exiting); last;
704 my $ty = $cl->{Type};
705 my $st = $cl->{SubType};
706 $prline->("$cl->{CommitId} $cl->{Type}");
707 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
708 push @processed, $cl;
709 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
710 if ($ty eq 'AddPatches') {
712 $rewrite_from_here->(\@upp_cl);
714 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
718 } elsif ($ty eq 'BreakwaterStart') {
720 $build_start->('FirstPackaging', $cur);
721 } elsif ($ty eq 'Upstream') {
725 } elsif ($ty eq 'Mixed') {
728 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
731 $queue->(\@brw_cl, "debian");
732 $queue->(\@upp_cl, "upstream");
733 $rewrite_from_here->(\@brw_cl);
736 } elsif ($ty eq 'Pseudomerge') {
737 my $contrib = $cl->{Contributor}{CommitId};
738 print $report " Contributor=$contrib" if $report;
739 push @pseudomerges, $cl;
740 $rewrite_from_here->(\@upp_cl);
743 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
745 $build_start->("Anchor", $cur);
746 } elsif ($ty eq 'DgitImportUnpatched') {
747 my $pm = $pseudomerges[-1];
749 # To an extent, this is heuristic. Imports don't have
750 # a useful history of the debian/ branch. We assume
751 # that the first pseudomerge after an import has a
752 # useful history of debian/, and ignore the histories
753 # from later pseudomerges. Often the first pseudomerge
754 # will be the dgit import of the upload to the actual
755 # suite intended by the non-dgit NMUer, and later
756 # pseudomerges may represent in-archive copies.
757 my $ovwrs = $pm->{Overwritten};
758 printf $report " PM=%s \@Overwr:%d",
759 $pm->{CommitId}, (scalar @$ovwrs)
762 printdebug "*** WALK BOMB DgitImportUnpatched\n";
765 my $ovwr = $ovwrs->[0]{CommitId};
766 printf $report " Overwr=%s", $ovwr if $report;
767 # This import has a tree which is just like a
768 # breakwater tree, but it has the wrong history. It
769 # ought to have the previous breakwater (which the
770 # pseudomerge overwrote) as an ancestor. That will
771 # make the history of the debian/ files correct. As
772 # for the upstream version: either it's the same as
773 # was ovewritten (ie, same as the previous
774 # breakwater), in which case that history is precisely
775 # right; or, otherwise, it was a non-gitish upload of a
776 # new upstream version. We can tell these apart by
777 # looking at the tree of the supposed upstream.
780 SpecialMethod => 'DgitImportDebianUpdate',
781 $xmsg->("convert dgit import: debian changes")
784 SpecialMethod => 'DgitImportUpstreamUpdate',
785 $xmsg->("convert dgit import: upstream update",
788 $prline->(" Import");
789 $rewrite_from_here->(\@brw_cl);
790 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
794 # Everything is from this import. This kind of import
795 # is already in valid breakwater format, with the
796 # patches as commits.
797 printf $report " NoPM" if $report;
798 # last thing we processed will have been the first patch,
799 # if there is one; which is fine, so no need to rewrite
800 # on account of this import
801 $build_start->("ImportOrigin", $cur);
805 printdebug "*** WALK BOMB unrecognised\n";
811 printdebug "*** WALK prep done cur=$cur".
812 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
814 return if $nogenerate;
816 # Now we build it back up again
822 my $read_tree_debian = sub {
824 read_tree_subdir 'debian', "$treeish:debian";
825 rm_subdir_cached 'debian/patches';
827 my $read_tree_upstream = sub {
829 runcmd @git, qw(read-tree), $treeish;
830 $read_tree_debian->($build);
833 $#upp_cl = $upp_limit if defined $upp_limit;
835 my $committer_authline = calculate_committer_authline();
837 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
839 confess "internal error" unless $build eq (pop @processed)->{CommitId};
842 mkdir $rd or $!==EEXIST or die $!;
844 runcmd @git, qw(read-tree), $build;
845 foreach my $cl (qw(Debian), (reverse @brw_cl),
846 { SpecialMethod => 'RecordBreakwaterTip' },
847 qw(Upstream), (reverse @upp_cl)) {
849 $current_method = $cl;
852 my $method = $cl->{SpecialMethod} // $current_method;
853 my @parents = ($build);
854 my $cltree = $cl->{CommitId};
855 printdebug "WALK BUILD ".($cltree//'undef').
856 " $method (rewriting=$rewriting)\n";
857 if ($method eq 'Debian') {
858 $read_tree_debian->($cltree);
859 } elsif ($method eq 'Upstream') {
860 $read_tree_upstream->($cltree);
861 } elsif ($method eq 'StartRewrite') {
864 } elsif ($method eq 'RecordBreakwaterTip') {
865 $breakwater = $build;
867 } elsif ($method eq 'DgitImportDebianUpdate') {
868 $read_tree_debian->($cltree);
869 } elsif ($method eq 'DgitImportUpstreamUpdate') {
870 confess unless $rewriting;
871 my $differs = (get_differs $build, $cltree);
872 next unless $differs & D_UPS;
873 $read_tree_upstream->($cltree);
874 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
879 my $procd = (pop @processed) // 'UNDEF';
882 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
885 my $newtree = cmdoutput @git, qw(write-tree);
887 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
888 $ch =~ s{^parent .*\n}{}mg;
889 $ch =~ s{(?=^author)}{
890 join '', map { "parent $_\n" } @parents
891 }me or confess "$ch ?";
893 $ch =~ s{^committer .*$}{$committer_authline}m
896 my $cf = "$rd/m$rewriting";
897 open CD, ">", $cf or die $!;
898 print CD $ch, "\n", $cl->{Msg} or die $!;
900 my @cmd = (@git, qw(hash-object));
901 push @cmd, qw(-w) if $rewriting;
902 push @cmd, qw(-t commit), $cf;
903 my $newcommit = cmdoutput @cmd;
904 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
906 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
912 my $final_check = get_differs $build, $input;
913 die sprintf "internal error %#x %s %s", $final_check, $build, $input
914 if $final_check & ~D_PAT_ADD;
916 my @r = ($build, $breakwater, $last_anchor);
917 printdebug "*** WALK RETURN @r\n";
922 git_check_unmodified();
923 return git_rev_parse qw(HEAD);
926 sub update_head ($$$) {
927 my ($old, $new, $mrest) = @_;
928 push @deferred_updates, "update HEAD $new $old";
929 run_deferred_updates $mrest;
932 sub update_head_checkout ($$$) {
933 my ($old, $new, $mrest) = @_;
934 update_head $old, $new, $mrest;
935 runcmd @git, qw(reset --hard);
938 sub update_head_postlaunder ($$$) {
939 my ($old, $tip, $reflogmsg) = @_;
940 return if $tip eq $old;
941 print "git-debrebase: laundered (head was $old)\n";
942 update_head $old, $tip, $reflogmsg;
943 # no tree changes except debian/patches
944 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
947 sub do_launder_head ($) {
948 my ($reflogmsg) = @_;
949 my $old = get_head();
951 my ($tip,$breakwater) = walk $old;
953 update_head_postlaunder $old, $tip, $reflogmsg;
954 return ($tip,$breakwater);
957 sub cmd_launder_v0 () {
958 badusage "no arguments to launder-v0 allowed" if @ARGV;
959 my $old = get_head();
960 my ($tip,$breakwater,$last_anchor) = walk $old;
961 update_head_postlaunder $old, $tip, 'launder';
962 printf "# breakwater tip\n%s\n", $breakwater;
963 printf "# working tip\n%s\n", $tip;
964 printf "# last anchor\n%s\n", $last_anchor;
967 sub defaultcmd_rebase () {
968 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
969 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
970 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
974 badusage "analyse does not support any options"
975 if @ARGV and $ARGV[0] =~ m/^-/;
976 badusage "too many arguments to analyse" if @ARGV>1;
979 $old = git_rev_parse $old;
981 $old = git_rev_parse 'HEAD';
983 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
984 STDOUT->error and die $!;
987 sub ffq_prev_branchinfo () {
988 my $current = git_get_symref();
989 return gdr_ffq_prev_branchinfo($current);
992 sub ffq_check ($;$$) {
993 # calls $ff and/or $notff zero or more times
994 # then returns either (status,message) where status is
999 # or (undef,undef, $ffq_prev,$gdrlast)
1000 # $ff and $notff are called like this:
1001 # $ff->("message for stdout\n");
1002 # $notff->('snag-name', $message);
1003 # normally $currentval should be HEAD
1004 my ($currentval, $ff, $notff) =@_;
1006 $ff //= sub { print $_[0] or die $!; };
1009 my ($status, $message, $current, $ffq_prev, $gdrlast)
1010 = ffq_prev_branchinfo();
1011 return ($status, $message) unless $status eq 'branch';
1013 my $exists = git_get_ref $ffq_prev;
1014 return ('exists',"$ffq_prev already exists") if $exists;
1016 return ('not-branch', 'HEAD symref is not to refs/heads/')
1017 unless $current =~ m{^refs/heads/};
1020 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1023 printdebug "ffq check_specs @check_specs\n";
1026 my ($lrref, $desc) = @_;
1027 printdebug "ffq might check $lrref ($desc)\n";
1029 for my $chk (@check_specs) {
1031 $invert = $glob =~ s{^[!^]}{};
1032 last if fnmatch $glob, $lrref;
1035 my $lrval = git_get_ref $lrref;
1036 return unless length $lrval;
1038 if (is_fast_fwd $lrval, $currentval) {
1039 $ff->("OK, you are ahead of $lrref\n");
1040 $checked{$lrref} = 1;
1041 } elsif (is_fast_fwd $currentval, $lrval) {
1042 $checked{$lrref} = -1;
1043 $notff->('behind', "you are behind $lrref, divergence risk");
1045 $checked{$lrref} = -1;
1046 $notff->('diverged', "you have diverged from $lrref");
1050 my $merge = cfg "branch.$branch.merge",1;
1051 if (defined $merge and $merge =~ m{^refs/heads/}) {
1053 printdebug "ffq merge $rhs\n";
1054 my $check_remote = sub {
1055 my ($remote, $desc) = @_;
1056 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1057 return unless defined $remote;
1058 $check->("refs/remotes/$remote/$rhs", $desc);
1060 $check_remote->((scalar cfg "branch.$branch.remote",1),
1061 'remote fetch/merge branch');
1062 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1063 (scalar cfg "branch.$branch.pushDefault",1),
1064 'remote push branch');
1066 if ($branch =~ m{^dgit/}) {
1067 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1068 } elsif ($branch =~ m{^master$}) {
1069 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1071 return (undef, undef, $ffq_prev, $gdrlast);
1074 sub record_ffq_prev_deferred () {
1075 # => ('status', "message")
1077 # deferred message is undef
1082 # if not ff from some branch we should be ff from, is an snag
1083 # if "deferred", will have added something about that to
1084 # @deferred_update_messages, and also maybe printed (already)
1085 # some messages about ff checks
1086 my $currentval = get_head();
1088 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1089 return ($status,$message) if defined $status;
1093 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1094 push @deferred_updates, "delete $gdrlast";
1095 push @deferred_update_messages, "Recorded current head for preservation";
1096 return ('deferred', undef);
1099 sub record_ffq_auto () {
1100 my ($status, $message) = record_ffq_prev_deferred();
1101 if ($status eq 'deferred' || $status eq 'exists') {
1103 snag $status, "could not record ffq-prev: $message";
1108 sub ffq_prev_info () {
1109 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1110 my ($status, $message, $current, $ffq_prev, $gdrlast)
1111 = ffq_prev_branchinfo();
1112 if ($status ne 'branch') {
1113 snag $status, "could not check ffq-prev: $message";
1116 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1117 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1120 sub stitch ($$$$$) {
1121 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1123 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1125 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1126 my $differs = get_differs $old_head, $ffq_prev_commitish;
1127 unless ($differs & ~D_PAT_ADD) {
1128 # ffq-prev is ahead of us, and the only tree changes it has
1129 # are possibly addition of things in debian/patches/.
1130 # Just wind forwards rather than making a pointless pseudomerge.
1131 push @deferred_updates,
1132 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1133 update_head_checkout $old_head, $ffq_prev_commitish,
1134 "stitch (fast forward)";
1139 # We make pseudomerges with L as the contributing parent.
1140 # This makes git rev-list --first-parent work properly.
1141 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1142 'Declare fast forward / record previous work',
1143 "[git-debrebase pseudomerge: $prose]",
1145 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1146 update_head $old_head, $new_head, "stitch: $prose";
1149 sub do_stitch ($;$) {
1150 my ($prose, $unclean) = @_;
1152 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1153 if (!$ffq_prev_commitish) {
1154 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1157 my $dangling_head = get_head();
1159 keycommits $dangling_head, $unclean,$unclean,$unclean;
1162 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1165 sub cmd_new_upstream () {
1166 # automatically and unconditionally launders before rebasing
1167 # if rebase --abort is used, laundering has still been done
1171 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1173 # parse args - low commitment
1174 my $spec_version = shift @ARGV;
1175 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1176 fail "bad version number \`$spec_version'" unless defined $new_version;
1177 if ($new_version->is_native()) {
1178 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1180 my $new_upstream_version = "$new_version";
1181 $new_upstream_version =~ s/-.*?$//;;
1183 my $new_upstream = shift @ARGV;
1184 if (!defined $new_upstream) {
1186 # todo: at some point maybe use git-deborig to do this
1187 foreach my $tagpfx ('', 'v', 'upstream/') {
1188 my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1189 $new_upstream = git_get_ref "refs/tags/$tag";
1190 last if length $new_upstream;
1193 if (!length $new_upstream) {
1194 fail "Could not determine appropriate upstream commitish.\n".
1195 " (Tried these tags: @tried)\n".
1196 " Check version, and specify upstream commitish explicitly.";
1199 $new_upstream = git_rev_parse $new_upstream;
1204 my ($n, @x) = @_; # may be ''
1205 my $pc = $pieces{$n} //= {
1207 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1209 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1214 my $newpiece = sub {
1215 my ($n, @x) = @_; # may be ''
1216 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1217 push @newpieces, $pc;
1222 New => $new_upstream,
1224 while (@ARGV && $ARGV[0] !~ m{^-}) {
1225 my $n = shift @ARGV;
1227 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1228 unless @ARGV && $ARGV[0] !~ m{^-};
1230 my $c = git_rev_parse shift @ARGV;
1231 die unless $n =~ m/^$extra_orig_namepart_re$/;
1232 $newpiece->($n, New => $c);
1235 # now we need to investigate the branch this generates the
1236 # laundered version but we don't switch to it yet
1237 my $old_head = get_head();
1238 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1240 my $old_bw_cl = classify $old_bw;
1241 my $old_anchor_cl = classify $old_anchor;
1243 if (!$old_anchor_cl->{OrigParents}) {
1244 snag 'anchor-treated',
1245 'old anchor is recognised due to --anchor, cannot check upstream';
1247 $old_upstream = parsecommit
1248 $old_anchor_cl->{OrigParents}[0]{CommitId};
1249 $piece->('', Old => $old_upstream->{CommitId});
1252 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1253 if ($old_upstream->{Msg} =~
1254 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1256 my @oldpieces = (split / /, $1);
1257 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1258 if ($old_n_parents != @oldpieces &&
1259 $old_n_parents != @oldpieces + 1) {
1260 snag 'upstream-confusing', sprintf
1261 "previous upstream combine %s".
1262 " mentions %d pieces (each implying one parent)".
1263 " but has %d parents".
1264 " (one per piece plus maybe a previous combine)",
1265 $old_upstream->{CommitId},
1266 (scalar @oldpieces),
1268 } elsif ($oldpieces[0] ne '.') {
1269 snag 'upstream-confusing', sprintf
1270 "previous upstream combine %s".
1271 " first piece is not \`.'",
1275 foreach my $i (0..$#oldpieces) {
1276 my $n = $oldpieces[$i];
1277 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1278 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1282 snag 'upstream-confusing',
1283 "previous upstream $old_upstream->{CommitId} is from".
1284 " git-debrebase but not an \`upstream-combine' commit";
1288 foreach my $pc (values %pieces) {
1289 if (!$old_upstream) {
1290 # we have complained already
1291 } elsif (!$pc->{Old}) {
1292 snag 'upstream-new-piece',
1293 "introducing upstream piece \`$pc->{Name}'";
1294 } elsif (!$pc->{New}) {
1295 snag 'upstream-rm-piece',
1296 "dropping upstream piece \`$pc->{Name}'";
1297 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1298 snag 'upstream-not-ff',
1299 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1303 printdebug "%pieces = ", (dd \%pieces), "\n";
1304 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1312 my @upstream_merge_parents;
1315 push @upstream_merge_parents, $old_upstream->{CommitId};
1318 foreach my $pc (@newpieces) { # always has '' first
1320 read_tree_subdir $pc->{Name}, $pc->{New};
1322 runcmd @git, qw(read-tree), $pc->{New};
1324 push @upstream_merge_parents, $pc->{New};
1327 # index now contains the new upstream
1329 if (@newpieces > 1) {
1330 # need to make the upstream subtree merge commit
1331 $new_upstream = make_commit \@upstream_merge_parents,
1332 [ "Combine upstreams for $new_upstream_version",
1333 ("[git-debrebase upstream-combine . ".
1334 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1339 # $new_upstream is either the single upstream commit, or the
1340 # combined commit we just made. Either way it will be the
1341 # "upstream" parent of the anchor merge.
1343 read_tree_subdir 'debian', "$old_bw:debian";
1345 # index now contains the anchor merge contents
1346 $new_bw = make_commit [ $old_bw, $new_upstream ],
1347 [ "Update to upstream $new_upstream_version",
1348 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1351 my $clogsignoff = cmdoutput qw(git show),
1352 '--pretty=format:%an <%ae> %aD',
1355 # Now we have to add a changelog stanza so the Debian version
1357 die if unlink "debian";
1358 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1359 unlink "debian/changelog" or $!==ENOENT or die $!;
1360 mkdir "debian" or die $!;
1361 open CN, ">", "debian/changelog" or die $!;
1362 my $oldclog = git_cat_file ":debian/changelog";
1363 $oldclog =~ m/^($package_re) \(\S+\) / or
1364 fail "cannot parse old changelog to get package name";
1366 print CN <<END, $oldclog or die $!;
1367 $p ($new_version) UNRELEASED; urgency=medium
1369 * Update to new upstream version $new_upstream_version.
1375 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1377 # Now we have the final new breakwater branch in the index
1378 $new_bw = make_commit [ $new_bw ],
1379 [ "Update changelog for new upstream $new_upstream_version",
1380 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1384 # we have constructed the new breakwater. we now need to commit to
1385 # the laundering output, because git-rebase can't easily be made
1386 # to make a replay list which is based on some other branch
1388 update_head_postlaunder $old_head, $old_laundered_tip,
1389 'launder for new upstream';
1391 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1392 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1393 "debrebase new-upstream $new_version: rebase";
1395 # now it's for the user to sort out
1398 sub cmd_record_ffq_prev () {
1399 badusage "no arguments allowed" if @ARGV;
1400 my ($status, $msg) = record_ffq_prev_deferred();
1401 if ($status eq 'exists' && $opt_noop_ok) {
1402 print "Previous head already recorded\n" or die $!;
1403 } elsif ($status eq 'deferred') {
1404 run_deferred_updates 'record-ffq-prev';
1406 fail "Could not preserve: $msg";
1411 badusage "no arguments allowed" if @ARGV;
1412 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1413 print "$bw\n" or die $!;
1416 sub cmd_breakwater () {
1417 badusage "no arguments allowed" if @ARGV;
1418 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1419 print "$bw\n" or die $!;
1423 badusage "no arguments allowed" if @ARGV;
1425 # todo: gdr status should print divergence info
1426 # todo: gdr status should print upstream component(s) info
1427 # todo: gdr should leave/maintain some refs with this kind of info ?
1429 my $oldest = { Badness => 0 };
1432 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1433 if ($oldest->{Badness} < $badness) {
1434 $oldest = $newest = undef;
1437 Badness => $badness,
1438 CommitId => $cl->{CommitId},
1442 $newest //= $oldest;
1444 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1445 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1446 sub { $note->(2, 'branch is unlaundered', @_); },
1447 sub { $note->(3, 'branch needs laundering', @_); },
1448 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1450 my $prcommitinfo = sub {
1452 flush STDOUT or die $!;
1453 runcmd @git, qw(--no-pager log -n1),
1454 '--pretty=format: %h %s%n',
1458 print "current branch contents, in git-debrebase terms:\n";
1459 if (!$oldest->{Badness}) {
1460 print " branch is laundered\n";
1462 print " $oldest->{OurMsg}\n";
1464 foreach my $info ($oldest, $newest) {
1465 my $cid = $info->{CommitId};
1466 next if $cid eq $printed;
1468 print " $info->{KcMsg}\n";
1469 $prcommitinfo->($cid);
1474 my ($cid, $what) = @_;
1475 if (!defined $cid) {
1476 print " $what is not well-defined\n";
1479 $prcommitinfo->($cid);
1482 print "key git-debrebase commits:\n";
1483 $prab->($anchor, 'anchor');
1484 $prab->($bw, 'breakwater');
1486 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1487 ffq_prev_branchinfo();
1489 print "branch and ref status, in git-debrebase terms:\n";
1491 print " $ffq_msg\n";
1493 $ffq_prev = git_get_ref $ffq_prev;
1494 $gdrlast = git_get_ref $gdrlast;
1496 print " unstitched; previous tip was:\n";
1497 $prcommitinfo->($ffq_prev);
1498 } elsif (!$gdrlast) {
1499 print " stitched? (no record of git-debrebase work)\n";
1500 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1501 print " stitched\n";
1503 print " not git-debrebase (diverged since last stitch)\n"
1509 my $prose = 'stitch';
1510 GetOptions('prose=s', \$prose) or badusage("bad options to stitch");
1511 badusage "no arguments allowed" if @ARGV;
1512 do_stitch $prose, 0;
1514 sub cmd_prepush () { cmd_stitch(); }
1517 badusage "no arguments allowed" if @ARGV;
1518 do_launder_head 'launder for git-debrebase quick';
1522 sub cmd_conclude () {
1523 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1524 if (!$ffq_prev_commitish) {
1525 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1528 my $dangling_head = get_head();
1530 badusage "no arguments allowed" if @ARGV;
1531 do_launder_head 'launder for git-debrebase quick';
1535 sub make_patches_staged ($) {
1537 # Produces the patches that would result from $head if it were
1539 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1542 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1543 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1544 my @gbp_cmd = (qw(gbp pq export));
1545 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1547 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1550 runcmd @git, qw(add -f debian/patches);
1554 sub make_patches ($) {
1556 keycommits $head, 0, \&snag;
1557 make_patches_staged $head;
1560 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1561 runcmd @git, qw(read-tree), $head;
1562 read_tree_subdir 'debian/patches', $ptree;
1563 $out = make_commit [$head], [
1564 'Commit patch queue (exported by git-debrebase)',
1565 '[git-debrebase: export and commit patches]',
1571 sub cmd_make_patches () {
1572 my $opt_quiet_would_amend;
1573 GetOptions('quiet-would-amend!', \$opt_quiet_would_amend)
1574 or badusage("bad options to make-patches");
1575 badusage "no arguments allowed" if @ARGV;
1576 my $old_head = get_head();
1577 my $new = make_patches $old_head;
1578 my $d = get_differs $old_head, $new;
1580 fail "No (more) patches to export." unless $opt_noop_ok;
1582 } elsif ($d == D_PAT_ADD) {
1584 update_head_checkout $old_head, $new, 'make-patches';
1586 print STDERR failmsg
1587 "Patch export produced patch amendments".
1588 " (abandoned output commit $new).".
1589 " Try laundering first."
1590 unless $opt_quiet_would_amend;
1595 sub cmd_convert_from_gbp () {
1596 badusage "needs 1 optional argument, the upstream git rev"
1598 my ($upstream_spec) = @ARGV;
1599 $upstream_spec //= 'refs/heads/upstream';
1600 my $upstream = git_rev_parse $upstream_spec;
1601 my $old_head = get_head();
1603 my $upsdiff = get_differs $upstream, $old_head;
1604 if ($upsdiff & D_UPS) {
1605 runcmd @git, qw(--no-pager diff),
1606 $upstream, $old_head,
1607 qw( -- :!/debian :/);
1608 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1611 if (!is_fast_fwd $upstream, $old_head) {
1612 snag 'upstream-not-ancestor',
1613 "upstream ($upstream) is not an ancestor of HEAD";
1615 my $wrong = cmdoutput
1616 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1617 qw(-- :/ :!/debian));
1618 if (length $wrong) {
1619 snag 'unexpected-upstream-changes',
1620 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1621 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1625 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1626 snag 'upstream-has-debian',
1627 "upstream ($upstream) contains debian/ directory";
1630 my $previous_dgit_view = eval {
1631 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1633 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1634 my ($stz, $desc) = @_;
1635 no warnings qw(exiting);
1636 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1637 next unless $stz->{Date};
1638 next unless $stz->{Distribution} ne 'UNRELEASED';
1639 $lvsn = $stz->{Version};
1640 $suite = $stz->{Distribution};
1643 die "neither of the first two changelog entries are released\n"
1644 unless defined $lvsn;
1645 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1646 my $mtag_pat = debiantag_maintview $lvsn, '*';
1647 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1649 die "could not find suitable maintainer view tag $mtag_pat\n"
1650 unless $mtag_pat =~ m{/};
1651 is_fast_fwd $mtag, 'HEAD' or
1652 die "HEAD is not FF from maintainer tag $mtag!";
1653 my $dtag = "archive/$mtag";
1654 is_fast_fwd $mtag, $dtag or
1655 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1656 print "will stitch in dgit view, $dtag\n";
1657 git_rev_parse $dtag;
1659 if (!$previous_dgit_view) {
1662 print STDERR "cannot stitch in dgit view: $@\n";
1665 snags_maybe_bail_early();
1671 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1672 # make a branch out of the patch queue - we'll want this in a mo
1673 runcmd qw(gbp pq import);
1674 # strip the patches out
1675 runcmd @git, qw(checkout -q gdr-internal~0);
1676 rm_subdir_cached 'debian/patches';
1677 $work = make_commit ['HEAD'], [
1678 'git-debrebase convert-from-gbp: drop patches from tree',
1679 'Delete debian/patches, as part of converting to git-debrebase format.',
1680 '[git-debrebase convert-from-gbp: drop patches from tree]'
1682 # make the anchor merge
1683 # the tree is already exactly right
1684 $work = make_commit [$work, $upstream], [
1685 'git-debrebase import: declare upstream',
1686 'First breakwater merge.',
1687 '[git-debrebase anchor: declare upstream]'
1690 # rebase the patch queue onto the new breakwater
1691 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1692 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1693 $work = git_rev_parse 'HEAD';
1695 if ($previous_dgit_view) {
1696 $work = make_commit [$work, $previous_dgit_view], [
1697 'git-debrebase import: declare ff from dgit archive view',
1698 '[git-debrebase pseudomerge: import-from-gbp]',
1705 update_head_checkout $old_head, $work, 'convert-from-gbp';
1708 sub cmd_convert_to_gbp () {
1709 badusage "no arguments allowed" if @ARGV;
1710 my $head = get_head();
1711 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1712 keycommits $head, 0;
1714 make_patches_staged $head;
1716 $out = make_commit ['HEAD'], [
1717 'Commit patch queue (converted from git-debrebase format)',
1718 '[git-debrebase convert-to-gbp: commit patches]',
1722 push @deferred_updates, "delete $ffq";
1723 push @deferred_updates, "delete $gdrlast";
1726 update_head_checkout $head, $out, "convert to gbp (v0)";
1727 print <<END or die $!;
1728 git-debrebase: converted to git-buildpackage branch format
1729 git-debrebase: WARNING: do not now run "git-debrebase" any more
1730 git-debrebase: WARNING: doing so would drop all upstream patches!
1734 sub cmd_downstream_rebase_launder_v0 () {
1735 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1737 $base = git_rev_parse $base;
1738 my $old_head = get_head();
1739 my $current = $old_head;
1742 if ($current eq $base) {
1743 $topmost_keep //= $current;
1744 print " $current BASE stop\n";
1747 my $cl = classify $current;
1748 print " $current $cl->{Type}";
1750 my $p0 = $cl->{Parents}[0]{CommitId};
1752 if ($cl->{Type} eq 'Pseudomerge') {
1753 print " ^".($cl->{Contributor}{Ix}+1);
1754 $next = $cl->{Contributor}{CommitId};
1755 } elsif ($cl->{Type} eq 'AddPatches' or
1756 $cl->{Type} eq 'Changelog') {
1766 $topmost_keep //= $current;
1768 die "to-be stripped changes not on top of the branch\n"
1773 if ($topmost_keep eq $old_head) {
1774 print "unchanged\n";
1776 print "updating to $topmost_keep\n";
1777 update_head_checkout
1778 $old_head, $topmost_keep,
1779 'downstream-rebase-launder-v0';
1783 GetOptions("D+" => \$debuglevel,
1784 'noop-ok', => \$opt_noop_ok,
1785 'f=s' => \@snag_force_opts,
1786 'anchor=s' => \@opt_anchors,
1789 my ($opt,$val) = @_;
1790 badusage "git-debrebase: no cuddling to -i for git-rebase"
1792 die if $opt_defaultcmd_interactive; # should not happen
1793 $opt_defaultcmd_interactive = [ qw(-i) ];
1794 # This access to @ARGV is excessive familiarity with
1795 # Getopt::Long, but there isn't another sensible
1796 # approach. '-i=s{0,}' does not work with bundling.
1797 push @$opt_defaultcmd_interactive, @ARGV;
1799 }) or badusage "bad options\n";
1800 initdebug('git-debrebase ');
1801 enabledebug if $debuglevel;
1803 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1804 chdir $toplevel or die "chdir $toplevel: $!";
1806 $rd = fresh_playground "$playprefix/misc";
1808 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1810 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1811 defaultcmd_rebase();
1813 my $cmd = shift @ARGV;
1816 $cmdfn = ${*::}{"cmd_$cmdfn"};
1818 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";