3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
6 # Copyright (C)2017,2018 Ian Jackson
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::GDR;
23 use Debian::Dgit::ExitStatus;
27 use Debian::Dgit qw(:DEFAULT :playground);
34 use Getopt::Long qw(:config posix_default gnu_compat bundling);
36 use File::FnMatch qw(:fnmatch);
39 our ($usage_message) = <<'END';
41 git-debrebase [<options>] [--|-i <git rebase options...>]
42 git-debrebase [<options>] status
43 git-debrebase [<options>] prepush [--prose=...]
44 git-debrebase [<options>] quick|conclude
45 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
46 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
48 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
51 our ($opt_force, $opt_noop_ok, @opt_anchors);
52 our ($opt_defaultcmd_interactive);
54 our $us = qw(git-debrebase);
60 print STDERR "$us: bad usage: $m\n";
66 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
67 GetOptions @_ or badusage $m;
71 my ($k, $optional) = @_;
73 my @cmd = qw(git config -z);
74 push @cmd, qw(--get-all) if wantarray;
76 my $out = cmdoutput_errok @cmd;
78 fail "missing required git config $k" unless $optional;
81 my @l = split /\0/, $out;
82 return wantarray ? @l : $l[0];
89 my $dd = new Data::Dumper [ $v ];
90 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
96 my $data = (git_cat_file $objid, 'commit');
97 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
101 sub D_UPS () { 0x02; } # upstream files
102 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
103 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
104 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
105 sub D_DEB_OTH () { 0x20; } # debian/changelog
106 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
108 our $playprefix = 'debrebase';
114 sub in_workarea ($) {
117 my $r = eval { $sub->(); };
118 { local $@; changedir $maindir; }
122 sub fresh_workarea () {
123 $workarea = fresh_playground "$playprefix/work";
124 in_workarea sub { playtree_setup };
127 our $snags_forced = 0;
128 our $snags_tripped = 0;
129 our $snags_summarised = 0;
130 our @deferred_updates;
131 our @deferred_update_messages;
133 sub all_snags_summarised () {
134 $snags_forced + $snags_tripped == $snags_summarised;
136 sub run_deferred_updates ($) {
139 confess 'dangerous internal error' unless all_snags_summarised();
141 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
142 debugcmd '>|', @upd_cmd;
143 open U, "|-", @upd_cmd or die $!;
144 foreach (@deferred_updates) {
145 printdebug ">= ", $_, "\n";
146 print U $_, "\n" or die $!;
149 close U or failedcmd @upd_cmd;
151 print $_, "\n" foreach @deferred_update_messages;
153 @deferred_updates = ();
154 @deferred_update_messages = ();
157 sub get_differs ($$) {
159 # This resembles quiltify_trees_differ, in dgit, a bit.
160 # But we don't care about modes, or dpkg-source-unrepresentable
161 # changes, and we don't need the plethora of different modes.
162 # Conversely we need to distinguish different kinds of changes to
163 # debian/ and debian/patches/.
168 my ($opts, $limits, $fn) = @_;
169 my @cmd = (@git, qw(diff-tree -z --no-renames));
171 push @cmd, "$_:" foreach $x, $y;
172 push @cmd, '--', @$limits;
173 my $diffs = cmdoutput @cmd;
174 foreach (split /\0/, $diffs) { $fn->(); }
177 $rundiff->([qw(--name-only)], [], sub {
178 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
181 if ($differs & DS_DEB) {
183 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
185 m{^debian/patches/} ? D_PAT_OTH :
186 $_ eq 'debian/changelog' ? D_DEB_CLOG :
189 die "mysterious debian changes $x..$y"
190 unless $differs & (D_PAT_OTH|DS_DEB);
193 if ($differs & D_PAT_OTH) {
195 $differs &= ~D_PAT_OTH;
197 $differs |= D_PAT_OTH;
198 no warnings qw(exiting); last;
200 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
201 no warnings qw(exiting);
202 if (!defined $mode) {
205 die unless s{^debian/patches/}{};
207 if ($mode eq 'A' && !m/\.series$/s) {
209 } elsif ($mode eq 'M' && $_ eq 'series') {
210 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
211 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
212 chomp $x_s; $x_s .= "\n";
213 $ok = $x_s eq substr($y_s, 0, length $x_s);
218 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
220 die "mysterious debian/patches changes $x..$y"
221 unless $differs & (D_PAT_ADD|D_PAT_OTH);
224 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
229 sub commit_pr_info ($) {
231 return Data::Dumper->dump([$r], [qw(commit)]);
234 sub calculate_committer_authline () {
235 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
236 'DUMMY COMMIT (git-debrebase)', "HEAD:";
237 my ($h,$m) = get_commit $c;
238 $h =~ m/^committer .*$/m or confess "($h) ?";
242 sub rm_subdir_cached ($) {
244 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
247 sub read_tree_subdir ($$) {
248 my ($subdir, $new_tree_object) = @_;
249 rm_subdir_cached $subdir;
250 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
253 sub make_commit ($$) {
254 my ($parents, $message_paras) = @_;
255 my $tree = cmdoutput @git, qw(write-tree);
256 my @cmd = (@git, qw(commit-tree), $tree);
257 push @cmd, qw(-p), $_ foreach @$parents;
258 push @cmd, qw(-m), $_ foreach @$message_paras;
259 return cmdoutput @cmd;
262 our @snag_force_opts;
264 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
265 if (grep { $_ eq $tag } @snag_force_opts) {
267 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
270 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
274 # Important: all mainline code must call snags_maybe_bail after
275 # any point where snag might be called, but before making changes
276 # (eg before any call to run_deferred_updates). snags_maybe_bail
277 # may be called more than once if necessary (but this is not ideal
278 # because then the messages about number of snags may be confusing).
279 sub snags_maybe_bail () {
280 return if all_snags_summarised();
283 "%s: snags: %d overriden by individual -f options\n",
286 if ($snags_tripped) {
289 "%s: snags: %d overriden by global --force\n",
293 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
297 $snags_summarised = $snags_forced + $snags_tripped;
299 sub snags_maybe_bail_early () {
300 # useful to bail out early without doing a lot of work;
301 # not a substitute for snags_maybe_bail.
302 snags_maybe_bail() if $snags_tripped && !$opt_force;
305 return $snags_forced || $snags_tripped;
308 # classify returns an info hash like this
310 # Hdr => # commit headers, including 1 final newline
311 # Msg => # commit message (so one newline is dropped)
313 # Type => (see below)
315 # Ix => $index # ie 0, 1, 2, ...
317 # Differs => return value from get_differs
319 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
321 # NewMsg => # commit message, but with any [dgit import ...] edited
322 # # to say "[was: ...]"
332 # has additional entres in classification result
333 # Overwritten = [ subset of Parents ]
334 # Contributor = $the_remaining_Parent
336 # DgitImportUnpatched
337 # has additional entry in classification result
338 # OrigParents = [ subset of Parents ]
341 # has additional entry in classification result
342 # OrigParents = [ subset of Parents ] # singleton list
349 # has additional entry in classification result
352 sub parsecommit ($;$) {
353 my ($objid, $p_ref) = @_;
354 # => hash with CommitId Hdr Msg Tree Parents
355 # Parents entries have only Ix CommitId
356 # $p_ref, if provided, must be [] and is used as a base for Parents
361 my ($h,$m) = get_commit $objid;
363 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
364 my (@ph) = $h =~ m/^parent (\w+)$/mg;
374 foreach my $ph (@ph) {
376 Ix => scalar @$p_ref,
388 my $r = parsecommit($objid, \@p);
392 $p->{Differs} = (get_differs $p->{CommitId}, $t),
395 printdebug "classify $objid \$t=$t \@p",
396 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
400 my ($type, @rest) = @_;
401 $r = { %$r, Type => $type, @rest };
403 printdebug " = $type ".(dd $r)."\n";
409 $r = { %$r, Type => qw(Unknown), Why => $why };
410 printdebug " ** Unknown\n";
414 if (grep { $_ eq $objid } @opt_anchors) {
415 return $classify->('TreatAsAnchor');
418 my @identical = grep { !$_->{Differs} } @p;
419 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
420 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
422 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
423 # multi-orig upstreams are represented with an anchor merge
424 # from a single upstream commit which combines the orig tarballs
426 # Every anchor tagged this way must be a merge.
427 # We are relying on the
428 # [git-debrebase anchor: ...]
429 # commit message annotation in "declare" anchor merges (which
430 # do not have any upstream changes), to distinguish those
431 # anchor merges from ordinary pseudomerges (which we might
432 # just try to strip).
434 # However, the user is going to be doing git-rebase a lot. We
435 # really don't want them to rewrite an anchor commit.
436 # git-rebase trips up on merges, so that is a useful safety
439 # BreakwaterStart commits are also anchors in the terminology
440 # of git-debrebase(5), but they are untagged (and always
441 # manually generated).
443 # We cannot not tolerate any tagged linear commit (ie,
444 # BreakwaterStart commits tagged `[anchor:') because such a
445 # thing could result from an erroneous linearising raw git
446 # rebase of a merge anchor. That would represent a corruption
447 # of the branch. and we want to detect and reject the results
448 # of such corruption before it makes it out anywhere. If we
449 # reject it here then we avoid making the pseudomerge which
450 # would be needed to push it.
452 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
453 @p == 2 or return $badanchor->("has other than two parents");
454 $haspatches and return $badanchor->("contains debian/patches");
456 # How to decide about l/r ordering of anchors ? git
457 # --topo-order prefers to expand 2nd parent first. There's
458 # already an easy rune to look for debian/ history anyway (git log
459 # debian/) so debian breakwater branch should be 1st parent; that
460 # way also there's also an easy rune to look for the upstream
461 # patches (--topo-order).
463 # Also this makes --first-parent be slightly more likely to
464 # be useful - it makes it provide a linearised breakwater history.
466 # Of course one can say somthing like
467 # gitk -- ':/' ':!/debian'
468 # to get _just_ the commits touching upstream files, and by
469 # the TREESAME logic in git-rev-list this will leave the
470 # breakwater into upstream at the first anchor. But that
471 # doesn't report debian/ changes at all.
473 # Other observations about gitk: by default, gitk seems to
474 # produce output in a different order to git-rev-list. I
475 # can't seem to find this documented anywhere. gitk
476 # --date-order DTRT. But, gitk always seems to put the
477 # parents from left to right, in order, so it's easy to see
478 # which way round a pseudomerge is.
480 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
481 $p[1]{Differs} & ~DS_DEB and
482 $badanchor->("upstream files differ from left parent");
483 $p[0]{Differs} & ~D_UPS and
484 $badanchor->("debian/ differs from right parent");
486 return $classify->(qw(Anchor),
487 OrigParents => [ $p[1] ]);
491 my $d = $r->{Parents}[0]{Differs};
492 if ($d == D_PAT_ADD) {
493 return $classify->(qw(AddPatches));
494 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
495 return $unknown->("edits debian/patches");
496 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
497 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
499 if ($d == D_DEB_CLOG) {
500 return $classify->(qw(Changelog));
502 return $classify->(qw(Packaging));
504 } elsif ($ty eq 'missing') {
505 return $classify->(qw(BreakwaterStart));
507 return $unknown->("parent's debian is not a directory");
509 } elsif ($d == D_UPS) {
510 return $classify->(qw(Upstream));
511 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
512 return $classify->(qw(Mixed));
514 return $unknown->("no changes");
516 confess "internal error $objid ?";
520 return $unknown->("origin commit");
523 if (@p == 2 && @identical == 1) {
524 my @overwritten = grep { $_->{Differs} } @p;
525 confess "internal error $objid ?" unless @overwritten==1;
526 return $classify->(qw(Pseudomerge),
527 Overwritten => [ $overwritten[0] ],
528 Contributor => $identical[0]);
530 if (@p == 2 && @identical == 2) {
532 my ($ph,$pm) = get_commit $_[0]{CommitId};
533 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
537 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
538 if ($order > 0) { # newer first
539 } elsif ($order < 0) {
540 @bytime = reverse @bytime;
542 # same age, default to order made by -s ours
543 # that is, commit was made by someone who preferred L
545 return $classify->(qw(Pseudomerge),
546 SubType => qw(Ambiguous),
547 Contributor => $bytime[0],
548 Overwritten => [ $bytime[1] ]);
551 my ($p_h, $p_m) = get_commit $p->{CommitId};
552 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
553 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
555 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
557 if (!(grep { !$_->{IsOrigin} } @p) and
558 (@orig_ps >= @p - 1) and
559 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
561 return $classify->(qw(DgitImportUnpatched),
562 OrigParents => \@orig_ps);
565 return $unknown->("complex merge");
568 sub keycommits ($;$$$$) {
569 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
570 # => ($anchor, $breakwater)
572 # $unclean->("unclean-$tagsfx", $msg, $cl)
573 # $furniture->("unclean-$tagsfx", $msg, $cl)
574 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
575 # is callled for each situation or commit that
576 # wouldn't be found in a laundered branch
577 # $furniture is for furniture commits such as might be found on an
578 # interchange branch (pseudomerge, d/patches, changelog)
579 # $trouble is for things whnich prevent the return of
580 # anchor and breakwater information; if that is ignored,
581 # then keycommits returns (undef, undef) instead.
582 # $fatal is for unprocessable commits, and should normally cause
583 # a failure. If ignored, agaion, (undef, undef) is returned.
585 # If a callback is undef, fail is called instead.
586 # If a callback is defined but false, the situation is ignored.
588 # no warnings qw(exiting); last;
589 # if the answer is no longer wanted.
591 my ($anchor, $breakwater);
594 $fatal //= sub { fail $_[1]; };
596 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
597 my $why = $mainwhy.$xwhy;
598 my $m = "branch needs laundering (run git-debrebase): $why";
599 fail $m unless defined $cb;
601 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
604 $cl = classify $head;
605 my $ty = $cl->{Type};
606 if ($ty eq 'Packaging') {
607 $breakwater //= $clogonly;
608 $breakwater //= $head;
609 } elsif ($ty eq 'Changelog') {
610 # this is going to count as the tip of the breakwater
611 # only if it has no upstream stuff before it
613 } elsif ($ty eq 'Anchor' or
614 $ty eq 'TreatAsAnchor' or
615 $ty eq 'BreakwaterStart') {
617 $breakwater //= $clogonly;
618 $breakwater //= $head;
620 } elsif ($ty eq 'Upstream') {
621 $x->($unclean, 'ordering',
622 "packaging change ($breakwater) follows upstream change"," (eg $head)")
623 if defined $breakwater;
626 } elsif ($ty eq 'Mixed') {
627 $x->($unclean, 'mixed',
628 "found mixed upstream/packaging commit"," ($head)");
631 } elsif ($ty eq 'Pseudomerge' or
632 $ty eq 'AddPatches') {
633 $x->($furniture, (lc $ty),
634 "found interchange bureaucracy commit ($ty)"," ($head)");
635 } elsif ($ty eq 'DgitImportUnpatched') {
636 $x->($trouble, 'dgitimport',
637 "found dgit dsc import ($head)");
638 return (undef,undef);
640 $x->($fatal, 'unprocessable',
641 "found unprocessable commit, cannot cope: $cl->{Why}",
643 return (undef,undef);
645 $head = $cl->{Parents}[0]{CommitId};
647 return ($anchor, $breakwater);
653 $nogenerate,$report) = @_;
654 # => ($tip, $breakwater_tip, $last_anchor)
655 # (or nothing, if $nogenerate)
657 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
659 # go through commits backwards
660 # we generate two lists of commits to apply:
661 # breakwater branch and upstream patches
662 my (@brw_cl, @upp_cl, @processed);
669 my ($prose, $info) = @_;
673 $ms .= "\n\n[git-debrebase$info: $prose]\n";
676 my $rewrite_from_here = sub {
678 my $sp_cl = { SpecialMethod => 'StartRewrite' };
680 push @processed, $sp_cl;
685 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
688 return unless $report;
689 print $report $prdelim, @_;
693 my $bomb = sub { # usage: return $bomb->();
694 print $report " Unprocessable" if $report;
695 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
698 return (undef,undef);
700 fail "found unprocessable commit, cannot cope:".
701 (defined $cl->{Why} ? "; $cl->{Why}": '').
702 " (commit $cur) (d.".
703 (join ' ', map { sprintf "%#x", $_->{Differs} }
704 @{ $cl->{Parents} }).
711 my $build_start = sub {
712 my ($msg, $parent) = @_;
715 no warnings qw(exiting); last;
722 my $ty = $cl->{Type};
723 my $st = $cl->{SubType};
724 $prline->("$cl->{CommitId} $cl->{Type}");
725 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
726 push @processed, $cl;
727 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
728 if ($ty eq 'AddPatches') {
730 $rewrite_from_here->(\@upp_cl);
732 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
736 } elsif ($ty eq 'BreakwaterStart') {
738 $build_start->('FirstPackaging', $cur);
739 } elsif ($ty eq 'Upstream') {
743 } elsif ($ty eq 'Mixed') {
746 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
749 $queue->(\@brw_cl, "debian");
750 $queue->(\@upp_cl, "upstream");
751 $rewrite_from_here->(\@brw_cl);
754 } elsif ($ty eq 'Pseudomerge') {
755 my $contrib = $cl->{Contributor}{CommitId};
756 print $report " Contributor=$contrib" if $report;
757 push @pseudomerges, $cl;
758 $rewrite_from_here->(\@upp_cl);
761 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
763 $build_start->("Anchor", $cur);
764 } elsif ($ty eq 'DgitImportUnpatched') {
765 my $pm = $pseudomerges[-1];
767 # To an extent, this is heuristic. Imports don't have
768 # a useful history of the debian/ branch. We assume
769 # that the first pseudomerge after an import has a
770 # useful history of debian/, and ignore the histories
771 # from later pseudomerges. Often the first pseudomerge
772 # will be the dgit import of the upload to the actual
773 # suite intended by the non-dgit NMUer, and later
774 # pseudomerges may represent in-archive copies.
775 my $ovwrs = $pm->{Overwritten};
776 printf $report " PM=%s \@Overwr:%d",
777 $pm->{CommitId}, (scalar @$ovwrs)
780 printdebug "*** WALK BOMB DgitImportUnpatched\n";
783 my $ovwr = $ovwrs->[0]{CommitId};
784 printf $report " Overwr=%s", $ovwr if $report;
785 # This import has a tree which is just like a
786 # breakwater tree, but it has the wrong history. It
787 # ought to have the previous breakwater (which the
788 # pseudomerge overwrote) as an ancestor. That will
789 # make the history of the debian/ files correct. As
790 # for the upstream version: either it's the same as
791 # was ovewritten (ie, same as the previous
792 # breakwater), in which case that history is precisely
793 # right; or, otherwise, it was a non-gitish upload of a
794 # new upstream version. We can tell these apart by
795 # looking at the tree of the supposed upstream.
798 SpecialMethod => 'DgitImportDebianUpdate',
799 $xmsg->("convert dgit import: debian changes")
802 SpecialMethod => 'DgitImportUpstreamUpdate',
803 $xmsg->("convert dgit import: upstream update",
806 $prline->(" Import");
807 $rewrite_from_here->(\@brw_cl);
808 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
812 # Everything is from this import. This kind of import
813 # is already in valid breakwater format, with the
814 # patches as commits.
815 printf $report " NoPM" if $report;
816 # last thing we processed will have been the first patch,
817 # if there is one; which is fine, so no need to rewrite
818 # on account of this import
819 $build_start->("ImportOrigin", $cur);
823 printdebug "*** WALK BOMB unrecognised\n";
829 printdebug "*** WALK prep done cur=$cur".
830 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
832 return if $nogenerate;
834 # Now we build it back up again
840 my $read_tree_debian = sub {
842 read_tree_subdir 'debian', "$treeish:debian";
843 rm_subdir_cached 'debian/patches';
845 my $read_tree_upstream = sub {
847 runcmd @git, qw(read-tree), $treeish;
848 $read_tree_debian->($build);
851 $#upp_cl = $upp_limit if defined $upp_limit;
853 my $committer_authline = calculate_committer_authline();
855 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
857 confess "internal error" unless $build eq (pop @processed)->{CommitId};
860 mkdir $rd or $!==EEXIST or die $!;
862 runcmd @git, qw(read-tree), $build;
863 foreach my $cl (qw(Debian), (reverse @brw_cl),
864 { SpecialMethod => 'RecordBreakwaterTip' },
865 qw(Upstream), (reverse @upp_cl)) {
867 $current_method = $cl;
870 my $method = $cl->{SpecialMethod} // $current_method;
871 my @parents = ($build);
872 my $cltree = $cl->{CommitId};
873 printdebug "WALK BUILD ".($cltree//'undef').
874 " $method (rewriting=$rewriting)\n";
875 if ($method eq 'Debian') {
876 $read_tree_debian->($cltree);
877 } elsif ($method eq 'Upstream') {
878 $read_tree_upstream->($cltree);
879 } elsif ($method eq 'StartRewrite') {
882 } elsif ($method eq 'RecordBreakwaterTip') {
883 $breakwater = $build;
885 } elsif ($method eq 'DgitImportDebianUpdate') {
886 $read_tree_debian->($cltree);
887 } elsif ($method eq 'DgitImportUpstreamUpdate') {
888 confess unless $rewriting;
889 my $differs = (get_differs $build, $cltree);
890 next unless $differs & D_UPS;
891 $read_tree_upstream->($cltree);
892 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
897 my $procd = (pop @processed) // 'UNDEF';
900 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
903 my $newtree = cmdoutput @git, qw(write-tree);
905 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
906 $ch =~ s{^parent .*\n}{}mg;
907 $ch =~ s{(?=^author)}{
908 join '', map { "parent $_\n" } @parents
909 }me or confess "$ch ?";
911 $ch =~ s{^committer .*$}{$committer_authline}m
914 my $cf = "$rd/m$rewriting";
915 open CD, ">", $cf or die $!;
916 print CD $ch, "\n", $cl->{Msg} or die $!;
918 my @cmd = (@git, qw(hash-object));
919 push @cmd, qw(-w) if $rewriting;
920 push @cmd, qw(-t commit), $cf;
921 my $newcommit = cmdoutput @cmd;
922 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
924 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
930 my $final_check = get_differs $build, $input;
931 die sprintf "internal error %#x %s %s", $final_check, $build, $input
932 if $final_check & ~D_PAT_ADD;
934 my @r = ($build, $breakwater, $last_anchor);
935 printdebug "*** WALK RETURN @r\n";
940 git_check_unmodified();
941 return git_rev_parse qw(HEAD);
944 sub update_head ($$$) {
945 my ($old, $new, $mrest) = @_;
946 push @deferred_updates, "update HEAD $new $old";
947 run_deferred_updates $mrest;
950 sub update_head_checkout ($$$) {
951 my ($old, $new, $mrest) = @_;
952 update_head $old, $new, $mrest;
953 runcmd @git, qw(reset --hard);
956 sub update_head_postlaunder ($$$) {
957 my ($old, $tip, $reflogmsg) = @_;
958 return if $tip eq $old;
959 print "git-debrebase: laundered (head was $old)\n";
960 update_head $old, $tip, $reflogmsg;
961 # no tree changes except debian/patches
962 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
965 sub do_launder_head ($) {
966 my ($reflogmsg) = @_;
967 my $old = get_head();
969 my ($tip,$breakwater) = walk $old;
971 update_head_postlaunder $old, $tip, $reflogmsg;
972 return ($tip,$breakwater);
975 sub cmd_launder_v0 () {
976 badusage "no arguments to launder-v0 allowed" if @ARGV;
977 my $old = get_head();
978 my ($tip,$breakwater,$last_anchor) = walk $old;
979 update_head_postlaunder $old, $tip, 'launder';
980 printf "# breakwater tip\n%s\n", $breakwater;
981 printf "# working tip\n%s\n", $tip;
982 printf "# last anchor\n%s\n", $last_anchor;
985 sub defaultcmd_rebase () {
986 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
987 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
988 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
992 badusage "analyse does not support any options"
993 if @ARGV and $ARGV[0] =~ m/^-/;
994 badusage "too many arguments to analyse" if @ARGV>1;
997 $old = git_rev_parse $old;
999 $old = git_rev_parse 'HEAD';
1001 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1002 STDOUT->error and die $!;
1005 sub ffq_prev_branchinfo () {
1006 my $current = git_get_symref();
1007 return gdr_ffq_prev_branchinfo($current);
1010 sub ffq_check ($;$$) {
1011 # calls $ff and/or $notff zero or more times
1012 # then returns either (status,message) where status is
1017 # or (undef,undef, $ffq_prev,$gdrlast)
1018 # $ff and $notff are called like this:
1019 # $ff->("message for stdout\n");
1020 # $notff->('snag-name', $message);
1021 # normally $currentval should be HEAD
1022 my ($currentval, $ff, $notff) =@_;
1024 $ff //= sub { print $_[0] or die $!; };
1027 my ($status, $message, $current, $ffq_prev, $gdrlast)
1028 = ffq_prev_branchinfo();
1029 return ($status, $message) unless $status eq 'branch';
1031 my $exists = git_get_ref $ffq_prev;
1032 return ('exists',"$ffq_prev already exists") if $exists;
1034 return ('not-branch', 'HEAD symref is not to refs/heads/')
1035 unless $current =~ m{^refs/heads/};
1038 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1041 printdebug "ffq check_specs @check_specs\n";
1044 my ($lrref, $desc) = @_;
1045 printdebug "ffq might check $lrref ($desc)\n";
1047 for my $chk (@check_specs) {
1049 $invert = $glob =~ s{^[!^]}{};
1050 last if fnmatch $glob, $lrref;
1053 my $lrval = git_get_ref $lrref;
1054 return unless length $lrval;
1056 if (is_fast_fwd $lrval, $currentval) {
1057 $ff->("OK, you are ahead of $lrref\n");
1058 $checked{$lrref} = 1;
1059 } elsif (is_fast_fwd $currentval, $lrval) {
1060 $checked{$lrref} = -1;
1061 $notff->('behind', "you are behind $lrref, divergence risk");
1063 $checked{$lrref} = -1;
1064 $notff->('diverged', "you have diverged from $lrref");
1068 my $merge = cfg "branch.$branch.merge",1;
1069 if (defined $merge and $merge =~ m{^refs/heads/}) {
1071 printdebug "ffq merge $rhs\n";
1072 my $check_remote = sub {
1073 my ($remote, $desc) = @_;
1074 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1075 return unless defined $remote;
1076 $check->("refs/remotes/$remote/$rhs", $desc);
1078 $check_remote->((scalar cfg "branch.$branch.remote",1),
1079 'remote fetch/merge branch');
1080 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1081 (scalar cfg "branch.$branch.pushDefault",1),
1082 'remote push branch');
1084 if ($branch =~ m{^dgit/}) {
1085 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1086 } elsif ($branch =~ m{^master$}) {
1087 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1089 return (undef, undef, $ffq_prev, $gdrlast);
1092 sub record_ffq_prev_deferred () {
1093 # => ('status', "message")
1095 # deferred message is undef
1100 # if not ff from some branch we should be ff from, is an snag
1101 # if "deferred", will have added something about that to
1102 # @deferred_update_messages, and also maybe printed (already)
1103 # some messages about ff checks
1104 my $currentval = get_head();
1106 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1107 return ($status,$message) if defined $status;
1111 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1112 push @deferred_updates, "delete $gdrlast";
1113 push @deferred_update_messages, "Recorded current head for preservation";
1114 return ('deferred', undef);
1117 sub record_ffq_auto () {
1118 my ($status, $message) = record_ffq_prev_deferred();
1119 if ($status eq 'deferred' || $status eq 'exists') {
1121 snag $status, "could not record ffq-prev: $message";
1126 sub ffq_prev_info () {
1127 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1128 my ($status, $message, $current, $ffq_prev, $gdrlast)
1129 = ffq_prev_branchinfo();
1130 if ($status ne 'branch') {
1131 snag $status, "could not check ffq-prev: $message";
1134 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1135 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1138 sub stitch ($$$$$) {
1139 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1141 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1143 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1144 my $differs = get_differs $old_head, $ffq_prev_commitish;
1145 unless ($differs & ~D_PAT_ADD) {
1146 # ffq-prev is ahead of us, and the only tree changes it has
1147 # are possibly addition of things in debian/patches/.
1148 # Just wind forwards rather than making a pointless pseudomerge.
1149 push @deferred_updates,
1150 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1151 update_head_checkout $old_head, $ffq_prev_commitish,
1152 "stitch (fast forward)";
1157 # We make pseudomerges with L as the contributing parent.
1158 # This makes git rev-list --first-parent work properly.
1159 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1160 'Declare fast forward / record previous work',
1161 "[git-debrebase pseudomerge: $prose]",
1163 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1164 update_head $old_head, $new_head, "stitch: $prose";
1167 sub do_stitch ($;$) {
1168 my ($prose, $unclean) = @_;
1170 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1171 if (!$ffq_prev_commitish) {
1172 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1175 my $dangling_head = get_head();
1177 keycommits $dangling_head, $unclean,$unclean,$unclean;
1180 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1183 sub resolve_upstream_version ($$) {
1184 my ($new_upstream, $version) = @_;
1186 my $new_upstream_version = "$version";
1187 $new_upstream_version =~ s/-.*?$//;;
1189 if (!defined $new_upstream) {
1191 # todo: at some point maybe use git-deborig to do this
1192 foreach my $tagpfx ('', 'v', 'upstream/') {
1193 my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1194 $new_upstream = git_get_ref "refs/tags/$tag";
1195 last if length $new_upstream;
1198 if (!length $new_upstream) {
1199 fail "Could not determine appropriate upstream commitish.\n".
1200 " (Tried these tags: @tried)\n".
1201 " Check version, and specify upstream commitish explicitly.";
1204 $new_upstream = git_rev_parse $new_upstream;
1206 return ($new_upstream, $new_upstream_version);
1209 sub cmd_new_upstream () {
1210 # automatically and unconditionally launders before rebasing
1211 # if rebase --abort is used, laundering has still been done
1215 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1217 # parse args - low commitment
1218 my $spec_version = shift @ARGV;
1219 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1220 fail "bad version number \`$spec_version'" unless defined $new_version;
1221 if ($new_version->is_native()) {
1222 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1225 my $new_upstream = shift @ARGV;
1226 my $new_upstream_version;
1227 ($new_upstream, $new_upstream_version) =
1228 resolve_upstream_version $new_upstream, $new_version;
1233 my ($n, @x) = @_; # may be ''
1234 my $pc = $pieces{$n} //= {
1236 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1238 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1243 my $newpiece = sub {
1244 my ($n, @x) = @_; # may be ''
1245 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1246 push @newpieces, $pc;
1251 New => $new_upstream,
1253 while (@ARGV && $ARGV[0] !~ m{^-}) {
1254 my $n = shift @ARGV;
1256 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1257 unless @ARGV && $ARGV[0] !~ m{^-};
1259 my $c = git_rev_parse shift @ARGV;
1260 die unless $n =~ m/^$extra_orig_namepart_re$/;
1261 $newpiece->($n, New => $c);
1264 # now we need to investigate the branch this generates the
1265 # laundered version but we don't switch to it yet
1266 my $old_head = get_head();
1267 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1269 my $old_bw_cl = classify $old_bw;
1270 my $old_anchor_cl = classify $old_anchor;
1272 if (!$old_anchor_cl->{OrigParents}) {
1273 snag 'anchor-treated',
1274 'old anchor is recognised due to --anchor, cannot check upstream';
1276 $old_upstream = parsecommit
1277 $old_anchor_cl->{OrigParents}[0]{CommitId};
1278 $piece->('', Old => $old_upstream->{CommitId});
1281 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1282 if ($old_upstream->{Msg} =~
1283 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1285 my @oldpieces = (split / /, $1);
1286 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1287 if ($old_n_parents != @oldpieces &&
1288 $old_n_parents != @oldpieces + 1) {
1289 snag 'upstream-confusing', sprintf
1290 "previous upstream combine %s".
1291 " mentions %d pieces (each implying one parent)".
1292 " but has %d parents".
1293 " (one per piece plus maybe a previous combine)",
1294 $old_upstream->{CommitId},
1295 (scalar @oldpieces),
1297 } elsif ($oldpieces[0] ne '.') {
1298 snag 'upstream-confusing', sprintf
1299 "previous upstream combine %s".
1300 " first piece is not \`.'",
1304 foreach my $i (0..$#oldpieces) {
1305 my $n = $oldpieces[$i];
1306 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1307 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1311 snag 'upstream-confusing',
1312 "previous upstream $old_upstream->{CommitId} is from".
1313 " git-debrebase but not an \`upstream-combine' commit";
1317 foreach my $pc (values %pieces) {
1318 if (!$old_upstream) {
1319 # we have complained already
1320 } elsif (!$pc->{Old}) {
1321 snag 'upstream-new-piece',
1322 "introducing upstream piece \`$pc->{Name}'";
1323 } elsif (!$pc->{New}) {
1324 snag 'upstream-rm-piece',
1325 "dropping upstream piece \`$pc->{Name}'";
1326 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1327 snag 'upstream-not-ff',
1328 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1332 printdebug "%pieces = ", (dd \%pieces), "\n";
1333 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1341 my @upstream_merge_parents;
1344 push @upstream_merge_parents, $old_upstream->{CommitId};
1347 foreach my $pc (@newpieces) { # always has '' first
1349 read_tree_subdir $pc->{Name}, $pc->{New};
1351 runcmd @git, qw(read-tree), $pc->{New};
1353 push @upstream_merge_parents, $pc->{New};
1356 # index now contains the new upstream
1358 if (@newpieces > 1) {
1359 # need to make the upstream subtree merge commit
1360 $new_upstream = make_commit \@upstream_merge_parents,
1361 [ "Combine upstreams for $new_upstream_version",
1362 ("[git-debrebase upstream-combine . ".
1363 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1368 # $new_upstream is either the single upstream commit, or the
1369 # combined commit we just made. Either way it will be the
1370 # "upstream" parent of the anchor merge.
1372 read_tree_subdir 'debian', "$old_bw:debian";
1374 # index now contains the anchor merge contents
1375 $new_bw = make_commit [ $old_bw, $new_upstream ],
1376 [ "Update to upstream $new_upstream_version",
1377 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1380 my $clogsignoff = cmdoutput qw(git show),
1381 '--pretty=format:%an <%ae> %aD',
1384 # Now we have to add a changelog stanza so the Debian version
1386 die if unlink "debian";
1387 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1388 unlink "debian/changelog" or $!==ENOENT or die $!;
1389 mkdir "debian" or die $!;
1390 open CN, ">", "debian/changelog" or die $!;
1391 my $oldclog = git_cat_file ":debian/changelog";
1392 $oldclog =~ m/^($package_re) \(\S+\) / or
1393 fail "cannot parse old changelog to get package name";
1395 print CN <<END, $oldclog or die $!;
1396 $p ($new_version) UNRELEASED; urgency=medium
1398 * Update to new upstream version $new_upstream_version.
1404 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1406 # Now we have the final new breakwater branch in the index
1407 $new_bw = make_commit [ $new_bw ],
1408 [ "Update changelog for new upstream $new_upstream_version",
1409 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1413 # we have constructed the new breakwater. we now need to commit to
1414 # the laundering output, because git-rebase can't easily be made
1415 # to make a replay list which is based on some other branch
1417 update_head_postlaunder $old_head, $old_laundered_tip,
1418 'launder for new upstream';
1420 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1421 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1422 "debrebase new-upstream $new_version: rebase";
1424 # now it's for the user to sort out
1427 sub cmd_record_ffq_prev () {
1428 badusage "no arguments allowed" if @ARGV;
1429 my ($status, $msg) = record_ffq_prev_deferred();
1430 if ($status eq 'exists' && $opt_noop_ok) {
1431 print "Previous head already recorded\n" or die $!;
1432 } elsif ($status eq 'deferred') {
1433 run_deferred_updates 'record-ffq-prev';
1435 fail "Could not preserve: $msg";
1440 badusage "no arguments allowed" if @ARGV;
1441 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1442 print "$bw\n" or die $!;
1445 sub cmd_breakwater () {
1446 badusage "no arguments allowed" if @ARGV;
1447 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1448 print "$bw\n" or die $!;
1452 badusage "no arguments allowed" if @ARGV;
1454 # todo: gdr status should print divergence info
1455 # todo: gdr status should print upstream component(s) info
1456 # todo: gdr should leave/maintain some refs with this kind of info ?
1458 my $oldest = { Badness => 0 };
1461 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1462 if ($oldest->{Badness} < $badness) {
1463 $oldest = $newest = undef;
1466 Badness => $badness,
1467 CommitId => $cl->{CommitId},
1471 $newest //= $oldest;
1473 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1474 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1475 sub { $note->(2, 'branch is unlaundered', @_); },
1476 sub { $note->(3, 'branch needs laundering', @_); },
1477 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1479 my $prcommitinfo = sub {
1481 flush STDOUT or die $!;
1482 runcmd @git, qw(--no-pager log -n1),
1483 '--pretty=format: %h %s%n',
1487 print "current branch contents, in git-debrebase terms:\n";
1488 if (!$oldest->{Badness}) {
1489 print " branch is laundered\n";
1491 print " $oldest->{OurMsg}\n";
1493 foreach my $info ($oldest, $newest) {
1494 my $cid = $info->{CommitId};
1495 next if $cid eq $printed;
1497 print " $info->{KcMsg}\n";
1498 $prcommitinfo->($cid);
1503 my ($cid, $what) = @_;
1504 if (!defined $cid) {
1505 print " $what is not well-defined\n";
1508 $prcommitinfo->($cid);
1511 print "key git-debrebase commits:\n";
1512 $prab->($anchor, 'anchor');
1513 $prab->($bw, 'breakwater');
1515 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1516 ffq_prev_branchinfo();
1518 print "branch and ref status, in git-debrebase terms:\n";
1520 print " $ffq_msg\n";
1522 $ffq_prev = git_get_ref $ffq_prev;
1523 $gdrlast = git_get_ref $gdrlast;
1525 print " unstitched; previous tip was:\n";
1526 $prcommitinfo->($ffq_prev);
1527 } elsif (!$gdrlast) {
1528 print " stitched? (no record of git-debrebase work)\n";
1529 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1530 print " stitched\n";
1532 print " not git-debrebase (diverged since last stitch)\n"
1538 my $prose = 'stitch';
1539 getoptions("bad options follow \`git-debrebase stitch'",
1540 'prose=s', \$prose);
1541 badusage "no arguments allowed" if @ARGV;
1542 do_stitch $prose, 0;
1544 sub cmd_prepush () { cmd_stitch(); }
1547 badusage "no arguments allowed" if @ARGV;
1548 do_launder_head 'launder for git-debrebase quick';
1552 sub cmd_conclude () {
1553 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1554 if (!$ffq_prev_commitish) {
1555 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1558 my $dangling_head = get_head();
1560 badusage "no arguments allowed" if @ARGV;
1561 do_launder_head 'launder for git-debrebase quick';
1565 sub make_patches_staged ($) {
1567 # Produces the patches that would result from $head if it were
1569 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1572 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1573 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1574 my @gbp_cmd = (qw(gbp pq export));
1575 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1577 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1580 runcmd @git, qw(add -f debian/patches);
1584 sub make_patches ($) {
1586 keycommits $head, 0, \&snag;
1587 make_patches_staged $head;
1590 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1591 runcmd @git, qw(read-tree), $head;
1592 read_tree_subdir 'debian/patches', $ptree;
1593 $out = make_commit [$head], [
1594 'Commit patch queue (exported by git-debrebase)',
1595 '[git-debrebase: export and commit patches]',
1601 sub cmd_make_patches () {
1602 my $opt_quiet_would_amend;
1603 getoptions("bad options follow \`git-debrebase make-patches'",
1604 'quiet-would-amend!', \$opt_quiet_would_amend);
1605 badusage "no arguments allowed" if @ARGV;
1606 my $old_head = get_head();
1607 my $new = make_patches $old_head;
1608 my $d = get_differs $old_head, $new;
1610 fail "No (more) patches to export." unless $opt_noop_ok;
1612 } elsif ($d == D_PAT_ADD) {
1614 update_head_checkout $old_head, $new, 'make-patches';
1616 print STDERR failmsg
1617 "Patch export produced patch amendments".
1618 " (abandoned output commit $new).".
1619 " Try laundering first."
1620 unless $opt_quiet_would_amend;
1625 sub cmd_convert_from_gbp () {
1626 badusage "want only 1 optional argument, the upstream git commitish"
1629 my $clogp = parsechangelog();
1630 my $version = $clogp->{'Version'}
1631 // die "missing Version from changelog";
1633 my ($upstream_spec) = @ARGV;
1635 my ($upstream, $upstream_version) =
1636 resolve_upstream_version($upstream_spec, $version);
1638 my $old_head = get_head();
1640 my $upsdiff = get_differs $upstream, $old_head;
1641 if ($upsdiff & D_UPS) {
1642 runcmd @git, qw(--no-pager diff --stat),
1643 $upstream, $old_head,
1644 qw( -- :!/debian :/);
1646 upstream ($upstream_spec) and HEAD are not
1647 identical in upstream files. See diffstat above, or run
1648 git diff $upstream_spec HEAD -- :!/debian :/
1652 if (!is_fast_fwd $upstream, $old_head) {
1653 snag 'upstream-not-ancestor',
1654 "upstream ($upstream) is not an ancestor of HEAD";
1656 my $wrong = cmdoutput
1657 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1658 qw(-- :/ :!/debian));
1659 if (length $wrong) {
1660 snag 'unexpected-upstream-changes',
1661 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1662 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1666 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1667 snag 'upstream-has-debian',
1668 "upstream ($upstream) contains debian/ directory";
1671 my $previous_dgit_view = eval {
1672 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1674 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1675 my ($stz, $desc) = @_;
1676 no warnings qw(exiting);
1677 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1678 next unless $stz->{Date};
1679 next unless $stz->{Distribution} ne 'UNRELEASED';
1680 $lvsn = $stz->{Version};
1681 $suite = $stz->{Distribution};
1684 die "neither of the first two changelog entries are released\n"
1685 unless defined $lvsn;
1686 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1687 my $mtag_pat = debiantag_maintview $lvsn, '*';
1688 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1690 die "could not find suitable maintainer view tag $mtag_pat\n"
1691 unless $mtag_pat =~ m{/};
1692 is_fast_fwd $mtag, 'HEAD' or
1693 die "HEAD is not FF from maintainer tag $mtag!";
1694 my $dtag = "archive/$mtag";
1695 is_fast_fwd $mtag, $dtag or
1696 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1697 print "will stitch in dgit view, $dtag\n";
1698 git_rev_parse $dtag;
1700 if (!$previous_dgit_view) {
1703 print STDERR "cannot stitch in dgit view: $@\n";
1706 snags_maybe_bail_early();
1712 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1713 # make a branch out of the patch queue - we'll want this in a mo
1714 runcmd qw(gbp pq import);
1715 # strip the patches out
1716 runcmd @git, qw(checkout -q gdr-internal~0);
1717 rm_subdir_cached 'debian/patches';
1718 $work = make_commit ['HEAD'], [
1719 'git-debrebase convert-from-gbp: drop patches from tree',
1720 'Delete debian/patches, as part of converting to git-debrebase format.',
1721 '[git-debrebase convert-from-gbp: drop patches from tree]'
1723 # make the anchor merge
1724 # the tree is already exactly right
1725 $work = make_commit [$work, $upstream], [
1726 'git-debrebase import: declare upstream',
1727 'First breakwater merge.',
1728 '[git-debrebase anchor: declare upstream]'
1731 # rebase the patch queue onto the new breakwater
1732 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1733 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1734 $work = git_rev_parse 'HEAD';
1736 if ($previous_dgit_view) {
1737 $work = make_commit [$work, $previous_dgit_view], [
1738 'git-debrebase import: declare ff from dgit archive view',
1739 '[git-debrebase pseudomerge: import-from-gbp]',
1746 update_head_checkout $old_head, $work, 'convert-from-gbp';
1749 sub cmd_convert_to_gbp () {
1750 badusage "no arguments allowed" if @ARGV;
1751 my $head = get_head();
1752 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1753 keycommits $head, 0;
1755 make_patches_staged $head;
1757 $out = make_commit ['HEAD'], [
1758 'Commit patch queue (converted from git-debrebase format)',
1759 '[git-debrebase convert-to-gbp: commit patches]',
1763 push @deferred_updates, "delete $ffq";
1764 push @deferred_updates, "delete $gdrlast";
1767 update_head_checkout $head, $out, "convert to gbp (v0)";
1768 print <<END or die $!;
1769 git-debrebase: converted to git-buildpackage branch format
1770 git-debrebase: WARNING: do not now run "git-debrebase" any more
1771 git-debrebase: WARNING: doing so would drop all upstream patches!
1775 sub cmd_downstream_rebase_launder_v0 () {
1776 badusage "needs 1 argument, the baseline" unless @ARGV==1;
1778 $base = git_rev_parse $base;
1779 my $old_head = get_head();
1780 my $current = $old_head;
1783 if ($current eq $base) {
1784 $topmost_keep //= $current;
1785 print " $current BASE stop\n";
1788 my $cl = classify $current;
1789 print " $current $cl->{Type}";
1791 my $p0 = $cl->{Parents}[0]{CommitId};
1793 if ($cl->{Type} eq 'Pseudomerge') {
1794 print " ^".($cl->{Contributor}{Ix}+1);
1795 $next = $cl->{Contributor}{CommitId};
1796 } elsif ($cl->{Type} eq 'AddPatches' or
1797 $cl->{Type} eq 'Changelog') {
1807 $topmost_keep //= $current;
1809 die "to-be stripped changes not on top of the branch\n"
1814 if ($topmost_keep eq $old_head) {
1815 print "unchanged\n";
1817 print "updating to $topmost_keep\n";
1818 update_head_checkout
1819 $old_head, $topmost_keep,
1820 'downstream-rebase-launder-v0';
1824 getoptions("bad options\n",
1825 "D+" => \$debuglevel,
1826 'noop-ok', => \$opt_noop_ok,
1827 'f=s' => \@snag_force_opts,
1828 'anchor=s' => \@opt_anchors,
1831 my ($opt,$val) = @_;
1832 badusage "git-debrebase: no cuddling to -i for git-rebase"
1834 die if $opt_defaultcmd_interactive; # should not happen
1835 $opt_defaultcmd_interactive = [ qw(-i) ];
1836 # This access to @ARGV is excessive familiarity with
1837 # Getopt::Long, but there isn't another sensible
1838 # approach. '-i=s{0,}' does not work with bundling.
1839 push @$opt_defaultcmd_interactive, @ARGV;
1842 'help' => sub { print $usage_message or die $!; finish 0; },
1845 initdebug('git-debrebase ');
1846 enabledebug if $debuglevel;
1848 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1849 chdir $toplevel or die "chdir $toplevel: $!";
1851 $rd = fresh_playground "$playprefix/misc";
1853 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1855 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1856 defaultcmd_rebase();
1858 my $cmd = shift @ARGV;
1861 $cmdfn = ${*::}{"cmd_$cmdfn"};
1863 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";