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 sub gbp_pq_export ($$$) {
314 my ($bname, $base, $tip) = @_;
315 # must be run in a workarea. $bname and patch-queue/$bname
316 # ought not to exist. Leaves you on patch-queue/$bname with
317 # the patches staged but not committed.
318 runcmd @git, qw(checkout -q -b), $bname, $base;
319 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
320 my @gbp_cmd = (qw(gbp pq export));
321 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
323 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
326 runcmd @git, qw(add -f debian/patches);
329 # classify returns an info hash like this
331 # Hdr => # commit headers, including 1 final newline
332 # Msg => # commit message (so one newline is dropped)
334 # Type => (see below)
336 # Ix => $index # ie 0, 1, 2, ...
338 # Differs => return value from get_differs
340 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
342 # NewMsg => # commit message, but with any [dgit import ...] edited
343 # # to say "[was: ...]"
353 # has additional entres in classification result
354 # Overwritten = [ subset of Parents ]
355 # Contributor = $the_remaining_Parent
357 # DgitImportUnpatched
358 # has additional entry in classification result
359 # OrigParents = [ subset of Parents ]
362 # has additional entry in classification result
363 # OrigParents = [ subset of Parents ] # singleton list
370 # has additional entry in classification result
373 sub parsecommit ($;$) {
374 my ($objid, $p_ref) = @_;
375 # => hash with CommitId Hdr Msg Tree Parents
376 # Parents entries have only Ix CommitId
377 # $p_ref, if provided, must be [] and is used as a base for Parents
382 my ($h,$m) = get_commit $objid;
384 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
385 my (@ph) = $h =~ m/^parent (\w+)$/mg;
395 foreach my $ph (@ph) {
397 Ix => scalar @$p_ref,
409 my $r = parsecommit($objid, \@p);
413 $p->{Differs} = (get_differs $p->{CommitId}, $t),
416 printdebug "classify $objid \$t=$t \@p",
417 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
421 my ($type, @rest) = @_;
422 $r = { %$r, Type => $type, @rest };
424 printdebug " = $type ".(dd $r)."\n";
430 $r = { %$r, Type => qw(Unknown), Why => $why };
431 printdebug " ** Unknown\n";
435 if (grep { $_ eq $objid } @opt_anchors) {
436 return $classify->('TreatAsAnchor');
439 my @identical = grep { !$_->{Differs} } @p;
440 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
441 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
443 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
444 # multi-orig upstreams are represented with an anchor merge
445 # from a single upstream commit which combines the orig tarballs
447 # Every anchor tagged this way must be a merge.
448 # We are relying on the
449 # [git-debrebase anchor: ...]
450 # commit message annotation in "declare" anchor merges (which
451 # do not have any upstream changes), to distinguish those
452 # anchor merges from ordinary pseudomerges (which we might
453 # just try to strip).
455 # However, the user is going to be doing git-rebase a lot. We
456 # really don't want them to rewrite an anchor commit.
457 # git-rebase trips up on merges, so that is a useful safety
460 # BreakwaterStart commits are also anchors in the terminology
461 # of git-debrebase(5), but they are untagged (and always
462 # manually generated).
464 # We cannot not tolerate any tagged linear commit (ie,
465 # BreakwaterStart commits tagged `[anchor:') because such a
466 # thing could result from an erroneous linearising raw git
467 # rebase of a merge anchor. That would represent a corruption
468 # of the branch. and we want to detect and reject the results
469 # of such corruption before it makes it out anywhere. If we
470 # reject it here then we avoid making the pseudomerge which
471 # would be needed to push it.
473 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
474 @p == 2 or return $badanchor->("has other than two parents");
475 $haspatches and return $badanchor->("contains debian/patches");
477 # How to decide about l/r ordering of anchors ? git
478 # --topo-order prefers to expand 2nd parent first. There's
479 # already an easy rune to look for debian/ history anyway (git log
480 # debian/) so debian breakwater branch should be 1st parent; that
481 # way also there's also an easy rune to look for the upstream
482 # patches (--topo-order).
484 # Also this makes --first-parent be slightly more likely to
485 # be useful - it makes it provide a linearised breakwater history.
487 # Of course one can say somthing like
488 # gitk -- ':/' ':!/debian'
489 # to get _just_ the commits touching upstream files, and by
490 # the TREESAME logic in git-rev-list this will leave the
491 # breakwater into upstream at the first anchor. But that
492 # doesn't report debian/ changes at all.
494 # Other observations about gitk: by default, gitk seems to
495 # produce output in a different order to git-rev-list. I
496 # can't seem to find this documented anywhere. gitk
497 # --date-order DTRT. But, gitk always seems to put the
498 # parents from left to right, in order, so it's easy to see
499 # which way round a pseudomerge is.
501 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
502 $p[1]{Differs} & ~DS_DEB and
503 $badanchor->("upstream files differ from left parent");
504 $p[0]{Differs} & ~D_UPS and
505 $badanchor->("debian/ differs from right parent");
507 return $classify->(qw(Anchor),
508 OrigParents => [ $p[1] ]);
512 my $d = $r->{Parents}[0]{Differs};
513 if ($d == D_PAT_ADD) {
514 return $classify->(qw(AddPatches));
515 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
516 return $unknown->("edits debian/patches");
517 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
518 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
520 if ($d == D_DEB_CLOG) {
521 return $classify->(qw(Changelog));
523 return $classify->(qw(Packaging));
525 } elsif ($ty eq 'missing') {
526 return $classify->(qw(BreakwaterStart));
528 return $unknown->("parent's debian is not a directory");
530 } elsif ($d == D_UPS) {
531 return $classify->(qw(Upstream));
532 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
533 return $classify->(qw(Mixed));
535 return $unknown->("no changes");
537 confess "internal error $objid ?";
541 return $unknown->("origin commit");
544 if (@p == 2 && @identical == 1) {
545 my @overwritten = grep { $_->{Differs} } @p;
546 confess "internal error $objid ?" unless @overwritten==1;
547 return $classify->(qw(Pseudomerge),
548 Overwritten => [ $overwritten[0] ],
549 Contributor => $identical[0]);
551 if (@p == 2 && @identical == 2) {
553 my ($ph,$pm) = get_commit $_[0]{CommitId};
554 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
558 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
559 if ($order > 0) { # newer first
560 } elsif ($order < 0) {
561 @bytime = reverse @bytime;
563 # same age, default to order made by -s ours
564 # that is, commit was made by someone who preferred L
566 return $classify->(qw(Pseudomerge),
567 SubType => qw(Ambiguous),
568 Contributor => $bytime[0],
569 Overwritten => [ $bytime[1] ]);
572 my ($p_h, $p_m) = get_commit $p->{CommitId};
573 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
574 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
576 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
578 if (!(grep { !$_->{IsOrigin} } @p) and
579 (@orig_ps >= @p - 1) and
580 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
582 return $classify->(qw(DgitImportUnpatched),
583 OrigParents => \@orig_ps);
586 return $unknown->("complex merge");
589 sub keycommits ($;$$$$) {
590 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
591 # => ($anchor, $breakwater)
593 # $unclean->("unclean-$tagsfx", $msg, $cl)
594 # $furniture->("unclean-$tagsfx", $msg, $cl)
595 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
596 # is callled for each situation or commit that
597 # wouldn't be found in a laundered branch
598 # $furniture is for furniture commits such as might be found on an
599 # interchange branch (pseudomerge, d/patches, changelog)
600 # $trouble is for things whnich prevent the return of
601 # anchor and breakwater information; if that is ignored,
602 # then keycommits returns (undef, undef) instead.
603 # $fatal is for unprocessable commits, and should normally cause
604 # a failure. If ignored, agaion, (undef, undef) is returned.
606 # If a callback is undef, fail is called instead.
607 # If a callback is defined but false, the situation is ignored.
609 # no warnings qw(exiting); last;
610 # if the answer is no longer wanted.
612 my ($anchor, $breakwater);
616 $fatal //= sub { fail $_[1]; };
618 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
619 my $why = $mainwhy.$xwhy;
620 my $m = "branch needs laundering (run git-debrebase): $why";
621 fail $m unless defined $cb;
623 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
626 $cl = classify $head;
627 my $ty = $cl->{Type};
628 if ($ty eq 'Packaging') {
629 $breakwater //= $clogonly;
630 $breakwater //= $head;
631 } elsif ($ty eq 'Changelog') {
632 # this is going to count as the tip of the breakwater
633 # only if it has no upstream stuff before it
635 } elsif ($ty eq 'Anchor' or
636 $ty eq 'TreatAsAnchor' or
637 $ty eq 'BreakwaterStart') {
639 $breakwater //= $clogonly;
640 $breakwater //= $head;
642 } elsif ($ty eq 'Upstream') {
643 $x->($unclean, 'ordering',
644 "packaging change ($breakwater) follows upstream change"," (eg $head)")
645 if defined $breakwater;
648 } elsif ($ty eq 'Mixed') {
649 $x->($unclean, 'mixed',
650 "found mixed upstream/packaging commit"," ($head)");
653 } elsif ($ty eq 'Pseudomerge' or
654 $ty eq 'AddPatches') {
656 $x->($furniture, (lc $ty),
657 "found interchange bureaucracy commit ($ty)"," ($head)");
658 } elsif ($ty eq 'DgitImportUnpatched') {
660 $x->($trouble, 'dgitimport',
661 "found dgit dsc import"," ($head)");
662 return (undef,undef);
664 $x->($fatal, 'unprocessable',
665 "found bare dgit dsc import with no prior history",
667 return (undef,undef);
670 $x->($fatal, 'unprocessable',
671 "found unprocessable commit, cannot cope: $cl->{Why}",
673 return (undef,undef);
675 $head = $cl->{Parents}[0]{CommitId};
677 return ($anchor, $breakwater);
683 $nogenerate,$report, $report_lprefix) = @_;
684 # => ($tip, $breakwater_tip, $last_anchor)
685 # (or nothing, if $nogenerate)
687 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
688 $report_lprefix //= '';
690 # go through commits backwards
691 # we generate two lists of commits to apply:
692 # breakwater branch and upstream patches
693 my (@brw_cl, @upp_cl, @processed);
700 my ($prose, $info) = @_;
704 $ms .= "\n\n[git-debrebase$info: $prose]\n";
707 my $rewrite_from_here = sub {
709 my $sp_cl = { SpecialMethod => 'StartRewrite' };
711 push @processed, $sp_cl;
716 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
719 return unless $report;
720 print $report $prdelim, $report_lprefix, @_;
724 my $bomb = sub { # usage: return $bomb->();
725 print $report " Unprocessable" if $report;
726 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
729 return (undef,undef);
731 fail "found unprocessable commit, cannot cope".
732 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
733 " (commit $cur) (d.".
734 (join ' ', map { sprintf "%#x", $_->{Differs} }
735 @{ $cl->{Parents} }).
742 my $build_start = sub {
743 my ($msg, $parent) = @_;
746 no warnings qw(exiting); last;
753 my $ty = $cl->{Type};
754 my $st = $cl->{SubType};
755 $prline->("$cl->{CommitId} $cl->{Type}");
756 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
757 push @processed, $cl;
758 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
759 if ($ty eq 'AddPatches') {
761 $rewrite_from_here->(\@upp_cl);
763 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
767 } elsif ($ty eq 'BreakwaterStart') {
769 $build_start->('FirstPackaging', $cur);
770 } elsif ($ty eq 'Upstream') {
774 } elsif ($ty eq 'Mixed') {
777 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
780 $queue->(\@brw_cl, "debian");
781 $queue->(\@upp_cl, "upstream");
782 $rewrite_from_here->(\@brw_cl);
785 } elsif ($ty eq 'Pseudomerge') {
786 my $contrib = $cl->{Contributor}{CommitId};
787 print $report " Contributor=$contrib" if $report;
788 push @pseudomerges, $cl;
789 $rewrite_from_here->(\@upp_cl);
792 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
794 $build_start->("Anchor", $cur);
795 } elsif ($ty eq 'DgitImportUnpatched') {
796 my $pm = $pseudomerges[-1];
798 # To an extent, this is heuristic. Imports don't have
799 # a useful history of the debian/ branch. We assume
800 # that the first pseudomerge after an import has a
801 # useful history of debian/, and ignore the histories
802 # from later pseudomerges. Often the first pseudomerge
803 # will be the dgit import of the upload to the actual
804 # suite intended by the non-dgit NMUer, and later
805 # pseudomerges may represent in-archive copies.
806 my $ovwrs = $pm->{Overwritten};
807 printf $report " PM=%s \@Overwr:%d",
808 $pm->{CommitId}, (scalar @$ovwrs)
811 printdebug "*** WALK BOMB DgitImportUnpatched\n";
814 my $ovwr = $ovwrs->[0]{CommitId};
815 printf $report " Overwr=%s", $ovwr if $report;
816 # This import has a tree which is just like a
817 # breakwater tree, but it has the wrong history. It
818 # ought to have the previous breakwater (which the
819 # pseudomerge overwrote) as an ancestor. That will
820 # make the history of the debian/ files correct. As
821 # for the upstream version: either it's the same as
822 # was ovewritten (ie, same as the previous
823 # breakwater), in which case that history is precisely
824 # right; or, otherwise, it was a non-gitish upload of a
825 # new upstream version. We can tell these apart by
826 # looking at the tree of the supposed upstream.
829 SpecialMethod => 'DgitImportDebianUpdate',
830 $xmsg->("convert dgit import: debian changes")
833 SpecialMethod => 'DgitImportUpstreamUpdate',
834 $xmsg->("convert dgit import: upstream update",
837 $prline->(" Import");
838 $rewrite_from_here->(\@brw_cl);
839 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
843 # Everything is from this import. This kind of import
844 # is already nearly in valid breakwater format, with the
845 # patches as commits. Unfortunately it contains
847 printdebug "*** WALK BOMB bare dgit import\n";
848 $cl->{Why} = "bare dgit dsc import";
853 printdebug "*** WALK BOMB unrecognised\n";
859 printdebug "*** WALK prep done cur=$cur".
860 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
862 return if $nogenerate;
864 # Now we build it back up again
870 my $read_tree_debian = sub {
872 read_tree_subdir 'debian', "$treeish:debian";
873 rm_subdir_cached 'debian/patches';
875 my $read_tree_upstream = sub {
877 runcmd @git, qw(read-tree), $treeish;
878 $read_tree_debian->($build);
881 $#upp_cl = $upp_limit if defined $upp_limit;
883 my $committer_authline = calculate_committer_authline();
885 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
887 confess "internal error" unless $build eq (pop @processed)->{CommitId};
890 mkdir $rd or $!==EEXIST or die $!;
892 runcmd @git, qw(read-tree), $build;
893 foreach my $cl (qw(Debian), (reverse @brw_cl),
894 { SpecialMethod => 'RecordBreakwaterTip' },
895 qw(Upstream), (reverse @upp_cl)) {
897 $current_method = $cl;
900 my $method = $cl->{SpecialMethod} // $current_method;
901 my @parents = ($build);
902 my $cltree = $cl->{CommitId};
903 printdebug "WALK BUILD ".($cltree//'undef').
904 " $method (rewriting=$rewriting)\n";
905 if ($method eq 'Debian') {
906 $read_tree_debian->($cltree);
907 } elsif ($method eq 'Upstream') {
908 $read_tree_upstream->($cltree);
909 } elsif ($method eq 'StartRewrite') {
912 } elsif ($method eq 'RecordBreakwaterTip') {
913 $breakwater = $build;
915 } elsif ($method eq 'DgitImportDebianUpdate') {
916 $read_tree_debian->($cltree);
917 } elsif ($method eq 'DgitImportUpstreamUpdate') {
918 confess unless $rewriting;
919 my $differs = (get_differs $build, $cltree);
920 next unless $differs & D_UPS;
921 $read_tree_upstream->($cltree);
922 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
927 my $procd = (pop @processed) // 'UNDEF';
930 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
933 my $newtree = cmdoutput @git, qw(write-tree);
935 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
936 $ch =~ s{^parent .*\n}{}mg;
937 $ch =~ s{(?=^author)}{
938 join '', map { "parent $_\n" } @parents
939 }me or confess "$ch ?";
941 $ch =~ s{^committer .*$}{$committer_authline}m
944 my $cf = "$rd/m$rewriting";
945 open CD, ">", $cf or die $!;
946 print CD $ch, "\n", $cl->{Msg} or die $!;
948 my @cmd = (@git, qw(hash-object));
949 push @cmd, qw(-w) if $rewriting;
950 push @cmd, qw(-t commit), $cf;
951 my $newcommit = cmdoutput @cmd;
952 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
954 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
960 my $final_check = get_differs $build, $input;
961 die sprintf "internal error %#x %s %s", $final_check, $build, $input
962 if $final_check & ~D_PAT_ADD;
964 my @r = ($build, $breakwater, $last_anchor);
965 printdebug "*** WALK RETURN @r\n";
970 git_check_unmodified();
971 return git_rev_parse qw(HEAD);
974 sub update_head ($$$) {
975 my ($old, $new, $mrest) = @_;
976 push @deferred_updates, "update HEAD $new $old";
977 run_deferred_updates $mrest;
980 sub update_head_checkout ($$$) {
981 my ($old, $new, $mrest) = @_;
982 update_head $old, $new, $mrest;
983 runcmd @git, qw(reset --hard);
986 sub update_head_postlaunder ($$$) {
987 my ($old, $tip, $reflogmsg) = @_;
988 return if $tip eq $old;
989 print "git-debrebase: laundered (head was $old)\n";
990 update_head $old, $tip, $reflogmsg;
991 # no tree changes except debian/patches
992 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
995 sub currently_rebasing() {
996 foreach (qw(rebase-merge rebase-apply)) {
997 return 1 if stat_exists "$maindir_gitdir/$_";
1002 sub bail_if_rebasing() {
1003 fail "you are in the middle of a git-rebase already"
1004 if currently_rebasing();
1007 sub do_launder_head ($) {
1008 my ($reflogmsg) = @_;
1009 my $old = get_head();
1011 my ($tip,$breakwater) = walk $old;
1013 update_head_postlaunder $old, $tip, $reflogmsg;
1014 return ($tip,$breakwater);
1017 sub cmd_launder_v0 () {
1018 badusage "no arguments to launder-v0 allowed" if @ARGV;
1019 my $old = get_head();
1020 my ($tip,$breakwater,$last_anchor) = walk $old;
1021 update_head_postlaunder $old, $tip, 'launder';
1022 printf "# breakwater tip\n%s\n", $breakwater;
1023 printf "# working tip\n%s\n", $tip;
1024 printf "# last anchor\n%s\n", $last_anchor;
1027 sub defaultcmd_rebase () {
1028 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1029 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1030 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1033 sub cmd_analyse () {
1034 badusage "analyse does not support any options"
1035 if @ARGV and $ARGV[0] =~ m/^-/;
1036 badusage "too many arguments to analyse" if @ARGV>1;
1039 $old = git_rev_parse $old;
1041 $old = git_rev_parse 'HEAD';
1043 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1044 STDOUT->error and die $!;
1047 sub ffq_prev_branchinfo () {
1048 my $current = git_get_symref();
1049 return gdr_ffq_prev_branchinfo($current);
1052 sub ffq_check ($;$$) {
1053 # calls $ff and/or $notff zero or more times
1054 # then returns either (status,message) where status is
1059 # or (undef,undef, $ffq_prev,$gdrlast)
1060 # $ff and $notff are called like this:
1061 # $ff->("message for stdout\n");
1062 # $notff->('snag-name', $message);
1063 # normally $currentval should be HEAD
1064 my ($currentval, $ff, $notff) =@_;
1066 $ff //= sub { print $_[0] or die $!; };
1069 my ($status, $message, $current, $ffq_prev, $gdrlast)
1070 = ffq_prev_branchinfo();
1071 return ($status, $message) unless $status eq 'branch';
1073 my $exists = git_get_ref $ffq_prev;
1074 return ('exists',"$ffq_prev already exists") if $exists;
1076 return ('not-branch', 'HEAD symref is not to refs/heads/')
1077 unless $current =~ m{^refs/heads/};
1080 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1083 printdebug "ffq check_specs @check_specs\n";
1086 my ($lrref, $desc) = @_;
1087 printdebug "ffq might check $lrref ($desc)\n";
1089 for my $chk (@check_specs) {
1091 $invert = $glob =~ s{^[!^]}{};
1092 last if fnmatch $glob, $lrref;
1095 my $lrval = git_get_ref $lrref;
1096 return unless length $lrval;
1098 if (is_fast_fwd $lrval, $currentval) {
1099 $ff->("OK, you are ahead of $lrref\n");
1100 $checked{$lrref} = 1;
1101 } elsif (is_fast_fwd $currentval, $lrval) {
1102 $checked{$lrref} = -1;
1103 $notff->('behind', "you are behind $lrref, divergence risk");
1105 $checked{$lrref} = -1;
1106 $notff->('diverged', "you have diverged from $lrref");
1110 my $merge = cfg "branch.$branch.merge",1;
1111 if (defined $merge and $merge =~ m{^refs/heads/}) {
1113 printdebug "ffq merge $rhs\n";
1114 my $check_remote = sub {
1115 my ($remote, $desc) = @_;
1116 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1117 return unless defined $remote;
1118 $check->("refs/remotes/$remote/$rhs", $desc);
1120 $check_remote->((scalar cfg "branch.$branch.remote",1),
1121 'remote fetch/merge branch');
1122 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1123 (scalar cfg "branch.$branch.pushDefault",1),
1124 'remote push branch');
1126 if ($branch =~ m{^dgit/}) {
1127 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1128 } elsif ($branch =~ m{^master$}) {
1129 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1131 return (undef, undef, $ffq_prev, $gdrlast);
1134 sub record_ffq_prev_deferred () {
1135 # => ('status', "message")
1137 # deferred message is undef
1142 # if not ff from some branch we should be ff from, is an snag
1143 # if "deferred", will have added something about that to
1144 # @deferred_update_messages, and also maybe printed (already)
1145 # some messages about ff checks
1147 my $currentval = get_head();
1149 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1150 return ($status,$message) if defined $status;
1154 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1155 push @deferred_updates, "delete $gdrlast";
1156 push @deferred_update_messages, "Recorded current head for preservation";
1157 return ('deferred', undef);
1160 sub record_ffq_auto () {
1161 my ($status, $message) = record_ffq_prev_deferred();
1162 if ($status eq 'deferred' || $status eq 'exists') {
1164 snag $status, "could not record ffq-prev: $message";
1169 sub ffq_prev_info () {
1171 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1172 my ($status, $message, $current, $ffq_prev, $gdrlast)
1173 = ffq_prev_branchinfo();
1174 if ($status ne 'branch') {
1175 snag $status, "could not check ffq-prev: $message";
1178 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1179 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1182 sub stitch ($$$$$) {
1183 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1185 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1187 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1188 my $differs = get_differs $old_head, $ffq_prev_commitish;
1189 unless ($differs & ~D_PAT_ADD) {
1190 # ffq-prev is ahead of us, and the only tree changes it has
1191 # are possibly addition of things in debian/patches/.
1192 # Just wind forwards rather than making a pointless pseudomerge.
1193 push @deferred_updates,
1194 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1195 update_head_checkout $old_head, $ffq_prev_commitish,
1196 "stitch (fast forward)";
1201 # We make pseudomerges with L as the contributing parent.
1202 # This makes git rev-list --first-parent work properly.
1203 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1204 'Declare fast forward / record previous work',
1205 "[git-debrebase pseudomerge: $prose]",
1207 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1208 update_head $old_head, $new_head, "stitch: $prose";
1211 sub do_stitch ($;$) {
1212 my ($prose, $unclean) = @_;
1214 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1215 if (!$ffq_prev_commitish) {
1216 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1219 my $dangling_head = get_head();
1221 keycommits $dangling_head, $unclean,$unclean,$unclean;
1224 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1227 sub upstream_commitish_search ($$) {
1228 my ($upstream_version, $tried) = @_;
1229 # todo: at some point maybe use git-deborig to do this
1230 foreach my $tagpfx ('', 'v', 'upstream/') {
1231 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1232 my $new_upstream = git_get_ref "refs/tags/$tag";
1234 return $new_upstream if length $new_upstream;
1238 sub resolve_upstream_version ($$) {
1239 my ($new_upstream, $upstream_version) = @_;
1241 if (!defined $new_upstream) {
1243 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1244 if (!length $new_upstream) {
1245 fail "Could not determine appropriate upstream commitish.\n".
1246 " (Tried these tags: @tried)\n".
1247 " Check version, and specify upstream commitish explicitly.";
1250 $new_upstream = git_rev_parse $new_upstream;
1252 return $new_upstream;
1255 sub cmd_new_upstream () {
1256 # automatically and unconditionally launders before rebasing
1257 # if rebase --abort is used, laundering has still been done
1261 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1263 # parse args - low commitment
1264 my $spec_version = shift @ARGV;
1265 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1266 fail "bad version number \`$spec_version'" unless defined $new_version;
1267 if ($new_version->is_native()) {
1268 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1271 my $new_upstream = shift @ARGV;
1272 my $new_upstream_version = upstreamversion $new_version;
1274 resolve_upstream_version $new_upstream, $new_upstream_version;
1279 my ($n, @x) = @_; # may be ''
1280 my $pc = $pieces{$n} //= {
1282 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1284 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1289 my $newpiece = sub {
1290 my ($n, @x) = @_; # may be ''
1291 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1292 push @newpieces, $pc;
1297 New => $new_upstream,
1299 while (@ARGV && $ARGV[0] !~ m{^-}) {
1300 my $n = shift @ARGV;
1302 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1303 unless @ARGV && $ARGV[0] !~ m{^-};
1305 my $c = git_rev_parse shift @ARGV;
1306 die unless $n =~ m/^$extra_orig_namepart_re$/;
1307 $newpiece->($n, New => $c);
1310 # now we need to investigate the branch this generates the
1311 # laundered version but we don't switch to it yet
1312 my $old_head = get_head();
1313 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1315 my $old_bw_cl = classify $old_bw;
1316 my $old_anchor_cl = classify $old_anchor;
1318 if (!$old_anchor_cl->{OrigParents}) {
1319 snag 'anchor-treated',
1320 'old anchor is recognised due to --anchor, cannot check upstream';
1322 $old_upstream = parsecommit
1323 $old_anchor_cl->{OrigParents}[0]{CommitId};
1324 $piece->('', Old => $old_upstream->{CommitId});
1327 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1328 if ($old_upstream->{Msg} =~
1329 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1331 my @oldpieces = (split / /, $1);
1332 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1333 if ($old_n_parents != @oldpieces &&
1334 $old_n_parents != @oldpieces + 1) {
1335 snag 'upstream-confusing', sprintf
1336 "previous upstream combine %s".
1337 " mentions %d pieces (each implying one parent)".
1338 " but has %d parents".
1339 " (one per piece plus maybe a previous combine)",
1340 $old_upstream->{CommitId},
1341 (scalar @oldpieces),
1343 } elsif ($oldpieces[0] ne '.') {
1344 snag 'upstream-confusing', sprintf
1345 "previous upstream combine %s".
1346 " first piece is not \`.'",
1350 foreach my $i (0..$#oldpieces) {
1351 my $n = $oldpieces[$i];
1352 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1353 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1357 snag 'upstream-confusing',
1358 "previous upstream $old_upstream->{CommitId} is from".
1359 " git-debrebase but not an \`upstream-combine' commit";
1363 foreach my $pc (values %pieces) {
1364 if (!$old_upstream) {
1365 # we have complained already
1366 } elsif (!$pc->{Old}) {
1367 snag 'upstream-new-piece',
1368 "introducing upstream piece \`$pc->{Name}'";
1369 } elsif (!$pc->{New}) {
1370 snag 'upstream-rm-piece',
1371 "dropping upstream piece \`$pc->{Name}'";
1372 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1373 snag 'upstream-not-ff',
1374 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1378 printdebug "%pieces = ", (dd \%pieces), "\n";
1379 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1387 my @upstream_merge_parents;
1390 push @upstream_merge_parents, $old_upstream->{CommitId};
1393 foreach my $pc (@newpieces) { # always has '' first
1395 read_tree_subdir $pc->{Name}, $pc->{New};
1397 runcmd @git, qw(read-tree), $pc->{New};
1399 push @upstream_merge_parents, $pc->{New};
1402 # index now contains the new upstream
1404 if (@newpieces > 1) {
1405 # need to make the upstream subtree merge commit
1406 $new_upstream = make_commit \@upstream_merge_parents,
1407 [ "Combine upstreams for $new_upstream_version",
1408 ("[git-debrebase upstream-combine . ".
1409 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1414 # $new_upstream is either the single upstream commit, or the
1415 # combined commit we just made. Either way it will be the
1416 # "upstream" parent of the anchor merge.
1418 read_tree_subdir 'debian', "$old_bw:debian";
1420 # index now contains the anchor merge contents
1421 $new_bw = make_commit [ $old_bw, $new_upstream ],
1422 [ "Update to upstream $new_upstream_version",
1423 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1426 my $clogsignoff = cmdoutput qw(git show),
1427 '--pretty=format:%an <%ae> %aD',
1430 # Now we have to add a changelog stanza so the Debian version
1432 die if unlink "debian";
1433 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1434 unlink "debian/changelog" or $!==ENOENT or die $!;
1435 mkdir "debian" or die $!;
1436 open CN, ">", "debian/changelog" or die $!;
1437 my $oldclog = git_cat_file ":debian/changelog";
1438 $oldclog =~ m/^($package_re) \(\S+\) / or
1439 fail "cannot parse old changelog to get package name";
1441 print CN <<END, $oldclog or die $!;
1442 $p ($new_version) UNRELEASED; urgency=medium
1444 * Update to new upstream version $new_upstream_version.
1450 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1452 # Now we have the final new breakwater branch in the index
1453 $new_bw = make_commit [ $new_bw ],
1454 [ "Update changelog for new upstream $new_upstream_version",
1455 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1459 # we have constructed the new breakwater. we now need to commit to
1460 # the laundering output, because git-rebase can't easily be made
1461 # to make a replay list which is based on some other branch
1463 update_head_postlaunder $old_head, $old_laundered_tip,
1464 'launder for new upstream';
1466 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1467 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1468 "debrebase new-upstream $new_version: rebase";
1470 # now it's for the user to sort out
1473 sub cmd_record_ffq_prev () {
1474 badusage "no arguments allowed" if @ARGV;
1475 my ($status, $msg) = record_ffq_prev_deferred();
1476 if ($status eq 'exists' && $opt_noop_ok) {
1477 print "Previous head already recorded\n" or die $!;
1478 } elsif ($status eq 'deferred') {
1479 run_deferred_updates 'record-ffq-prev';
1481 fail "Could not preserve: $msg";
1486 badusage "no arguments allowed" if @ARGV;
1487 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1488 print "$bw\n" or die $!;
1491 sub cmd_breakwater () {
1492 badusage "no arguments allowed" if @ARGV;
1493 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1494 print "$bw\n" or die $!;
1498 badusage "no arguments allowed" if @ARGV;
1500 # todo: gdr status should print divergence info
1501 # todo: gdr status should print upstream component(s) info
1502 # todo: gdr should leave/maintain some refs with this kind of info ?
1504 my $oldest = { Badness => 0 };
1507 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1508 if ($oldest->{Badness} < $badness) {
1509 $oldest = $newest = undef;
1512 Badness => $badness,
1513 CommitId => $cl->{CommitId},
1517 $newest //= $oldest;
1519 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1520 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1521 sub { $note->(2, 'branch is unlaundered', @_); },
1522 sub { $note->(3, 'branch needs laundering', @_); },
1523 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1525 my $prcommitinfo = sub {
1527 flush STDOUT or die $!;
1528 runcmd @git, qw(--no-pager log -n1),
1529 '--pretty=format: %h %s%n',
1533 print "current branch contents, in git-debrebase terms:\n";
1534 if (!$oldest->{Badness}) {
1535 print " branch is laundered\n";
1537 print " $oldest->{OurMsg}\n";
1539 foreach my $info ($oldest, $newest) {
1540 my $cid = $info->{CommitId};
1541 next if $cid eq $printed;
1543 print " $info->{KcMsg}\n";
1544 $prcommitinfo->($cid);
1549 my ($cid, $what) = @_;
1550 if (!defined $cid) {
1551 print " $what is not well-defined\n";
1554 $prcommitinfo->($cid);
1557 print "key git-debrebase commits:\n";
1558 $prab->($anchor, 'anchor');
1559 $prab->($bw, 'breakwater');
1561 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1562 ffq_prev_branchinfo();
1564 print "branch and ref status, in git-debrebase terms:\n";
1566 print " $ffq_msg\n";
1568 $ffq_prev = git_get_ref $ffq_prev;
1569 $gdrlast = git_get_ref $gdrlast;
1571 print " unstitched; previous tip was:\n";
1572 $prcommitinfo->($ffq_prev);
1573 } elsif (!$gdrlast) {
1574 print " stitched? (no record of git-debrebase work)\n";
1575 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1576 print " stitched\n";
1578 print " not git-debrebase (diverged since last stitch)\n"
1581 print "you are currently rebasing\n" if currently_rebasing();
1585 my $prose = 'stitch';
1586 getoptions("stitch",
1587 'prose=s', \$prose);
1588 badusage "no arguments allowed" if @ARGV;
1589 do_stitch $prose, 0;
1591 sub cmd_prepush () { cmd_stitch(); }
1594 badusage "no arguments allowed" if @ARGV;
1595 do_launder_head 'launder for git-debrebase quick';
1599 sub cmd_conclude () {
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 $dangling_head = get_head();
1607 badusage "no arguments allowed" if @ARGV;
1608 do_launder_head 'launder for git-debrebase quick';
1613 if (currently_rebasing()) {
1614 runcmd @git, qw(rebase --abort);
1616 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1617 if (!$ffq_prev_commitish) {
1618 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1621 my $scrapping_head = get_head();
1622 badusage "no arguments allowed" if @ARGV;
1623 push @deferred_updates,
1624 "update $gdrlast $ffq_prev_commitish $git_null_obj",
1625 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
1627 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
1630 sub make_patches_staged ($) {
1632 # Produces the patches that would result from $head if it were
1634 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1637 gbp_pq_export 'bw', $secret_bw, $secret_head;
1641 sub make_patches ($) {
1643 keycommits $head, 0, \&snag;
1644 make_patches_staged $head;
1647 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1648 runcmd @git, qw(read-tree), $head;
1649 read_tree_subdir 'debian/patches', $ptree;
1650 $out = make_commit [$head], [
1651 'Commit patch queue (exported by git-debrebase)',
1652 '[git-debrebase: export and commit patches]',
1658 sub cmd_make_patches () {
1659 my $opt_quiet_would_amend;
1660 getoptions("make-patches",
1661 'quiet-would-amend!', \$opt_quiet_would_amend);
1662 badusage "no arguments allowed" if @ARGV;
1664 my $old_head = get_head();
1665 my $new = make_patches $old_head;
1666 my $d = get_differs $old_head, $new;
1668 fail "No (more) patches to export." unless $opt_noop_ok;
1670 } elsif ($d == D_PAT_ADD) {
1672 update_head_checkout $old_head, $new, 'make-patches';
1674 print STDERR failmsg
1675 "Patch export produced patch amendments".
1676 " (abandoned output commit $new).".
1677 " Try laundering first."
1678 unless $opt_quiet_would_amend;
1683 sub cmd_convert_from_gbp () {
1684 badusage "want only 1 optional argument, the upstream git commitish"
1687 my $clogp = parsechangelog();
1688 my $version = $clogp->{'Version'}
1689 // die "missing Version from changelog";
1691 my ($upstream_spec) = @ARGV;
1693 my $upstream_version = upstreamversion $version;
1695 resolve_upstream_version($upstream_spec, $upstream_version);
1697 my $old_head = get_head();
1699 my $upsdiff = get_differs $upstream, $old_head;
1700 if ($upsdiff & D_UPS) {
1701 runcmd @git, qw(--no-pager diff --stat),
1702 $upstream, $old_head,
1703 qw( -- :!/debian :/);
1705 upstream ($upstream_spec) and HEAD are not
1706 identical in upstream files. See diffstat above, or run
1707 git diff $upstream_spec HEAD -- :!/debian :/
1711 if (!is_fast_fwd $upstream, $old_head) {
1712 snag 'upstream-not-ancestor',
1713 "upstream ($upstream) is not an ancestor of HEAD";
1715 my $wrong = cmdoutput
1716 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1717 qw(-- :/ :!/debian));
1718 if (length $wrong) {
1719 snag 'unexpected-upstream-changes',
1720 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1721 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1725 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1726 snag 'upstream-has-debian',
1727 "upstream ($upstream) contains debian/ directory";
1730 my $previous_dgit_view = eval {
1731 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1733 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1734 my ($stz, $desc) = @_;
1735 no warnings qw(exiting);
1736 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1737 next unless $stz->{Date};
1738 next unless $stz->{Distribution} ne 'UNRELEASED';
1739 $lvsn = $stz->{Version};
1740 $suite = $stz->{Distribution};
1743 die "neither of the first two changelog entries are released\n"
1744 unless defined $lvsn;
1745 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1746 my $mtag_pat = debiantag_maintview $lvsn, '*';
1747 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1749 die "could not find suitable maintainer view tag $mtag_pat\n"
1750 unless $mtag_pat =~ m{/};
1751 is_fast_fwd $mtag, 'HEAD' or
1752 die "HEAD is not FF from maintainer tag $mtag!";
1753 my $dtag = "archive/$mtag";
1754 is_fast_fwd $mtag, $dtag or
1755 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1756 print "will stitch in dgit view, $dtag\n";
1757 git_rev_parse $dtag;
1759 if (!$previous_dgit_view) {
1762 print STDERR "cannot stitch in dgit view: $@\n";
1765 snags_maybe_bail_early();
1771 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1772 # make a branch out of the patch queue - we'll want this in a mo
1773 runcmd qw(gbp pq import);
1774 # strip the patches out
1775 runcmd @git, qw(checkout -q gdr-internal~0);
1776 rm_subdir_cached 'debian/patches';
1777 $work = make_commit ['HEAD'], [
1778 'git-debrebase convert-from-gbp: drop patches from tree',
1779 'Delete debian/patches, as part of converting to git-debrebase format.',
1780 '[git-debrebase convert-from-gbp: drop patches from tree]'
1782 # make the anchor merge
1783 # the tree is already exactly right
1784 $work = make_commit [$work, $upstream], [
1785 'git-debrebase import: declare upstream',
1786 'First breakwater merge.',
1787 '[git-debrebase anchor: declare upstream]'
1790 # rebase the patch queue onto the new breakwater
1791 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1792 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1793 $work = git_rev_parse 'HEAD';
1795 if ($previous_dgit_view) {
1796 $work = make_commit [$work, $previous_dgit_view], [
1797 'git-debrebase import: declare ff from dgit archive view',
1798 '[git-debrebase pseudomerge: import-from-gbp]',
1805 update_head_checkout $old_head, $work, 'convert-from-gbp';
1808 sub cmd_convert_to_gbp () {
1809 badusage "no arguments allowed" if @ARGV;
1810 my $head = get_head();
1811 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1812 keycommits $head, 0;
1814 make_patches_staged $head;
1816 $out = make_commit ['HEAD'], [
1817 'Commit patch queue (converted from git-debrebase format)',
1818 '[git-debrebase convert-to-gbp: commit patches]',
1822 push @deferred_updates, "delete $ffq";
1823 push @deferred_updates, "delete $gdrlast";
1826 update_head_checkout $head, $out, "convert to gbp (v0)";
1827 print <<END or die $!;
1828 git-debrebase: converted to git-buildpackage branch format
1829 git-debrebase: WARNING: do not now run "git-debrebase" any more
1830 git-debrebase: WARNING: doing so would drop all upstream patches!
1834 sub cmd_convert_from_dgit_view () {
1835 my $clogp = parsechangelog();
1837 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
1843 getoptions("convert-from-dgit-view",
1844 'diagnose!', \$diagnose,
1845 'build-products-dir:s', \$bpd,
1846 'origs!', \$do_origs,
1848 'always-convert-anyway!', \$always);
1849 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
1854 my $spec = shift @ARGV;
1855 my $commit = git_rev_parse "$spec^{commit}";
1856 push @upstreams, { Commit => $commit,
1857 Source => "$ARGV[0], from command line",
1862 my $head = get_head();
1866 my $trouble = sub { $troubles++; };
1867 keycommits $head, sub{}, sub{}, $trouble, $trouble;
1868 printdebug "troubles=$troubles\n";
1871 $us: Branch already seems to be in git-debrebase format!
1872 $us: --always-convert-anyway would do the conversion operation anyway
1873 $us: but is probably a bad idea. Probably, you wanted to do nothing.
1875 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
1880 snags_maybe_bail_early();
1882 my $version = upstreamversion $clogp->{Version};
1883 print STDERR "Considering possible commits corresponding to upstream:\n";
1888 my $ups_tag = upstream_commitish_search $version, \@tried;
1890 my $this = "git tag $tried[-1]";
1891 push @upstreams, { Commit => $ups_tag,
1896 " git tag: no suitable tag found (tried %s)\n",
1901 my $p = $clogp->{'Source'};
1902 # we do a quick check to see if there are plausible origs
1904 if (!opendir BPD, $bpd) {
1905 die "$bpd: opendir: $!" unless $!==ENOENT;
1907 while ($!=0, my $f = readdir BPD) {
1908 next unless is_orig_file_of_p_v $f, $p, $version;
1910 " orig: found what looks like a .orig, %s\n",
1915 die "read $bpd: $!" if $!;
1919 my $tree = cmdoutput
1920 @dgit, qw(--build-products-dir), $bpd,
1921 qw(print-unapplied-treeish);
1924 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
1925 rm_subdir_cached 'debian';
1926 $tree = cmdoutput @git, qw(write-tree);
1927 my $ups_synth = make_commit [], [ <<END, <<END,
1928 Import effective orig tree for upstream version $version
1930 This includes the contents of the .orig(s), minus any debian/ directory.
1932 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
1935 push @upstreams, { Commit => $ups_synth,
1936 Source => "orig(s) imported via dgit",
1941 " orig: no suitable origs found (looked for %s in %s)\n",
1942 "${p}_".(stripeoch $version)."...", $bpd;
1947 my $some_patches = stat_exists 'debian/patches/series';
1949 print STDERR "Evaluating possible commits corresponding to upstream:\n";
1952 foreach my $u (@upstreams) {
1956 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
1957 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
1958 runcmd @git, qw(clean -xdff);
1959 runcmd @git, qw(checkout), $head, qw(-- debian);
1960 if ($some_patches) {
1961 rm_subdir_cached 'debian/patches';
1962 $work = make_commit [ $work ], [
1963 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
1964 "Drop upstream changes, and delete debian/patches, as part of converting\n".
1965 "to git-debrebase format. Upstream changes will appear as commits.",
1966 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
1969 $work = make_commit [ $work, $u->{Commit} ], [
1970 'git-debrebase convert-from-dgit-view: declare upstream',
1971 '(Re)constructed breakwater merge.',
1972 '[git-debrebase anchor: declare upstream]'
1974 runcmd @git, qw(checkout --quiet -b mk), $work;
1975 if ($some_patches) {
1976 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
1977 runcmd @git, qw(reset --quiet);
1978 my @gbp_cmd = (qw(gbp pq import));
1980 my $gbp_err = "../gbp-pq-err";
1981 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
1983 my $r = system @gbp_cmd;
1986 " %s: couldn't apply patches: gbp pq %s",
1987 $u->{Source}, waitstatusmsg();
1991 my $work = git_rev_parse qw(HEAD);
1992 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
1993 if (length $diffout) {
1995 " $u->{Source}: applying patches gives different tree\n";
1996 print STDERR $diffout if $diagnose;
2000 $u->{Result} = $work;
2008 Could not find or construct a suitable upstream commit.
2009 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2010 upstream commmit explicitly or provide suitable origs.
2014 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2016 ffq_check $result->{Result};
2018 update_head_checkout $head, $result->{Result},
2019 'convert-from-dgit-view';
2022 sub cmd_downstream_rebase_launder_v0 () {
2023 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2025 $base = git_rev_parse $base;
2026 my $old_head = get_head();
2027 my $current = $old_head;
2030 if ($current eq $base) {
2031 $topmost_keep //= $current;
2032 print " $current BASE stop\n";
2035 my $cl = classify $current;
2036 print " $current $cl->{Type}";
2038 my $p0 = $cl->{Parents}[0]{CommitId};
2040 if ($cl->{Type} eq 'Pseudomerge') {
2041 print " ^".($cl->{Contributor}{Ix}+1);
2042 $next = $cl->{Contributor}{CommitId};
2043 } elsif ($cl->{Type} eq 'AddPatches' or
2044 $cl->{Type} eq 'Changelog') {
2054 $topmost_keep //= $current;
2056 die "to-be stripped changes not on top of the branch\n"
2061 if ($topmost_keep eq $old_head) {
2062 print "unchanged\n";
2064 print "updating to $topmost_keep\n";
2065 update_head_checkout
2066 $old_head, $topmost_keep,
2067 'downstream-rebase-launder-v0';
2073 "D+" => \$debuglevel,
2074 'noop-ok', => \$opt_noop_ok,
2075 'f=s' => \@snag_force_opts,
2076 'anchor=s' => \@opt_anchors,
2077 '--dgit=s' => \($dgit[0]),
2080 my ($opt,$val) = @_;
2081 badusage "git-debrebase: no cuddling to -i for git-rebase"
2083 die if $opt_defaultcmd_interactive; # should not happen
2084 $opt_defaultcmd_interactive = [ qw(-i) ];
2085 # This access to @ARGV is excessive familiarity with
2086 # Getopt::Long, but there isn't another sensible
2087 # approach. '-i=s{0,}' does not work with bundling.
2088 push @$opt_defaultcmd_interactive, @ARGV;
2091 'help' => sub { print $usage_message or die $!; finish 0; },
2094 initdebug('git-debrebase ');
2095 enabledebug if $debuglevel;
2097 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2098 chdir $toplevel or die "chdir $toplevel: $!";
2100 $rd = fresh_playground "$playprefix/misc";
2102 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2104 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2105 defaultcmd_rebase();
2107 my $cmd = shift @ARGV;
2110 $cmdfn = ${*::}{"cmd_$cmdfn"};
2112 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";