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 read_tree_debian ($) {
260 read_tree_subdir 'debian', "$treeish:debian";
261 rm_subdir_cached 'debian/patches';
264 sub read_tree_upstream ($) {
266 my $save = cmdoutput @git, qw(write-tree --prefix=debian/);
267 runcmd @git, qw(read-tree), $treeish;
268 read_tree_subdir 'debian', $save;
269 rm_subdir_cached 'debian/patches';
272 sub make_commit ($$) {
273 my ($parents, $message_paras) = @_;
274 my $tree = cmdoutput @git, qw(write-tree);
275 my @cmd = (@git, qw(commit-tree), $tree);
276 push @cmd, qw(-p), $_ foreach @$parents;
277 push @cmd, qw(-m), $_ foreach @$message_paras;
278 return cmdoutput @cmd;
281 our @snag_force_opts;
283 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
284 if (grep { $_ eq $tag } @snag_force_opts) {
286 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
289 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
293 # Important: all mainline code must call snags_maybe_bail after
294 # any point where snag might be called, but before making changes
295 # (eg before any call to run_deferred_updates). snags_maybe_bail
296 # may be called more than once if necessary (but this is not ideal
297 # because then the messages about number of snags may be confusing).
298 sub snags_maybe_bail () {
299 return if all_snags_summarised();
302 "%s: snags: %d overriden by individual -f options\n",
305 if ($snags_tripped) {
308 "%s: snags: %d overriden by global --force\n",
312 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
316 $snags_summarised = $snags_forced + $snags_tripped;
318 sub snags_maybe_bail_early () {
319 # useful to bail out early without doing a lot of work;
320 # not a substitute for snags_maybe_bail.
321 snags_maybe_bail() if $snags_tripped && !$opt_force;
324 return $snags_forced || $snags_tripped;
327 sub gbp_pq_export ($$$) {
328 my ($bname, $base, $tip) = @_;
329 # must be run in a workarea. $bname and patch-queue/$bname
330 # ought not to exist. Leaves you on patch-queue/$bname with
331 # the patches staged but not committed.
332 runcmd @git, qw(checkout -q -b), $bname, $base;
333 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
334 my @gbp_cmd = (qw(gbp pq export));
335 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
337 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
340 runcmd @git, qw(add -f debian/patches);
343 # classify returns an info hash like this
345 # Hdr => # commit headers, including 1 final newline
346 # Msg => # commit message (so one newline is dropped)
348 # Type => (see below)
350 # Ix => $index # ie 0, 1, 2, ...
352 # Differs => return value from get_differs
354 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
356 # NewMsg => # commit message, but with any [dgit import ...] edited
357 # # to say "[was: ...]"
367 # has additional entres in classification result
368 # Overwritten = [ subset of Parents ]
369 # Contributor = $the_remaining_Parent
371 # DgitImportUnpatched
372 # has additional entry in classification result
373 # OrigParents = [ subset of Parents ]
376 # has additional entry in classification result
377 # OrigParents = [ subset of Parents ] # singleton list
384 # has additional entry in classification result
387 sub parsecommit ($;$) {
388 my ($objid, $p_ref) = @_;
389 # => hash with CommitId Hdr Msg Tree Parents
390 # Parents entries have only Ix CommitId
391 # $p_ref, if provided, must be [] and is used as a base for Parents
396 my ($h,$m) = get_commit $objid;
398 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
399 my (@ph) = $h =~ m/^parent (\w+)$/mg;
409 foreach my $ph (@ph) {
411 Ix => scalar @$p_ref,
423 my $r = parsecommit($objid, \@p);
427 $p->{Differs} = (get_differs $p->{CommitId}, $t),
430 printdebug "classify $objid \$t=$t \@p",
431 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
435 my ($type, @rest) = @_;
436 $r = { %$r, Type => $type, @rest };
438 printdebug " = $type ".(dd $r)."\n";
444 $r = { %$r, Type => qw(Unknown), Why => $why };
445 printdebug " ** Unknown\n";
449 if (grep { $_ eq $objid } @opt_anchors) {
450 return $classify->('TreatAsAnchor');
453 my @identical = grep { !$_->{Differs} } @p;
454 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
455 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
457 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
458 # multi-orig upstreams are represented with an anchor merge
459 # from a single upstream commit which combines the orig tarballs
461 # Every anchor tagged this way must be a merge.
462 # We are relying on the
463 # [git-debrebase anchor: ...]
464 # commit message annotation in "declare" anchor merges (which
465 # do not have any upstream changes), to distinguish those
466 # anchor merges from ordinary pseudomerges (which we might
467 # just try to strip).
469 # However, the user is going to be doing git-rebase a lot. We
470 # really don't want them to rewrite an anchor commit.
471 # git-rebase trips up on merges, so that is a useful safety
474 # BreakwaterStart commits are also anchors in the terminology
475 # of git-debrebase(5), but they are untagged (and always
476 # manually generated).
478 # We cannot not tolerate any tagged linear commit (ie,
479 # BreakwaterStart commits tagged `[anchor:') because such a
480 # thing could result from an erroneous linearising raw git
481 # rebase of a merge anchor. That would represent a corruption
482 # of the branch. and we want to detect and reject the results
483 # of such corruption before it makes it out anywhere. If we
484 # reject it here then we avoid making the pseudomerge which
485 # would be needed to push it.
487 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
488 @p == 2 or return $badanchor->("has other than two parents");
489 $haspatches and return $badanchor->("contains debian/patches");
491 # How to decide about l/r ordering of anchors ? git
492 # --topo-order prefers to expand 2nd parent first. There's
493 # already an easy rune to look for debian/ history anyway (git log
494 # debian/) so debian breakwater branch should be 1st parent; that
495 # way also there's also an easy rune to look for the upstream
496 # patches (--topo-order).
498 # Also this makes --first-parent be slightly more likely to
499 # be useful - it makes it provide a linearised breakwater history.
501 # Of course one can say somthing like
502 # gitk -- ':/' ':!/debian'
503 # to get _just_ the commits touching upstream files, and by
504 # the TREESAME logic in git-rev-list this will leave the
505 # breakwater into upstream at the first anchor. But that
506 # doesn't report debian/ changes at all.
508 # Other observations about gitk: by default, gitk seems to
509 # produce output in a different order to git-rev-list. I
510 # can't seem to find this documented anywhere. gitk
511 # --date-order DTRT. But, gitk always seems to put the
512 # parents from left to right, in order, so it's easy to see
513 # which way round a pseudomerge is.
515 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
516 $p[1]{Differs} & ~DS_DEB and
517 $badanchor->("upstream files differ from left parent");
518 $p[0]{Differs} & ~D_UPS and
519 $badanchor->("debian/ differs from right parent");
521 return $classify->(qw(Anchor),
522 OrigParents => [ $p[1] ]);
526 my $d = $r->{Parents}[0]{Differs};
527 if ($d == D_PAT_ADD) {
528 return $classify->(qw(AddPatches));
529 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
530 return $unknown->("edits debian/patches");
531 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
532 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
534 if ($d == D_DEB_CLOG) {
535 return $classify->(qw(Changelog));
537 return $classify->(qw(Packaging));
539 } elsif ($ty eq 'missing') {
540 return $classify->(qw(BreakwaterStart));
542 return $unknown->("parent's debian is not a directory");
544 } elsif ($d == D_UPS) {
545 return $classify->(qw(Upstream));
546 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
547 return $classify->(qw(Mixed));
549 return $unknown->("no changes");
551 confess "internal error $objid ?";
555 return $unknown->("origin commit");
558 if (@p == 2 && @identical == 1) {
559 my @overwritten = grep { $_->{Differs} } @p;
560 confess "internal error $objid ?" unless @overwritten==1;
561 return $classify->(qw(Pseudomerge),
562 Overwritten => [ $overwritten[0] ],
563 Contributor => $identical[0]);
565 if (@p == 2 && @identical == 2) {
567 my ($ph,$pm) = get_commit $_[0]{CommitId};
568 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
572 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
573 if ($order > 0) { # newer first
574 } elsif ($order < 0) {
575 @bytime = reverse @bytime;
577 # same age, default to order made by -s ours
578 # that is, commit was made by someone who preferred L
580 return $classify->(qw(Pseudomerge),
581 SubType => qw(Ambiguous),
582 Contributor => $bytime[0],
583 Overwritten => [ $bytime[1] ]);
586 my ($p_h, $p_m) = get_commit $p->{CommitId};
587 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
588 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
590 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
592 if (!(grep { !$_->{IsOrigin} } @p) and
593 (@orig_ps >= @p - 1) and
594 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
596 return $classify->(qw(DgitImportUnpatched),
597 OrigParents => \@orig_ps);
600 return $unknown->("complex merge");
603 sub keycommits ($;$$$$) {
604 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
605 # => ($anchor, $breakwater)
607 # $unclean->("unclean-$tagsfx", $msg, $cl)
608 # $furniture->("unclean-$tagsfx", $msg, $cl)
609 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
610 # is callled for each situation or commit that
611 # wouldn't be found in a laundered branch
612 # $furniture is for furniture commits such as might be found on an
613 # interchange branch (pseudomerge, d/patches, changelog)
614 # $trouble is for things whnich prevent the return of
615 # anchor and breakwater information; if that is ignored,
616 # then keycommits returns (undef, undef) instead.
617 # $fatal is for unprocessable commits, and should normally cause
618 # a failure. If ignored, agaion, (undef, undef) is returned.
620 # If a callback is undef, fail is called instead.
621 # If a callback is defined but false, the situation is ignored.
623 # no warnings qw(exiting); last;
624 # if the answer is no longer wanted.
626 my ($anchor, $breakwater);
630 $fatal //= sub { fail $_[1]; };
632 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
633 my $why = $mainwhy.$xwhy;
634 my $m = "branch needs laundering (run git-debrebase): $why";
635 fail $m unless defined $cb;
637 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
640 $cl = classify $head;
641 my $ty = $cl->{Type};
642 if ($ty eq 'Packaging') {
643 $breakwater //= $clogonly;
644 $breakwater //= $head;
645 } elsif ($ty eq 'Changelog') {
646 # this is going to count as the tip of the breakwater
647 # only if it has no upstream stuff before it
649 } elsif ($ty eq 'Anchor' or
650 $ty eq 'TreatAsAnchor' or
651 $ty eq 'BreakwaterStart') {
653 $breakwater //= $clogonly;
654 $breakwater //= $head;
656 } elsif ($ty eq 'Upstream') {
657 $x->($unclean, 'ordering',
658 "packaging change ($breakwater) follows upstream change"," (eg $head)")
659 if defined $breakwater;
662 } elsif ($ty eq 'Mixed') {
663 $x->($unclean, 'mixed',
664 "found mixed upstream/packaging commit"," ($head)");
667 } elsif ($ty eq 'Pseudomerge' or
668 $ty eq 'AddPatches') {
670 $x->($furniture, (lc $ty),
671 "found interchange bureaucracy commit ($ty)"," ($head)");
672 } elsif ($ty eq 'DgitImportUnpatched') {
674 $x->($trouble, 'dgitimport',
675 "found dgit dsc import"," ($head)");
676 return (undef,undef);
678 $x->($fatal, 'unprocessable',
679 "found bare dgit dsc import with no prior history",
681 return (undef,undef);
684 $x->($fatal, 'unprocessable',
685 "found unprocessable commit, cannot cope: $cl->{Why}",
687 return (undef,undef);
689 $head = $cl->{Parents}[0]{CommitId};
691 return ($anchor, $breakwater);
697 $nogenerate,$report, $report_lprefix) = @_;
698 # => ($tip, $breakwater_tip, $last_anchor)
699 # (or nothing, if $nogenerate)
701 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
702 $report_lprefix //= '';
704 # go through commits backwards
705 # we generate two lists of commits to apply:
706 # breakwater branch and upstream patches
707 my (@brw_cl, @upp_cl, @processed);
714 my ($prose, $info) = @_;
718 $ms .= "\n\n[git-debrebase$info: $prose]\n";
721 my $rewrite_from_here = sub {
723 my $sp_cl = { SpecialMethod => 'StartRewrite' };
725 push @processed, $sp_cl;
730 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
733 return unless $report;
734 print $report $prdelim, $report_lprefix, @_;
738 my $bomb = sub { # usage: return $bomb->();
739 print $report " Unprocessable" if $report;
740 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
743 return (undef,undef);
745 fail "found unprocessable commit, cannot cope".
746 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
747 " (commit $cur) (d.".
748 (join ' ', map { sprintf "%#x", $_->{Differs} }
749 @{ $cl->{Parents} }).
756 my $build_start = sub {
757 my ($msg, $parent) = @_;
760 no warnings qw(exiting); last;
767 my $ty = $cl->{Type};
768 my $st = $cl->{SubType};
769 $prline->("$cl->{CommitId} $cl->{Type}");
770 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
771 push @processed, $cl;
772 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
773 if ($ty eq 'AddPatches') {
775 $rewrite_from_here->(\@upp_cl);
777 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
781 } elsif ($ty eq 'BreakwaterStart') {
783 $build_start->('FirstPackaging', $cur);
784 } elsif ($ty eq 'Upstream') {
788 } elsif ($ty eq 'Mixed') {
791 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
794 $queue->(\@brw_cl, "debian");
795 $queue->(\@upp_cl, "upstream");
796 $rewrite_from_here->(\@brw_cl);
799 } elsif ($ty eq 'Pseudomerge') {
800 my $contrib = $cl->{Contributor}{CommitId};
801 print $report " Contributor=$contrib" if $report;
802 push @pseudomerges, $cl;
803 $rewrite_from_here->(\@upp_cl);
806 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
808 $build_start->("Anchor", $cur);
809 } elsif ($ty eq 'DgitImportUnpatched') {
810 my $pm = $pseudomerges[-1];
812 # To an extent, this is heuristic. Imports don't have
813 # a useful history of the debian/ branch. We assume
814 # that the first pseudomerge after an import has a
815 # useful history of debian/, and ignore the histories
816 # from later pseudomerges. Often the first pseudomerge
817 # will be the dgit import of the upload to the actual
818 # suite intended by the non-dgit NMUer, and later
819 # pseudomerges may represent in-archive copies.
820 my $ovwrs = $pm->{Overwritten};
821 printf $report " PM=%s \@Overwr:%d",
822 $pm->{CommitId}, (scalar @$ovwrs)
825 printdebug "*** WALK BOMB DgitImportUnpatched\n";
828 my $ovwr = $ovwrs->[0]{CommitId};
829 printf $report " Overwr=%s", $ovwr if $report;
830 # This import has a tree which is just like a
831 # breakwater tree, but it has the wrong history. It
832 # ought to have the previous breakwater (which the
833 # pseudomerge overwrote) as an ancestor. That will
834 # make the history of the debian/ files correct. As
835 # for the upstream version: either it's the same as
836 # was ovewritten (ie, same as the previous
837 # breakwater), in which case that history is precisely
838 # right; or, otherwise, it was a non-gitish upload of a
839 # new upstream version. We can tell these apart by
840 # looking at the tree of the supposed upstream.
843 SpecialMethod => 'DgitImportDebianUpdate',
844 $xmsg->("convert dgit import: debian changes")
847 SpecialMethod => 'DgitImportUpstreamUpdate',
848 $xmsg->("convert dgit import: upstream update",
851 $prline->(" Import");
852 $rewrite_from_here->(\@brw_cl);
853 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
857 # Everything is from this import. This kind of import
858 # is already nearly in valid breakwater format, with the
859 # patches as commits. Unfortunately it contains
861 printdebug "*** WALK BOMB bare dgit import\n";
862 $cl->{Why} = "bare dgit dsc import";
867 printdebug "*** WALK BOMB unrecognised\n";
873 printdebug "*** WALK prep done cur=$cur".
874 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
876 return if $nogenerate;
878 # Now we build it back up again
884 $#upp_cl = $upp_limit if defined $upp_limit;
886 my $committer_authline = calculate_committer_authline();
888 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
890 confess "internal error" unless $build eq (pop @processed)->{CommitId};
893 mkdir $rd or $!==EEXIST or die $!;
895 runcmd @git, qw(read-tree), $build;
896 foreach my $cl (qw(Debian), (reverse @brw_cl),
897 { SpecialMethod => 'RecordBreakwaterTip' },
898 qw(Upstream), (reverse @upp_cl)) {
900 $current_method = $cl;
903 my $method = $cl->{SpecialMethod} // $current_method;
904 my @parents = ($build);
905 my $cltree = $cl->{CommitId};
906 printdebug "WALK BUILD ".($cltree//'undef').
907 " $method (rewriting=$rewriting)\n";
908 if ($method eq 'Debian') {
909 read_tree_debian($cltree);
910 } elsif ($method eq 'Upstream') {
911 read_tree_upstream($cltree);
912 } elsif ($method eq 'StartRewrite') {
915 } elsif ($method eq 'RecordBreakwaterTip') {
916 $breakwater = $build;
918 } elsif ($method eq 'DgitImportDebianUpdate') {
919 read_tree_debian($cltree);
920 } elsif ($method eq 'DgitImportUpstreamUpdate') {
921 confess unless $rewriting;
922 my $differs = (get_differs $build, $cltree);
923 next unless $differs & D_UPS;
924 read_tree_upstream($cltree);
925 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
930 my $procd = (pop @processed) // 'UNDEF';
933 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
936 my $newtree = cmdoutput @git, qw(write-tree);
938 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
939 $ch =~ s{^parent .*\n}{}mg;
940 $ch =~ s{(?=^author)}{
941 join '', map { "parent $_\n" } @parents
942 }me or confess "$ch ?";
944 $ch =~ s{^committer .*$}{$committer_authline}m
947 my $cf = "$rd/m$rewriting";
948 open CD, ">", $cf or die $!;
949 print CD $ch, "\n", $cl->{Msg} or die $!;
951 my @cmd = (@git, qw(hash-object));
952 push @cmd, qw(-w) if $rewriting;
953 push @cmd, qw(-t commit), $cf;
954 my $newcommit = cmdoutput @cmd;
955 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
957 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
963 my $final_check = get_differs $build, $input;
964 die sprintf "internal error %#x %s %s", $final_check, $build, $input
965 if $final_check & ~D_PAT_ADD;
967 my @r = ($build, $breakwater, $last_anchor);
968 printdebug "*** WALK RETURN @r\n";
973 git_check_unmodified();
974 return git_rev_parse qw(HEAD);
977 sub update_head ($$$) {
978 my ($old, $new, $mrest) = @_;
979 push @deferred_updates, "update HEAD $new $old";
980 run_deferred_updates $mrest;
983 sub update_head_checkout ($$$) {
984 my ($old, $new, $mrest) = @_;
985 update_head $old, $new, $mrest;
986 runcmd @git, qw(reset --hard);
989 sub update_head_postlaunder ($$$) {
990 my ($old, $tip, $reflogmsg) = @_;
991 return if $tip eq $old;
992 print "git-debrebase: laundered (head was $old)\n";
993 update_head $old, $tip, $reflogmsg;
994 # no tree changes except debian/patches
995 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
998 sub currently_rebasing() {
999 foreach (qw(rebase-merge rebase-apply)) {
1000 return 1 if stat_exists "$maindir_gitdir/$_";
1005 sub bail_if_rebasing() {
1006 fail "you are in the middle of a git-rebase already"
1007 if currently_rebasing();
1010 sub do_launder_head ($) {
1011 my ($reflogmsg) = @_;
1012 my $old = get_head();
1014 my ($tip,$breakwater) = walk $old;
1016 update_head_postlaunder $old, $tip, $reflogmsg;
1017 return ($tip,$breakwater);
1020 sub cmd_launder_v0 () {
1021 badusage "no arguments to launder-v0 allowed" if @ARGV;
1022 my $old = get_head();
1023 my ($tip,$breakwater,$last_anchor) = walk $old;
1024 update_head_postlaunder $old, $tip, 'launder';
1025 printf "# breakwater tip\n%s\n", $breakwater;
1026 printf "# working tip\n%s\n", $tip;
1027 printf "# last anchor\n%s\n", $last_anchor;
1030 sub defaultcmd_rebase () {
1031 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1032 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1033 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1036 sub cmd_analyse () {
1037 badusage "analyse does not support any options"
1038 if @ARGV and $ARGV[0] =~ m/^-/;
1039 badusage "too many arguments to analyse" if @ARGV>1;
1042 $old = git_rev_parse $old;
1044 $old = git_rev_parse 'HEAD';
1046 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1047 STDOUT->error and die $!;
1050 sub ffq_prev_branchinfo () {
1051 my $current = git_get_symref();
1052 return gdr_ffq_prev_branchinfo($current);
1055 sub ffq_check ($;$$) {
1056 # calls $ff and/or $notff zero or more times
1057 # then returns either (status,message) where status is
1062 # or (undef,undef, $ffq_prev,$gdrlast)
1063 # $ff and $notff are called like this:
1064 # $ff->("message for stdout\n");
1065 # $notff->('snag-name', $message);
1066 # normally $currentval should be HEAD
1067 my ($currentval, $ff, $notff) =@_;
1069 $ff //= sub { print $_[0] or die $!; };
1072 my ($status, $message, $current, $ffq_prev, $gdrlast)
1073 = ffq_prev_branchinfo();
1074 return ($status, $message) unless $status eq 'branch';
1076 my $exists = git_get_ref $ffq_prev;
1077 return ('exists',"$ffq_prev already exists") if $exists;
1079 return ('not-branch', 'HEAD symref is not to refs/heads/')
1080 unless $current =~ m{^refs/heads/};
1083 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1086 printdebug "ffq check_specs @check_specs\n";
1089 my ($lrref, $desc) = @_;
1090 printdebug "ffq might check $lrref ($desc)\n";
1092 for my $chk (@check_specs) {
1094 $invert = $glob =~ s{^[!^]}{};
1095 last if fnmatch $glob, $lrref;
1098 my $lrval = git_get_ref $lrref;
1099 return unless length $lrval;
1101 if (is_fast_fwd $lrval, $currentval) {
1102 $ff->("OK, you are ahead of $lrref\n");
1103 $checked{$lrref} = 1;
1104 } elsif (is_fast_fwd $currentval, $lrval) {
1105 $checked{$lrref} = -1;
1106 $notff->('behind', "you are behind $lrref, divergence risk");
1108 $checked{$lrref} = -1;
1109 $notff->('diverged', "you have diverged from $lrref");
1113 my $merge = cfg "branch.$branch.merge",1;
1114 if (defined $merge and $merge =~ m{^refs/heads/}) {
1116 printdebug "ffq merge $rhs\n";
1117 my $check_remote = sub {
1118 my ($remote, $desc) = @_;
1119 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1120 return unless defined $remote;
1121 $check->("refs/remotes/$remote/$rhs", $desc);
1123 $check_remote->((scalar cfg "branch.$branch.remote",1),
1124 'remote fetch/merge branch');
1125 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1126 (scalar cfg "branch.$branch.pushDefault",1),
1127 'remote push branch');
1129 if ($branch =~ m{^dgit/}) {
1130 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1131 } elsif ($branch =~ m{^master$}) {
1132 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1134 return (undef, undef, $ffq_prev, $gdrlast);
1137 sub record_ffq_prev_deferred () {
1138 # => ('status', "message")
1140 # deferred message is undef
1145 # if not ff from some branch we should be ff from, is an snag
1146 # if "deferred", will have added something about that to
1147 # @deferred_update_messages, and also maybe printed (already)
1148 # some messages about ff checks
1150 my $currentval = get_head();
1152 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1153 return ($status,$message) if defined $status;
1157 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1158 push @deferred_updates, "delete $gdrlast";
1159 push @deferred_update_messages, "Recorded previous head for preservation";
1160 return ('deferred', undef);
1163 sub record_ffq_auto () {
1164 my ($status, $message) = record_ffq_prev_deferred();
1165 if ($status eq 'deferred' || $status eq 'exists') {
1167 snag $status, "could not record ffq-prev: $message";
1172 sub ffq_prev_info () {
1174 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1175 my ($status, $message, $current, $ffq_prev, $gdrlast)
1176 = ffq_prev_branchinfo();
1177 if ($status ne 'branch') {
1178 snag $status, "could not check ffq-prev: $message";
1181 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1182 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1185 sub stitch ($$$$$) {
1186 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1188 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1190 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1191 my $differs = get_differs $old_head, $ffq_prev_commitish;
1192 unless ($differs & ~D_PAT_ADD) {
1193 # ffq-prev is ahead of us, and the only tree changes it has
1194 # are possibly addition of things in debian/patches/.
1195 # Just wind forwards rather than making a pointless pseudomerge.
1196 push @deferred_updates,
1197 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1198 update_head_checkout $old_head, $ffq_prev_commitish,
1199 "stitch (fast forward)";
1204 # We make pseudomerges with L as the contributing parent.
1205 # This makes git rev-list --first-parent work properly.
1206 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1207 'Declare fast forward / record previous work',
1208 "[git-debrebase pseudomerge: $prose]",
1210 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1211 update_head $old_head, $new_head, "stitch: $prose";
1214 sub do_stitch ($;$) {
1215 my ($prose, $unclean) = @_;
1217 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1218 if (!$ffq_prev_commitish) {
1219 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1222 my $dangling_head = get_head();
1224 keycommits $dangling_head, $unclean,$unclean,$unclean;
1227 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1230 sub upstream_commitish_search ($$) {
1231 my ($upstream_version, $tried) = @_;
1232 # todo: at some point maybe use git-deborig to do this
1233 foreach my $tagpfx ('', 'v', 'upstream/') {
1234 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1235 my $new_upstream = git_get_ref "refs/tags/$tag";
1237 return $new_upstream if length $new_upstream;
1241 sub resolve_upstream_version ($$) {
1242 my ($new_upstream, $upstream_version) = @_;
1244 if (!defined $new_upstream) {
1246 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1247 if (!length $new_upstream) {
1248 fail "Could not determine appropriate upstream commitish.\n".
1249 " (Tried these tags: @tried)\n".
1250 " Check version, and specify upstream commitish explicitly.";
1253 $new_upstream = git_rev_parse $new_upstream;
1255 return $new_upstream;
1258 sub cmd_new_upstream () {
1259 # automatically and unconditionally launders before rebasing
1260 # if rebase --abort is used, laundering has still been done
1264 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1266 # parse args - low commitment
1267 my $spec_version = shift @ARGV;
1268 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1269 fail "bad version number \`$spec_version'" unless defined $new_version;
1270 if ($new_version->is_native()) {
1271 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1274 my $new_upstream = shift @ARGV;
1275 my $new_upstream_version = upstreamversion $new_version;
1277 resolve_upstream_version $new_upstream, $new_upstream_version;
1282 my ($n, @x) = @_; # may be ''
1283 my $pc = $pieces{$n} //= {
1285 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1287 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1292 my $newpiece = sub {
1293 my ($n, @x) = @_; # may be ''
1294 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1295 push @newpieces, $pc;
1300 New => $new_upstream,
1302 while (@ARGV && $ARGV[0] !~ m{^-}) {
1303 my $n = shift @ARGV;
1305 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1306 unless @ARGV && $ARGV[0] !~ m{^-};
1308 my $c = git_rev_parse shift @ARGV;
1309 die unless $n =~ m/^$extra_orig_namepart_re$/;
1310 $newpiece->($n, New => $c);
1313 # now we need to investigate the branch this generates the
1314 # laundered version but we don't switch to it yet
1315 my $old_head = get_head();
1316 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1318 my $old_bw_cl = classify $old_bw;
1319 my $old_anchor_cl = classify $old_anchor;
1321 if (!$old_anchor_cl->{OrigParents}) {
1322 snag 'anchor-treated',
1323 'old anchor is recognised due to --anchor, cannot check upstream';
1325 $old_upstream = parsecommit
1326 $old_anchor_cl->{OrigParents}[0]{CommitId};
1327 $piece->('', Old => $old_upstream->{CommitId});
1330 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1331 if ($old_upstream->{Msg} =~
1332 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1334 my @oldpieces = (split / /, $1);
1335 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1336 if ($old_n_parents != @oldpieces &&
1337 $old_n_parents != @oldpieces + 1) {
1338 snag 'upstream-confusing', sprintf
1339 "previous upstream combine %s".
1340 " mentions %d pieces (each implying one parent)".
1341 " but has %d parents".
1342 " (one per piece plus maybe a previous combine)",
1343 $old_upstream->{CommitId},
1344 (scalar @oldpieces),
1346 } elsif ($oldpieces[0] ne '.') {
1347 snag 'upstream-confusing', sprintf
1348 "previous upstream combine %s".
1349 " first piece is not \`.'",
1353 foreach my $i (0..$#oldpieces) {
1354 my $n = $oldpieces[$i];
1355 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1356 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1360 snag 'upstream-confusing',
1361 "previous upstream $old_upstream->{CommitId} is from".
1362 " git-debrebase but not an \`upstream-combine' commit";
1366 foreach my $pc (values %pieces) {
1367 if (!$old_upstream) {
1368 # we have complained already
1369 } elsif (!$pc->{Old}) {
1370 snag 'upstream-new-piece',
1371 "introducing upstream piece \`$pc->{Name}'";
1372 } elsif (!$pc->{New}) {
1373 snag 'upstream-rm-piece',
1374 "dropping upstream piece \`$pc->{Name}'";
1375 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1376 snag 'upstream-not-ff',
1377 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1381 printdebug "%pieces = ", (dd \%pieces), "\n";
1382 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1390 my @upstream_merge_parents;
1393 push @upstream_merge_parents, $old_upstream->{CommitId};
1396 foreach my $pc (@newpieces) { # always has '' first
1398 read_tree_subdir $pc->{Name}, $pc->{New};
1400 runcmd @git, qw(read-tree), $pc->{New};
1402 push @upstream_merge_parents, $pc->{New};
1405 # index now contains the new upstream
1407 if (@newpieces > 1) {
1408 # need to make the upstream subtree merge commit
1409 $new_upstream = make_commit \@upstream_merge_parents,
1410 [ "Combine upstreams for $new_upstream_version",
1411 ("[git-debrebase upstream-combine . ".
1412 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1417 # $new_upstream is either the single upstream commit, or the
1418 # combined commit we just made. Either way it will be the
1419 # "upstream" parent of the anchor merge.
1421 read_tree_subdir 'debian', "$old_bw:debian";
1423 # index now contains the anchor merge contents
1424 $new_bw = make_commit [ $old_bw, $new_upstream ],
1425 [ "Update to upstream $new_upstream_version",
1426 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1429 my $clogsignoff = cmdoutput qw(git show),
1430 '--pretty=format:%an <%ae> %aD',
1433 # Now we have to add a changelog stanza so the Debian version
1435 die if unlink "debian";
1436 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1437 unlink "debian/changelog" or $!==ENOENT or die $!;
1438 mkdir "debian" or die $!;
1439 open CN, ">", "debian/changelog" or die $!;
1440 my $oldclog = git_cat_file ":debian/changelog";
1441 $oldclog =~ m/^($package_re) \(\S+\) / or
1442 fail "cannot parse old changelog to get package name";
1444 print CN <<END, $oldclog or die $!;
1445 $p ($new_version) UNRELEASED; urgency=medium
1447 * Update to new upstream version $new_upstream_version.
1453 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1455 # Now we have the final new breakwater branch in the index
1456 $new_bw = make_commit [ $new_bw ],
1457 [ "Update changelog for new upstream $new_upstream_version",
1458 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1462 # we have constructed the new breakwater. we now need to commit to
1463 # the laundering output, because git-rebase can't easily be made
1464 # to make a replay list which is based on some other branch
1466 update_head_postlaunder $old_head, $old_laundered_tip,
1467 'launder for new upstream';
1469 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1470 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1471 "debrebase new-upstream $new_version: rebase";
1473 # now it's for the user to sort out
1476 sub cmd_record_ffq_prev () {
1477 badusage "no arguments allowed" if @ARGV;
1478 my ($status, $msg) = record_ffq_prev_deferred();
1479 if ($status eq 'exists' && $opt_noop_ok) {
1480 print "Previous head already recorded\n" or die $!;
1481 } elsif ($status eq 'deferred') {
1482 run_deferred_updates 'record-ffq-prev';
1484 fail "Could not preserve: $msg";
1489 badusage "no arguments allowed" if @ARGV;
1490 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1491 print "$bw\n" or die $!;
1494 sub cmd_breakwater () {
1495 badusage "no arguments allowed" if @ARGV;
1496 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1497 print "$bw\n" or die $!;
1501 badusage "no arguments allowed" if @ARGV;
1503 # todo: gdr status should print divergence info
1504 # todo: gdr status should print upstream component(s) info
1505 # todo: gdr should leave/maintain some refs with this kind of info ?
1507 my $oldest = { Badness => 0 };
1510 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1511 if ($oldest->{Badness} < $badness) {
1512 $oldest = $newest = undef;
1515 Badness => $badness,
1516 CommitId => $cl->{CommitId},
1520 $newest //= $oldest;
1522 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1523 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1524 sub { $note->(2, 'branch is unlaundered', @_); },
1525 sub { $note->(3, 'branch needs laundering', @_); },
1526 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1528 my $prcommitinfo = sub {
1530 flush STDOUT or die $!;
1531 runcmd @git, qw(--no-pager log -n1),
1532 '--pretty=format: %h %s%n',
1536 print "current branch contents, in git-debrebase terms:\n";
1537 if (!$oldest->{Badness}) {
1538 print " branch is laundered\n";
1540 print " $oldest->{OurMsg}\n";
1542 foreach my $info ($oldest, $newest) {
1543 my $cid = $info->{CommitId};
1544 next if $cid eq $printed;
1546 print " $info->{KcMsg}\n";
1547 $prcommitinfo->($cid);
1552 my ($cid, $what) = @_;
1553 if (!defined $cid) {
1554 print " $what is not well-defined\n";
1557 $prcommitinfo->($cid);
1560 print "key git-debrebase commits:\n";
1561 $prab->($anchor, 'anchor');
1562 $prab->($bw, 'breakwater');
1564 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1565 ffq_prev_branchinfo();
1567 print "branch and ref status, in git-debrebase terms:\n";
1569 print " $ffq_msg\n";
1571 $ffq_prev = git_get_ref $ffq_prev;
1572 $gdrlast = git_get_ref $gdrlast;
1574 print " unstitched; previous tip was:\n";
1575 $prcommitinfo->($ffq_prev);
1576 } elsif (!$gdrlast) {
1577 print " stitched? (no record of git-debrebase work)\n";
1578 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1579 print " stitched\n";
1581 print " not git-debrebase (diverged since last stitch)\n"
1584 print "you are currently rebasing\n" if currently_rebasing();
1588 my $prose = 'stitch';
1589 getoptions("stitch",
1590 'prose=s', \$prose);
1591 badusage "no arguments allowed" if @ARGV;
1592 do_stitch $prose, 0;
1594 sub cmd_prepush () { cmd_stitch(); }
1597 badusage "no arguments allowed" if @ARGV;
1598 do_launder_head 'launder for git-debrebase quick';
1602 sub cmd_conclude () {
1603 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1604 if (!$ffq_prev_commitish) {
1605 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1608 my $dangling_head = get_head();
1610 badusage "no arguments allowed" if @ARGV;
1611 do_launder_head 'launder for git-debrebase quick';
1616 if (currently_rebasing()) {
1617 runcmd @git, qw(rebase --abort);
1619 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1620 if (!$ffq_prev_commitish) {
1621 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1624 my $scrapping_head = get_head();
1625 badusage "no arguments allowed" if @ARGV;
1626 push @deferred_updates,
1627 "update $gdrlast $ffq_prev_commitish $git_null_obj",
1628 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
1630 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
1633 sub make_patches_staged ($) {
1635 # Produces the patches that would result from $head if it were
1637 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1640 gbp_pq_export 'bw', $secret_bw, $secret_head;
1644 sub make_patches ($) {
1646 keycommits $head, 0, \&snag;
1647 make_patches_staged $head;
1650 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1651 runcmd @git, qw(read-tree), $head;
1652 read_tree_subdir 'debian/patches', $ptree;
1653 $out = make_commit [$head], [
1654 'Commit patch queue (exported by git-debrebase)',
1655 '[git-debrebase: export and commit patches]',
1661 sub cmd_make_patches () {
1662 my $opt_quiet_would_amend;
1663 getoptions("make-patches",
1664 'quiet-would-amend!', \$opt_quiet_would_amend);
1665 badusage "no arguments allowed" if @ARGV;
1667 my $old_head = get_head();
1668 my $new = make_patches $old_head;
1669 my $d = get_differs $old_head, $new;
1671 fail "No (more) patches to export." unless $opt_noop_ok;
1673 } elsif ($d == D_PAT_ADD) {
1675 update_head_checkout $old_head, $new, 'make-patches';
1677 print STDERR failmsg
1678 "Patch export produced patch amendments".
1679 " (abandoned output commit $new).".
1680 " Try laundering first."
1681 unless $opt_quiet_would_amend;
1686 sub cmd_convert_from_gbp () {
1687 badusage "want only 1 optional argument, the upstream git commitish"
1690 my $clogp = parsechangelog();
1691 my $version = $clogp->{'Version'}
1692 // die "missing Version from changelog";
1694 my ($upstream_spec) = @ARGV;
1696 my $upstream_version = upstreamversion $version;
1698 resolve_upstream_version($upstream_spec, $upstream_version);
1700 my $old_head = get_head();
1702 my $upsdiff = get_differs $upstream, $old_head;
1703 if ($upsdiff & D_UPS) {
1704 runcmd @git, qw(--no-pager diff --stat),
1705 $upstream, $old_head,
1706 qw( -- :!/debian :/);
1708 upstream ($upstream_spec) and HEAD are not
1709 identical in upstream files. See diffstat above, or run
1710 git diff $upstream_spec HEAD -- :!/debian :/
1714 if (!is_fast_fwd $upstream, $old_head) {
1715 snag 'upstream-not-ancestor',
1716 "upstream ($upstream) is not an ancestor of HEAD";
1718 my $wrong = cmdoutput
1719 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1720 qw(-- :/ :!/debian));
1721 if (length $wrong) {
1722 snag 'unexpected-upstream-changes',
1723 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1724 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1728 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1729 snag 'upstream-has-debian',
1730 "upstream ($upstream) contains debian/ directory";
1733 my $previous_dgit_view = eval {
1734 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1736 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1737 my ($stz, $desc) = @_;
1738 no warnings qw(exiting);
1739 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1740 next unless $stz->{Date};
1741 next unless $stz->{Distribution} ne 'UNRELEASED';
1742 $lvsn = $stz->{Version};
1743 $suite = $stz->{Distribution};
1746 die "neither of the first two changelog entries are released\n"
1747 unless defined $lvsn;
1748 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1749 my $mtag_pat = debiantag_maintview $lvsn, '*';
1750 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1752 die "could not find suitable maintainer view tag $mtag_pat\n"
1753 unless $mtag_pat =~ m{/};
1754 is_fast_fwd $mtag, 'HEAD' or
1755 die "HEAD is not FF from maintainer tag $mtag!";
1756 my $dtag = "archive/$mtag";
1757 is_fast_fwd $mtag, $dtag or
1758 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1759 print "will stitch in dgit view, $dtag\n";
1760 git_rev_parse $dtag;
1762 if (!$previous_dgit_view) {
1765 print STDERR "cannot stitch in dgit view: $@\n";
1768 snags_maybe_bail_early();
1774 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1775 # make a branch out of the patch queue - we'll want this in a mo
1776 runcmd qw(gbp pq import);
1777 # strip the patches out
1778 runcmd @git, qw(checkout -q gdr-internal~0);
1779 rm_subdir_cached 'debian/patches';
1780 $work = make_commit ['HEAD'], [
1781 'git-debrebase convert-from-gbp: drop patches from tree',
1782 'Delete debian/patches, as part of converting to git-debrebase format.',
1783 '[git-debrebase convert-from-gbp: drop patches from tree]'
1785 # make the anchor merge
1786 # the tree is already exactly right
1787 $work = make_commit [$work, $upstream], [
1788 'git-debrebase import: declare upstream',
1789 'First breakwater merge.',
1790 '[git-debrebase anchor: declare upstream]'
1793 # rebase the patch queue onto the new breakwater
1794 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1795 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1796 $work = git_rev_parse 'HEAD';
1798 if ($previous_dgit_view) {
1799 $work = make_commit [$work, $previous_dgit_view], [
1800 'git-debrebase import: declare ff from dgit archive view',
1801 '[git-debrebase pseudomerge: import-from-gbp]',
1808 update_head_checkout $old_head, $work, 'convert-from-gbp';
1811 sub cmd_convert_to_gbp () {
1812 badusage "no arguments allowed" if @ARGV;
1813 my $head = get_head();
1814 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1815 keycommits $head, 0;
1817 make_patches_staged $head;
1819 $out = make_commit ['HEAD'], [
1820 'Commit patch queue (converted from git-debrebase format)',
1821 '[git-debrebase convert-to-gbp: commit patches]',
1825 push @deferred_updates, "delete $ffq";
1826 push @deferred_updates, "delete $gdrlast";
1829 update_head_checkout $head, $out, "convert to gbp (v0)";
1830 print <<END or die $!;
1831 git-debrebase: converted to git-buildpackage branch format
1832 git-debrebase: WARNING: do not now run "git-debrebase" any more
1833 git-debrebase: WARNING: doing so would drop all upstream patches!
1837 sub cmd_convert_from_dgit_view () {
1838 my $clogp = parsechangelog();
1840 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
1846 getoptions("convert-from-dgit-view",
1847 'diagnose!', \$diagnose,
1848 'build-products-dir:s', \$bpd,
1849 'origs!', \$do_origs,
1851 'always-convert-anyway!', \$always);
1852 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
1857 my $spec = shift @ARGV;
1858 my $commit = git_rev_parse "$spec^{commit}";
1859 push @upstreams, { Commit => $commit,
1860 Source => "$ARGV[0], from command line",
1865 my $head = get_head();
1869 my $trouble = sub { $troubles++; };
1870 keycommits $head, sub{}, sub{}, $trouble, $trouble;
1871 printdebug "troubles=$troubles\n";
1874 $us: Branch already seems to be in git-debrebase format!
1875 $us: --always-convert-anyway would do the conversion operation anyway
1876 $us: but is probably a bad idea. Probably, you wanted to do nothing.
1878 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
1883 snags_maybe_bail_early();
1885 my $version = upstreamversion $clogp->{Version};
1886 print STDERR "Considering possible commits corresponding to upstream:\n";
1891 my $ups_tag = upstream_commitish_search $version, \@tried;
1893 my $this = "git tag $tried[-1]";
1894 push @upstreams, { Commit => $ups_tag,
1899 " git tag: no suitable tag found (tried %s)\n",
1904 my $p = $clogp->{'Source'};
1905 # we do a quick check to see if there are plausible origs
1907 if (!opendir BPD, $bpd) {
1908 die "$bpd: opendir: $!" unless $!==ENOENT;
1910 while ($!=0, my $f = readdir BPD) {
1911 next unless is_orig_file_of_p_v $f, $p, $version;
1913 " orig: found what looks like a .orig, %s\n",
1918 die "read $bpd: $!" if $!;
1922 my $tree = cmdoutput
1923 @dgit, qw(--build-products-dir), $bpd,
1924 qw(print-unapplied-treeish);
1927 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
1928 rm_subdir_cached 'debian';
1929 $tree = cmdoutput @git, qw(write-tree);
1930 my $ups_synth = make_commit [], [ <<END, <<END,
1931 Import effective orig tree for upstream version $version
1933 This includes the contents of the .orig(s), minus any debian/ directory.
1935 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
1938 push @upstreams, { Commit => $ups_synth,
1939 Source => "orig(s) imported via dgit",
1944 " orig: no suitable origs found (looked for %s in %s)\n",
1945 "${p}_".(stripeoch $version)."...", $bpd;
1950 my $some_patches = stat_exists 'debian/patches/series';
1952 print STDERR "Evaluating possible commits corresponding to upstream:\n";
1955 foreach my $u (@upstreams) {
1959 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
1960 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
1961 runcmd @git, qw(clean -xdff);
1962 runcmd @git, qw(checkout), $head, qw(-- debian);
1963 if ($some_patches) {
1964 rm_subdir_cached 'debian/patches';
1965 $work = make_commit [ $work ], [
1966 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
1967 "Drop upstream changes, and delete debian/patches, as part of converting\n".
1968 "to git-debrebase format. Upstream changes will appear as commits.",
1969 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
1972 $work = make_commit [ $work, $u->{Commit} ], [
1973 'git-debrebase convert-from-dgit-view: declare upstream',
1974 '(Re)constructed breakwater merge.',
1975 '[git-debrebase anchor: declare upstream]'
1977 runcmd @git, qw(checkout --quiet -b mk), $work;
1978 if ($some_patches) {
1979 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
1980 runcmd @git, qw(reset --quiet);
1981 my @gbp_cmd = (qw(gbp pq import));
1983 my $gbp_err = "../gbp-pq-err";
1984 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
1986 my $r = system @gbp_cmd;
1989 " %s: couldn't apply patches: gbp pq %s",
1990 $u->{Source}, waitstatusmsg();
1994 my $work = git_rev_parse qw(HEAD);
1995 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
1996 if (length $diffout) {
1998 " $u->{Source}: applying patches gives different tree\n";
1999 print STDERR $diffout if $diagnose;
2003 $u->{Result} = $work;
2011 Could not find or construct a suitable upstream commit.
2012 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2013 upstream commmit explicitly or provide suitable origs.
2017 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2019 ffq_check $result->{Result};
2021 update_head_checkout $head, $result->{Result},
2022 'convert-from-dgit-view';
2025 sub cmd_downstream_rebase_launder_v0 () {
2026 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2028 $base = git_rev_parse $base;
2029 my $old_head = get_head();
2030 my $current = $old_head;
2033 if ($current eq $base) {
2034 $topmost_keep //= $current;
2035 print " $current BASE stop\n";
2038 my $cl = classify $current;
2039 print " $current $cl->{Type}";
2041 my $p0 = $cl->{Parents}[0]{CommitId};
2043 if ($cl->{Type} eq 'Pseudomerge') {
2044 print " ^".($cl->{Contributor}{Ix}+1);
2045 $next = $cl->{Contributor}{CommitId};
2046 } elsif ($cl->{Type} eq 'AddPatches' or
2047 $cl->{Type} eq 'Changelog') {
2057 $topmost_keep //= $current;
2059 die "to-be stripped changes not on top of the branch\n"
2064 if ($topmost_keep eq $old_head) {
2065 print "unchanged\n";
2067 print "updating to $topmost_keep\n";
2068 update_head_checkout
2069 $old_head, $topmost_keep,
2070 'downstream-rebase-launder-v0';
2076 "D+" => \$debuglevel,
2077 'noop-ok', => \$opt_noop_ok,
2078 'f=s' => \@snag_force_opts,
2079 'anchor=s' => \@opt_anchors,
2080 '--dgit=s' => \($dgit[0]),
2083 my ($opt,$val) = @_;
2084 badusage "git-debrebase: no cuddling to -i for git-rebase"
2086 die if $opt_defaultcmd_interactive; # should not happen
2087 $opt_defaultcmd_interactive = [ qw(-i) ];
2088 # This access to @ARGV is excessive familiarity with
2089 # Getopt::Long, but there isn't another sensible
2090 # approach. '-i=s{0,}' does not work with bundling.
2091 push @$opt_defaultcmd_interactive, @ARGV;
2094 'help' => sub { print $usage_message or die $!; finish 0; },
2097 initdebug('git-debrebase ');
2098 enabledebug if $debuglevel;
2100 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2101 chdir $toplevel or die "chdir $toplevel: $!";
2103 $rd = fresh_playground "$playprefix/misc";
2105 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2107 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2108 defaultcmd_rebase();
2110 my $cmd = shift @ARGV;
2113 $cmdfn = ${*::}{"cmd_$cmdfn"};
2115 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";