3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
6 # Copyright (C)2017,2018 Ian Jackson
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::GDR;
23 use Debian::Dgit::ExitStatus;
27 use Debian::Dgit qw(:DEFAULT :playground);
34 use Getopt::Long qw(:config posix_default gnu_compat bundling);
36 use File::FnMatch qw(:fnmatch);
39 our ($usage_message) = <<'END';
41 git-debrebase [<options>] [--|-i <git rebase options...>]
42 git-debrebase [<options>] status
43 git-debrebase [<options>] prepush [--prose=...]
44 git-debrebase [<options>] quick|conclude
45 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
46 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
48 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
51 our ($opt_force, $opt_noop_ok, @opt_anchors);
52 our ($opt_defaultcmd_interactive);
54 our $us = qw(git-debrebase);
60 print STDERR "$us: bad usage: $m\n";
66 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
67 GetOptions @_ or badusage $m;
71 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
75 my ($k, $optional) = @_;
77 my @cmd = qw(git config -z);
78 push @cmd, qw(--get-all) if wantarray;
80 my $out = cmdoutput_errok @cmd;
82 fail "missing required git config $k" unless $optional;
85 my @l = split /\0/, $out;
86 return wantarray ? @l : $l[0];
93 my $dd = new Data::Dumper [ $v ];
94 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
100 my $data = (git_cat_file $objid, 'commit');
101 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
105 sub D_UPS () { 0x02; } # upstream files
106 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
107 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
108 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
109 sub D_DEB_OTH () { 0x20; } # debian/changelog
110 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
112 our $playprefix = 'debrebase';
117 our @dgit = qw(dgit);
119 sub in_workarea ($) {
122 my $r = eval { $sub->(); };
123 { local $@; changedir $maindir; }
127 sub fresh_workarea () {
128 $workarea = fresh_playground "$playprefix/work";
129 in_workarea sub { playtree_setup };
132 our $snags_forced = 0;
133 our $snags_tripped = 0;
134 our $snags_summarised = 0;
135 our @deferred_updates;
136 our @deferred_update_messages;
138 sub all_snags_summarised () {
139 $snags_forced + $snags_tripped == $snags_summarised;
141 sub run_deferred_updates ($) {
144 confess 'dangerous internal error' unless all_snags_summarised();
146 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
147 debugcmd '>|', @upd_cmd;
148 open U, "|-", @upd_cmd or die $!;
149 foreach (@deferred_updates) {
150 printdebug ">= ", $_, "\n";
151 print U $_, "\n" or die $!;
154 close U or failedcmd @upd_cmd;
156 print $_, "\n" foreach @deferred_update_messages;
158 @deferred_updates = ();
159 @deferred_update_messages = ();
162 sub get_differs ($$) {
164 # This resembles quiltify_trees_differ, in dgit, a bit.
165 # But we don't care about modes, or dpkg-source-unrepresentable
166 # changes, and we don't need the plethora of different modes.
167 # Conversely we need to distinguish different kinds of changes to
168 # debian/ and debian/patches/.
173 my ($opts, $limits, $fn) = @_;
174 my @cmd = (@git, qw(diff-tree -z --no-renames));
176 push @cmd, "$_:" foreach $x, $y;
177 push @cmd, '--', @$limits;
178 my $diffs = cmdoutput @cmd;
179 foreach (split /\0/, $diffs) { $fn->(); }
182 $rundiff->([qw(--name-only)], [], sub {
183 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
186 if ($differs & DS_DEB) {
188 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
190 m{^debian/patches/} ? D_PAT_OTH :
191 $_ eq 'debian/changelog' ? D_DEB_CLOG :
194 die "mysterious debian changes $x..$y"
195 unless $differs & (D_PAT_OTH|DS_DEB);
198 if ($differs & D_PAT_OTH) {
200 $differs &= ~D_PAT_OTH;
202 $differs |= D_PAT_OTH;
203 no warnings qw(exiting); last;
205 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
206 no warnings qw(exiting);
207 if (!defined $mode) {
210 die unless s{^debian/patches/}{};
212 if ($mode eq 'A' && !m/\.series$/s) {
214 } elsif ($mode eq 'M' && $_ eq 'series') {
215 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
216 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
217 chomp $x_s; $x_s .= "\n";
218 $ok = $x_s eq substr($y_s, 0, length $x_s);
223 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
225 die "mysterious debian/patches changes $x..$y"
226 unless $differs & (D_PAT_ADD|D_PAT_OTH);
229 printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
234 sub commit_pr_info ($) {
236 return Data::Dumper->dump([$r], [qw(commit)]);
239 sub calculate_committer_authline () {
240 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
241 'DUMMY COMMIT (git-debrebase)', "HEAD:";
242 my ($h,$m) = get_commit $c;
243 $h =~ m/^committer .*$/m or confess "($h) ?";
247 sub rm_subdir_cached ($) {
249 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
252 sub read_tree_subdir ($$) {
253 my ($subdir, $new_tree_object) = @_;
254 rm_subdir_cached $subdir;
255 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
258 sub make_commit ($$) {
259 my ($parents, $message_paras) = @_;
260 my $tree = cmdoutput @git, qw(write-tree);
261 my @cmd = (@git, qw(commit-tree), $tree);
262 push @cmd, qw(-p), $_ foreach @$parents;
263 push @cmd, qw(-m), $_ foreach @$message_paras;
264 return cmdoutput @cmd;
267 our @snag_force_opts;
269 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
270 if (grep { $_ eq $tag } @snag_force_opts) {
272 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
275 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
279 # Important: all mainline code must call snags_maybe_bail after
280 # any point where snag might be called, but before making changes
281 # (eg before any call to run_deferred_updates). snags_maybe_bail
282 # may be called more than once if necessary (but this is not ideal
283 # because then the messages about number of snags may be confusing).
284 sub snags_maybe_bail () {
285 return if all_snags_summarised();
288 "%s: snags: %d overriden by individual -f options\n",
291 if ($snags_tripped) {
294 "%s: snags: %d overriden by global --force\n",
298 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
302 $snags_summarised = $snags_forced + $snags_tripped;
304 sub snags_maybe_bail_early () {
305 # useful to bail out early without doing a lot of work;
306 # not a substitute for snags_maybe_bail.
307 snags_maybe_bail() if $snags_tripped && !$opt_force;
310 return $snags_forced || $snags_tripped;
313 # classify returns an info hash like this
315 # Hdr => # commit headers, including 1 final newline
316 # Msg => # commit message (so one newline is dropped)
318 # Type => (see below)
320 # Ix => $index # ie 0, 1, 2, ...
322 # Differs => return value from get_differs
324 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
326 # NewMsg => # commit message, but with any [dgit import ...] edited
327 # # to say "[was: ...]"
337 # has additional entres in classification result
338 # Overwritten = [ subset of Parents ]
339 # Contributor = $the_remaining_Parent
341 # DgitImportUnpatched
342 # has additional entry in classification result
343 # OrigParents = [ subset of Parents ]
346 # has additional entry in classification result
347 # OrigParents = [ subset of Parents ] # singleton list
354 # has additional entry in classification result
357 sub parsecommit ($;$) {
358 my ($objid, $p_ref) = @_;
359 # => hash with CommitId Hdr Msg Tree Parents
360 # Parents entries have only Ix CommitId
361 # $p_ref, if provided, must be [] and is used as a base for Parents
366 my ($h,$m) = get_commit $objid;
368 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
369 my (@ph) = $h =~ m/^parent (\w+)$/mg;
379 foreach my $ph (@ph) {
381 Ix => scalar @$p_ref,
393 my $r = parsecommit($objid, \@p);
397 $p->{Differs} = (get_differs $p->{CommitId}, $t),
400 printdebug "classify $objid \$t=$t \@p",
401 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
405 my ($type, @rest) = @_;
406 $r = { %$r, Type => $type, @rest };
408 printdebug " = $type ".(dd $r)."\n";
414 $r = { %$r, Type => qw(Unknown), Why => $why };
415 printdebug " ** Unknown\n";
419 if (grep { $_ eq $objid } @opt_anchors) {
420 return $classify->('TreatAsAnchor');
423 my @identical = grep { !$_->{Differs} } @p;
424 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
425 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
427 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
428 # multi-orig upstreams are represented with an anchor merge
429 # from a single upstream commit which combines the orig tarballs
431 # Every anchor tagged this way must be a merge.
432 # We are relying on the
433 # [git-debrebase anchor: ...]
434 # commit message annotation in "declare" anchor merges (which
435 # do not have any upstream changes), to distinguish those
436 # anchor merges from ordinary pseudomerges (which we might
437 # just try to strip).
439 # However, the user is going to be doing git-rebase a lot. We
440 # really don't want them to rewrite an anchor commit.
441 # git-rebase trips up on merges, so that is a useful safety
444 # BreakwaterStart commits are also anchors in the terminology
445 # of git-debrebase(5), but they are untagged (and always
446 # manually generated).
448 # We cannot not tolerate any tagged linear commit (ie,
449 # BreakwaterStart commits tagged `[anchor:') because such a
450 # thing could result from an erroneous linearising raw git
451 # rebase of a merge anchor. That would represent a corruption
452 # of the branch. and we want to detect and reject the results
453 # of such corruption before it makes it out anywhere. If we
454 # reject it here then we avoid making the pseudomerge which
455 # would be needed to push it.
457 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
458 @p == 2 or return $badanchor->("has other than two parents");
459 $haspatches and return $badanchor->("contains debian/patches");
461 # How to decide about l/r ordering of anchors ? git
462 # --topo-order prefers to expand 2nd parent first. There's
463 # already an easy rune to look for debian/ history anyway (git log
464 # debian/) so debian breakwater branch should be 1st parent; that
465 # way also there's also an easy rune to look for the upstream
466 # patches (--topo-order).
468 # Also this makes --first-parent be slightly more likely to
469 # be useful - it makes it provide a linearised breakwater history.
471 # Of course one can say somthing like
472 # gitk -- ':/' ':!/debian'
473 # to get _just_ the commits touching upstream files, and by
474 # the TREESAME logic in git-rev-list this will leave the
475 # breakwater into upstream at the first anchor. But that
476 # doesn't report debian/ changes at all.
478 # Other observations about gitk: by default, gitk seems to
479 # produce output in a different order to git-rev-list. I
480 # can't seem to find this documented anywhere. gitk
481 # --date-order DTRT. But, gitk always seems to put the
482 # parents from left to right, in order, so it's easy to see
483 # which way round a pseudomerge is.
485 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
486 $p[1]{Differs} & ~DS_DEB and
487 $badanchor->("upstream files differ from left parent");
488 $p[0]{Differs} & ~D_UPS and
489 $badanchor->("debian/ differs from right parent");
491 return $classify->(qw(Anchor),
492 OrigParents => [ $p[1] ]);
496 my $d = $r->{Parents}[0]{Differs};
497 if ($d == D_PAT_ADD) {
498 return $classify->(qw(AddPatches));
499 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
500 return $unknown->("edits debian/patches");
501 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
502 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
504 if ($d == D_DEB_CLOG) {
505 return $classify->(qw(Changelog));
507 return $classify->(qw(Packaging));
509 } elsif ($ty eq 'missing') {
510 return $classify->(qw(BreakwaterStart));
512 return $unknown->("parent's debian is not a directory");
514 } elsif ($d == D_UPS) {
515 return $classify->(qw(Upstream));
516 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
517 return $classify->(qw(Mixed));
519 return $unknown->("no changes");
521 confess "internal error $objid ?";
525 return $unknown->("origin commit");
528 if (@p == 2 && @identical == 1) {
529 my @overwritten = grep { $_->{Differs} } @p;
530 confess "internal error $objid ?" unless @overwritten==1;
531 return $classify->(qw(Pseudomerge),
532 Overwritten => [ $overwritten[0] ],
533 Contributor => $identical[0]);
535 if (@p == 2 && @identical == 2) {
537 my ($ph,$pm) = get_commit $_[0]{CommitId};
538 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
542 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
543 if ($order > 0) { # newer first
544 } elsif ($order < 0) {
545 @bytime = reverse @bytime;
547 # same age, default to order made by -s ours
548 # that is, commit was made by someone who preferred L
550 return $classify->(qw(Pseudomerge),
551 SubType => qw(Ambiguous),
552 Contributor => $bytime[0],
553 Overwritten => [ $bytime[1] ]);
556 my ($p_h, $p_m) = get_commit $p->{CommitId};
557 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
558 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
560 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
562 if (!(grep { !$_->{IsOrigin} } @p) and
563 (@orig_ps >= @p - 1) and
564 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
566 return $classify->(qw(DgitImportUnpatched),
567 OrigParents => \@orig_ps);
570 return $unknown->("complex merge");
573 sub keycommits ($;$$$$) {
574 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
575 # => ($anchor, $breakwater)
577 # $unclean->("unclean-$tagsfx", $msg, $cl)
578 # $furniture->("unclean-$tagsfx", $msg, $cl)
579 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
580 # is callled for each situation or commit that
581 # wouldn't be found in a laundered branch
582 # $furniture is for furniture commits such as might be found on an
583 # interchange branch (pseudomerge, d/patches, changelog)
584 # $trouble is for things whnich prevent the return of
585 # anchor and breakwater information; if that is ignored,
586 # then keycommits returns (undef, undef) instead.
587 # $fatal is for unprocessable commits, and should normally cause
588 # a failure. If ignored, agaion, (undef, undef) is returned.
590 # If a callback is undef, fail is called instead.
591 # If a callback is defined but false, the situation is ignored.
593 # no warnings qw(exiting); last;
594 # if the answer is no longer wanted.
596 my ($anchor, $breakwater);
600 $fatal //= sub { fail $_[1]; };
602 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
603 my $why = $mainwhy.$xwhy;
604 my $m = "branch needs laundering (run git-debrebase): $why";
605 fail $m unless defined $cb;
607 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
610 $cl = classify $head;
611 my $ty = $cl->{Type};
612 if ($ty eq 'Packaging') {
613 $breakwater //= $clogonly;
614 $breakwater //= $head;
615 } elsif ($ty eq 'Changelog') {
616 # this is going to count as the tip of the breakwater
617 # only if it has no upstream stuff before it
619 } elsif ($ty eq 'Anchor' or
620 $ty eq 'TreatAsAnchor' or
621 $ty eq 'BreakwaterStart') {
623 $breakwater //= $clogonly;
624 $breakwater //= $head;
626 } elsif ($ty eq 'Upstream') {
627 $x->($unclean, 'ordering',
628 "packaging change ($breakwater) follows upstream change"," (eg $head)")
629 if defined $breakwater;
632 } elsif ($ty eq 'Mixed') {
633 $x->($unclean, 'mixed',
634 "found mixed upstream/packaging commit"," ($head)");
637 } elsif ($ty eq 'Pseudomerge' or
638 $ty eq 'AddPatches') {
640 $x->($furniture, (lc $ty),
641 "found interchange bureaucracy commit ($ty)"," ($head)");
642 } elsif ($ty eq 'DgitImportUnpatched') {
644 $x->($trouble, 'dgitimport',
645 "found dgit dsc import"," ($head)");
646 return (undef,undef);
648 $x->($fatal, 'unprocessable',
649 "found bare dgit dsc import with no prior history",
651 return (undef,undef);
654 $x->($fatal, 'unprocessable',
655 "found unprocessable commit, cannot cope: $cl->{Why}",
657 return (undef,undef);
659 $head = $cl->{Parents}[0]{CommitId};
661 return ($anchor, $breakwater);
667 $nogenerate,$report, $report_lprefix) = @_;
668 # => ($tip, $breakwater_tip, $last_anchor)
669 # (or nothing, if $nogenerate)
671 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
672 $report_lprefix //= '';
674 # go through commits backwards
675 # we generate two lists of commits to apply:
676 # breakwater branch and upstream patches
677 my (@brw_cl, @upp_cl, @processed);
684 my ($prose, $info) = @_;
688 $ms .= "\n\n[git-debrebase$info: $prose]\n";
691 my $rewrite_from_here = sub {
693 my $sp_cl = { SpecialMethod => 'StartRewrite' };
695 push @processed, $sp_cl;
700 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
703 return unless $report;
704 print $report $prdelim, $report_lprefix, @_;
708 my $bomb = sub { # usage: return $bomb->();
709 print $report " Unprocessable" if $report;
710 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
713 return (undef,undef);
715 fail "found unprocessable commit, cannot cope".
716 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
717 " (commit $cur) (d.".
718 (join ' ', map { sprintf "%#x", $_->{Differs} }
719 @{ $cl->{Parents} }).
726 my $build_start = sub {
727 my ($msg, $parent) = @_;
730 no warnings qw(exiting); last;
737 my $ty = $cl->{Type};
738 my $st = $cl->{SubType};
739 $prline->("$cl->{CommitId} $cl->{Type}");
740 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
741 push @processed, $cl;
742 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
743 if ($ty eq 'AddPatches') {
745 $rewrite_from_here->(\@upp_cl);
747 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
751 } elsif ($ty eq 'BreakwaterStart') {
753 $build_start->('FirstPackaging', $cur);
754 } elsif ($ty eq 'Upstream') {
758 } elsif ($ty eq 'Mixed') {
761 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
764 $queue->(\@brw_cl, "debian");
765 $queue->(\@upp_cl, "upstream");
766 $rewrite_from_here->(\@brw_cl);
769 } elsif ($ty eq 'Pseudomerge') {
770 my $contrib = $cl->{Contributor}{CommitId};
771 print $report " Contributor=$contrib" if $report;
772 push @pseudomerges, $cl;
773 $rewrite_from_here->(\@upp_cl);
776 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
778 $build_start->("Anchor", $cur);
779 } elsif ($ty eq 'DgitImportUnpatched') {
780 my $pm = $pseudomerges[-1];
782 # To an extent, this is heuristic. Imports don't have
783 # a useful history of the debian/ branch. We assume
784 # that the first pseudomerge after an import has a
785 # useful history of debian/, and ignore the histories
786 # from later pseudomerges. Often the first pseudomerge
787 # will be the dgit import of the upload to the actual
788 # suite intended by the non-dgit NMUer, and later
789 # pseudomerges may represent in-archive copies.
790 my $ovwrs = $pm->{Overwritten};
791 printf $report " PM=%s \@Overwr:%d",
792 $pm->{CommitId}, (scalar @$ovwrs)
795 printdebug "*** WALK BOMB DgitImportUnpatched\n";
798 my $ovwr = $ovwrs->[0]{CommitId};
799 printf $report " Overwr=%s", $ovwr if $report;
800 # This import has a tree which is just like a
801 # breakwater tree, but it has the wrong history. It
802 # ought to have the previous breakwater (which the
803 # pseudomerge overwrote) as an ancestor. That will
804 # make the history of the debian/ files correct. As
805 # for the upstream version: either it's the same as
806 # was ovewritten (ie, same as the previous
807 # breakwater), in which case that history is precisely
808 # right; or, otherwise, it was a non-gitish upload of a
809 # new upstream version. We can tell these apart by
810 # looking at the tree of the supposed upstream.
813 SpecialMethod => 'DgitImportDebianUpdate',
814 $xmsg->("convert dgit import: debian changes")
817 SpecialMethod => 'DgitImportUpstreamUpdate',
818 $xmsg->("convert dgit import: upstream update",
821 $prline->(" Import");
822 $rewrite_from_here->(\@brw_cl);
823 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
827 # Everything is from this import. This kind of import
828 # is already nearly in valid breakwater format, with the
829 # patches as commits. Unfortunately it contains
831 printdebug "*** WALK BOMB bare dgit import\n";
832 $cl->{Why} = "bare dgit dsc import";
837 printdebug "*** WALK BOMB unrecognised\n";
843 printdebug "*** WALK prep done cur=$cur".
844 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
846 return if $nogenerate;
848 # Now we build it back up again
854 my $read_tree_debian = sub {
856 read_tree_subdir 'debian', "$treeish:debian";
857 rm_subdir_cached 'debian/patches';
859 my $read_tree_upstream = sub {
861 runcmd @git, qw(read-tree), $treeish;
862 $read_tree_debian->($build);
865 $#upp_cl = $upp_limit if defined $upp_limit;
867 my $committer_authline = calculate_committer_authline();
869 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
871 confess "internal error" unless $build eq (pop @processed)->{CommitId};
874 mkdir $rd or $!==EEXIST or die $!;
876 runcmd @git, qw(read-tree), $build;
877 foreach my $cl (qw(Debian), (reverse @brw_cl),
878 { SpecialMethod => 'RecordBreakwaterTip' },
879 qw(Upstream), (reverse @upp_cl)) {
881 $current_method = $cl;
884 my $method = $cl->{SpecialMethod} // $current_method;
885 my @parents = ($build);
886 my $cltree = $cl->{CommitId};
887 printdebug "WALK BUILD ".($cltree//'undef').
888 " $method (rewriting=$rewriting)\n";
889 if ($method eq 'Debian') {
890 $read_tree_debian->($cltree);
891 } elsif ($method eq 'Upstream') {
892 $read_tree_upstream->($cltree);
893 } elsif ($method eq 'StartRewrite') {
896 } elsif ($method eq 'RecordBreakwaterTip') {
897 $breakwater = $build;
899 } elsif ($method eq 'DgitImportDebianUpdate') {
900 $read_tree_debian->($cltree);
901 } elsif ($method eq 'DgitImportUpstreamUpdate') {
902 confess unless $rewriting;
903 my $differs = (get_differs $build, $cltree);
904 next unless $differs & D_UPS;
905 $read_tree_upstream->($cltree);
906 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
911 my $procd = (pop @processed) // 'UNDEF';
914 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
917 my $newtree = cmdoutput @git, qw(write-tree);
919 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
920 $ch =~ s{^parent .*\n}{}mg;
921 $ch =~ s{(?=^author)}{
922 join '', map { "parent $_\n" } @parents
923 }me or confess "$ch ?";
925 $ch =~ s{^committer .*$}{$committer_authline}m
928 my $cf = "$rd/m$rewriting";
929 open CD, ">", $cf or die $!;
930 print CD $ch, "\n", $cl->{Msg} or die $!;
932 my @cmd = (@git, qw(hash-object));
933 push @cmd, qw(-w) if $rewriting;
934 push @cmd, qw(-t commit), $cf;
935 my $newcommit = cmdoutput @cmd;
936 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
938 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
944 my $final_check = get_differs $build, $input;
945 die sprintf "internal error %#x %s %s", $final_check, $build, $input
946 if $final_check & ~D_PAT_ADD;
948 my @r = ($build, $breakwater, $last_anchor);
949 printdebug "*** WALK RETURN @r\n";
954 git_check_unmodified();
955 return git_rev_parse qw(HEAD);
958 sub update_head ($$$) {
959 my ($old, $new, $mrest) = @_;
960 push @deferred_updates, "update HEAD $new $old";
961 run_deferred_updates $mrest;
964 sub update_head_checkout ($$$) {
965 my ($old, $new, $mrest) = @_;
966 update_head $old, $new, $mrest;
967 runcmd @git, qw(reset --hard);
970 sub update_head_postlaunder ($$$) {
971 my ($old, $tip, $reflogmsg) = @_;
972 return if $tip eq $old;
973 print "git-debrebase: laundered (head was $old)\n";
974 update_head $old, $tip, $reflogmsg;
975 # no tree changes except debian/patches
976 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
979 sub currently_rebasing() {
980 foreach (qw(rebase-merge rebase-apply)) {
981 return 1 if stat_exists "$maindir_gitdir/$_";
986 sub bail_if_rebasing() {
987 fail "you are in the middle of a git-rebase already"
988 if currently_rebasing();
991 sub do_launder_head ($) {
992 my ($reflogmsg) = @_;
993 my $old = get_head();
995 my ($tip,$breakwater) = walk $old;
997 update_head_postlaunder $old, $tip, $reflogmsg;
998 return ($tip,$breakwater);
1001 sub cmd_launder_v0 () {
1002 badusage "no arguments to launder-v0 allowed" if @ARGV;
1003 my $old = get_head();
1004 my ($tip,$breakwater,$last_anchor) = walk $old;
1005 update_head_postlaunder $old, $tip, 'launder';
1006 printf "# breakwater tip\n%s\n", $breakwater;
1007 printf "# working tip\n%s\n", $tip;
1008 printf "# last anchor\n%s\n", $last_anchor;
1011 sub defaultcmd_rebase () {
1012 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1013 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1014 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1017 sub cmd_analyse () {
1018 badusage "analyse does not support any options"
1019 if @ARGV and $ARGV[0] =~ m/^-/;
1020 badusage "too many arguments to analyse" if @ARGV>1;
1023 $old = git_rev_parse $old;
1025 $old = git_rev_parse 'HEAD';
1027 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1028 STDOUT->error and die $!;
1031 sub ffq_prev_branchinfo () {
1032 my $current = git_get_symref();
1033 return gdr_ffq_prev_branchinfo($current);
1036 sub ffq_check ($;$$) {
1037 # calls $ff and/or $notff zero or more times
1038 # then returns either (status,message) where status is
1043 # or (undef,undef, $ffq_prev,$gdrlast)
1044 # $ff and $notff are called like this:
1045 # $ff->("message for stdout\n");
1046 # $notff->('snag-name', $message);
1047 # normally $currentval should be HEAD
1048 my ($currentval, $ff, $notff) =@_;
1050 $ff //= sub { print $_[0] or die $!; };
1053 my ($status, $message, $current, $ffq_prev, $gdrlast)
1054 = ffq_prev_branchinfo();
1055 return ($status, $message) unless $status eq 'branch';
1057 my $exists = git_get_ref $ffq_prev;
1058 return ('exists',"$ffq_prev already exists") if $exists;
1060 return ('not-branch', 'HEAD symref is not to refs/heads/')
1061 unless $current =~ m{^refs/heads/};
1064 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1067 printdebug "ffq check_specs @check_specs\n";
1070 my ($lrref, $desc) = @_;
1071 printdebug "ffq might check $lrref ($desc)\n";
1073 for my $chk (@check_specs) {
1075 $invert = $glob =~ s{^[!^]}{};
1076 last if fnmatch $glob, $lrref;
1079 my $lrval = git_get_ref $lrref;
1080 return unless length $lrval;
1082 if (is_fast_fwd $lrval, $currentval) {
1083 $ff->("OK, you are ahead of $lrref\n");
1084 $checked{$lrref} = 1;
1085 } elsif (is_fast_fwd $currentval, $lrval) {
1086 $checked{$lrref} = -1;
1087 $notff->('behind', "you are behind $lrref, divergence risk");
1089 $checked{$lrref} = -1;
1090 $notff->('diverged', "you have diverged from $lrref");
1094 my $merge = cfg "branch.$branch.merge",1;
1095 if (defined $merge and $merge =~ m{^refs/heads/}) {
1097 printdebug "ffq merge $rhs\n";
1098 my $check_remote = sub {
1099 my ($remote, $desc) = @_;
1100 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1101 return unless defined $remote;
1102 $check->("refs/remotes/$remote/$rhs", $desc);
1104 $check_remote->((scalar cfg "branch.$branch.remote",1),
1105 'remote fetch/merge branch');
1106 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1107 (scalar cfg "branch.$branch.pushDefault",1),
1108 'remote push branch');
1110 if ($branch =~ m{^dgit/}) {
1111 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1112 } elsif ($branch =~ m{^master$}) {
1113 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1115 return (undef, undef, $ffq_prev, $gdrlast);
1118 sub record_ffq_prev_deferred () {
1119 # => ('status', "message")
1121 # deferred message is undef
1126 # if not ff from some branch we should be ff from, is an snag
1127 # if "deferred", will have added something about that to
1128 # @deferred_update_messages, and also maybe printed (already)
1129 # some messages about ff checks
1131 my $currentval = get_head();
1133 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1134 return ($status,$message) if defined $status;
1138 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1139 push @deferred_updates, "delete $gdrlast";
1140 push @deferred_update_messages, "Recorded current head for preservation";
1141 return ('deferred', undef);
1144 sub record_ffq_auto () {
1145 my ($status, $message) = record_ffq_prev_deferred();
1146 if ($status eq 'deferred' || $status eq 'exists') {
1148 snag $status, "could not record ffq-prev: $message";
1153 sub ffq_prev_info () {
1155 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1156 my ($status, $message, $current, $ffq_prev, $gdrlast)
1157 = ffq_prev_branchinfo();
1158 if ($status ne 'branch') {
1159 snag $status, "could not check ffq-prev: $message";
1162 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1163 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1166 sub stitch ($$$$$) {
1167 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1169 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1171 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1172 my $differs = get_differs $old_head, $ffq_prev_commitish;
1173 unless ($differs & ~D_PAT_ADD) {
1174 # ffq-prev is ahead of us, and the only tree changes it has
1175 # are possibly addition of things in debian/patches/.
1176 # Just wind forwards rather than making a pointless pseudomerge.
1177 push @deferred_updates,
1178 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1179 update_head_checkout $old_head, $ffq_prev_commitish,
1180 "stitch (fast forward)";
1185 # We make pseudomerges with L as the contributing parent.
1186 # This makes git rev-list --first-parent work properly.
1187 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1188 'Declare fast forward / record previous work',
1189 "[git-debrebase pseudomerge: $prose]",
1191 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1192 update_head $old_head, $new_head, "stitch: $prose";
1195 sub do_stitch ($;$) {
1196 my ($prose, $unclean) = @_;
1198 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1199 if (!$ffq_prev_commitish) {
1200 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1203 my $dangling_head = get_head();
1205 keycommits $dangling_head, $unclean,$unclean,$unclean;
1208 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1211 sub upstream_commitish_search ($$) {
1212 my ($upstream_version, $tried) = @_;
1213 # todo: at some point maybe use git-deborig to do this
1214 foreach my $tagpfx ('', 'v', 'upstream/') {
1215 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1216 my $new_upstream = git_get_ref "refs/tags/$tag";
1218 return $new_upstream if length $new_upstream;
1222 sub resolve_upstream_version ($$) {
1223 my ($new_upstream, $upstream_version) = @_;
1225 if (!defined $new_upstream) {
1227 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1228 if (!length $new_upstream) {
1229 fail "Could not determine appropriate upstream commitish.\n".
1230 " (Tried these tags: @tried)\n".
1231 " Check version, and specify upstream commitish explicitly.";
1234 $new_upstream = git_rev_parse $new_upstream;
1236 return $new_upstream;
1239 sub cmd_new_upstream () {
1240 # automatically and unconditionally launders before rebasing
1241 # if rebase --abort is used, laundering has still been done
1245 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1247 # parse args - low commitment
1248 my $spec_version = shift @ARGV;
1249 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1250 fail "bad version number \`$spec_version'" unless defined $new_version;
1251 if ($new_version->is_native()) {
1252 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1255 my $new_upstream = shift @ARGV;
1256 my $new_upstream_version = upstreamversion $new_version;
1258 resolve_upstream_version $new_upstream, $new_upstream_version;
1263 my ($n, @x) = @_; # may be ''
1264 my $pc = $pieces{$n} //= {
1266 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1268 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1273 my $newpiece = sub {
1274 my ($n, @x) = @_; # may be ''
1275 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1276 push @newpieces, $pc;
1281 New => $new_upstream,
1283 while (@ARGV && $ARGV[0] !~ m{^-}) {
1284 my $n = shift @ARGV;
1286 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1287 unless @ARGV && $ARGV[0] !~ m{^-};
1289 my $c = git_rev_parse shift @ARGV;
1290 die unless $n =~ m/^$extra_orig_namepart_re$/;
1291 $newpiece->($n, New => $c);
1294 # now we need to investigate the branch this generates the
1295 # laundered version but we don't switch to it yet
1296 my $old_head = get_head();
1297 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1299 my $old_bw_cl = classify $old_bw;
1300 my $old_anchor_cl = classify $old_anchor;
1302 if (!$old_anchor_cl->{OrigParents}) {
1303 snag 'anchor-treated',
1304 'old anchor is recognised due to --anchor, cannot check upstream';
1306 $old_upstream = parsecommit
1307 $old_anchor_cl->{OrigParents}[0]{CommitId};
1308 $piece->('', Old => $old_upstream->{CommitId});
1311 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1312 if ($old_upstream->{Msg} =~
1313 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1315 my @oldpieces = (split / /, $1);
1316 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1317 if ($old_n_parents != @oldpieces &&
1318 $old_n_parents != @oldpieces + 1) {
1319 snag 'upstream-confusing', sprintf
1320 "previous upstream combine %s".
1321 " mentions %d pieces (each implying one parent)".
1322 " but has %d parents".
1323 " (one per piece plus maybe a previous combine)",
1324 $old_upstream->{CommitId},
1325 (scalar @oldpieces),
1327 } elsif ($oldpieces[0] ne '.') {
1328 snag 'upstream-confusing', sprintf
1329 "previous upstream combine %s".
1330 " first piece is not \`.'",
1334 foreach my $i (0..$#oldpieces) {
1335 my $n = $oldpieces[$i];
1336 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1337 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1341 snag 'upstream-confusing',
1342 "previous upstream $old_upstream->{CommitId} is from".
1343 " git-debrebase but not an \`upstream-combine' commit";
1347 foreach my $pc (values %pieces) {
1348 if (!$old_upstream) {
1349 # we have complained already
1350 } elsif (!$pc->{Old}) {
1351 snag 'upstream-new-piece',
1352 "introducing upstream piece \`$pc->{Name}'";
1353 } elsif (!$pc->{New}) {
1354 snag 'upstream-rm-piece',
1355 "dropping upstream piece \`$pc->{Name}'";
1356 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1357 snag 'upstream-not-ff',
1358 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1362 printdebug "%pieces = ", (dd \%pieces), "\n";
1363 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1371 my @upstream_merge_parents;
1374 push @upstream_merge_parents, $old_upstream->{CommitId};
1377 foreach my $pc (@newpieces) { # always has '' first
1379 read_tree_subdir $pc->{Name}, $pc->{New};
1381 runcmd @git, qw(read-tree), $pc->{New};
1383 push @upstream_merge_parents, $pc->{New};
1386 # index now contains the new upstream
1388 if (@newpieces > 1) {
1389 # need to make the upstream subtree merge commit
1390 $new_upstream = make_commit \@upstream_merge_parents,
1391 [ "Combine upstreams for $new_upstream_version",
1392 ("[git-debrebase upstream-combine . ".
1393 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1398 # $new_upstream is either the single upstream commit, or the
1399 # combined commit we just made. Either way it will be the
1400 # "upstream" parent of the anchor merge.
1402 read_tree_subdir 'debian', "$old_bw:debian";
1404 # index now contains the anchor merge contents
1405 $new_bw = make_commit [ $old_bw, $new_upstream ],
1406 [ "Update to upstream $new_upstream_version",
1407 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1410 my $clogsignoff = cmdoutput qw(git show),
1411 '--pretty=format:%an <%ae> %aD',
1414 # Now we have to add a changelog stanza so the Debian version
1416 die if unlink "debian";
1417 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1418 unlink "debian/changelog" or $!==ENOENT or die $!;
1419 mkdir "debian" or die $!;
1420 open CN, ">", "debian/changelog" or die $!;
1421 my $oldclog = git_cat_file ":debian/changelog";
1422 $oldclog =~ m/^($package_re) \(\S+\) / or
1423 fail "cannot parse old changelog to get package name";
1425 print CN <<END, $oldclog or die $!;
1426 $p ($new_version) UNRELEASED; urgency=medium
1428 * Update to new upstream version $new_upstream_version.
1434 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1436 # Now we have the final new breakwater branch in the index
1437 $new_bw = make_commit [ $new_bw ],
1438 [ "Update changelog for new upstream $new_upstream_version",
1439 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1443 # we have constructed the new breakwater. we now need to commit to
1444 # the laundering output, because git-rebase can't easily be made
1445 # to make a replay list which is based on some other branch
1447 update_head_postlaunder $old_head, $old_laundered_tip,
1448 'launder for new upstream';
1450 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1451 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1452 "debrebase new-upstream $new_version: rebase";
1454 # now it's for the user to sort out
1457 sub cmd_record_ffq_prev () {
1458 badusage "no arguments allowed" if @ARGV;
1459 my ($status, $msg) = record_ffq_prev_deferred();
1460 if ($status eq 'exists' && $opt_noop_ok) {
1461 print "Previous head already recorded\n" or die $!;
1462 } elsif ($status eq 'deferred') {
1463 run_deferred_updates 'record-ffq-prev';
1465 fail "Could not preserve: $msg";
1470 badusage "no arguments allowed" if @ARGV;
1471 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1472 print "$bw\n" or die $!;
1475 sub cmd_breakwater () {
1476 badusage "no arguments allowed" if @ARGV;
1477 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1478 print "$bw\n" or die $!;
1482 badusage "no arguments allowed" if @ARGV;
1484 # todo: gdr status should print divergence info
1485 # todo: gdr status should print upstream component(s) info
1486 # todo: gdr should leave/maintain some refs with this kind of info ?
1488 my $oldest = { Badness => 0 };
1491 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1492 if ($oldest->{Badness} < $badness) {
1493 $oldest = $newest = undef;
1496 Badness => $badness,
1497 CommitId => $cl->{CommitId},
1501 $newest //= $oldest;
1503 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1504 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1505 sub { $note->(2, 'branch is unlaundered', @_); },
1506 sub { $note->(3, 'branch needs laundering', @_); },
1507 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1509 my $prcommitinfo = sub {
1511 flush STDOUT or die $!;
1512 runcmd @git, qw(--no-pager log -n1),
1513 '--pretty=format: %h %s%n',
1517 print "current branch contents, in git-debrebase terms:\n";
1518 if (!$oldest->{Badness}) {
1519 print " branch is laundered\n";
1521 print " $oldest->{OurMsg}\n";
1523 foreach my $info ($oldest, $newest) {
1524 my $cid = $info->{CommitId};
1525 next if $cid eq $printed;
1527 print " $info->{KcMsg}\n";
1528 $prcommitinfo->($cid);
1533 my ($cid, $what) = @_;
1534 if (!defined $cid) {
1535 print " $what is not well-defined\n";
1538 $prcommitinfo->($cid);
1541 print "key git-debrebase commits:\n";
1542 $prab->($anchor, 'anchor');
1543 $prab->($bw, 'breakwater');
1545 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1546 ffq_prev_branchinfo();
1548 print "branch and ref status, in git-debrebase terms:\n";
1550 print " $ffq_msg\n";
1552 $ffq_prev = git_get_ref $ffq_prev;
1553 $gdrlast = git_get_ref $gdrlast;
1555 print " unstitched; previous tip was:\n";
1556 $prcommitinfo->($ffq_prev);
1557 } elsif (!$gdrlast) {
1558 print " stitched? (no record of git-debrebase work)\n";
1559 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1560 print " stitched\n";
1562 print " not git-debrebase (diverged since last stitch)\n"
1565 print "you are currently rebasing\n" if currently_rebasing();
1569 my $prose = 'stitch';
1570 getoptions("stitch",
1571 'prose=s', \$prose);
1572 badusage "no arguments allowed" if @ARGV;
1573 do_stitch $prose, 0;
1575 sub cmd_prepush () { cmd_stitch(); }
1578 badusage "no arguments allowed" if @ARGV;
1579 do_launder_head 'launder for git-debrebase quick';
1583 sub cmd_conclude () {
1584 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1585 if (!$ffq_prev_commitish) {
1586 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1589 my $dangling_head = get_head();
1591 badusage "no arguments allowed" if @ARGV;
1592 do_launder_head 'launder for git-debrebase quick';
1597 if (currently_rebasing()) {
1598 runcmd @git, qw(rebase --abort);
1600 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1601 if (!$ffq_prev_commitish) {
1602 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1605 my $scrapping_head = get_head();
1606 badusage "no arguments allowed" if @ARGV;
1607 push @deferred_updates,
1608 "update $gdrlast $ffq_prev_commitish $git_null_obj",
1609 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
1611 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
1614 sub make_patches_staged ($) {
1616 # Produces the patches that would result from $head if it were
1618 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1621 runcmd @git, qw(checkout -q -b bw), $secret_bw;
1622 runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1623 my @gbp_cmd = (qw(gbp pq export));
1624 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1626 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1629 runcmd @git, qw(add -f debian/patches);
1633 sub make_patches ($) {
1635 keycommits $head, 0, \&snag;
1636 make_patches_staged $head;
1639 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1640 runcmd @git, qw(read-tree), $head;
1641 read_tree_subdir 'debian/patches', $ptree;
1642 $out = make_commit [$head], [
1643 'Commit patch queue (exported by git-debrebase)',
1644 '[git-debrebase: export and commit patches]',
1650 sub cmd_make_patches () {
1651 my $opt_quiet_would_amend;
1652 getoptions("make-patches",
1653 'quiet-would-amend!', \$opt_quiet_would_amend);
1654 badusage "no arguments allowed" if @ARGV;
1656 my $old_head = get_head();
1657 my $new = make_patches $old_head;
1658 my $d = get_differs $old_head, $new;
1660 fail "No (more) patches to export." unless $opt_noop_ok;
1662 } elsif ($d == D_PAT_ADD) {
1664 update_head_checkout $old_head, $new, 'make-patches';
1666 print STDERR failmsg
1667 "Patch export produced patch amendments".
1668 " (abandoned output commit $new).".
1669 " Try laundering first."
1670 unless $opt_quiet_would_amend;
1675 sub cmd_convert_from_gbp () {
1676 badusage "want only 1 optional argument, the upstream git commitish"
1679 my $clogp = parsechangelog();
1680 my $version = $clogp->{'Version'}
1681 // die "missing Version from changelog";
1683 my ($upstream_spec) = @ARGV;
1685 my $upstream_version = upstreamversion $version;
1687 resolve_upstream_version($upstream_spec, $upstream_version);
1689 my $old_head = get_head();
1691 my $upsdiff = get_differs $upstream, $old_head;
1692 if ($upsdiff & D_UPS) {
1693 runcmd @git, qw(--no-pager diff --stat),
1694 $upstream, $old_head,
1695 qw( -- :!/debian :/);
1697 upstream ($upstream_spec) and HEAD are not
1698 identical in upstream files. See diffstat above, or run
1699 git diff $upstream_spec HEAD -- :!/debian :/
1703 if (!is_fast_fwd $upstream, $old_head) {
1704 snag 'upstream-not-ancestor',
1705 "upstream ($upstream) is not an ancestor of HEAD";
1707 my $wrong = cmdoutput
1708 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1709 qw(-- :/ :!/debian));
1710 if (length $wrong) {
1711 snag 'unexpected-upstream-changes',
1712 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1713 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1717 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1718 snag 'upstream-has-debian',
1719 "upstream ($upstream) contains debian/ directory";
1722 my $previous_dgit_view = eval {
1723 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1725 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1726 my ($stz, $desc) = @_;
1727 no warnings qw(exiting);
1728 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1729 next unless $stz->{Date};
1730 next unless $stz->{Distribution} ne 'UNRELEASED';
1731 $lvsn = $stz->{Version};
1732 $suite = $stz->{Distribution};
1735 die "neither of the first two changelog entries are released\n"
1736 unless defined $lvsn;
1737 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1738 my $mtag_pat = debiantag_maintview $lvsn, '*';
1739 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1741 die "could not find suitable maintainer view tag $mtag_pat\n"
1742 unless $mtag_pat =~ m{/};
1743 is_fast_fwd $mtag, 'HEAD' or
1744 die "HEAD is not FF from maintainer tag $mtag!";
1745 my $dtag = "archive/$mtag";
1746 is_fast_fwd $mtag, $dtag or
1747 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1748 print "will stitch in dgit view, $dtag\n";
1749 git_rev_parse $dtag;
1751 if (!$previous_dgit_view) {
1754 print STDERR "cannot stitch in dgit view: $@\n";
1757 snags_maybe_bail_early();
1763 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1764 # make a branch out of the patch queue - we'll want this in a mo
1765 runcmd qw(gbp pq import);
1766 # strip the patches out
1767 runcmd @git, qw(checkout -q gdr-internal~0);
1768 rm_subdir_cached 'debian/patches';
1769 $work = make_commit ['HEAD'], [
1770 'git-debrebase convert-from-gbp: drop patches from tree',
1771 'Delete debian/patches, as part of converting to git-debrebase format.',
1772 '[git-debrebase convert-from-gbp: drop patches from tree]'
1774 # make the anchor merge
1775 # the tree is already exactly right
1776 $work = make_commit [$work, $upstream], [
1777 'git-debrebase import: declare upstream',
1778 'First breakwater merge.',
1779 '[git-debrebase anchor: declare upstream]'
1782 # rebase the patch queue onto the new breakwater
1783 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1784 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1785 $work = git_rev_parse 'HEAD';
1787 if ($previous_dgit_view) {
1788 $work = make_commit [$work, $previous_dgit_view], [
1789 'git-debrebase import: declare ff from dgit archive view',
1790 '[git-debrebase pseudomerge: import-from-gbp]',
1797 update_head_checkout $old_head, $work, 'convert-from-gbp';
1800 sub cmd_convert_to_gbp () {
1801 badusage "no arguments allowed" if @ARGV;
1802 my $head = get_head();
1803 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1804 keycommits $head, 0;
1806 make_patches_staged $head;
1808 $out = make_commit ['HEAD'], [
1809 'Commit patch queue (converted from git-debrebase format)',
1810 '[git-debrebase convert-to-gbp: commit patches]',
1814 push @deferred_updates, "delete $ffq";
1815 push @deferred_updates, "delete $gdrlast";
1818 update_head_checkout $head, $out, "convert to gbp (v0)";
1819 print <<END or die $!;
1820 git-debrebase: converted to git-buildpackage branch format
1821 git-debrebase: WARNING: do not now run "git-debrebase" any more
1822 git-debrebase: WARNING: doing so would drop all upstream patches!
1826 sub cmd_convert_from_dgit_view () {
1827 my $clogp = parsechangelog();
1829 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
1835 getoptions("convert-from-dgit-view",
1836 'diagnose!', \$diagnose,
1837 'build-products-dir:s', \$bpd,
1838 'origs!', \$do_origs,
1840 'always-convert-anyway!', \$always);
1841 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
1846 my $spec = shift @ARGV;
1847 my $commit = git_rev_parse "$spec^{commit}";
1848 push @upstreams, { Commit => $commit,
1849 Source => "$ARGV[0], from command line",
1854 my $head = get_head();
1858 my $trouble = sub { $troubles++; };
1859 keycommits $head, sub{}, sub{}, $trouble, $trouble;
1860 printdebug "troubles=$troubles\n";
1863 $us: Branch already seems to be in git-debrebase format!
1864 $us: --always-convert-anyway would do the conversion operation anyway
1865 $us: but is probably a bad idea. Probably, you wanted to do nothing.
1867 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
1872 snags_maybe_bail_early();
1874 my $version = upstreamversion $clogp->{Version};
1875 print STDERR "Considering possible commits corresponding to upstream:\n";
1880 my $ups_tag = upstream_commitish_search $version, \@tried;
1882 my $this = "git tag $tried[-1]";
1883 push @upstreams, { Commit => $ups_tag,
1888 " git tag: no suitable tag found (tried %s)\n",
1893 my $p = $clogp->{'Source'};
1894 # we do a quick check to see if there are plausible origs
1896 if (!opendir BPD, $bpd) {
1897 die "$bpd: opendir: $!" unless $!==ENOENT;
1899 while ($!=0, my $f = readdir BPD) {
1900 next unless is_orig_file_of_p_v $f, $p, $version;
1902 " orig: found what looks like a .orig, %s\n",
1907 die "read $bpd: $!" if $!;
1911 my $tree = cmdoutput
1912 @dgit, qw(--build-products-dir), $bpd,
1913 qw(print-unapplied-treeish);
1916 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
1917 rm_subdir_cached 'debian';
1918 $tree = cmdoutput @git, qw(write-tree);
1919 my $ups_synth = make_commit [], [ <<END, <<END,
1920 Import effective orig tree for upstream version $version
1922 This includes the contents of the .orig(s), minus any debian/ directory.
1924 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
1927 push @upstreams, { Commit => $ups_synth,
1928 Source => "orig(s) imported via dgit",
1933 " orig: no suitable origs found (looked for %s in %s)\n",
1934 "${p}_".(stripeoch $version)."...", $bpd;
1939 my $some_patches = stat_exists 'debian/patches/series';
1941 print STDERR "Evaluating possible commits corresponding to upstream:\n";
1944 foreach my $u (@upstreams) {
1948 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
1949 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
1950 runcmd @git, qw(clean -xdff);
1951 runcmd @git, qw(checkout), $head, qw(-- debian);
1952 if ($some_patches) {
1953 rm_subdir_cached 'debian/patches';
1954 $work = make_commit [ $work ], [
1955 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
1956 "Drop upstream changes, and delete debian/patches, as part of converting\n".
1957 "to git-debrebase format. Upstream changes will appear as commits.",
1958 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
1961 $work = make_commit [ $work, $u->{Commit} ], [
1962 'git-debrebase convert-from-dgit-view: declare upstream',
1963 '(Re)constructed breakwater merge.',
1964 '[git-debrebase anchor: declare upstream]'
1966 runcmd @git, qw(checkout --quiet -b mk), $work;
1967 if ($some_patches) {
1968 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
1969 runcmd @git, qw(reset --quiet);
1970 my @gbp_cmd = (qw(gbp pq import));
1972 my $gbp_err = "../gbp-pq-err";
1973 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
1975 my $r = system @gbp_cmd;
1978 " %s: couldn't apply patches: gbp pq %s",
1979 $u->{Source}, waitstatusmsg();
1983 my $work = git_rev_parse qw(HEAD);
1984 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
1985 if (length $diffout) {
1987 " $u->{Source}: applying patches gives different tree\n";
1988 print STDERR $diffout if $diagnose;
1992 $u->{Result} = $work;
2000 Could not find or construct a suitable upstream commit.
2001 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2002 upstream commmit explicitly or provide suitable origs.
2006 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2008 ffq_check $result->{Result};
2010 update_head_checkout $head, $result->{Result},
2011 'convert-from-dgit-view';
2014 sub cmd_downstream_rebase_launder_v0 () {
2015 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2017 $base = git_rev_parse $base;
2018 my $old_head = get_head();
2019 my $current = $old_head;
2022 if ($current eq $base) {
2023 $topmost_keep //= $current;
2024 print " $current BASE stop\n";
2027 my $cl = classify $current;
2028 print " $current $cl->{Type}";
2030 my $p0 = $cl->{Parents}[0]{CommitId};
2032 if ($cl->{Type} eq 'Pseudomerge') {
2033 print " ^".($cl->{Contributor}{Ix}+1);
2034 $next = $cl->{Contributor}{CommitId};
2035 } elsif ($cl->{Type} eq 'AddPatches' or
2036 $cl->{Type} eq 'Changelog') {
2046 $topmost_keep //= $current;
2048 die "to-be stripped changes not on top of the branch\n"
2053 if ($topmost_keep eq $old_head) {
2054 print "unchanged\n";
2056 print "updating to $topmost_keep\n";
2057 update_head_checkout
2058 $old_head, $topmost_keep,
2059 'downstream-rebase-launder-v0';
2065 "D+" => \$debuglevel,
2066 'noop-ok', => \$opt_noop_ok,
2067 'f=s' => \@snag_force_opts,
2068 'anchor=s' => \@opt_anchors,
2069 '--dgit=s' => \($dgit[0]),
2072 my ($opt,$val) = @_;
2073 badusage "git-debrebase: no cuddling to -i for git-rebase"
2075 die if $opt_defaultcmd_interactive; # should not happen
2076 $opt_defaultcmd_interactive = [ qw(-i) ];
2077 # This access to @ARGV is excessive familiarity with
2078 # Getopt::Long, but there isn't another sensible
2079 # approach. '-i=s{0,}' does not work with bundling.
2080 push @$opt_defaultcmd_interactive, @ARGV;
2083 'help' => sub { print $usage_message or die $!; finish 0; },
2086 initdebug('git-debrebase ');
2087 enabledebug if $debuglevel;
2089 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2090 chdir $toplevel or die "chdir $toplevel: $!";
2092 $rd = fresh_playground "$playprefix/misc";
2094 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2096 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2097 defaultcmd_rebase();
2099 my $cmd = shift @ARGV;
2102 $cmdfn = ${*::}{"cmd_$cmdfn"};
2104 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";