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 "$us: bad usage: $m\n";
54 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
55 GetOptions @_ or badusage $m;
59 my ($k, $optional) = @_;
61 my @cmd = qw(git config -z);
62 push @cmd, qw(--get-all) if wantarray;
64 my $out = cmdoutput_errok @cmd;
66 fail "missing required git config $k" unless $optional;
69 my @l = split /\0/, $out;
70 return wantarray ? @l : $l[0];
77 my $dd = new Data::Dumper [ $v ];
78 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
84 my $data = (git_cat_file $objid, 'commit');
85 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
89 sub D_UPS () { 0x02; } # upstream files
90 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
91 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
92 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
93 sub D_DEB_OTH () { 0x20; } # debian/changelog
94 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
96 our $playprefix = 'debrebase';
102 sub in_workarea ($) {
105 my $r = eval { $sub->(); };
106 { local $@; changedir $maindir; }
110 sub fresh_workarea () {
111 $workarea = fresh_playground "$playprefix/work";
112 in_workarea sub { playtree_setup };
115 our $snags_forced = 0;
116 our $snags_tripped = 0;
117 our $snags_summarised = 0;
118 our @deferred_updates;
119 our @deferred_update_messages;
121 sub all_snags_summarised () {
122 $snags_forced + $snags_tripped == $snags_summarised;
124 sub run_deferred_updates ($) {
127 confess 'dangerous internal error' unless all_snags_summarised();
129 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
130 debugcmd '>|', @upd_cmd;
131 open U, "|-", @upd_cmd or die $!;
132 foreach (@deferred_updates) {
133 printdebug ">= ", $_, "\n";
134 print U $_, "\n" or die $!;
137 close U or failedcmd @upd_cmd;
139 print $_, "\n" foreach @deferred_update_messages;
141 @deferred_updates = ();
142 @deferred_update_messages = ();
145 sub get_differs ($$) {
147 # This resembles quiltify_trees_differ, in dgit, a bit.
148 # But we don't care about modes, or dpkg-source-unrepresentable
149 # changes, and we don't need the plethora of different modes.
150 # Conversely we need to distinguish different kinds of changes to
151 # debian/ and debian/patches/.
156 my ($opts, $limits, $fn) = @_;
157 my @cmd = (@git, qw(diff-tree -z --no-renames));
159 push @cmd, "$_:" foreach $x, $y;
160 push @cmd, '--', @$limits;
161 my $diffs = cmdoutput @cmd;
162 foreach (split /\0/, $diffs) { $fn->(); }
165 $rundiff->([qw(--name-only)], [], sub {
166 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
169 if ($differs & DS_DEB) {
171 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
173 m{^debian/patches/} ? D_PAT_OTH :
174 $_ eq 'debian/changelog' ? D_DEB_CLOG :
177 die "mysterious debian changes $x..$y"
178 unless $differs & (D_PAT_OTH|DS_DEB);
181 if ($differs & D_PAT_OTH) {
183 $differs &= ~D_PAT_OTH;
185 $differs |= D_PAT_OTH;
186 no warnings qw(exiting); last;
188 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
189 no warnings qw(exiting);
190 if (!defined $mode) {
193 die unless s{^debian/patches/}{};
195 if ($mode eq 'A' && !m/\.series$/s) {
197 } elsif ($mode eq 'M' && $_ eq 'series') {
198 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
199 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
200 chomp $x_s; $x_s .= "\n";
201 $ok = $x_s eq substr($y_s, 0, length $x_s);
206 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
208 die "mysterious debian/patches changes $x..$y"
209 unless $differs & (D_PAT_ADD|D_PAT_OTH);
212 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
217 sub commit_pr_info ($) {
219 return Data::Dumper->dump([$r], [qw(commit)]);
222 sub calculate_committer_authline () {
223 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
224 'DUMMY COMMIT (git-debrebase)', "HEAD:";
225 my ($h,$m) = get_commit $c;
226 $h =~ m/^committer .*$/m or confess "($h) ?";
230 sub rm_subdir_cached ($) {
232 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
235 sub read_tree_subdir ($$) {
236 my ($subdir, $new_tree_object) = @_;
237 rm_subdir_cached $subdir;
238 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
241 sub make_commit ($$) {
242 my ($parents, $message_paras) = @_;
243 my $tree = cmdoutput @git, qw(write-tree);
244 my @cmd = (@git, qw(commit-tree), $tree);
245 push @cmd, qw(-p), $_ foreach @$parents;
246 push @cmd, qw(-m), $_ foreach @$message_paras;
247 return cmdoutput @cmd;
250 our @snag_force_opts;
252 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
253 if (grep { $_ eq $tag } @snag_force_opts) {
255 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
258 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
262 # Important: all mainline code must call snags_maybe_bail after
263 # any point where snag might be called, but before making changes
264 # (eg before any call to run_deferred_updates). snags_maybe_bail
265 # may be called more than once if necessary (but this is not ideal
266 # because then the messages about number of snags may be confusing).
267 sub snags_maybe_bail () {
268 return if all_snags_summarised();
271 "%s: snags: %d overriden by individual -f options\n",
274 if ($snags_tripped) {
277 "%s: snags: %d overriden by global --force\n",
281 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
285 $snags_summarised = $snags_forced + $snags_tripped;
287 sub snags_maybe_bail_early () {
288 # useful to bail out early without doing a lot of work;
289 # not a substitute for snags_maybe_bail.
290 snags_maybe_bail() if $snags_tripped && !$opt_force;
293 return $snags_forced || $snags_tripped;
296 # classify returns an info hash like this
298 # Hdr => # commit headers, including 1 final newline
299 # Msg => # commit message (so one newline is dropped)
301 # Type => (see below)
303 # Ix => $index # ie 0, 1, 2, ...
305 # Differs => return value from get_differs
307 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
309 # NewMsg => # commit message, but with any [dgit import ...] edited
310 # # to say "[was: ...]"
320 # has additional entres in classification result
321 # Overwritten = [ subset of Parents ]
322 # Contributor = $the_remaining_Parent
324 # DgitImportUnpatched
325 # has additional entry in classification result
326 # OrigParents = [ subset of Parents ]
329 # has additional entry in classification result
330 # OrigParents = [ subset of Parents ] # singleton list
337 # has additional entry in classification result
340 sub parsecommit ($;$) {
341 my ($objid, $p_ref) = @_;
342 # => hash with CommitId Hdr Msg Tree Parents
343 # Parents entries have only Ix CommitId
344 # $p_ref, if provided, must be [] and is used as a base for Parents
349 my ($h,$m) = get_commit $objid;
351 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
352 my (@ph) = $h =~ m/^parent (\w+)$/mg;
362 foreach my $ph (@ph) {
364 Ix => scalar @$p_ref,
376 my $r = parsecommit($objid, \@p);
380 $p->{Differs} = (get_differs $p->{CommitId}, $t),
383 printdebug "classify $objid \$t=$t \@p",
384 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
388 my ($type, @rest) = @_;
389 $r = { %$r, Type => $type, @rest };
391 printdebug " = $type ".(dd $r)."\n";
397 $r = { %$r, Type => qw(Unknown), Why => $why };
398 printdebug " ** Unknown\n";
402 if (grep { $_ eq $objid } @opt_anchors) {
403 return $classify->('TreatAsAnchor');
406 my @identical = grep { !$_->{Differs} } @p;
407 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
408 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
410 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
411 # multi-orig upstreams are represented with an anchor merge
412 # from a single upstream commit which combines the orig tarballs
414 # Every anchor tagged this way must be a merge.
415 # We are relying on the
416 # [git-debrebase anchor: ...]
417 # commit message annotation in "declare" anchor merges (which
418 # do not have any upstream changes), to distinguish those
419 # anchor merges from ordinary pseudomerges (which we might
420 # just try to strip).
422 # However, the user is going to be doing git-rebase a lot. We
423 # really don't want them to rewrite an anchor commit.
424 # git-rebase trips up on merges, so that is a useful safety
427 # BreakwaterStart commits are also anchors in the terminology
428 # of git-debrebase(5), but they are untagged (and always
429 # manually generated).
431 # We cannot not tolerate any tagged linear commit (ie,
432 # BreakwaterStart commits tagged `[anchor:') because such a
433 # thing could result from an erroneous linearising raw git
434 # rebase of a merge anchor. That would represent a corruption
435 # of the branch. and we want to detect and reject the results
436 # of such corruption before it makes it out anywhere. If we
437 # reject it here then we avoid making the pseudomerge which
438 # would be needed to push it.
440 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
441 @p == 2 or return $badanchor->("has other than two parents");
442 $haspatches and return $badanchor->("contains debian/patches");
444 # How to decide about l/r ordering of anchors ? git
445 # --topo-order prefers to expand 2nd parent first. There's
446 # already an easy rune to look for debian/ history anyway (git log
447 # debian/) so debian breakwater branch should be 1st parent; that
448 # way also there's also an easy rune to look for the upstream
449 # patches (--topo-order).
451 # Also this makes --first-parent be slightly more likely to
452 # be useful - it makes it provide a linearised breakwater history.
454 # Of course one can say somthing like
455 # gitk -- ':/' ':!/debian'
456 # to get _just_ the commits touching upstream files, and by
457 # the TREESAME logic in git-rev-list this will leave the
458 # breakwater into upstream at the first anchor. But that
459 # doesn't report debian/ changes at all.
461 # Other observations about gitk: by default, gitk seems to
462 # produce output in a different order to git-rev-list. I
463 # can't seem to find this documented anywhere. gitk
464 # --date-order DTRT. But, gitk always seems to put the
465 # parents from left to right, in order, so it's easy to see
466 # which way round a pseudomerge is.
468 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
469 $p[1]{Differs} & ~DS_DEB and
470 $badanchor->("upstream files differ from left parent");
471 $p[0]{Differs} & ~D_UPS and
472 $badanchor->("debian/ differs from right parent");
474 return $classify->(qw(Anchor),
475 OrigParents => [ $p[1] ]);
479 my $d = $r->{Parents}[0]{Differs};
480 if ($d == D_PAT_ADD) {
481 return $classify->(qw(AddPatches));
482 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
483 return $unknown->("edits debian/patches");
484 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
485 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
487 if ($d == D_DEB_CLOG) {
488 return $classify->(qw(Changelog));
490 return $classify->(qw(Packaging));
492 } elsif ($ty eq 'missing') {
493 return $classify->(qw(BreakwaterStart));
495 return $unknown->("parent's debian is not a directory");
497 } elsif ($d == D_UPS) {
498 return $classify->(qw(Upstream));
499 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
500 return $classify->(qw(Mixed));
502 return $unknown->("no changes");
504 confess "internal error $objid ?";
508 return $unknown->("origin commit");
511 if (@p == 2 && @identical == 1) {
512 my @overwritten = grep { $_->{Differs} } @p;
513 confess "internal error $objid ?" unless @overwritten==1;
514 return $classify->(qw(Pseudomerge),
515 Overwritten => [ $overwritten[0] ],
516 Contributor => $identical[0]);
518 if (@p == 2 && @identical == 2) {
520 my ($ph,$pm) = get_commit $_[0]{CommitId};
521 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
525 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
526 if ($order > 0) { # newer first
527 } elsif ($order < 0) {
528 @bytime = reverse @bytime;
530 # same age, default to order made by -s ours
531 # that is, commit was made by someone who preferred L
533 return $classify->(qw(Pseudomerge),
534 SubType => qw(Ambiguous),
535 Contributor => $bytime[0],
536 Overwritten => [ $bytime[1] ]);
539 my ($p_h, $p_m) = get_commit $p->{CommitId};
540 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
541 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
543 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
545 if (!(grep { !$_->{IsOrigin} } @p) and
546 (@orig_ps >= @p - 1) and
547 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
549 return $classify->(qw(DgitImportUnpatched),
550 OrigParents => \@orig_ps);
553 return $unknown->("complex merge");
556 sub keycommits ($;$$$$) {
557 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
558 # => ($anchor, $breakwater)
560 # $unclean->("unclean-$tagsfx", $msg, $cl)
561 # $furniture->("unclean-$tagsfx", $msg, $cl)
562 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
563 # is callled for each situation or commit that
564 # wouldn't be found in a laundered branch
565 # $furniture is for furniture commits such as might be found on an
566 # interchange branch (pseudomerge, d/patches, changelog)
567 # $trouble is for things whnich prevent the return of
568 # anchor and breakwater information; if that is ignored,
569 # then keycommits returns (undef, undef) instead.
570 # $fatal is for unprocessable commits, and should normally cause
571 # a failure. If ignored, agaion, (undef, undef) is returned.
573 # If a callback is undef, fail is called instead.
574 # If a callback is defined but false, the situation is ignored.
576 # no warnings qw(exiting); last;
577 # if the answer is no longer wanted.
579 my ($anchor, $breakwater);
582 $fatal //= sub { fail $_[1]; };
584 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
585 my $why = $mainwhy.$xwhy;
586 my $m = "branch needs laundering (run git-debrebase): $why";
587 fail $m unless defined $cb;
589 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
592 $cl = classify $head;
593 my $ty = $cl->{Type};
594 if ($ty eq 'Packaging') {
595 $breakwater //= $clogonly;
596 $breakwater //= $head;
597 } elsif ($ty eq 'Changelog') {
598 # this is going to count as the tip of the breakwater
599 # only if it has no upstream stuff before it
601 } elsif ($ty eq 'Anchor' or
602 $ty eq 'TreatAsAnchor' or
603 $ty eq 'BreakwaterStart') {
605 $breakwater //= $clogonly;
606 $breakwater //= $head;
608 } elsif ($ty eq 'Upstream') {
609 $x->($unclean, 'ordering',
610 "packaging change ($breakwater) follows upstream change"," (eg $head)")
611 if defined $breakwater;
614 } elsif ($ty eq 'Mixed') {
615 $x->($unclean, 'mixed',
616 "found mixed upstream/packaging commit"," ($head)");
619 } elsif ($ty eq 'Pseudomerge' or
620 $ty eq 'AddPatches') {
621 $x->($furniture, (lc $ty),
622 "found interchange bureaucracy commit ($ty)"," ($head)");
623 } elsif ($ty eq 'DgitImportUnpatched') {
624 $x->($trouble, 'dgitimport',
625 "found dgit dsc import ($head)");
626 return (undef,undef);
628 $x->($fatal, 'unprocessable',
629 "found unprocessable commit, cannot cope: $cl->{Why}",
631 return (undef,undef);
633 $head = $cl->{Parents}[0]{CommitId};
635 return ($anchor, $breakwater);
641 $nogenerate,$report) = @_;
642 # => ($tip, $breakwater_tip, $last_anchor)
643 # (or nothing, if $nogenerate)
645 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
647 # go through commits backwards
648 # we generate two lists of commits to apply:
649 # breakwater branch and upstream patches
650 my (@brw_cl, @upp_cl, @processed);
657 my ($prose, $info) = @_;
661 $ms .= "\n\n[git-debrebase$info: $prose]\n";
664 my $rewrite_from_here = sub {
666 my $sp_cl = { SpecialMethod => 'StartRewrite' };
668 push @processed, $sp_cl;
673 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
676 return unless $report;
677 print $report $prdelim, @_;
681 my $bomb = sub { # usage: return $bomb->();
682 print $report " Unprocessable" if $report;
683 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
686 return (undef,undef);
688 fail "found unprocessable commit, cannot cope:".
689 (defined $cl->{Why} ? "; $cl->{Why}": '').
690 " (commit $cur) (d.".
691 (join ' ', map { sprintf "%#x", $_->{Differs} }
692 @{ $cl->{Parents} }).
699 my $build_start = sub {
700 my ($msg, $parent) = @_;
703 no warnings qw(exiting); last;
710 my $ty = $cl->{Type};
711 my $st = $cl->{SubType};
712 $prline->("$cl->{CommitId} $cl->{Type}");
713 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
714 push @processed, $cl;
715 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
716 if ($ty eq 'AddPatches') {
718 $rewrite_from_here->(\@upp_cl);
720 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
724 } elsif ($ty eq 'BreakwaterStart') {
726 $build_start->('FirstPackaging', $cur);
727 } elsif ($ty eq 'Upstream') {
731 } elsif ($ty eq 'Mixed') {
734 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
737 $queue->(\@brw_cl, "debian");
738 $queue->(\@upp_cl, "upstream");
739 $rewrite_from_here->(\@brw_cl);
742 } elsif ($ty eq 'Pseudomerge') {
743 my $contrib = $cl->{Contributor}{CommitId};
744 print $report " Contributor=$contrib" if $report;
745 push @pseudomerges, $cl;
746 $rewrite_from_here->(\@upp_cl);
749 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
751 $build_start->("Anchor", $cur);
752 } elsif ($ty eq 'DgitImportUnpatched') {
753 my $pm = $pseudomerges[-1];
755 # To an extent, this is heuristic. Imports don't have
756 # a useful history of the debian/ branch. We assume
757 # that the first pseudomerge after an import has a
758 # useful history of debian/, and ignore the histories
759 # from later pseudomerges. Often the first pseudomerge
760 # will be the dgit import of the upload to the actual
761 # suite intended by the non-dgit NMUer, and later
762 # pseudomerges may represent in-archive copies.
763 my $ovwrs = $pm->{Overwritten};
764 printf $report " PM=%s \@Overwr:%d",
765 $pm->{CommitId}, (scalar @$ovwrs)
768 printdebug "*** WALK BOMB DgitImportUnpatched\n";
771 my $ovwr = $ovwrs->[0]{CommitId};
772 printf $report " Overwr=%s", $ovwr if $report;
773 # This import has a tree which is just like a
774 # breakwater tree, but it has the wrong history. It
775 # ought to have the previous breakwater (which the
776 # pseudomerge overwrote) as an ancestor. That will
777 # make the history of the debian/ files correct. As
778 # for the upstream version: either it's the same as
779 # was ovewritten (ie, same as the previous
780 # breakwater), in which case that history is precisely
781 # right; or, otherwise, it was a non-gitish upload of a
782 # new upstream version. We can tell these apart by
783 # looking at the tree of the supposed upstream.
786 SpecialMethod => 'DgitImportDebianUpdate',
787 $xmsg->("convert dgit import: debian changes")
790 SpecialMethod => 'DgitImportUpstreamUpdate',
791 $xmsg->("convert dgit import: upstream update",
794 $prline->(" Import");
795 $rewrite_from_here->(\@brw_cl);
796 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
800 # Everything is from this import. This kind of import
801 # is already in valid breakwater format, with the
802 # patches as commits.
803 printf $report " NoPM" if $report;
804 # last thing we processed will have been the first patch,
805 # if there is one; which is fine, so no need to rewrite
806 # on account of this import
807 $build_start->("ImportOrigin", $cur);
811 printdebug "*** WALK BOMB unrecognised\n";
817 printdebug "*** WALK prep done cur=$cur".
818 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
820 return if $nogenerate;
822 # Now we build it back up again
828 my $read_tree_debian = sub {
830 read_tree_subdir 'debian', "$treeish:debian";
831 rm_subdir_cached 'debian/patches';
833 my $read_tree_upstream = sub {
835 runcmd @git, qw(read-tree), $treeish;
836 $read_tree_debian->($build);
839 $#upp_cl = $upp_limit if defined $upp_limit;
841 my $committer_authline = calculate_committer_authline();
843 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
845 confess "internal error" unless $build eq (pop @processed)->{CommitId};
848 mkdir $rd or $!==EEXIST or die $!;
850 runcmd @git, qw(read-tree), $build;
851 foreach my $cl (qw(Debian), (reverse @brw_cl),
852 { SpecialMethod => 'RecordBreakwaterTip' },
853 qw(Upstream), (reverse @upp_cl)) {
855 $current_method = $cl;
858 my $method = $cl->{SpecialMethod} // $current_method;
859 my @parents = ($build);
860 my $cltree = $cl->{CommitId};
861 printdebug "WALK BUILD ".($cltree//'undef').
862 " $method (rewriting=$rewriting)\n";
863 if ($method eq 'Debian') {
864 $read_tree_debian->($cltree);
865 } elsif ($method eq 'Upstream') {
866 $read_tree_upstream->($cltree);
867 } elsif ($method eq 'StartRewrite') {
870 } elsif ($method eq 'RecordBreakwaterTip') {
871 $breakwater = $build;
873 } elsif ($method eq 'DgitImportDebianUpdate') {
874 $read_tree_debian->($cltree);
875 } elsif ($method eq 'DgitImportUpstreamUpdate') {
876 confess unless $rewriting;
877 my $differs = (get_differs $build, $cltree);
878 next unless $differs & D_UPS;
879 $read_tree_upstream->($cltree);
880 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
885 my $procd = (pop @processed) // 'UNDEF';
888 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
891 my $newtree = cmdoutput @git, qw(write-tree);
893 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
894 $ch =~ s{^parent .*\n}{}mg;
895 $ch =~ s{(?=^author)}{
896 join '', map { "parent $_\n" } @parents
897 }me or confess "$ch ?";
899 $ch =~ s{^committer .*$}{$committer_authline}m
902 my $cf = "$rd/m$rewriting";
903 open CD, ">", $cf or die $!;
904 print CD $ch, "\n", $cl->{Msg} or die $!;
906 my @cmd = (@git, qw(hash-object));
907 push @cmd, qw(-w) if $rewriting;
908 push @cmd, qw(-t commit), $cf;
909 my $newcommit = cmdoutput @cmd;
910 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
912 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
918 my $final_check = get_differs $build, $input;
919 die sprintf "internal error %#x %s %s", $final_check, $build, $input
920 if $final_check & ~D_PAT_ADD;
922 my @r = ($build, $breakwater, $last_anchor);
923 printdebug "*** WALK RETURN @r\n";
928 git_check_unmodified();
929 return git_rev_parse qw(HEAD);
932 sub update_head ($$$) {
933 my ($old, $new, $mrest) = @_;
934 push @deferred_updates, "update HEAD $new $old";
935 run_deferred_updates $mrest;
938 sub update_head_checkout ($$$) {
939 my ($old, $new, $mrest) = @_;
940 update_head $old, $new, $mrest;
941 runcmd @git, qw(reset --hard);
944 sub update_head_postlaunder ($$$) {
945 my ($old, $tip, $reflogmsg) = @_;
946 return if $tip eq $old;
947 print "git-debrebase: laundered (head was $old)\n";
948 update_head $old, $tip, $reflogmsg;
949 # no tree changes except debian/patches
950 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
953 sub do_launder_head ($) {
954 my ($reflogmsg) = @_;
955 my $old = get_head();
957 my ($tip,$breakwater) = walk $old;
959 update_head_postlaunder $old, $tip, $reflogmsg;
960 return ($tip,$breakwater);
963 sub cmd_launder_v0 () {
964 badusage "no arguments to launder-v0 allowed" if @ARGV;
965 my $old = get_head();
966 my ($tip,$breakwater,$last_anchor) = walk $old;
967 update_head_postlaunder $old, $tip, 'launder';
968 printf "# breakwater tip\n%s\n", $breakwater;
969 printf "# working tip\n%s\n", $tip;
970 printf "# last anchor\n%s\n", $last_anchor;
973 sub defaultcmd_rebase () {
974 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
975 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
976 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
980 badusage "analyse does not support any options"
981 if @ARGV and $ARGV[0] =~ m/^-/;
982 badusage "too many arguments to analyse" if @ARGV>1;
985 $old = git_rev_parse $old;
987 $old = git_rev_parse 'HEAD';
989 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
990 STDOUT->error and die $!;
993 sub ffq_prev_branchinfo () {
994 my $current = git_get_symref();
995 return gdr_ffq_prev_branchinfo($current);
998 sub ffq_check ($;$$) {
999 # calls $ff and/or $notff zero or more times
1000 # then returns either (status,message) where status is
1005 # or (undef,undef, $ffq_prev,$gdrlast)
1006 # $ff and $notff are called like this:
1007 # $ff->("message for stdout\n");
1008 # $notff->('snag-name', $message);
1009 # normally $currentval should be HEAD
1010 my ($currentval, $ff, $notff) =@_;
1012 $ff //= sub { print $_[0] or die $!; };
1015 my ($status, $message, $current, $ffq_prev, $gdrlast)
1016 = ffq_prev_branchinfo();
1017 return ($status, $message) unless $status eq 'branch';
1019 my $exists = git_get_ref $ffq_prev;
1020 return ('exists',"$ffq_prev already exists") if $exists;
1022 return ('not-branch', 'HEAD symref is not to refs/heads/')
1023 unless $current =~ m{^refs/heads/};
1026 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1029 printdebug "ffq check_specs @check_specs\n";
1032 my ($lrref, $desc) = @_;
1033 printdebug "ffq might check $lrref ($desc)\n";
1035 for my $chk (@check_specs) {
1037 $invert = $glob =~ s{^[!^]}{};
1038 last if fnmatch $glob, $lrref;
1041 my $lrval = git_get_ref $lrref;
1042 return unless length $lrval;
1044 if (is_fast_fwd $lrval, $currentval) {
1045 $ff->("OK, you are ahead of $lrref\n");
1046 $checked{$lrref} = 1;
1047 } elsif (is_fast_fwd $currentval, $lrval) {
1048 $checked{$lrref} = -1;
1049 $notff->('behind', "you are behind $lrref, divergence risk");
1051 $checked{$lrref} = -1;
1052 $notff->('diverged', "you have diverged from $lrref");
1056 my $merge = cfg "branch.$branch.merge",1;
1057 if (defined $merge and $merge =~ m{^refs/heads/}) {
1059 printdebug "ffq merge $rhs\n";
1060 my $check_remote = sub {
1061 my ($remote, $desc) = @_;
1062 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1063 return unless defined $remote;
1064 $check->("refs/remotes/$remote/$rhs", $desc);
1066 $check_remote->((scalar cfg "branch.$branch.remote",1),
1067 'remote fetch/merge branch');
1068 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1069 (scalar cfg "branch.$branch.pushDefault",1),
1070 'remote push branch');
1072 if ($branch =~ m{^dgit/}) {
1073 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1074 } elsif ($branch =~ m{^master$}) {
1075 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1077 return (undef, undef, $ffq_prev, $gdrlast);
1080 sub record_ffq_prev_deferred () {
1081 # => ('status', "message")
1083 # deferred message is undef
1088 # if not ff from some branch we should be ff from, is an snag
1089 # if "deferred", will have added something about that to
1090 # @deferred_update_messages, and also maybe printed (already)
1091 # some messages about ff checks
1092 my $currentval = get_head();
1094 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1095 return ($status,$message) if defined $status;
1099 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1100 push @deferred_updates, "delete $gdrlast";
1101 push @deferred_update_messages, "Recorded current head for preservation";
1102 return ('deferred', undef);
1105 sub record_ffq_auto () {
1106 my ($status, $message) = record_ffq_prev_deferred();
1107 if ($status eq 'deferred' || $status eq 'exists') {
1109 snag $status, "could not record ffq-prev: $message";
1114 sub ffq_prev_info () {
1115 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1116 my ($status, $message, $current, $ffq_prev, $gdrlast)
1117 = ffq_prev_branchinfo();
1118 if ($status ne 'branch') {
1119 snag $status, "could not check ffq-prev: $message";
1122 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1123 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1126 sub stitch ($$$$$) {
1127 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1129 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1131 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1132 my $differs = get_differs $old_head, $ffq_prev_commitish;
1133 unless ($differs & ~D_PAT_ADD) {
1134 # ffq-prev is ahead of us, and the only tree changes it has
1135 # are possibly addition of things in debian/patches/.
1136 # Just wind forwards rather than making a pointless pseudomerge.
1137 push @deferred_updates,
1138 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1139 update_head_checkout $old_head, $ffq_prev_commitish,
1140 "stitch (fast forward)";
1145 # We make pseudomerges with L as the contributing parent.
1146 # This makes git rev-list --first-parent work properly.
1147 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1148 'Declare fast forward / record previous work',
1149 "[git-debrebase pseudomerge: $prose]",
1151 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1152 update_head $old_head, $new_head, "stitch: $prose";
1155 sub do_stitch ($;$) {
1156 my ($prose, $unclean) = @_;
1158 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1159 if (!$ffq_prev_commitish) {
1160 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1163 my $dangling_head = get_head();
1165 keycommits $dangling_head, $unclean,$unclean,$unclean;
1168 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1171 sub resolve_upstream_version ($$) {
1172 my ($new_upstream, $version) = @_;
1174 my $new_upstream_version = "$version";
1175 $new_upstream_version =~ s/-.*?$//;;
1177 if (!defined $new_upstream) {
1179 # todo: at some point maybe use git-deborig to do this
1180 foreach my $tagpfx ('', 'v', 'upstream/') {
1181 my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1182 $new_upstream = git_get_ref "refs/tags/$tag";
1183 last if length $new_upstream;
1186 if (!length $new_upstream) {
1187 fail "Could not determine appropriate upstream commitish.\n".
1188 " (Tried these tags: @tried)\n".
1189 " Check version, and specify upstream commitish explicitly.";
1192 $new_upstream = git_rev_parse $new_upstream;
1194 return ($new_upstream, $new_upstream_version);
1197 sub cmd_new_upstream () {
1198 # automatically and unconditionally launders before rebasing
1199 # if rebase --abort is used, laundering has still been done
1203 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1205 # parse args - low commitment
1206 my $spec_version = shift @ARGV;
1207 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1208 fail "bad version number \`$spec_version'" unless defined $new_version;
1209 if ($new_version->is_native()) {
1210 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1213 my $new_upstream = shift @ARGV;
1214 my $new_upstream_version;
1215 ($new_upstream, $new_upstream_version) =
1216 resolve_upstream_version $new_upstream, $new_version;
1221 my ($n, @x) = @_; # may be ''
1222 my $pc = $pieces{$n} //= {
1224 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1226 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1231 my $newpiece = sub {
1232 my ($n, @x) = @_; # may be ''
1233 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1234 push @newpieces, $pc;
1239 New => $new_upstream,
1241 while (@ARGV && $ARGV[0] !~ m{^-}) {
1242 my $n = shift @ARGV;
1244 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1245 unless @ARGV && $ARGV[0] !~ m{^-};
1247 my $c = git_rev_parse shift @ARGV;
1248 die unless $n =~ m/^$extra_orig_namepart_re$/;
1249 $newpiece->($n, New => $c);
1252 # now we need to investigate the branch this generates the
1253 # laundered version but we don't switch to it yet
1254 my $old_head = get_head();
1255 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1257 my $old_bw_cl = classify $old_bw;
1258 my $old_anchor_cl = classify $old_anchor;
1260 if (!$old_anchor_cl->{OrigParents}) {
1261 snag 'anchor-treated',
1262 'old anchor is recognised due to --anchor, cannot check upstream';
1264 $old_upstream = parsecommit
1265 $old_anchor_cl->{OrigParents}[0]{CommitId};
1266 $piece->('', Old => $old_upstream->{CommitId});
1269 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1270 if ($old_upstream->{Msg} =~
1271 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1273 my @oldpieces = (split / /, $1);
1274 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1275 if ($old_n_parents != @oldpieces &&
1276 $old_n_parents != @oldpieces + 1) {
1277 snag 'upstream-confusing', sprintf
1278 "previous upstream combine %s".
1279 " mentions %d pieces (each implying one parent)".
1280 " but has %d parents".
1281 " (one per piece plus maybe a previous combine)",
1282 $old_upstream->{CommitId},
1283 (scalar @oldpieces),
1285 } elsif ($oldpieces[0] ne '.') {
1286 snag 'upstream-confusing', sprintf
1287 "previous upstream combine %s".
1288 " first piece is not \`.'",
1292 foreach my $i (0..$#oldpieces) {
1293 my $n = $oldpieces[$i];
1294 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1295 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1299 snag 'upstream-confusing',
1300 "previous upstream $old_upstream->{CommitId} is from".
1301 " git-debrebase but not an \`upstream-combine' commit";
1305 foreach my $pc (values %pieces) {
1306 if (!$old_upstream) {
1307 # we have complained already
1308 } elsif (!$pc->{Old}) {
1309 snag 'upstream-new-piece',
1310 "introducing upstream piece \`$pc->{Name}'";
1311 } elsif (!$pc->{New}) {
1312 snag 'upstream-rm-piece',
1313 "dropping upstream piece \`$pc->{Name}'";
1314 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1315 snag 'upstream-not-ff',
1316 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1320 printdebug "%pieces = ", (dd \%pieces), "\n";
1321 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1329 my @upstream_merge_parents;
1332 push @upstream_merge_parents, $old_upstream->{CommitId};
1335 foreach my $pc (@newpieces) { # always has '' first
1337 read_tree_subdir $pc->{Name}, $pc->{New};
1339 runcmd @git, qw(read-tree), $pc->{New};
1341 push @upstream_merge_parents, $pc->{New};
1344 # index now contains the new upstream
1346 if (@newpieces > 1) {
1347 # need to make the upstream subtree merge commit
1348 $new_upstream = make_commit \@upstream_merge_parents,
1349 [ "Combine upstreams for $new_upstream_version",
1350 ("[git-debrebase upstream-combine . ".
1351 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1356 # $new_upstream is either the single upstream commit, or the
1357 # combined commit we just made. Either way it will be the
1358 # "upstream" parent of the anchor merge.
1360 read_tree_subdir 'debian', "$old_bw:debian";
1362 # index now contains the anchor merge contents
1363 $new_bw = make_commit [ $old_bw, $new_upstream ],
1364 [ "Update to upstream $new_upstream_version",
1365 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1368 my $clogsignoff = cmdoutput qw(git show),
1369 '--pretty=format:%an <%ae> %aD',
1372 # Now we have to add a changelog stanza so the Debian version
1374 die if unlink "debian";
1375 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1376 unlink "debian/changelog" or $!==ENOENT or die $!;
1377 mkdir "debian" or die $!;
1378 open CN, ">", "debian/changelog" or die $!;
1379 my $oldclog = git_cat_file ":debian/changelog";
1380 $oldclog =~ m/^($package_re) \(\S+\) / or
1381 fail "cannot parse old changelog to get package name";
1383 print CN <<END, $oldclog or die $!;
1384 $p ($new_version) UNRELEASED; urgency=medium
1386 * Update to new upstream version $new_upstream_version.
1392 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1394 # Now we have the final new breakwater branch in the index
1395 $new_bw = make_commit [ $new_bw ],
1396 [ "Update changelog for new upstream $new_upstream_version",
1397 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1401 # we have constructed the new breakwater. we now need to commit to
1402 # the laundering output, because git-rebase can't easily be made
1403 # to make a replay list which is based on some other branch
1405 update_head_postlaunder $old_head, $old_laundered_tip,
1406 'launder for new upstream';
1408 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1409 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1410 "debrebase new-upstream $new_version: rebase";
1412 # now it's for the user to sort out
1415 sub cmd_record_ffq_prev () {
1416 badusage "no arguments allowed" if @ARGV;
1417 my ($status, $msg) = record_ffq_prev_deferred();
1418 if ($status eq 'exists' && $opt_noop_ok) {
1419 print "Previous head already recorded\n" or die $!;
1420 } elsif ($status eq 'deferred') {
1421 run_deferred_updates 'record-ffq-prev';
1423 fail "Could not preserve: $msg";
1428 badusage "no arguments allowed" if @ARGV;
1429 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1430 print "$bw\n" or die $!;
1433 sub cmd_breakwater () {
1434 badusage "no arguments allowed" if @ARGV;
1435 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1436 print "$bw\n" or die $!;
1440 badusage "no arguments allowed" if @ARGV;
1442 # todo: gdr status should print divergence info
1443 # todo: gdr status should print upstream component(s) info
1444 # todo: gdr should leave/maintain some refs with this kind of info ?
1446 my $oldest = { Badness => 0 };
1449 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1450 if ($oldest->{Badness} < $badness) {
1451 $oldest = $newest = undef;
1454 Badness => $badness,
1455 CommitId => $cl->{CommitId},
1459 $newest //= $oldest;
1461 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1462 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1463 sub { $note->(2, 'branch is unlaundered', @_); },
1464 sub { $note->(3, 'branch needs laundering', @_); },
1465 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1467 my $prcommitinfo = sub {
1469 flush STDOUT or die $!;
1470 runcmd @git, qw(--no-pager log -n1),
1471 '--pretty=format: %h %s%n',
1475 print "current branch contents, in git-debrebase terms:\n";
1476 if (!$oldest->{Badness}) {
1477 print " branch is laundered\n";
1479 print " $oldest->{OurMsg}\n";
1481 foreach my $info ($oldest, $newest) {
1482 my $cid = $info->{CommitId};
1483 next if $cid eq $printed;
1485 print " $info->{KcMsg}\n";
1486 $prcommitinfo->($cid);
1491 my ($cid, $what) = @_;
1492 if (!defined $cid) {
1493 print " $what is not well-defined\n";
1496 $prcommitinfo->($cid);
1499 print "key git-debrebase commits:\n";
1500 $prab->($anchor, 'anchor');
1501 $prab->($bw, 'breakwater');
1503 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1504 ffq_prev_branchinfo();
1506 print "branch and ref status, in git-debrebase terms:\n";
1508 print " $ffq_msg\n";
1510 $ffq_prev = git_get_ref $ffq_prev;
1511 $gdrlast = git_get_ref $gdrlast;
1513 print " unstitched; previous tip was:\n";
1514 $prcommitinfo->($ffq_prev);
1515 } elsif (!$gdrlast) {
1516 print " stitched? (no record of git-debrebase work)\n";
1517 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1518 print " stitched\n";
1520 print " not git-debrebase (diverged since last stitch)\n"
1526 my $prose = 'stitch';
1527 getoptions("bad options follow \`git-debrebase stitch'",
1528 'prose=s', \$prose);
1529 badusage "no arguments allowed" if @ARGV;
1530 do_stitch $prose, 0;
1532 sub cmd_prepush () { cmd_stitch(); }
1535 badusage "no arguments allowed" if @ARGV;
1536 do_launder_head 'launder for git-debrebase quick';
1540 sub cmd_conclude () {
1541 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1542 if (!$ffq_prev_commitish) {
1543 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1546 my $dangling_head = get_head();
1548 badusage "no arguments allowed" if @ARGV;
1549 do_launder_head 'launder for git-debrebase quick';
1553 sub make_patches_staged ($) {
1555 # Produces the patches that would result from $head if it were
1557 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1560 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1561 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1562 my @gbp_cmd = (qw(gbp pq export));
1563 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1565 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1568 runcmd @git, qw(add -f debian/patches);
1572 sub make_patches ($) {
1574 keycommits $head, 0, \&snag;
1575 make_patches_staged $head;
1578 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1579 runcmd @git, qw(read-tree), $head;
1580 read_tree_subdir 'debian/patches', $ptree;
1581 $out = make_commit [$head], [
1582 'Commit patch queue (exported by git-debrebase)',
1583 '[git-debrebase: export and commit patches]',
1589 sub cmd_make_patches () {
1590 my $opt_quiet_would_amend;
1591 getoptions("bad options follow \`git-debrebase make-patches'",
1592 'quiet-would-amend!', \$opt_quiet_would_amend);
1593 badusage "no arguments allowed" if @ARGV;
1594 my $old_head = get_head();
1595 my $new = make_patches $old_head;
1596 my $d = get_differs $old_head, $new;
1598 fail "No (more) patches to export." unless $opt_noop_ok;
1600 } elsif ($d == D_PAT_ADD) {
1602 update_head_checkout $old_head, $new, 'make-patches';
1604 print STDERR failmsg
1605 "Patch export produced patch amendments".
1606 " (abandoned output commit $new).".
1607 " Try laundering first."
1608 unless $opt_quiet_would_amend;
1613 sub cmd_convert_from_gbp () {
1614 badusage "want only 1 optional argument, the upstream git commitish"
1617 my $clogp = parsechangelog();
1618 my $version = $clogp->{'Version'}
1619 // die "missing Version from changelog";
1621 my ($upstream_spec) = @ARGV;
1623 my ($upstream, $upstream_version) =
1624 resolve_upstream_version($upstream_spec, $version);
1626 my $old_head = get_head();
1628 my $upsdiff = get_differs $upstream, $old_head;
1629 if ($upsdiff & D_UPS) {
1630 runcmd @git, qw(--no-pager diff),
1631 $upstream, $old_head,
1632 qw( -- :!/debian :/);
1633 fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1636 if (!is_fast_fwd $upstream, $old_head) {
1637 snag 'upstream-not-ancestor',
1638 "upstream ($upstream) is not an ancestor of HEAD";
1640 my $wrong = cmdoutput
1641 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1642 qw(-- :/ :!/debian));
1643 if (length $wrong) {
1644 snag 'unexpected-upstream-changes',
1645 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1646 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1650 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1651 snag 'upstream-has-debian',
1652 "upstream ($upstream) contains debian/ directory";
1655 my $previous_dgit_view = eval {
1656 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1658 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1659 my ($stz, $desc) = @_;
1660 no warnings qw(exiting);
1661 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1662 next unless $stz->{Date};
1663 next unless $stz->{Distribution} ne 'UNRELEASED';
1664 $lvsn = $stz->{Version};
1665 $suite = $stz->{Distribution};
1668 die "neither of the first two changelog entries are released\n"
1669 unless defined $lvsn;
1670 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1671 my $mtag_pat = debiantag_maintview $lvsn, '*';
1672 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1674 die "could not find suitable maintainer view tag $mtag_pat\n"
1675 unless $mtag_pat =~ m{/};
1676 is_fast_fwd $mtag, 'HEAD' or
1677 die "HEAD is not FF from maintainer tag $mtag!";
1678 my $dtag = "archive/$mtag";
1679 is_fast_fwd $mtag, $dtag or
1680 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1681 print "will stitch in dgit view, $dtag\n";
1682 git_rev_parse $dtag;
1684 if (!$previous_dgit_view) {
1687 print STDERR "cannot stitch in dgit view: $@\n";
1690 snags_maybe_bail_early();
1696 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1697 # make a branch out of the patch queue - we'll want this in a mo
1698 runcmd qw(gbp pq import);
1699 # strip the patches out
1700 runcmd @git, qw(checkout -q gdr-internal~0);
1701 rm_subdir_cached 'debian/patches';
1702 $work = make_commit ['HEAD'], [
1703 'git-debrebase convert-from-gbp: drop patches from tree',
1704 'Delete debian/patches, as part of converting to git-debrebase format.',
1705 '[git-debrebase convert-from-gbp: drop patches from tree]'
1707 # make the anchor merge
1708 # the tree is already exactly right
1709 $work = make_commit [$work, $upstream], [
1710 'git-debrebase import: declare upstream',
1711 'First breakwater merge.',
1712 '[git-debrebase anchor: declare upstream]'
1715 # rebase the patch queue onto the new breakwater
1716 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1717 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1718 $work = git_rev_parse 'HEAD';
1720 if ($previous_dgit_view) {
1721 $work = make_commit [$work, $previous_dgit_view], [
1722 'git-debrebase import: declare ff from dgit archive view',
1723 '[git-debrebase pseudomerge: import-from-gbp]',
1730 update_head_checkout $old_head, $work, 'convert-from-gbp';
1733 sub cmd_convert_to_gbp () {
1734 badusage "no arguments allowed" if @ARGV;
1735 my $head = get_head();
1736 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1737 keycommits $head, 0;
1739 make_patches_staged $head;
1741 $out = make_commit ['HEAD'], [
1742 'Commit patch queue (converted from git-debrebase format)',
1743 '[git-debrebase convert-to-gbp: commit patches]',
1747 push @deferred_updates, "delete $ffq";
1748 push @deferred_updates, "delete $gdrlast";
1751 update_head_checkout $head, $out, "convert to gbp (v0)";
1752 print <<END or die $!;
1753 git-debrebase: converted to git-buildpackage branch format
1754 git-debrebase: WARNING: do not now run "git-debrebase" any more
1755 git-debrebase: WARNING: doing so would drop all upstream patches!
1759 sub cmd_downstream_rebase_launder_v0 () {
1760 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1762 $base = git_rev_parse $base;
1763 my $old_head = get_head();
1764 my $current = $old_head;
1767 if ($current eq $base) {
1768 $topmost_keep //= $current;
1769 print " $current BASE stop\n";
1772 my $cl = classify $current;
1773 print " $current $cl->{Type}";
1775 my $p0 = $cl->{Parents}[0]{CommitId};
1777 if ($cl->{Type} eq 'Pseudomerge') {
1778 print " ^".($cl->{Contributor}{Ix}+1);
1779 $next = $cl->{Contributor}{CommitId};
1780 } elsif ($cl->{Type} eq 'AddPatches' or
1781 $cl->{Type} eq 'Changelog') {
1791 $topmost_keep //= $current;
1793 die "to-be stripped changes not on top of the branch\n"
1798 if ($topmost_keep eq $old_head) {
1799 print "unchanged\n";
1801 print "updating to $topmost_keep\n";
1802 update_head_checkout
1803 $old_head, $topmost_keep,
1804 'downstream-rebase-launder-v0';
1808 getoptions("bad options\n",
1809 "D+" => \$debuglevel,
1810 'noop-ok', => \$opt_noop_ok,
1811 'f=s' => \@snag_force_opts,
1812 'anchor=s' => \@opt_anchors,
1815 my ($opt,$val) = @_;
1816 badusage "git-debrebase: no cuddling to -i for git-rebase"
1818 die if $opt_defaultcmd_interactive; # should not happen
1819 $opt_defaultcmd_interactive = [ qw(-i) ];
1820 # This access to @ARGV is excessive familiarity with
1821 # Getopt::Long, but there isn't another sensible
1822 # approach. '-i=s{0,}' does not work with bundling.
1823 push @$opt_defaultcmd_interactive, @ARGV;
1827 initdebug('git-debrebase ');
1828 enabledebug if $debuglevel;
1830 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1831 chdir $toplevel or die "chdir $toplevel: $!";
1833 $rd = fresh_playground "$playprefix/misc";
1835 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1837 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1838 defaultcmd_rebase();
1840 my $cmd = shift @ARGV;
1843 $cmdfn = ${*::}{"cmd_$cmdfn"};
1845 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";