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 make_commit ($$) {
265 my ($parents, $message_paras) = @_;
266 my $tree = cmdoutput @git, qw(write-tree);
267 my @cmd = (@git, qw(commit-tree), $tree);
268 push @cmd, qw(-p), $_ foreach @$parents;
269 push @cmd, qw(-m), $_ foreach @$message_paras;
270 return cmdoutput @cmd;
273 our @snag_force_opts;
275 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
276 if (grep { $_ eq $tag } @snag_force_opts) {
278 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
281 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
285 # Important: all mainline code must call snags_maybe_bail after
286 # any point where snag might be called, but before making changes
287 # (eg before any call to run_deferred_updates). snags_maybe_bail
288 # may be called more than once if necessary (but this is not ideal
289 # because then the messages about number of snags may be confusing).
290 sub snags_maybe_bail () {
291 return if all_snags_summarised();
294 "%s: snags: %d overriden by individual -f options\n",
297 if ($snags_tripped) {
300 "%s: snags: %d overriden by global --force\n",
304 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
308 $snags_summarised = $snags_forced + $snags_tripped;
310 sub snags_maybe_bail_early () {
311 # useful to bail out early without doing a lot of work;
312 # not a substitute for snags_maybe_bail.
313 snags_maybe_bail() if $snags_tripped && !$opt_force;
316 return $snags_forced || $snags_tripped;
319 sub gbp_pq_export ($$$) {
320 my ($bname, $base, $tip) = @_;
321 # must be run in a workarea. $bname and patch-queue/$bname
322 # ought not to exist. Leaves you on patch-queue/$bname with
323 # the patches staged but not committed.
324 runcmd @git, qw(checkout -q -b), $bname, $base;
325 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
326 my @gbp_cmd = (qw(gbp pq export));
327 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
329 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
332 runcmd @git, qw(add -f debian/patches);
335 # classify returns an info hash like this
337 # Hdr => # commit headers, including 1 final newline
338 # Msg => # commit message (so one newline is dropped)
340 # Type => (see below)
342 # Ix => $index # ie 0, 1, 2, ...
344 # Differs => return value from get_differs
346 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
348 # NewMsg => # commit message, but with any [dgit import ...] edited
349 # # to say "[was: ...]"
359 # has additional entres in classification result
360 # Overwritten = [ subset of Parents ]
361 # Contributor = $the_remaining_Parent
363 # DgitImportUnpatched
364 # has additional entry in classification result
365 # OrigParents = [ subset of Parents ]
368 # has additional entry in classification result
369 # OrigParents = [ subset of Parents ] # singleton list
376 # has additional entry in classification result
379 sub parsecommit ($;$) {
380 my ($objid, $p_ref) = @_;
381 # => hash with CommitId Hdr Msg Tree Parents
382 # Parents entries have only Ix CommitId
383 # $p_ref, if provided, must be [] and is used as a base for Parents
388 my ($h,$m) = get_commit $objid;
390 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
391 my (@ph) = $h =~ m/^parent (\w+)$/mg;
401 foreach my $ph (@ph) {
403 Ix => scalar @$p_ref,
415 my $r = parsecommit($objid, \@p);
419 $p->{Differs} = (get_differs $p->{CommitId}, $t),
422 printdebug "classify $objid \$t=$t \@p",
423 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
427 my ($type, @rest) = @_;
428 $r = { %$r, Type => $type, @rest };
430 printdebug " = $type ".(dd $r)."\n";
436 $r = { %$r, Type => qw(Unknown), Why => $why };
437 printdebug " ** Unknown\n";
441 if (grep { $_ eq $objid } @opt_anchors) {
442 return $classify->('TreatAsAnchor');
445 my @identical = grep { !$_->{Differs} } @p;
446 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
447 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
449 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
450 # multi-orig upstreams are represented with an anchor merge
451 # from a single upstream commit which combines the orig tarballs
453 # Every anchor tagged this way must be a merge.
454 # We are relying on the
455 # [git-debrebase anchor: ...]
456 # commit message annotation in "declare" anchor merges (which
457 # do not have any upstream changes), to distinguish those
458 # anchor merges from ordinary pseudomerges (which we might
459 # just try to strip).
461 # However, the user is going to be doing git-rebase a lot. We
462 # really don't want them to rewrite an anchor commit.
463 # git-rebase trips up on merges, so that is a useful safety
466 # BreakwaterStart commits are also anchors in the terminology
467 # of git-debrebase(5), but they are untagged (and always
468 # manually generated).
470 # We cannot not tolerate any tagged linear commit (ie,
471 # BreakwaterStart commits tagged `[anchor:') because such a
472 # thing could result from an erroneous linearising raw git
473 # rebase of a merge anchor. That would represent a corruption
474 # of the branch. and we want to detect and reject the results
475 # of such corruption before it makes it out anywhere. If we
476 # reject it here then we avoid making the pseudomerge which
477 # would be needed to push it.
479 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
480 @p == 2 or return $badanchor->("has other than two parents");
481 $haspatches and return $badanchor->("contains debian/patches");
483 # How to decide about l/r ordering of anchors ? git
484 # --topo-order prefers to expand 2nd parent first. There's
485 # already an easy rune to look for debian/ history anyway (git log
486 # debian/) so debian breakwater branch should be 1st parent; that
487 # way also there's also an easy rune to look for the upstream
488 # patches (--topo-order).
490 # Also this makes --first-parent be slightly more likely to
491 # be useful - it makes it provide a linearised breakwater history.
493 # Of course one can say somthing like
494 # gitk -- ':/' ':!/debian'
495 # to get _just_ the commits touching upstream files, and by
496 # the TREESAME logic in git-rev-list this will leave the
497 # breakwater into upstream at the first anchor. But that
498 # doesn't report debian/ changes at all.
500 # Other observations about gitk: by default, gitk seems to
501 # produce output in a different order to git-rev-list. I
502 # can't seem to find this documented anywhere. gitk
503 # --date-order DTRT. But, gitk always seems to put the
504 # parents from left to right, in order, so it's easy to see
505 # which way round a pseudomerge is.
507 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
508 $p[1]{Differs} & ~DS_DEB and
509 $badanchor->("upstream files differ from left parent");
510 $p[0]{Differs} & ~D_UPS and
511 $badanchor->("debian/ differs from right parent");
513 return $classify->(qw(Anchor),
514 OrigParents => [ $p[1] ]);
518 my $d = $r->{Parents}[0]{Differs};
519 if ($d == D_PAT_ADD) {
520 return $classify->(qw(AddPatches));
521 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
522 return $unknown->("edits debian/patches");
523 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
524 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
526 if ($d == D_DEB_CLOG) {
527 return $classify->(qw(Changelog));
529 return $classify->(qw(Packaging));
531 } elsif ($ty eq 'missing') {
532 return $classify->(qw(BreakwaterStart));
534 return $unknown->("parent's debian is not a directory");
536 } elsif ($d == D_UPS) {
537 return $classify->(qw(Upstream));
538 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
539 return $classify->(qw(Mixed));
541 return $unknown->("no changes");
543 confess "internal error $objid ?";
547 return $unknown->("origin commit");
550 if (@p == 2 && @identical == 1) {
551 my @overwritten = grep { $_->{Differs} } @p;
552 confess "internal error $objid ?" unless @overwritten==1;
553 return $classify->(qw(Pseudomerge),
554 Overwritten => [ $overwritten[0] ],
555 Contributor => $identical[0]);
557 if (@p == 2 && @identical == 2) {
559 my ($ph,$pm) = get_commit $_[0]{CommitId};
560 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
564 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
565 if ($order > 0) { # newer first
566 } elsif ($order < 0) {
567 @bytime = reverse @bytime;
569 # same age, default to order made by -s ours
570 # that is, commit was made by someone who preferred L
572 return $classify->(qw(Pseudomerge),
573 SubType => qw(Ambiguous),
574 Contributor => $bytime[0],
575 Overwritten => [ $bytime[1] ]);
578 my ($p_h, $p_m) = get_commit $p->{CommitId};
579 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
580 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
582 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
584 if (!(grep { !$_->{IsOrigin} } @p) and
585 (@orig_ps >= @p - 1) and
586 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
588 return $classify->(qw(DgitImportUnpatched),
589 OrigParents => \@orig_ps);
592 return $unknown->("complex merge");
595 sub keycommits ($;$$$$) {
596 my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
597 # => ($anchor, $breakwater)
599 # $unclean->("unclean-$tagsfx", $msg, $cl)
600 # $furniture->("unclean-$tagsfx", $msg, $cl)
601 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
602 # is callled for each situation or commit that
603 # wouldn't be found in a laundered branch
604 # $furniture is for furniture commits such as might be found on an
605 # interchange branch (pseudomerge, d/patches, changelog)
606 # $trouble is for things whnich prevent the return of
607 # anchor and breakwater information; if that is ignored,
608 # then keycommits returns (undef, undef) instead.
609 # $fatal is for unprocessable commits, and should normally cause
610 # a failure. If ignored, agaion, (undef, undef) is returned.
612 # If a callback is undef, fail is called instead.
613 # If a callback is defined but false, the situation is ignored.
615 # no warnings qw(exiting); last;
616 # if the answer is no longer wanted.
618 my ($anchor, $breakwater);
622 $fatal //= sub { fail $_[1]; };
624 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
625 my $why = $mainwhy.$xwhy;
626 my $m = "branch needs laundering (run git-debrebase): $why";
627 fail $m unless defined $cb;
629 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
632 $cl = classify $head;
633 my $ty = $cl->{Type};
634 if ($ty eq 'Packaging') {
635 $breakwater //= $clogonly;
636 $breakwater //= $head;
637 } elsif ($ty eq 'Changelog') {
638 # this is going to count as the tip of the breakwater
639 # only if it has no upstream stuff before it
641 } elsif ($ty eq 'Anchor' or
642 $ty eq 'TreatAsAnchor' or
643 $ty eq 'BreakwaterStart') {
645 $breakwater //= $clogonly;
646 $breakwater //= $head;
648 } elsif ($ty eq 'Upstream') {
649 $x->($unclean, 'ordering',
650 "packaging change ($breakwater) follows upstream change"," (eg $head)")
651 if defined $breakwater;
654 } elsif ($ty eq 'Mixed') {
655 $x->($unclean, 'mixed',
656 "found mixed upstream/packaging commit"," ($head)");
659 } elsif ($ty eq 'Pseudomerge' or
660 $ty eq 'AddPatches') {
662 $x->($furniture, (lc $ty),
663 "found interchange bureaucracy commit ($ty)"," ($head)");
664 } elsif ($ty eq 'DgitImportUnpatched') {
666 $x->($trouble, 'dgitimport',
667 "found dgit dsc import"," ($head)");
668 return (undef,undef);
670 $x->($fatal, 'unprocessable',
671 "found bare dgit dsc import with no prior history",
673 return (undef,undef);
676 $x->($fatal, 'unprocessable',
677 "found unprocessable commit, cannot cope: $cl->{Why}",
679 return (undef,undef);
681 $head = $cl->{Parents}[0]{CommitId};
683 return ($anchor, $breakwater);
689 $nogenerate,$report, $report_lprefix) = @_;
690 # => ($tip, $breakwater_tip, $last_anchor)
691 # (or nothing, if $nogenerate)
693 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
694 $report_lprefix //= '';
696 # go through commits backwards
697 # we generate two lists of commits to apply:
698 # breakwater branch and upstream patches
699 my (@brw_cl, @upp_cl, @processed);
706 my ($prose, $info) = @_;
710 $ms .= "\n\n[git-debrebase$info: $prose]\n";
713 my $rewrite_from_here = sub {
715 my $sp_cl = { SpecialMethod => 'StartRewrite' };
717 push @processed, $sp_cl;
722 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
725 return unless $report;
726 print $report $prdelim, $report_lprefix, @_;
730 my $bomb = sub { # usage: return $bomb->();
731 print $report " Unprocessable" if $report;
732 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
735 return (undef,undef);
737 fail "found unprocessable commit, cannot cope".
738 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
739 " (commit $cur) (d.".
740 (join ' ', map { sprintf "%#x", $_->{Differs} }
741 @{ $cl->{Parents} }).
748 my $build_start = sub {
749 my ($msg, $parent) = @_;
752 no warnings qw(exiting); last;
759 my $ty = $cl->{Type};
760 my $st = $cl->{SubType};
761 $prline->("$cl->{CommitId} $cl->{Type}");
762 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
763 push @processed, $cl;
764 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
765 if ($ty eq 'AddPatches') {
767 $rewrite_from_here->(\@upp_cl);
769 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
773 } elsif ($ty eq 'BreakwaterStart') {
775 $build_start->('FirstPackaging', $cur);
776 } elsif ($ty eq 'Upstream') {
780 } elsif ($ty eq 'Mixed') {
783 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
786 $queue->(\@brw_cl, "debian");
787 $queue->(\@upp_cl, "upstream");
788 $rewrite_from_here->(\@brw_cl);
791 } elsif ($ty eq 'Pseudomerge') {
792 my $contrib = $cl->{Contributor}{CommitId};
793 print $report " Contributor=$contrib" if $report;
794 push @pseudomerges, $cl;
795 $rewrite_from_here->(\@upp_cl);
798 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
800 $build_start->("Anchor", $cur);
801 } elsif ($ty eq 'DgitImportUnpatched') {
802 my $pm = $pseudomerges[-1];
804 # To an extent, this is heuristic. Imports don't have
805 # a useful history of the debian/ branch. We assume
806 # that the first pseudomerge after an import has a
807 # useful history of debian/, and ignore the histories
808 # from later pseudomerges. Often the first pseudomerge
809 # will be the dgit import of the upload to the actual
810 # suite intended by the non-dgit NMUer, and later
811 # pseudomerges may represent in-archive copies.
812 my $ovwrs = $pm->{Overwritten};
813 printf $report " PM=%s \@Overwr:%d",
814 $pm->{CommitId}, (scalar @$ovwrs)
817 printdebug "*** WALK BOMB DgitImportUnpatched\n";
820 my $ovwr = $ovwrs->[0]{CommitId};
821 printf $report " Overwr=%s", $ovwr if $report;
822 # This import has a tree which is just like a
823 # breakwater tree, but it has the wrong history. It
824 # ought to have the previous breakwater (which the
825 # pseudomerge overwrote) as an ancestor. That will
826 # make the history of the debian/ files correct. As
827 # for the upstream version: either it's the same as
828 # was ovewritten (ie, same as the previous
829 # breakwater), in which case that history is precisely
830 # right; or, otherwise, it was a non-gitish upload of a
831 # new upstream version. We can tell these apart by
832 # looking at the tree of the supposed upstream.
835 SpecialMethod => 'DgitImportDebianUpdate',
836 $xmsg->("convert dgit import: debian changes")
839 SpecialMethod => 'DgitImportUpstreamUpdate',
840 $xmsg->("convert dgit import: upstream update",
843 $prline->(" Import");
844 $rewrite_from_here->(\@brw_cl);
845 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
849 # Everything is from this import. This kind of import
850 # is already nearly in valid breakwater format, with the
851 # patches as commits. Unfortunately it contains
853 printdebug "*** WALK BOMB bare dgit import\n";
854 $cl->{Why} = "bare dgit dsc import";
859 printdebug "*** WALK BOMB unrecognised\n";
865 printdebug "*** WALK prep done cur=$cur".
866 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
868 return if $nogenerate;
870 # Now we build it back up again
876 my $read_tree_upstream = sub {
878 runcmd @git, qw(read-tree), $treeish;
879 read_tree_debian($build);
882 $#upp_cl = $upp_limit if defined $upp_limit;
884 my $committer_authline = calculate_committer_authline();
886 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
888 confess "internal error" unless $build eq (pop @processed)->{CommitId};
891 mkdir $rd or $!==EEXIST or die $!;
893 runcmd @git, qw(read-tree), $build;
894 foreach my $cl (qw(Debian), (reverse @brw_cl),
895 { SpecialMethod => 'RecordBreakwaterTip' },
896 qw(Upstream), (reverse @upp_cl)) {
898 $current_method = $cl;
901 my $method = $cl->{SpecialMethod} // $current_method;
902 my @parents = ($build);
903 my $cltree = $cl->{CommitId};
904 printdebug "WALK BUILD ".($cltree//'undef').
905 " $method (rewriting=$rewriting)\n";
906 if ($method eq 'Debian') {
907 read_tree_debian($cltree);
908 } elsif ($method eq 'Upstream') {
909 $read_tree_upstream->($cltree);
910 } elsif ($method eq 'StartRewrite') {
913 } elsif ($method eq 'RecordBreakwaterTip') {
914 $breakwater = $build;
916 } elsif ($method eq 'DgitImportDebianUpdate') {
917 read_tree_debian($cltree);
918 } elsif ($method eq 'DgitImportUpstreamUpdate') {
919 confess unless $rewriting;
920 my $differs = (get_differs $build, $cltree);
921 next unless $differs & D_UPS;
922 $read_tree_upstream->($cltree);
923 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
928 my $procd = (pop @processed) // 'UNDEF';
931 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
934 my $newtree = cmdoutput @git, qw(write-tree);
936 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
937 $ch =~ s{^parent .*\n}{}mg;
938 $ch =~ s{(?=^author)}{
939 join '', map { "parent $_\n" } @parents
940 }me or confess "$ch ?";
942 $ch =~ s{^committer .*$}{$committer_authline}m
945 my $cf = "$rd/m$rewriting";
946 open CD, ">", $cf or die $!;
947 print CD $ch, "\n", $cl->{Msg} or die $!;
949 my @cmd = (@git, qw(hash-object));
950 push @cmd, qw(-w) if $rewriting;
951 push @cmd, qw(-t commit), $cf;
952 my $newcommit = cmdoutput @cmd;
953 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
955 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
961 my $final_check = get_differs $build, $input;
962 die sprintf "internal error %#x %s %s", $final_check, $build, $input
963 if $final_check & ~D_PAT_ADD;
965 my @r = ($build, $breakwater, $last_anchor);
966 printdebug "*** WALK RETURN @r\n";
971 git_check_unmodified();
972 return git_rev_parse qw(HEAD);
975 sub update_head ($$$) {
976 my ($old, $new, $mrest) = @_;
977 push @deferred_updates, "update HEAD $new $old";
978 run_deferred_updates $mrest;
981 sub update_head_checkout ($$$) {
982 my ($old, $new, $mrest) = @_;
983 update_head $old, $new, $mrest;
984 runcmd @git, qw(reset --hard);
987 sub update_head_postlaunder ($$$) {
988 my ($old, $tip, $reflogmsg) = @_;
989 return if $tip eq $old;
990 print "git-debrebase: laundered (head was $old)\n";
991 update_head $old, $tip, $reflogmsg;
992 # no tree changes except debian/patches
993 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
996 sub currently_rebasing() {
997 foreach (qw(rebase-merge rebase-apply)) {
998 return 1 if stat_exists "$maindir_gitdir/$_";
1003 sub bail_if_rebasing() {
1004 fail "you are in the middle of a git-rebase already"
1005 if currently_rebasing();
1008 sub do_launder_head ($) {
1009 my ($reflogmsg) = @_;
1010 my $old = get_head();
1012 my ($tip,$breakwater) = walk $old;
1014 update_head_postlaunder $old, $tip, $reflogmsg;
1015 return ($tip,$breakwater);
1018 sub cmd_launder_v0 () {
1019 badusage "no arguments to launder-v0 allowed" if @ARGV;
1020 my $old = get_head();
1021 my ($tip,$breakwater,$last_anchor) = walk $old;
1022 update_head_postlaunder $old, $tip, 'launder';
1023 printf "# breakwater tip\n%s\n", $breakwater;
1024 printf "# working tip\n%s\n", $tip;
1025 printf "# last anchor\n%s\n", $last_anchor;
1028 sub defaultcmd_rebase () {
1029 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1030 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1031 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1034 sub cmd_analyse () {
1035 badusage "analyse does not support any options"
1036 if @ARGV and $ARGV[0] =~ m/^-/;
1037 badusage "too many arguments to analyse" if @ARGV>1;
1040 $old = git_rev_parse $old;
1042 $old = git_rev_parse 'HEAD';
1044 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1045 STDOUT->error and die $!;
1048 sub ffq_prev_branchinfo () {
1049 my $current = git_get_symref();
1050 return gdr_ffq_prev_branchinfo($current);
1053 sub ffq_check ($;$$) {
1054 # calls $ff and/or $notff zero or more times
1055 # then returns either (status,message) where status is
1060 # or (undef,undef, $ffq_prev,$gdrlast)
1061 # $ff and $notff are called like this:
1062 # $ff->("message for stdout\n");
1063 # $notff->('snag-name', $message);
1064 # normally $currentval should be HEAD
1065 my ($currentval, $ff, $notff) =@_;
1067 $ff //= sub { print $_[0] or die $!; };
1070 my ($status, $message, $current, $ffq_prev, $gdrlast)
1071 = ffq_prev_branchinfo();
1072 return ($status, $message) unless $status eq 'branch';
1074 my $exists = git_get_ref $ffq_prev;
1075 return ('exists',"$ffq_prev already exists") if $exists;
1077 return ('not-branch', 'HEAD symref is not to refs/heads/')
1078 unless $current =~ m{^refs/heads/};
1081 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1084 printdebug "ffq check_specs @check_specs\n";
1087 my ($lrref, $desc) = @_;
1088 printdebug "ffq might check $lrref ($desc)\n";
1090 for my $chk (@check_specs) {
1092 $invert = $glob =~ s{^[!^]}{};
1093 last if fnmatch $glob, $lrref;
1096 my $lrval = git_get_ref $lrref;
1097 return unless length $lrval;
1099 if (is_fast_fwd $lrval, $currentval) {
1100 $ff->("OK, you are ahead of $lrref\n");
1101 $checked{$lrref} = 1;
1102 } elsif (is_fast_fwd $currentval, $lrval) {
1103 $checked{$lrref} = -1;
1104 $notff->('behind', "you are behind $lrref, divergence risk");
1106 $checked{$lrref} = -1;
1107 $notff->('diverged', "you have diverged from $lrref");
1111 my $merge = cfg "branch.$branch.merge",1;
1112 if (defined $merge and $merge =~ m{^refs/heads/}) {
1114 printdebug "ffq merge $rhs\n";
1115 my $check_remote = sub {
1116 my ($remote, $desc) = @_;
1117 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1118 return unless defined $remote;
1119 $check->("refs/remotes/$remote/$rhs", $desc);
1121 $check_remote->((scalar cfg "branch.$branch.remote",1),
1122 'remote fetch/merge branch');
1123 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1124 (scalar cfg "branch.$branch.pushDefault",1),
1125 'remote push branch');
1127 if ($branch =~ m{^dgit/}) {
1128 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1129 } elsif ($branch =~ m{^master$}) {
1130 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1132 return (undef, undef, $ffq_prev, $gdrlast);
1135 sub record_ffq_prev_deferred () {
1136 # => ('status', "message")
1138 # deferred message is undef
1143 # if not ff from some branch we should be ff from, is an snag
1144 # if "deferred", will have added something about that to
1145 # @deferred_update_messages, and also maybe printed (already)
1146 # some messages about ff checks
1148 my $currentval = get_head();
1150 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1151 return ($status,$message) if defined $status;
1155 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1156 push @deferred_updates, "delete $gdrlast";
1157 push @deferred_update_messages, "Recorded current head for preservation";
1158 return ('deferred', undef);
1161 sub record_ffq_auto () {
1162 my ($status, $message) = record_ffq_prev_deferred();
1163 if ($status eq 'deferred' || $status eq 'exists') {
1165 snag $status, "could not record ffq-prev: $message";
1170 sub ffq_prev_info () {
1172 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1173 my ($status, $message, $current, $ffq_prev, $gdrlast)
1174 = ffq_prev_branchinfo();
1175 if ($status ne 'branch') {
1176 snag $status, "could not check ffq-prev: $message";
1179 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1180 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1183 sub stitch ($$$$$) {
1184 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1186 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1188 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1189 my $differs = get_differs $old_head, $ffq_prev_commitish;
1190 unless ($differs & ~D_PAT_ADD) {
1191 # ffq-prev is ahead of us, and the only tree changes it has
1192 # are possibly addition of things in debian/patches/.
1193 # Just wind forwards rather than making a pointless pseudomerge.
1194 push @deferred_updates,
1195 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1196 update_head_checkout $old_head, $ffq_prev_commitish,
1197 "stitch (fast forward)";
1202 # We make pseudomerges with L as the contributing parent.
1203 # This makes git rev-list --first-parent work properly.
1204 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1205 'Declare fast forward / record previous work',
1206 "[git-debrebase pseudomerge: $prose]",
1208 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1209 update_head $old_head, $new_head, "stitch: $prose";
1212 sub do_stitch ($;$) {
1213 my ($prose, $unclean) = @_;
1215 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1216 if (!$ffq_prev_commitish) {
1217 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1220 my $dangling_head = get_head();
1222 keycommits $dangling_head, $unclean,$unclean,$unclean;
1225 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1228 sub upstream_commitish_search ($$) {
1229 my ($upstream_version, $tried) = @_;
1230 # todo: at some point maybe use git-deborig to do this
1231 foreach my $tagpfx ('', 'v', 'upstream/') {
1232 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1233 my $new_upstream = git_get_ref "refs/tags/$tag";
1235 return $new_upstream if length $new_upstream;
1239 sub resolve_upstream_version ($$) {
1240 my ($new_upstream, $upstream_version) = @_;
1242 if (!defined $new_upstream) {
1244 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1245 if (!length $new_upstream) {
1246 fail "Could not determine appropriate upstream commitish.\n".
1247 " (Tried these tags: @tried)\n".
1248 " Check version, and specify upstream commitish explicitly.";
1251 $new_upstream = git_rev_parse $new_upstream;
1253 return $new_upstream;
1256 sub cmd_new_upstream () {
1257 # automatically and unconditionally launders before rebasing
1258 # if rebase --abort is used, laundering has still been done
1262 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1264 # parse args - low commitment
1265 my $spec_version = shift @ARGV;
1266 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1267 fail "bad version number \`$spec_version'" unless defined $new_version;
1268 if ($new_version->is_native()) {
1269 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1272 my $new_upstream = shift @ARGV;
1273 my $new_upstream_version = upstreamversion $new_version;
1275 resolve_upstream_version $new_upstream, $new_upstream_version;
1280 my ($n, @x) = @_; # may be ''
1281 my $pc = $pieces{$n} //= {
1283 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1285 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1290 my $newpiece = sub {
1291 my ($n, @x) = @_; # may be ''
1292 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1293 push @newpieces, $pc;
1298 New => $new_upstream,
1300 while (@ARGV && $ARGV[0] !~ m{^-}) {
1301 my $n = shift @ARGV;
1303 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1304 unless @ARGV && $ARGV[0] !~ m{^-};
1306 my $c = git_rev_parse shift @ARGV;
1307 die unless $n =~ m/^$extra_orig_namepart_re$/;
1308 $newpiece->($n, New => $c);
1311 # now we need to investigate the branch this generates the
1312 # laundered version but we don't switch to it yet
1313 my $old_head = get_head();
1314 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1316 my $old_bw_cl = classify $old_bw;
1317 my $old_anchor_cl = classify $old_anchor;
1319 if (!$old_anchor_cl->{OrigParents}) {
1320 snag 'anchor-treated',
1321 'old anchor is recognised due to --anchor, cannot check upstream';
1323 $old_upstream = parsecommit
1324 $old_anchor_cl->{OrigParents}[0]{CommitId};
1325 $piece->('', Old => $old_upstream->{CommitId});
1328 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1329 if ($old_upstream->{Msg} =~
1330 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1332 my @oldpieces = (split / /, $1);
1333 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1334 if ($old_n_parents != @oldpieces &&
1335 $old_n_parents != @oldpieces + 1) {
1336 snag 'upstream-confusing', sprintf
1337 "previous upstream combine %s".
1338 " mentions %d pieces (each implying one parent)".
1339 " but has %d parents".
1340 " (one per piece plus maybe a previous combine)",
1341 $old_upstream->{CommitId},
1342 (scalar @oldpieces),
1344 } elsif ($oldpieces[0] ne '.') {
1345 snag 'upstream-confusing', sprintf
1346 "previous upstream combine %s".
1347 " first piece is not \`.'",
1351 foreach my $i (0..$#oldpieces) {
1352 my $n = $oldpieces[$i];
1353 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1354 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1358 snag 'upstream-confusing',
1359 "previous upstream $old_upstream->{CommitId} is from".
1360 " git-debrebase but not an \`upstream-combine' commit";
1364 foreach my $pc (values %pieces) {
1365 if (!$old_upstream) {
1366 # we have complained already
1367 } elsif (!$pc->{Old}) {
1368 snag 'upstream-new-piece',
1369 "introducing upstream piece \`$pc->{Name}'";
1370 } elsif (!$pc->{New}) {
1371 snag 'upstream-rm-piece',
1372 "dropping upstream piece \`$pc->{Name}'";
1373 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1374 snag 'upstream-not-ff',
1375 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1379 printdebug "%pieces = ", (dd \%pieces), "\n";
1380 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1388 my @upstream_merge_parents;
1391 push @upstream_merge_parents, $old_upstream->{CommitId};
1394 foreach my $pc (@newpieces) { # always has '' first
1396 read_tree_subdir $pc->{Name}, $pc->{New};
1398 runcmd @git, qw(read-tree), $pc->{New};
1400 push @upstream_merge_parents, $pc->{New};
1403 # index now contains the new upstream
1405 if (@newpieces > 1) {
1406 # need to make the upstream subtree merge commit
1407 $new_upstream = make_commit \@upstream_merge_parents,
1408 [ "Combine upstreams for $new_upstream_version",
1409 ("[git-debrebase upstream-combine . ".
1410 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1415 # $new_upstream is either the single upstream commit, or the
1416 # combined commit we just made. Either way it will be the
1417 # "upstream" parent of the anchor merge.
1419 read_tree_subdir 'debian', "$old_bw:debian";
1421 # index now contains the anchor merge contents
1422 $new_bw = make_commit [ $old_bw, $new_upstream ],
1423 [ "Update to upstream $new_upstream_version",
1424 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1427 my $clogsignoff = cmdoutput qw(git show),
1428 '--pretty=format:%an <%ae> %aD',
1431 # Now we have to add a changelog stanza so the Debian version
1433 die if unlink "debian";
1434 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1435 unlink "debian/changelog" or $!==ENOENT or die $!;
1436 mkdir "debian" or die $!;
1437 open CN, ">", "debian/changelog" or die $!;
1438 my $oldclog = git_cat_file ":debian/changelog";
1439 $oldclog =~ m/^($package_re) \(\S+\) / or
1440 fail "cannot parse old changelog to get package name";
1442 print CN <<END, $oldclog or die $!;
1443 $p ($new_version) UNRELEASED; urgency=medium
1445 * Update to new upstream version $new_upstream_version.
1451 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1453 # Now we have the final new breakwater branch in the index
1454 $new_bw = make_commit [ $new_bw ],
1455 [ "Update changelog for new upstream $new_upstream_version",
1456 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1460 # we have constructed the new breakwater. we now need to commit to
1461 # the laundering output, because git-rebase can't easily be made
1462 # to make a replay list which is based on some other branch
1464 update_head_postlaunder $old_head, $old_laundered_tip,
1465 'launder for new upstream';
1467 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1468 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1469 "debrebase new-upstream $new_version: rebase";
1471 # now it's for the user to sort out
1474 sub cmd_record_ffq_prev () {
1475 badusage "no arguments allowed" if @ARGV;
1476 my ($status, $msg) = record_ffq_prev_deferred();
1477 if ($status eq 'exists' && $opt_noop_ok) {
1478 print "Previous head already recorded\n" or die $!;
1479 } elsif ($status eq 'deferred') {
1480 run_deferred_updates 'record-ffq-prev';
1482 fail "Could not preserve: $msg";
1487 badusage "no arguments allowed" if @ARGV;
1488 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1489 print "$bw\n" or die $!;
1492 sub cmd_breakwater () {
1493 badusage "no arguments allowed" if @ARGV;
1494 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1495 print "$bw\n" or die $!;
1499 badusage "no arguments allowed" if @ARGV;
1501 # todo: gdr status should print divergence info
1502 # todo: gdr status should print upstream component(s) info
1503 # todo: gdr should leave/maintain some refs with this kind of info ?
1505 my $oldest = { Badness => 0 };
1508 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1509 if ($oldest->{Badness} < $badness) {
1510 $oldest = $newest = undef;
1513 Badness => $badness,
1514 CommitId => $cl->{CommitId},
1518 $newest //= $oldest;
1520 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1521 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1522 sub { $note->(2, 'branch is unlaundered', @_); },
1523 sub { $note->(3, 'branch needs laundering', @_); },
1524 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1526 my $prcommitinfo = sub {
1528 flush STDOUT or die $!;
1529 runcmd @git, qw(--no-pager log -n1),
1530 '--pretty=format: %h %s%n',
1534 print "current branch contents, in git-debrebase terms:\n";
1535 if (!$oldest->{Badness}) {
1536 print " branch is laundered\n";
1538 print " $oldest->{OurMsg}\n";
1540 foreach my $info ($oldest, $newest) {
1541 my $cid = $info->{CommitId};
1542 next if $cid eq $printed;
1544 print " $info->{KcMsg}\n";
1545 $prcommitinfo->($cid);
1550 my ($cid, $what) = @_;
1551 if (!defined $cid) {
1552 print " $what is not well-defined\n";
1555 $prcommitinfo->($cid);
1558 print "key git-debrebase commits:\n";
1559 $prab->($anchor, 'anchor');
1560 $prab->($bw, 'breakwater');
1562 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1563 ffq_prev_branchinfo();
1565 print "branch and ref status, in git-debrebase terms:\n";
1567 print " $ffq_msg\n";
1569 $ffq_prev = git_get_ref $ffq_prev;
1570 $gdrlast = git_get_ref $gdrlast;
1572 print " unstitched; previous tip was:\n";
1573 $prcommitinfo->($ffq_prev);
1574 } elsif (!$gdrlast) {
1575 print " stitched? (no record of git-debrebase work)\n";
1576 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1577 print " stitched\n";
1579 print " not git-debrebase (diverged since last stitch)\n"
1582 print "you are currently rebasing\n" if currently_rebasing();
1586 my $prose = 'stitch';
1587 getoptions("stitch",
1588 'prose=s', \$prose);
1589 badusage "no arguments allowed" if @ARGV;
1590 do_stitch $prose, 0;
1592 sub cmd_prepush () { cmd_stitch(); }
1595 badusage "no arguments allowed" if @ARGV;
1596 do_launder_head 'launder for git-debrebase quick';
1600 sub cmd_conclude () {
1601 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1602 if (!$ffq_prev_commitish) {
1603 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1606 my $dangling_head = get_head();
1608 badusage "no arguments allowed" if @ARGV;
1609 do_launder_head 'launder for git-debrebase quick';
1614 if (currently_rebasing()) {
1615 runcmd @git, qw(rebase --abort);
1617 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1618 if (!$ffq_prev_commitish) {
1619 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1622 my $scrapping_head = get_head();
1623 badusage "no arguments allowed" if @ARGV;
1624 push @deferred_updates,
1625 "update $gdrlast $ffq_prev_commitish $git_null_obj",
1626 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
1628 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
1631 sub make_patches_staged ($) {
1633 # Produces the patches that would result from $head if it were
1635 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1638 gbp_pq_export 'bw', $secret_bw, $secret_head;
1642 sub make_patches ($) {
1644 keycommits $head, 0, \&snag;
1645 make_patches_staged $head;
1648 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1649 runcmd @git, qw(read-tree), $head;
1650 read_tree_subdir 'debian/patches', $ptree;
1651 $out = make_commit [$head], [
1652 'Commit patch queue (exported by git-debrebase)',
1653 '[git-debrebase: export and commit patches]',
1659 sub cmd_make_patches () {
1660 my $opt_quiet_would_amend;
1661 getoptions("make-patches",
1662 'quiet-would-amend!', \$opt_quiet_would_amend);
1663 badusage "no arguments allowed" if @ARGV;
1665 my $old_head = get_head();
1666 my $new = make_patches $old_head;
1667 my $d = get_differs $old_head, $new;
1669 fail "No (more) patches to export." unless $opt_noop_ok;
1671 } elsif ($d == D_PAT_ADD) {
1673 update_head_checkout $old_head, $new, 'make-patches';
1675 print STDERR failmsg
1676 "Patch export produced patch amendments".
1677 " (abandoned output commit $new).".
1678 " Try laundering first."
1679 unless $opt_quiet_would_amend;
1684 sub cmd_convert_from_gbp () {
1685 badusage "want only 1 optional argument, the upstream git commitish"
1688 my $clogp = parsechangelog();
1689 my $version = $clogp->{'Version'}
1690 // die "missing Version from changelog";
1692 my ($upstream_spec) = @ARGV;
1694 my $upstream_version = upstreamversion $version;
1696 resolve_upstream_version($upstream_spec, $upstream_version);
1698 my $old_head = get_head();
1700 my $upsdiff = get_differs $upstream, $old_head;
1701 if ($upsdiff & D_UPS) {
1702 runcmd @git, qw(--no-pager diff --stat),
1703 $upstream, $old_head,
1704 qw( -- :!/debian :/);
1706 upstream ($upstream_spec) and HEAD are not
1707 identical in upstream files. See diffstat above, or run
1708 git diff $upstream_spec HEAD -- :!/debian :/
1712 if (!is_fast_fwd $upstream, $old_head) {
1713 snag 'upstream-not-ancestor',
1714 "upstream ($upstream) is not an ancestor of HEAD";
1716 my $wrong = cmdoutput
1717 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1718 qw(-- :/ :!/debian));
1719 if (length $wrong) {
1720 snag 'unexpected-upstream-changes',
1721 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1722 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1726 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1727 snag 'upstream-has-debian',
1728 "upstream ($upstream) contains debian/ directory";
1731 my $previous_dgit_view = eval {
1732 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1734 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1735 my ($stz, $desc) = @_;
1736 no warnings qw(exiting);
1737 printdebug 'CHANGELOG ', Dumper($desc, $stz);
1738 next unless $stz->{Date};
1739 next unless $stz->{Distribution} ne 'UNRELEASED';
1740 $lvsn = $stz->{Version};
1741 $suite = $stz->{Distribution};
1744 die "neither of the first two changelog entries are released\n"
1745 unless defined $lvsn;
1746 print "last finished-looking changelog entry: ($lvsn) $suite\n";
1747 my $mtag_pat = debiantag_maintview $lvsn, '*';
1748 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1750 die "could not find suitable maintainer view tag $mtag_pat\n"
1751 unless $mtag_pat =~ m{/};
1752 is_fast_fwd $mtag, 'HEAD' or
1753 die "HEAD is not FF from maintainer tag $mtag!";
1754 my $dtag = "archive/$mtag";
1755 is_fast_fwd $mtag, $dtag or
1756 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1757 print "will stitch in dgit view, $dtag\n";
1758 git_rev_parse $dtag;
1760 if (!$previous_dgit_view) {
1763 print STDERR "cannot stitch in dgit view: $@\n";
1766 snags_maybe_bail_early();
1772 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1773 # make a branch out of the patch queue - we'll want this in a mo
1774 runcmd qw(gbp pq import);
1775 # strip the patches out
1776 runcmd @git, qw(checkout -q gdr-internal~0);
1777 rm_subdir_cached 'debian/patches';
1778 $work = make_commit ['HEAD'], [
1779 'git-debrebase convert-from-gbp: drop patches from tree',
1780 'Delete debian/patches, as part of converting to git-debrebase format.',
1781 '[git-debrebase convert-from-gbp: drop patches from tree]'
1783 # make the anchor merge
1784 # the tree is already exactly right
1785 $work = make_commit [$work, $upstream], [
1786 'git-debrebase import: declare upstream',
1787 'First breakwater merge.',
1788 '[git-debrebase anchor: declare upstream]'
1791 # rebase the patch queue onto the new breakwater
1792 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1793 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1794 $work = git_rev_parse 'HEAD';
1796 if ($previous_dgit_view) {
1797 $work = make_commit [$work, $previous_dgit_view], [
1798 'git-debrebase import: declare ff from dgit archive view',
1799 '[git-debrebase pseudomerge: import-from-gbp]',
1806 update_head_checkout $old_head, $work, 'convert-from-gbp';
1809 sub cmd_convert_to_gbp () {
1810 badusage "no arguments allowed" if @ARGV;
1811 my $head = get_head();
1812 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1813 keycommits $head, 0;
1815 make_patches_staged $head;
1817 $out = make_commit ['HEAD'], [
1818 'Commit patch queue (converted from git-debrebase format)',
1819 '[git-debrebase convert-to-gbp: commit patches]',
1823 push @deferred_updates, "delete $ffq";
1824 push @deferred_updates, "delete $gdrlast";
1827 update_head_checkout $head, $out, "convert to gbp (v0)";
1828 print <<END or die $!;
1829 git-debrebase: converted to git-buildpackage branch format
1830 git-debrebase: WARNING: do not now run "git-debrebase" any more
1831 git-debrebase: WARNING: doing so would drop all upstream patches!
1835 sub cmd_convert_from_dgit_view () {
1836 my $clogp = parsechangelog();
1838 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
1844 getoptions("convert-from-dgit-view",
1845 'diagnose!', \$diagnose,
1846 'build-products-dir:s', \$bpd,
1847 'origs!', \$do_origs,
1849 'always-convert-anyway!', \$always);
1850 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
1855 my $spec = shift @ARGV;
1856 my $commit = git_rev_parse "$spec^{commit}";
1857 push @upstreams, { Commit => $commit,
1858 Source => "$ARGV[0], from command line",
1863 my $head = get_head();
1867 my $trouble = sub { $troubles++; };
1868 keycommits $head, sub{}, sub{}, $trouble, $trouble;
1869 printdebug "troubles=$troubles\n";
1872 $us: Branch already seems to be in git-debrebase format!
1873 $us: --always-convert-anyway would do the conversion operation anyway
1874 $us: but is probably a bad idea. Probably, you wanted to do nothing.
1876 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
1881 snags_maybe_bail_early();
1883 my $version = upstreamversion $clogp->{Version};
1884 print STDERR "Considering possible commits corresponding to upstream:\n";
1889 my $ups_tag = upstream_commitish_search $version, \@tried;
1891 my $this = "git tag $tried[-1]";
1892 push @upstreams, { Commit => $ups_tag,
1897 " git tag: no suitable tag found (tried %s)\n",
1902 my $p = $clogp->{'Source'};
1903 # we do a quick check to see if there are plausible origs
1905 if (!opendir BPD, $bpd) {
1906 die "$bpd: opendir: $!" unless $!==ENOENT;
1908 while ($!=0, my $f = readdir BPD) {
1909 next unless is_orig_file_of_p_v $f, $p, $version;
1911 " orig: found what looks like a .orig, %s\n",
1916 die "read $bpd: $!" if $!;
1920 my $tree = cmdoutput
1921 @dgit, qw(--build-products-dir), $bpd,
1922 qw(print-unapplied-treeish);
1925 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
1926 rm_subdir_cached 'debian';
1927 $tree = cmdoutput @git, qw(write-tree);
1928 my $ups_synth = make_commit [], [ <<END, <<END,
1929 Import effective orig tree for upstream version $version
1931 This includes the contents of the .orig(s), minus any debian/ directory.
1933 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
1936 push @upstreams, { Commit => $ups_synth,
1937 Source => "orig(s) imported via dgit",
1942 " orig: no suitable origs found (looked for %s in %s)\n",
1943 "${p}_".(stripeoch $version)."...", $bpd;
1948 my $some_patches = stat_exists 'debian/patches/series';
1950 print STDERR "Evaluating possible commits corresponding to upstream:\n";
1953 foreach my $u (@upstreams) {
1957 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
1958 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
1959 runcmd @git, qw(clean -xdff);
1960 runcmd @git, qw(checkout), $head, qw(-- debian);
1961 if ($some_patches) {
1962 rm_subdir_cached 'debian/patches';
1963 $work = make_commit [ $work ], [
1964 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
1965 "Drop upstream changes, and delete debian/patches, as part of converting\n".
1966 "to git-debrebase format. Upstream changes will appear as commits.",
1967 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
1970 $work = make_commit [ $work, $u->{Commit} ], [
1971 'git-debrebase convert-from-dgit-view: declare upstream',
1972 '(Re)constructed breakwater merge.',
1973 '[git-debrebase anchor: declare upstream]'
1975 runcmd @git, qw(checkout --quiet -b mk), $work;
1976 if ($some_patches) {
1977 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
1978 runcmd @git, qw(reset --quiet);
1979 my @gbp_cmd = (qw(gbp pq import));
1981 my $gbp_err = "../gbp-pq-err";
1982 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
1984 my $r = system @gbp_cmd;
1987 " %s: couldn't apply patches: gbp pq %s",
1988 $u->{Source}, waitstatusmsg();
1992 my $work = git_rev_parse qw(HEAD);
1993 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
1994 if (length $diffout) {
1996 " $u->{Source}: applying patches gives different tree\n";
1997 print STDERR $diffout if $diagnose;
2001 $u->{Result} = $work;
2009 Could not find or construct a suitable upstream commit.
2010 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2011 upstream commmit explicitly or provide suitable origs.
2015 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2017 ffq_check $result->{Result};
2019 update_head_checkout $head, $result->{Result},
2020 'convert-from-dgit-view';
2023 sub cmd_downstream_rebase_launder_v0 () {
2024 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2026 $base = git_rev_parse $base;
2027 my $old_head = get_head();
2028 my $current = $old_head;
2031 if ($current eq $base) {
2032 $topmost_keep //= $current;
2033 print " $current BASE stop\n";
2036 my $cl = classify $current;
2037 print " $current $cl->{Type}";
2039 my $p0 = $cl->{Parents}[0]{CommitId};
2041 if ($cl->{Type} eq 'Pseudomerge') {
2042 print " ^".($cl->{Contributor}{Ix}+1);
2043 $next = $cl->{Contributor}{CommitId};
2044 } elsif ($cl->{Type} eq 'AddPatches' or
2045 $cl->{Type} eq 'Changelog') {
2055 $topmost_keep //= $current;
2057 die "to-be stripped changes not on top of the branch\n"
2062 if ($topmost_keep eq $old_head) {
2063 print "unchanged\n";
2065 print "updating to $topmost_keep\n";
2066 update_head_checkout
2067 $old_head, $topmost_keep,
2068 'downstream-rebase-launder-v0';
2074 "D+" => \$debuglevel,
2075 'noop-ok', => \$opt_noop_ok,
2076 'f=s' => \@snag_force_opts,
2077 'anchor=s' => \@opt_anchors,
2078 '--dgit=s' => \($dgit[0]),
2081 my ($opt,$val) = @_;
2082 badusage "git-debrebase: no cuddling to -i for git-rebase"
2084 die if $opt_defaultcmd_interactive; # should not happen
2085 $opt_defaultcmd_interactive = [ qw(-i) ];
2086 # This access to @ARGV is excessive familiarity with
2087 # Getopt::Long, but there isn't another sensible
2088 # approach. '-i=s{0,}' does not work with bundling.
2089 push @$opt_defaultcmd_interactive, @ARGV;
2092 'help' => sub { print $usage_message or die $!; finish 0; },
2095 initdebug('git-debrebase ');
2096 enabledebug if $debuglevel;
2098 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2099 chdir $toplevel or die "chdir $toplevel: $!";
2101 $rd = fresh_playground "$playprefix/misc";
2103 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2105 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2106 defaultcmd_rebase();
2108 my $cmd = shift @ARGV;
2111 $cmdfn = ${*::}{"cmd_$cmdfn"};
2113 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";