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 $_[2]; };
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 die "commit $cur: Cannot cope with this commit (d.".
683 (join ' ', map { sprintf "%#x", $_->{Differs} }
684 @{ $cl->{Parents} }).
685 (defined $cl->{Why} ? "; $cl->{Why}": '').
692 my $build_start = sub {
693 my ($msg, $parent) = @_;
696 no warnings qw(exiting); last;
703 my $ty = $cl->{Type};
704 my $st = $cl->{SubType};
705 $prline->("$cl->{CommitId} $cl->{Type}");
706 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
707 push @processed, $cl;
708 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
709 if ($ty eq 'AddPatches') {
711 $rewrite_from_here->(\@upp_cl);
713 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
717 } elsif ($ty eq 'BreakwaterStart') {
719 $build_start->('FirstPackaging', $cur);
720 } elsif ($ty eq 'Upstream') {
724 } elsif ($ty eq 'Mixed') {
727 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
730 $queue->(\@brw_cl, "debian");
731 $queue->(\@upp_cl, "upstream");
732 $rewrite_from_here->(\@brw_cl);
735 } elsif ($ty eq 'Pseudomerge') {
736 my $contrib = $cl->{Contributor}{CommitId};
737 print $report " Contributor=$contrib" if $report;
738 push @pseudomerges, $cl;
739 $rewrite_from_here->(\@upp_cl);
742 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
744 $build_start->("Anchor", $cur);
745 } elsif ($ty eq 'DgitImportUnpatched') {
746 my $pm = $pseudomerges[-1];
748 # To an extent, this is heuristic. Imports don't have
749 # a useful history of the debian/ branch. We assume
750 # that the first pseudomerge after an import has a
751 # useful history of debian/, and ignore the histories
752 # from later pseudomerges. Often the first pseudomerge
753 # will be the dgit import of the upload to the actual
754 # suite intended by the non-dgit NMUer, and later
755 # pseudomerges may represent in-archive copies.
756 my $ovwrs = $pm->{Overwritten};
757 printf $report " PM=%s \@Overwr:%d",
758 $pm->{CommitId}, (scalar @$ovwrs)
761 printdebug "*** WALK BOMB DgitImportUnpatched\n";
764 my $ovwr = $ovwrs->[0]{CommitId};
765 printf $report " Overwr=%s", $ovwr if $report;
766 # This import has a tree which is just like a
767 # breakwater tree, but it has the wrong history. It
768 # ought to have the previous breakwater (which the
769 # pseudomerge overwrote) as an ancestor. That will
770 # make the history of the debian/ files correct. As
771 # for the upstream version: either it's the same as
772 # was ovewritten (ie, same as the previous
773 # breakwater), in which case that history is precisely
774 # right; or, otherwise, it was a non-gitish upload of a
775 # new upstream version. We can tell these apart by
776 # looking at the tree of the supposed upstream.
779 SpecialMethod => 'DgitImportDebianUpdate',
780 $xmsg->("convert dgit import: debian changes")
783 SpecialMethod => 'DgitImportUpstreamUpdate',
784 $xmsg->("convert dgit import: upstream update",
787 $prline->(" Import");
788 $rewrite_from_here->(\@brw_cl);
789 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
793 # Everything is from this import. This kind of import
794 # is already in valid breakwater format, with the
795 # patches as commits.
796 printf $report " NoPM" if $report;
797 # last thing we processed will have been the first patch,
798 # if there is one; which is fine, so no need to rewrite
799 # on account of this import
800 $build_start->("ImportOrigin", $cur);
804 printdebug "*** WALK BOMB unrecognised\n";
810 printdebug "*** WALK prep done cur=$cur".
811 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
813 return if $nogenerate;
815 # Now we build it back up again
821 my $read_tree_debian = sub {
823 read_tree_subdir 'debian', "$treeish:debian";
824 rm_subdir_cached 'debian/patches';
826 my $read_tree_upstream = sub {
828 runcmd @git, qw(read-tree), $treeish;
829 $read_tree_debian->($build);
832 $#upp_cl = $upp_limit if defined $upp_limit;
834 my $committer_authline = calculate_committer_authline();
836 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
838 confess "internal error" unless $build eq (pop @processed)->{CommitId};
841 mkdir $rd or $!==EEXIST or die $!;
843 runcmd @git, qw(read-tree), $build;
844 foreach my $cl (qw(Debian), (reverse @brw_cl),
845 { SpecialMethod => 'RecordBreakwaterTip' },
846 qw(Upstream), (reverse @upp_cl)) {
848 $current_method = $cl;
851 my $method = $cl->{SpecialMethod} // $current_method;
852 my @parents = ($build);
853 my $cltree = $cl->{CommitId};
854 printdebug "WALK BUILD ".($cltree//'undef').
855 " $method (rewriting=$rewriting)\n";
856 if ($method eq 'Debian') {
857 $read_tree_debian->($cltree);
858 } elsif ($method eq 'Upstream') {
859 $read_tree_upstream->($cltree);
860 } elsif ($method eq 'StartRewrite') {
863 } elsif ($method eq 'RecordBreakwaterTip') {
864 $breakwater = $build;
866 } elsif ($method eq 'DgitImportDebianUpdate') {
867 $read_tree_debian->($cltree);
868 } elsif ($method eq 'DgitImportUpstreamUpdate') {
869 confess unless $rewriting;
870 my $differs = (get_differs $build, $cltree);
871 next unless $differs & D_UPS;
872 $read_tree_upstream->($cltree);
873 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
878 my $procd = (pop @processed) // 'UNDEF';
881 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
884 my $newtree = cmdoutput @git, qw(write-tree);
886 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
887 $ch =~ s{^parent .*\n}{}mg;
888 $ch =~ s{(?=^author)}{
889 join '', map { "parent $_\n" } @parents
890 }me or confess "$ch ?";
892 $ch =~ s{^committer .*$}{$committer_authline}m
895 my $cf = "$rd/m$rewriting";
896 open CD, ">", $cf or die $!;
897 print CD $ch, "\n", $cl->{Msg} or die $!;
899 my @cmd = (@git, qw(hash-object));
900 push @cmd, qw(-w) if $rewriting;
901 push @cmd, qw(-t commit), $cf;
902 my $newcommit = cmdoutput @cmd;
903 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
905 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
911 my $final_check = get_differs $build, $input;
912 die sprintf "internal error %#x %s %s", $final_check, $build, $input
913 if $final_check & ~D_PAT_ADD;
915 my @r = ($build, $breakwater, $last_anchor);
916 printdebug "*** WALK RETURN @r\n";
921 git_check_unmodified();
922 return git_rev_parse qw(HEAD);
925 sub update_head ($$$) {
926 my ($old, $new, $mrest) = @_;
927 push @deferred_updates, "update HEAD $new $old";
928 run_deferred_updates $mrest;
931 sub update_head_checkout ($$$) {
932 my ($old, $new, $mrest) = @_;
933 update_head $old, $new, $mrest;
934 runcmd @git, qw(reset --hard);
937 sub update_head_postlaunder ($$$) {
938 my ($old, $tip, $reflogmsg) = @_;
939 return if $tip eq $old;
940 print "git-debrebase: laundered (head was $old)\n";
941 update_head $old, $tip, $reflogmsg;
942 # no tree changes except debian/patches
943 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
946 sub do_launder_head ($) {
947 my ($reflogmsg) = @_;
948 my $old = get_head();
950 my ($tip,$breakwater) = walk $old;
952 update_head_postlaunder $old, $tip, $reflogmsg;
953 return ($tip,$breakwater);
956 sub cmd_launder_v0 () {
957 badusage "no arguments to launder-v0 allowed" if @ARGV;
958 my $old = get_head();
959 my ($tip,$breakwater,$last_anchor) = walk $old;
960 update_head_postlaunder $old, $tip, 'launder';
961 printf "# breakwater tip\n%s\n", $breakwater;
962 printf "# working tip\n%s\n", $tip;
963 printf "# last anchor\n%s\n", $last_anchor;
966 sub defaultcmd_rebase () {
967 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
968 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
969 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
973 die if ($ARGV[0]//'') =~ m/^-/;
974 badusage "too many arguments to analyse" if @ARGV>1;
977 $old = git_rev_parse $old;
979 $old = git_rev_parse 'HEAD';
981 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
982 STDOUT->error and die $!;
985 sub ffq_prev_branchinfo () {
986 my $current = git_get_symref();
987 return gdr_ffq_prev_branchinfo($current);
990 sub ffq_check ($;$$) {
991 # calls $ff and/or $notff zero or more times
992 # then returns either (status,message) where status is
997 # or (undef,undef, $ffq_prev,$gdrlast)
998 # $ff and $notff are called like this:
999 # $ff->("message for stdout\n");
1000 # $notff->('snag-name', $message);
1001 # normally $currentval should be HEAD
1002 my ($currentval, $ff, $notff) =@_;
1004 $ff //= sub { print $_[0] or die $!; };
1007 my ($status, $message, $current, $ffq_prev, $gdrlast)
1008 = ffq_prev_branchinfo();
1009 return ($status, $message) unless $status eq 'branch';
1011 my $exists = git_get_ref $ffq_prev;
1012 return ('exists',"$ffq_prev already exists") if $exists;
1014 return ('not-branch', 'HEAD symref is not to refs/heads/')
1015 unless $current =~ m{^refs/heads/};
1018 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1021 printdebug "ffq check_specs @check_specs\n";
1024 my ($lrref, $desc) = @_;
1025 printdebug "ffq might check $lrref ($desc)\n";
1027 for my $chk (@check_specs) {
1029 $invert = $glob =~ s{^[!^]}{};
1030 last if fnmatch $glob, $lrref;
1033 my $lrval = git_get_ref $lrref;
1034 return unless length $lrval;
1036 if (is_fast_fwd $lrval, $currentval) {
1037 $ff->("OK, you are ahead of $lrref\n");
1038 $checked{$lrref} = 1;
1039 } elsif (is_fast_fwd $currentval, $lrval) {
1040 $checked{$lrref} = -1;
1041 $notff->('behind', "you are behind $lrref, divergence risk");
1043 $checked{$lrref} = -1;
1044 $notff->('diverged', "you have diverged from $lrref");
1048 my $merge = cfg "branch.$branch.merge",1;
1049 if (defined $merge and $merge =~ m{^refs/heads/}) {
1051 printdebug "ffq merge $rhs\n";
1052 my $check_remote = sub {
1053 my ($remote, $desc) = @_;
1054 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1055 return unless defined $remote;
1056 $check->("refs/remotes/$remote/$rhs", $desc);
1058 $check_remote->((scalar cfg "branch.$branch.remote",1),
1059 'remote fetch/merge branch');
1060 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1061 (scalar cfg "branch.$branch.pushDefault",1),
1062 'remote push branch');
1064 if ($branch =~ m{^dgit/}) {
1065 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1066 } elsif ($branch =~ m{^master$}) {
1067 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1069 return (undef, undef, $ffq_prev, $gdrlast);
1072 sub record_ffq_prev_deferred () {
1073 # => ('status', "message")
1075 # deferred message is undef
1080 # if not ff from some branch we should be ff from, is an snag
1081 # if "deferred", will have added something about that to
1082 # @deferred_update_messages, and also maybe printed (already)
1083 # some messages about ff checks
1084 my $currentval = get_head();
1086 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1087 return ($status,$message) if defined $status;
1091 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1092 push @deferred_updates, "delete $gdrlast";
1093 push @deferred_update_messages, "Recorded current head for preservation";
1094 return ('deferred', undef);
1097 sub record_ffq_auto () {
1098 my ($status, $message) = record_ffq_prev_deferred();
1099 if ($status eq 'deferred' || $status eq 'exists') {
1101 snag $status, "could not record ffq-prev: $message";
1106 sub ffq_prev_info () {
1107 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1108 my ($status, $message, $current, $ffq_prev, $gdrlast)
1109 = ffq_prev_branchinfo();
1110 if ($status ne 'branch') {
1111 snag $status, "could not check ffq-prev: $message";
1114 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1115 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1118 sub stitch ($$$$$) {
1119 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1121 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1123 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1124 my $differs = get_differs $old_head, $ffq_prev_commitish;
1125 unless ($differs & ~D_PAT_ADD) {
1126 # ffq-prev is ahead of us, and the only tree changes it has
1127 # are possibly addition of things in debian/patches/.
1128 # Just wind forwards rather than making a pointless pseudomerge.
1129 push @deferred_updates,
1130 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1131 update_head_checkout $old_head, $ffq_prev_commitish,
1132 "stitch (fast forward)";
1137 # We make pseudomerges with L as the contributing parent.
1138 # This makes git rev-list --first-parent work properly.
1139 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1140 'Declare fast forward / record previous work',
1141 "[git-debrebase pseudomerge: $prose]",
1143 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1144 update_head $old_head, $new_head, "stitch: $prose";
1147 sub do_stitch ($;$) {
1148 my ($prose, $unclean) = @_;
1150 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1151 if (!$ffq_prev_commitish) {
1152 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1155 my $dangling_head = get_head();
1157 keycommits $dangling_head, $unclean,$unclean,$unclean;
1160 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1163 sub cmd_new_upstream () {
1164 # automatically and unconditionally launders before rebasing
1165 # if rebase --abort is used, laundering has still been done
1169 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1171 # parse args - low commitment
1172 my $spec_version = shift @ARGV;
1173 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1174 if ($new_version->is_native()) {
1175 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1177 my $new_upstream_version = $new_version->version();
1179 my $new_upstream = shift @ARGV;
1180 if (!defined $new_upstream) {
1182 # todo: at some point maybe use git-deborig to do this
1183 foreach my $tagpfx ('', 'v', 'upstream/') {
1184 my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1185 $new_upstream = git_get_ref "refs/tags/$tag";
1186 last if length $new_upstream;
1189 if (!length $new_upstream) {
1190 fail "Could not determine appropriate upstream commitish.\n".
1191 " (Tried these tags: @tried)\n".
1192 " Check version, and specify upstream commitish explicitly.";
1195 $new_upstream = git_rev_parse $new_upstream;
1200 my ($n, @x) = @_; # may be ''
1201 my $pc = $pieces{$n} //= {
1203 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1205 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1210 my $newpiece = sub {
1211 my ($n, @x) = @_; # may be ''
1212 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1213 push @newpieces, $pc;
1218 New => $new_upstream,
1220 while (@ARGV && $ARGV[0] !~ m{^-}) {
1221 my $n = shift @ARGV;
1223 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1224 unless @ARGV && $ARGV[0] !~ m{^-};
1226 my $c = git_rev_parse shift @ARGV;
1227 die unless $n =~ m/^$extra_orig_namepart_re$/;
1228 $newpiece->($n, New => $c);
1231 # now we need to investigate the branch this generates the
1232 # laundered version but we don't switch to it yet
1233 my $old_head = get_head();
1234 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1236 my $old_bw_cl = classify $old_bw;
1237 my $old_anchor_cl = classify $old_anchor;
1239 if (!$old_anchor_cl->{OrigParents}) {
1240 snag 'anchor-treated',
1241 'old anchor is recognised due to --anchor, cannot check upstream';
1243 $old_upstream = parsecommit
1244 $old_anchor_cl->{OrigParents}[0]{CommitId};
1245 $piece->('', Old => $old_upstream->{CommitId});
1248 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1249 if ($old_upstream->{Msg} =~
1250 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1252 my @oldpieces = (split / /, $1);
1253 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1254 if ($old_n_parents != @oldpieces &&
1255 $old_n_parents != @oldpieces + 1) {
1256 snag 'upstream-confusing', sprintf
1257 "previous upstream combine %s".
1258 " mentions %d pieces (each implying one parent)".
1259 " but has %d parents".
1260 " (one per piece plus maybe a previous combine)",
1261 $old_upstream->{CommitId},
1262 (scalar @oldpieces),
1264 } elsif ($oldpieces[0] ne '.') {
1265 snag 'upstream-confusing', sprintf
1266 "previous upstream combine %s".
1267 " first piece is not \`.'",
1271 foreach my $i (0..$#oldpieces) {
1272 my $n = $oldpieces[$i];
1273 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1274 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1278 snag 'upstream-confusing',
1279 "previous upstream $old_upstream->{CommitId} is from".
1280 " git-debrebase but not an \`upstream-combine' commit";
1284 foreach my $pc (values %pieces) {
1285 if (!$old_upstream) {
1286 # we have complained already
1287 } elsif (!$pc->{Old}) {
1288 snag 'upstream-new-piece',
1289 "introducing upstream piece \`$pc->{Name}'";
1290 } elsif (!$pc->{New}) {
1291 snag 'upstream-rm-piece',
1292 "dropping upstream piece \`$pc->{Name}'";
1293 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1294 snag 'upstream-not-ff',
1295 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1299 printdebug "%pieces = ", (dd \%pieces), "\n";
1300 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1308 my @upstream_merge_parents;
1311 push @upstream_merge_parents, $old_upstream->{CommitId};
1314 foreach my $pc (@newpieces) { # always has '' first
1316 read_tree_subdir $pc->{Name}, $pc->{New};
1318 runcmd @git, qw(read-tree), $pc->{New};
1320 push @upstream_merge_parents, $pc->{New};
1323 # index now contains the new upstream
1325 if (@newpieces > 1) {
1326 # need to make the upstream subtree merge commit
1327 $new_upstream = make_commit \@upstream_merge_parents,
1328 [ "Combine upstreams for $new_upstream_version",
1329 ("[git-debrebase upstream-combine . ".
1330 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1335 # $new_upstream is either the single upstream commit, or the
1336 # combined commit we just made. Either way it will be the
1337 # "upstream" parent of the anchor merge.
1339 read_tree_subdir 'debian', "$old_bw:debian";
1341 # index now contains the anchor merge contents
1342 $new_bw = make_commit [ $old_bw, $new_upstream ],
1343 [ "Update to upstream $new_upstream_version",
1344 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1347 my $clogsignoff = cmdoutput qw(git show),
1348 '--pretty=format:%an <%ae> %aD',
1351 # Now we have to add a changelog stanza so the Debian version
1353 die if unlink "debian";
1354 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1355 unlink "debian/changelog" or $!==ENOENT or die $!;
1356 mkdir "debian" or die $!;
1357 open CN, ">", "debian/changelog" or die $!;
1358 my $oldclog = git_cat_file ":debian/changelog";
1359 $oldclog =~ m/^($package_re) \(\S+\) / or
1360 fail "cannot parse old changelog to get package name";
1362 print CN <<END, $oldclog or die $!;
1363 $p ($new_version) UNRELEASED; urgency=medium
1365 * Update to new upstream version $new_upstream_version.
1371 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1373 # Now we have the final new breakwater branch in the index
1374 $new_bw = make_commit [ $new_bw ],
1375 [ "Update changelog for new upstream $new_upstream_version",
1376 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1380 # we have constructed the new breakwater. we now need to commit to
1381 # the laundering output, because git-rebase can't easily be made
1382 # to make a replay list which is based on some other branch
1384 update_head_postlaunder $old_head, $old_laundered_tip,
1385 'launder for new upstream';
1387 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1388 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1389 "debrebase new-upstream $new_version: rebase";
1391 # now it's for the user to sort out
1394 sub cmd_record_ffq_prev () {
1395 badusage "no arguments allowed" if @ARGV;
1396 my ($status, $msg) = record_ffq_prev_deferred();
1397 if ($status eq 'exists' && $opt_noop_ok) {
1398 print "Previous head already recorded\n" or die $!;
1399 } elsif ($status eq 'deferred') {
1400 run_deferred_updates 'record-ffq-prev';
1402 fail "Could not preserve: $msg";
1407 badusage "no arguments allowed" if @ARGV;
1408 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1409 print "$bw\n" or die $!;
1412 sub cmd_breakwater () {
1413 badusage "no arguments allowed" if @ARGV;
1414 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1415 print "$bw\n" or die $!;
1419 badusage "no arguments allowed" if @ARGV;
1421 # todo: gdr status should print divergence info
1422 # todo: gdr status should print upstream component(s) info
1423 # todo: gdr should leave/maintain some refs with this kind of info ?
1425 my $oldest = { Badness => 0 };
1428 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1429 if ($oldest->{Badness} < $badness) {
1430 $oldest = $newest = undef;
1433 Badness => $badness,
1434 CommitId => $cl->{CommitId},
1438 $newest //= $oldest;
1440 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1441 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1442 sub { $note->(2, 'branch is unlaundered', @_); },
1443 sub { $note->(3, 'branch needs laundering', @_); },
1444 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1446 my $prcommitinfo = sub {
1448 flush STDOUT or die $!;
1449 runcmd @git, qw(--no-pager log -n1),
1450 '--pretty=format: %h %s%n',
1454 print "current branch contents, in git-debrebase terms:\n";
1455 if (!$oldest->{Badness}) {
1456 print " branch is laundered\n";
1458 print " $oldest->{OurMsg}\n";
1460 foreach my $info ($oldest, $newest) {
1461 my $cid = $info->{CommitId};
1462 next if $cid eq $printed;
1464 print " $info->{KcMsg}\n";
1465 $prcommitinfo->($cid);
1470 my ($cid, $what) = @_;
1471 if (!defined $cid) {
1472 print " $what is not well-defined\n";
1475 $prcommitinfo->($cid);
1478 print "key git-debrebase commits:\n";
1479 $prab->($anchor, 'anchor');
1480 $prab->($bw, 'breakwater');
1482 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1483 ffq_prev_branchinfo();
1485 print "branch and ref status, in git-debrebase terms:\n";
1487 print " $ffq_msg\n";
1489 $ffq_prev = git_get_ref $ffq_prev;
1490 $gdrlast = git_get_ref $gdrlast;
1492 print " unstitched; previous tip was:\n";
1493 $prcommitinfo->($ffq_prev);
1494 } elsif (!$gdrlast) {
1495 print " stitched? (no record of git-debrebase work)\n";
1496 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1497 print " stitched\n";
1499 print " not git-debrebase (diverged since last stitch)\n"
1505 my $prose = 'stitch';
1506 GetOptions('prose=s', \$prose) or badusage("bad options to stitch");
1507 badusage "no arguments allowed" if @ARGV;
1508 do_stitch $prose, 0;
1510 sub cmd_prepush () { cmd_stitch(); }
1513 badusage "no arguments allowed" if @ARGV;
1514 do_launder_head 'launder for git-debrebase quick';
1518 sub cmd_conclude () {
1519 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1520 if (!$ffq_prev_commitish) {
1521 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1524 my $dangling_head = get_head();
1526 badusage "no arguments allowed" if @ARGV;
1527 do_launder_head 'launder for git-debrebase quick';
1531 sub make_patches_staged ($) {
1533 # Produces the patches that would result from $head if it were
1535 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1538 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1539 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1540 my @gbp_cmd = (qw(gbp pq export));
1541 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1543 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1546 runcmd @git, qw(add -f debian/patches);
1550 sub make_patches ($) {
1552 keycommits $head, 0, \&snag;
1553 make_patches_staged $head;
1556 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1557 runcmd @git, qw(read-tree), $head;
1558 read_tree_subdir 'debian/patches', $ptree;
1559 $out = make_commit [$head], [
1560 'Commit patch queue (exported by git-debrebase)',
1561 '[git-debrebase: export and commit patches]',
1567 sub cmd_make_patches () {
1568 my $opt_quiet_would_amend;
1569 GetOptions('quiet-would-amend!', \$opt_quiet_would_amend)
1570 or badusage("bad options to make-patches");
1571 badusage "no arguments allowed" if @ARGV;
1572 my $old_head = get_head();
1573 my $new = make_patches $old_head;
1574 my $d = get_differs $old_head, $new;
1576 fail "No (more) patches to export." unless $opt_noop_ok;
1578 } elsif ($d == D_PAT_ADD) {
1580 update_head_checkout $old_head, $new, 'make-patches';
1582 print STDERR failmsg
1583 "Patch export produced patch amendments".
1584 " (abandoned output commit $new).".
1585 " Try laundering first."
1586 unless $opt_quiet_would_amend;
1591 sub cmd_convert_from_gbp () {
1592 badusage "needs 1 optional argument, the upstream git rev"
1594 my ($upstream_spec) = @ARGV;
1595 $upstream_spec //= 'refs/heads/upstream';
1596 my $upstream = git_rev_parse $upstream_spec;
1597 my $old_head = get_head();
1599 my $upsdiff = get_differs $upstream, $old_head;
1600 if ($upsdiff & D_UPS) {
1601 runcmd @git, qw(--no-pager diff),
1602 $upstream, $old_head,
1603 qw( -- :!/debian :/);
1604 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1607 if (!is_fast_fwd $upstream, $old_head) {
1608 snag 'upstream-not-ancestor',
1609 "upstream ($upstream) is not an ancestor of HEAD";
1611 my $wrong = cmdoutput
1612 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1613 qw(-- :/ :!/debian));
1614 if (length $wrong) {
1615 snag 'unexpected-upstream-changes',
1616 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1617 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1621 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1622 snag 'upstream-has-debian',
1623 "upstream ($upstream) contains debian/ directory";
1626 my $previous_dgit_view = eval {
1627 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1629 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1630 my ($stz, $desc) = @_;
1631 no warnings qw(exiting);
1632 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1633 next unless $stz->{Date};
1634 next unless $stz->{Distribution} ne 'UNRELEASED';
1635 $lvsn = $stz->{Version};
1636 $suite = $stz->{Distribution};
1639 die "neither of the first two changelog entries are released\n"
1640 unless defined $lvsn;
1641 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1642 my $mtag_pat = debiantag_maintview $lvsn, '*';
1643 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1645 die "could not find suitable maintainer view tag $mtag_pat\n"
1646 unless $mtag_pat =~ m{/};
1647 is_fast_fwd $mtag, 'HEAD' or
1648 die "HEAD is not FF from maintainer tag $mtag!";
1649 my $dtag = "archive/$mtag";
1650 is_fast_fwd $mtag, $dtag or
1651 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1652 print "will stitch in dgit view, $dtag\n";
1653 git_rev_parse $dtag;
1655 if (!$previous_dgit_view) {
1658 print STDERR "cannot stitch in dgit view: $@\n";
1661 snags_maybe_bail_early();
1667 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1668 # make a branch out of the patch queue - we'll want this in a mo
1669 runcmd qw(gbp pq import);
1670 # strip the patches out
1671 runcmd @git, qw(checkout -q gdr-internal~0);
1672 rm_subdir_cached 'debian/patches';
1673 $work = make_commit ['HEAD'], [
1674 'git-debrebase convert-from-gbp: drop patches from tree',
1675 'Delete debian/patches, as part of converting to git-debrebase format.',
1676 '[git-debrebase convert-from-gbp: drop patches from tree]'
1678 # make the anchor merge
1679 # the tree is already exactly right
1680 $work = make_commit [$work, $upstream], [
1681 'git-debrebase import: declare upstream',
1682 'First breakwater merge.',
1683 '[git-debrebase anchor: declare upstream]'
1686 # rebase the patch queue onto the new breakwater
1687 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1688 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1689 $work = git_rev_parse 'HEAD';
1691 if ($previous_dgit_view) {
1692 $work = make_commit [$work, $previous_dgit_view], [
1693 'git-debrebase import: declare ff from dgit archive view',
1694 '[git-debrebase pseudomerge: import-from-gbp]',
1701 update_head_checkout $old_head, $work, 'convert-from-gbp';
1704 sub cmd_convert_to_gbp () {
1705 badusage "no arguments allowed" if @ARGV;
1706 my $head = get_head();
1707 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1708 keycommits $head, 0;
1710 make_patches_staged $head;
1712 $out = make_commit ['HEAD'], [
1713 'Commit patch queue (converted from git-debrebase format)',
1714 '[git-debrebase convert-to-gbp: commit patches]',
1718 push @deferred_updates, "delete $ffq";
1719 push @deferred_updates, "delete $gdrlast";
1722 update_head_checkout $head, $out, "convert to gbp (v0)";
1723 print <<END or die $!;
1724 git-debrebase: converted to git-buildpackage branch format
1725 git-debrebase: WARNING: do not now run "git-debrebase" any more
1726 git-debrebase: WARNING: doing so would drop all upstream patches!
1730 sub cmd_downstream_rebase_launder_v0 () {
1731 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1733 $base = git_rev_parse $base;
1734 my $old_head = get_head();
1735 my $current = $old_head;
1738 if ($current eq $base) {
1739 $topmost_keep //= $current;
1740 print " $current BASE stop\n";
1743 my $cl = classify $current;
1744 print " $current $cl->{Type}";
1746 my $p0 = $cl->{Parents}[0]{CommitId};
1748 if ($cl->{Type} eq 'Pseudomerge') {
1749 print " ^".($cl->{Contributor}{Ix}+1);
1750 $next = $cl->{Contributor}{CommitId};
1751 } elsif ($cl->{Type} eq 'AddPatches' or
1752 $cl->{Type} eq 'Changelog') {
1762 $topmost_keep //= $current;
1764 die "to-be stripped changes not on top of the branch\n"
1769 if ($topmost_keep eq $old_head) {
1770 print "unchanged\n";
1772 print "updating to $topmost_keep\n";
1773 update_head_checkout
1774 $old_head, $topmost_keep,
1775 'downstream-rebase-launder-v0';
1779 GetOptions("D+" => \$debuglevel,
1780 'noop-ok', => \$opt_noop_ok,
1781 'f=s' => \@snag_force_opts,
1782 'anchor=s' => \@opt_anchors,
1785 my ($opt,$val) = @_;
1786 badusage "git-debrebase: no cuddling to -i for git-rebase"
1788 die if $opt_defaultcmd_interactive; # should not happen
1789 $opt_defaultcmd_interactive = [ qw(-i) ];
1790 # This access to @ARGV is excessive familiarity with
1791 # Getopt::Long, but there isn't another sensible
1792 # approach. '-i=s{0,}' does not work with bundling.
1793 push @$opt_defaultcmd_interactive, @ARGV;
1795 }) or badusage "bad options\n";
1796 initdebug('git-debrebase ');
1797 enabledebug if $debuglevel;
1799 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1800 chdir $toplevel or die "chdir $toplevel: $!";
1802 $rd = fresh_playground "$playprefix/misc";
1804 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1806 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1807 defaultcmd_rebase();
1809 my $cmd = shift @ARGV;
1812 $cmdfn = ${*::}{"cmd_$cmdfn"};
1814 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";