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 $debugcmd_when_debuglevel = 2;
41 our ($usage_message) = <<'END';
43 git-debrebase [<options>] [--|-i <git rebase options...>]
44 git-debrebase [<options>] status
45 git-debrebase [<options>] prepush [--prose=...]
46 git-debrebase [<options>] quick|conclude
47 git-debrebase [<options>] new-upstream <new-version> [<details ...>]
48 git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
50 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
53 our ($opt_force, $opt_noop_ok, @opt_anchors);
54 our ($opt_defaultcmd_interactive);
56 our $us = qw(git-debrebase);
62 print STDERR "$us: bad usage: $m\n";
68 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
69 GetOptions @_ or badusage $m;
73 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
77 my ($k, $optional) = @_;
79 my @cmd = qw(git config -z);
80 push @cmd, qw(--get-all) if wantarray;
82 my $out = cmdoutput_errok @cmd;
84 fail "missing required git config $k" unless $optional;
87 my @l = split /\0/, $out;
88 return wantarray ? @l : $l[0];
95 my $dd = new Data::Dumper [ $v ];
96 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
102 my $data = (git_cat_file $objid, 'commit');
103 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
107 sub D_UPS () { 0x02; } # upstream files
108 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
109 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
110 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
111 sub D_DEB_OTH () { 0x20; } # debian/changelog
112 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
114 our $playprefix = 'debrebase';
119 our @dgit = qw(dgit);
121 sub in_workarea ($) {
124 my $r = eval { $sub->(); };
125 { local $@; changedir $maindir; }
129 sub fresh_workarea () {
130 $workarea = fresh_playground "$playprefix/work";
131 in_workarea sub { playtree_setup };
134 our $snags_forced = 0;
135 our $snags_tripped = 0;
136 our $snags_summarised = 0;
137 our @deferred_updates;
138 our @deferred_update_messages;
140 sub all_snags_summarised () {
141 $snags_forced + $snags_tripped == $snags_summarised;
143 sub run_deferred_updates ($) {
146 confess 'dangerous internal error' unless all_snags_summarised();
148 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
149 debugcmd '>|', @upd_cmd;
150 open U, "|-", @upd_cmd or die $!;
151 foreach (@deferred_updates) {
152 printdebug ">= ", $_, "\n";
153 print U $_, "\n" or die $!;
156 close U or failedcmd @upd_cmd;
158 print $_, "\n" foreach @deferred_update_messages;
160 @deferred_updates = ();
161 @deferred_update_messages = ();
164 sub get_differs ($$) {
166 # This resembles quiltify_trees_differ, in dgit, a bit.
167 # But we don't care about modes, or dpkg-source-unrepresentable
168 # changes, and we don't need the plethora of different modes.
169 # Conversely we need to distinguish different kinds of changes to
170 # debian/ and debian/patches/.
175 my ($opts, $limits, $fn) = @_;
176 my @cmd = (@git, qw(diff-tree -z --no-renames));
178 push @cmd, "$_:" foreach $x, $y;
179 push @cmd, '--', @$limits;
180 my $diffs = cmdoutput @cmd;
181 foreach (split /\0/, $diffs) { $fn->(); }
184 $rundiff->([qw(--name-only)], [], sub {
185 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
188 if ($differs & DS_DEB) {
190 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
192 m{^debian/patches/} ? D_PAT_OTH :
193 $_ eq 'debian/changelog' ? D_DEB_CLOG :
196 die "mysterious debian changes $x..$y"
197 unless $differs & (D_PAT_OTH|DS_DEB);
200 if ($differs & D_PAT_OTH) {
202 $differs &= ~D_PAT_OTH;
204 $differs |= D_PAT_OTH;
205 no warnings qw(exiting); last;
207 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
208 no warnings qw(exiting);
209 if (!defined $mode) {
212 die unless s{^debian/patches/}{};
214 if ($mode eq 'A' && !m/\.series$/s) {
216 } elsif ($mode eq 'M' && $_ eq 'series') {
217 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
218 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
219 chomp $x_s; $x_s .= "\n";
220 $ok = $x_s eq substr($y_s, 0, length $x_s);
225 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
227 die "mysterious debian/patches changes $x..$y"
228 unless $differs & (D_PAT_ADD|D_PAT_OTH);
231 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
236 sub commit_pr_info ($) {
238 return Data::Dumper->dump([$r], [qw(commit)]);
241 sub calculate_committer_authline () {
242 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
243 'DUMMY COMMIT (git-debrebase)', "HEAD:";
244 my ($h,$m) = get_commit $c;
245 $h =~ m/^committer .*$/m or confess "($h) ?";
249 sub rm_subdir_cached ($) {
251 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
254 sub read_tree_subdir ($$) {
255 my ($subdir, $new_tree_object) = @_;
256 rm_subdir_cached $subdir;
257 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
260 sub read_tree_debian ($) {
262 read_tree_subdir 'debian', "$treeish:debian";
263 rm_subdir_cached 'debian/patches';
266 sub read_tree_upstream ($;$) {
267 my ($treeish, $keep_patches) = @_;
268 my $save = cmdoutput @git, qw(write-tree --prefix=debian/);
269 runcmd @git, qw(read-tree), $treeish;
270 read_tree_subdir 'debian', $save;
271 rm_subdir_cached 'debian/patches' unless $keep_patches;
274 sub make_commit ($$) {
275 my ($parents, $message_paras) = @_;
276 my $tree = cmdoutput @git, qw(write-tree);
277 my @cmd = (@git, qw(commit-tree), $tree);
278 push @cmd, qw(-p), $_ foreach @$parents;
279 push @cmd, qw(-m), $_ foreach @$message_paras;
280 return cmdoutput @cmd;
283 our @snag_force_opts;
285 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
286 if (grep { $_ eq $tag } @snag_force_opts) {
288 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
291 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
295 # Important: all mainline code must call snags_maybe_bail after
296 # any point where snag might be called, but before making changes
297 # (eg before any call to run_deferred_updates). snags_maybe_bail
298 # may be called more than once if necessary (but this is not ideal
299 # because then the messages about number of snags may be confusing).
300 sub snags_maybe_bail () {
301 return if all_snags_summarised();
304 "%s: snags: %d overriden by individual -f options\n",
307 if ($snags_tripped) {
310 "%s: snags: %d overriden by global --force\n",
314 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
318 $snags_summarised = $snags_forced + $snags_tripped;
320 sub snags_maybe_bail_early () {
321 # useful to bail out early without doing a lot of work;
322 # not a substitute for snags_maybe_bail.
323 snags_maybe_bail() if $snags_tripped && !$opt_force;
326 return $snags_forced || $snags_tripped;
329 sub gbp_pq_export ($$$) {
330 my ($bname, $base, $tip) = @_;
331 # must be run in a workarea. $bname and patch-queue/$bname
332 # ought not to exist. Leaves you on patch-queue/$bname with
333 # the patches staged but not committed.
334 printdebug "gbp_pq_export $bname $base $tip\n";
335 runcmd @git, qw(checkout -q -b), $bname, $base;
336 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
337 my @gbp_cmd = (qw(gbp pq export));
338 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
340 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
343 runcmd @git, qw(add -f debian/patches);
347 # xxx allow merge resolution separately from laundering, before git merge
349 # xxx general gdr docs highlight forbidden things
350 # xxx general gdr docs list allowable things ?
351 # xxx general gdr docs explicitly forbid some rebase
353 # xxx provide a way for the user to help
354 # xxx (eg, provide wreckage provide way to continue)
357 # use git-format-patch?
358 # our own patch identification algorithm?
359 # this is an alternative strategy
361 sub merge_series ($$;@) {
362 my ($newbase, $base_q, @input_qs) = @_;
363 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
364 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
365 # ^ specifies several patch series (currently we only support exactly 2)
366 # return value is a commit which is the result of
367 # merging the two versions of the same topic branch
368 # $input_q[0] and $input_q[1]
369 # with respect to the old version
373 # Creates, in *_q, a key MR for its private use
375 printdebug "merge_series newbase=$newbase\n";
377 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
378 $base_q->{MR}{S} = 'base';
381 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
382 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
383 # $prereq{<patch filename>} exists or not (even later)
387 local $workarea = fresh_playground "$playprefix/merge";
388 my $seriesfile = "debian/patches/series";
391 foreach my $q ($base_q, reverse @input_qs) {
393 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
394 if (open S, $seriesfile) {
396 while (my $patch = <S>) {
397 chomp $patch or die $!;
398 $prereq{$patch} //= {};
399 foreach my $earlier (@earlier) {
400 $prereq{$patch}{$earlier}{$s}++ and die;
402 push @earlier, $patch;
403 stat "debian/patches/$patch" or die "$patch ?";
405 S->error and die "$seriesfile $!";
408 die "$seriesfile $!" unless $!==ENOENT;
410 read_tree_upstream $newbase, 1;
411 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
412 "Convert $s to patch queue for merging",
413 "[git-debrebase merge-innards patch-queue import:".
416 printdebug "merge_series pec $pec ";
417 runcmd @git, qw(rm -q --cached), $seriesfile;
418 $pec = make_commit [ $pec ], [
419 "Drop series file from $s to avoid merge trouble",
420 "[git-debrebase merge-innards patch-queue prep:".
423 printdebug "pec' $pec\n";
424 runcmd @git, qw(reset -q --hard), $pec;
425 $q->{MR}{PEC} = $pec;
427 # now, because of reverse, we are on $input_q->{MR}{OQC}
428 runcmd @git, qw(checkout -q -b merge);
429 printdebug "merge_series merging...\n";
430 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
431 debugcmd '+', @mergecmd;
433 if (system @mergecmd) {
437 printdebug "merge_series merge ok, series...\n";
438 # We need to construct a new series file
439 # Firstly, resolve prereq
440 foreach my $f (sort keys %prereq) {
441 printdebug "merge_series patch\t$f\t";
442 if (!stat_exists "debian/patches/$f") {
443 print DEBUG " drop\n" if $debuglevel;
444 # git merge deleted it; that's how we tell it's not wanted
448 print DEBUG " keep\n" if $debuglevel;
449 foreach my $g (sort keys %{ $prereq{$f} }) {
450 my $gfp = $prereq{$f}{$g};
451 printdebug "merge_series prereq\t$f\t-> $g\t";
452 if (!!$gfp->{0} == !!$gfp->{1}
455 print DEBUG "\tkeep\n" if $debuglevel;
457 print DEBUG "\tdrop\n" if $debuglevel;
458 delete $prereq{$f}{$g};
465 return scalar keys %{ $prereq{$f} };
468 my $nodate = time + 1;
470 # $authordate{<patch filename>};
471 my $authordate = sub {
473 $authordate{$f} //= do {
474 open PF, "<", "debian/patches/$f" or die "$f $!";
476 return $nodate if m/^$/;
477 last if s{^Date: }{};
480 return cmdoutput qw(date +%s -d), $_;
484 open NS, '>', $seriesfile or die $!;
486 while (keys %prereq) {
488 foreach my $try (sort keys %prereq) {
491 $unsat->($try) <=> $unsat->($best) or
492 $authordate->($try) <=> $authordate->($best) or
498 printdebug "merge_series series next $best\n";
499 print NS "$best\n" or die $!;
500 delete $prereq{$best};
501 foreach my $gp (values %prereq) {
506 runcmd @git, qw(add), $seriesfile;
507 runcmd @git, qw(commit --quiet -m), 'Merged series';
509 printdebug "merge_series series gbp pq import\n";
510 runcmd qw(gbp pq import);
512 # OK now we are on patch-queue/merge, and we need to rebase
513 # onto the intended parent and drop the patches from each one
515 printdebug "merge_series series ok, building...\n";
516 my $build = $newbase;
517 my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
518 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
519 my $commit = git_cat_file $c, 'commit';
520 printdebug "merge_series series ok, building $c\n";
521 read_tree_upstream $c;
522 my $tree = cmdoutput @git, qw(write-tree);
523 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
524 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
525 open C, ">", "../mcommit" or die $!;
526 print C $commit or die $!;
528 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
531 runcmd @git, qw(update-ref refs/heads/result), $result;
533 runcmd @git, qw(checkout -q -b debug);
534 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
535 runcmd @git, qw(add .);
536 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
537 printdebug sprintf "merge_series done debug=%s\n",
538 git_rev_parse 'HEAD';
540 printdebug "merge_series returns $result\n";
544 # classify returns an info hash like this
546 # Hdr => # commit headers, including 1 final newline
547 # Msg => # commit message (so one newline is dropped)
549 # Type => (see below)
551 # Ix => $index # ie 0, 1, 2, ...
553 # Differs => return value from get_differs
555 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
557 # NewMsg => # commit message, but with any [dgit import ...] edited
558 # # to say "[was: ...]"
568 # has additional entres in classification result
569 # Overwritten = [ subset of Parents ]
570 # Contributor = $the_remaining_Parent
572 # DgitImportUnpatched
573 # has additional entry in classification result
574 # OrigParents = [ subset of Parents ]
577 # has additional entry in classification result
578 # OrigParents = [ subset of Parents ] # singleton list
585 # has additional entry in classification result
588 sub parsecommit ($;$) {
589 my ($objid, $p_ref) = @_;
590 # => hash with CommitId Hdr Msg Tree Parents
591 # Parents entries have only Ix CommitId
592 # $p_ref, if provided, must be [] and is used as a base for Parents
597 my ($h,$m) = get_commit $objid;
599 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
600 my (@ph) = $h =~ m/^parent (\w+)$/mg;
610 foreach my $ph (@ph) {
612 Ix => scalar @$p_ref,
624 my $r = parsecommit($objid, \@p);
628 $p->{Differs} = (get_differs $p->{CommitId}, $t),
631 printdebug "classify $objid \$t=$t \@p",
632 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
636 my ($type, @rest) = @_;
637 $r = { %$r, Type => $type, @rest };
639 printdebug " = $type ".(dd $r)."\n";
645 $r = { %$r, Type => qw(Unknown), Why => $why };
646 printdebug " ** Unknown\n";
650 if (grep { $_ eq $objid } @opt_anchors) {
651 return $classify->('TreatAsAnchor');
654 my @identical = grep { !$_->{Differs} } @p;
655 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
656 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
658 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
659 # multi-orig upstreams are represented with an anchor merge
660 # from a single upstream commit which combines the orig tarballs
662 # Every anchor tagged this way must be a merge.
663 # We are relying on the
664 # [git-debrebase anchor: ...]
665 # commit message annotation in "declare" anchor merges (which
666 # do not have any upstream changes), to distinguish those
667 # anchor merges from ordinary pseudomerges (which we might
668 # just try to strip).
670 # However, the user is going to be doing git-rebase a lot. We
671 # really don't want them to rewrite an anchor commit.
672 # git-rebase trips up on merges, so that is a useful safety
675 # BreakwaterStart commits are also anchors in the terminology
676 # of git-debrebase(5), but they are untagged (and always
677 # manually generated).
679 # We cannot not tolerate any tagged linear commit (ie,
680 # BreakwaterStart commits tagged `[anchor:') because such a
681 # thing could result from an erroneous linearising raw git
682 # rebase of a merge anchor. That would represent a corruption
683 # of the branch. and we want to detect and reject the results
684 # of such corruption before it makes it out anywhere. If we
685 # reject it here then we avoid making the pseudomerge which
686 # would be needed to push it.
688 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
689 @p == 2 or return $badanchor->("has other than two parents");
690 $haspatches and return $badanchor->("contains debian/patches");
692 # How to decide about l/r ordering of anchors ? git
693 # --topo-order prefers to expand 2nd parent first. There's
694 # already an easy rune to look for debian/ history anyway (git log
695 # debian/) so debian breakwater branch should be 1st parent; that
696 # way also there's also an easy rune to look for the upstream
697 # patches (--topo-order).
699 # Also this makes --first-parent be slightly more likely to
700 # be useful - it makes it provide a linearised breakwater history.
702 # Of course one can say somthing like
703 # gitk -- ':/' ':!/debian'
704 # to get _just_ the commits touching upstream files, and by
705 # the TREESAME logic in git-rev-list this will leave the
706 # breakwater into upstream at the first anchor. But that
707 # doesn't report debian/ changes at all.
709 # Other observations about gitk: by default, gitk seems to
710 # produce output in a different order to git-rev-list. I
711 # can't seem to find this documented anywhere. gitk
712 # --date-order DTRT. But, gitk always seems to put the
713 # parents from left to right, in order, so it's easy to see
714 # which way round a pseudomerge is.
716 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
717 $p[1]{Differs} & ~DS_DEB and
718 $badanchor->("upstream files differ from left parent");
719 $p[0]{Differs} & ~D_UPS and
720 $badanchor->("debian/ differs from right parent");
722 return $classify->(qw(Anchor),
723 OrigParents => [ $p[1] ]);
727 my $d = $r->{Parents}[0]{Differs};
728 if ($d == D_PAT_ADD) {
729 return $classify->(qw(AddPatches));
730 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
731 return $unknown->("edits debian/patches");
732 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
733 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
735 if ($d == D_DEB_CLOG) {
736 return $classify->(qw(Changelog));
738 return $classify->(qw(Packaging));
740 } elsif ($ty eq 'missing') {
741 return $classify->(qw(BreakwaterStart));
743 return $unknown->("parent's debian is not a directory");
745 } elsif ($d == D_UPS) {
746 return $classify->(qw(Upstream));
747 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
748 return $classify->(qw(Mixed));
750 return $unknown->("no changes");
752 confess "internal error $objid ?";
756 return $unknown->("origin commit");
759 if (@p == 2 && @identical == 1) {
760 my @overwritten = grep { $_->{Differs} } @p;
761 confess "internal error $objid ?" unless @overwritten==1;
762 return $classify->(qw(Pseudomerge),
763 Overwritten => [ $overwritten[0] ],
764 Contributor => $identical[0]);
766 if (@p == 2 && @identical == 2) {
768 my ($ph,$pm) = get_commit $_[0]{CommitId};
769 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
773 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
774 if ($order > 0) { # newer first
775 } elsif ($order < 0) {
776 @bytime = reverse @bytime;
778 # same age, default to order made by -s ours
779 # that is, commit was made by someone who preferred L
781 return $classify->(qw(Pseudomerge),
782 SubType => qw(Ambiguous),
783 Contributor => $bytime[0],
784 Overwritten => [ $bytime[1] ]);
787 my ($p_h, $p_m) = get_commit $p->{CommitId};
788 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
789 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
791 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
793 if (!(grep { !$_->{IsOrigin} } @p) and
794 (@orig_ps >= @p - 1) and
795 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
797 return $classify->(qw(DgitImportUnpatched),
798 OrigParents => \@orig_ps);
802 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
803 # xxx ^ metadata tag needs adding to (5)
804 return $classify->("MergedBreakwaters");
806 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
807 return $unknown->("unknown kind of merge from $1");
810 return $unknown->("octopus merge");
813 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
814 return $unknown->("general two-parent merge");
817 return $classify->("VanillaMerge");
820 sub keycommits ($;$$$$$);
822 sub mergedbreakwaters_anchor ($) {
825 foreach my $p (@{ $cl->{Parents} }) {
826 my ($panchor, $pbw) = keycommits $p->{CommitId},
827 undef,undef,undef,undef, 1;
828 $best_anchor = $panchor
829 if !defined $best_anchor
830 or is_fast_fwd $best_anchor, $panchor;
835 sub keycommits ($;$$$$$) {
836 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
837 # => ($anchor, $breakwater)
839 # $unclean->("unclean-$tagsfx", $msg, $cl)
840 # $furniture->("unclean-$tagsfx", $msg, $cl)
841 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
842 # is callled for each situation or commit that
843 # wouldn't be found in a laundered branch
844 # $furniture is for furniture commits such as might be found on an
845 # interchange branch (pseudomerge, d/patches, changelog)
846 # $trouble is for things whnich prevent the return of
847 # anchor and breakwater information; if that is ignored,
848 # then keycommits returns (undef, undef) instead.
849 # $fatal is for unprocessable commits, and should normally cause
850 # a failure. If ignored, agaion, (undef, undef) is returned.
852 # If $claimed_bw, this is supposed to be a breakwater commit.
854 # If a callback is undef, fail is called instead.
855 # If a callback is defined but false, the situation is ignored.
857 # no warnings qw(exiting); last;
858 # if the answer is no longer wanted.
860 my ($anchor, $breakwater);
861 $breakwater = $head if $claimed_bw;
865 $fatal //= sub { fail $_[1]; };
867 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
868 my $why = $mainwhy.$xwhy;
869 my $m = "branch needs laundering (run git-debrebase): $why";
870 fail $m unless defined $cb;
872 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
874 my $found_anchor = sub {
876 $breakwater //= $clogonly;
877 $breakwater //= $head;
878 no warnings qw(exiting);
882 $cl = classify $head;
883 my $ty = $cl->{Type};
884 if ($ty eq 'Packaging') {
885 $breakwater //= $clogonly;
886 $breakwater //= $head;
887 } elsif ($ty eq 'Changelog') {
888 # this is going to count as the tip of the breakwater
889 # only if it has no upstream stuff before it
891 } elsif ($ty eq 'Anchor' or
892 $ty eq 'TreatAsAnchor' or
893 $ty eq 'BreakwaterStart') {
894 $found_anchor->($head);
895 } elsif ($ty eq 'Upstream') {
896 $x->($unclean, 'ordering',
897 "packaging change ($breakwater) follows upstream change"," (eg $head)")
898 if defined $breakwater;
901 } elsif ($ty eq 'Mixed') {
902 $x->($unclean, 'mixed',
903 "found mixed upstream/packaging commit"," ($head)");
906 } elsif ($ty eq 'Pseudomerge' or
907 $ty eq 'AddPatches') {
909 $x->($furniture, (lc $ty),
910 "found interchange bureaucracy commit ($ty)"," ($head)");
911 } elsif ($ty eq 'DgitImportUnpatched') {
913 $x->($trouble, 'dgitimport',
914 "found dgit dsc import"," ($head)");
915 return (undef,undef);
917 $x->($fatal, 'unprocessable',
918 "found bare dgit dsc import with no prior history",
920 return (undef,undef);
922 } elsif ($ty eq 'VanillaMerge') {
923 $x->($trouble, 'vanillamerge',
924 "found vanilla merge"," ($head)");
925 return (undef,undef);
926 } elsif ($ty eq 'MergedBreakwaters') {
927 $found_anchor->(mergedbreakwaters_anchor $cl);
929 $x->($fatal, 'unprocessable',
930 "found unprocessable commit, cannot cope: $cl->{Why}",
932 return (undef,undef);
934 $head = $cl->{Parents}[0]{CommitId};
936 return ($anchor, $breakwater);
942 $nogenerate,$report, $report_lprefix) = @_;
943 # => ($tip, $breakwater_tip, $last_anchor)
944 # (or nothing, if $nogenerate)
946 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
947 $report_lprefix //= '';
949 # go through commits backwards
950 # we generate two lists of commits to apply:
951 # breakwater branch and upstream patches
952 my (@brw_cl, @upp_cl, @processed);
959 my ($prose, $info) = @_;
963 $ms .= "\n\n[git-debrebase$info: $prose]\n";
966 my $rewrite_from_here = sub {
968 my $sp_cl = { SpecialMethod => 'StartRewrite' };
970 push @processed, $sp_cl;
975 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
978 return unless $report;
979 print $report $prdelim, $report_lprefix, @_;
983 my $bomb = sub { # usage: return $bomb->();
984 print $report " Unprocessable" if $report;
985 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
988 return (undef,undef);
990 fail "found unprocessable commit, cannot cope".
991 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
992 " (commit $cur) (d.".
993 (join ' ', map { sprintf "%#x", $_->{Differs} }
994 @{ $cl->{Parents} }).
1001 my $build_start = sub {
1002 my ($msg, $parent) = @_;
1005 no warnings qw(exiting); last;
1009 fail "something useful about failed merge attempt @_ xxx".Dumper($cl);
1015 $cl = classify $cur;
1016 my $ty = $cl->{Type};
1017 my $st = $cl->{SubType};
1018 $prline->("$cl->{CommitId} $cl->{Type}");
1019 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1020 push @processed, $cl;
1021 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1022 if ($ty eq 'AddPatches') {
1024 $rewrite_from_here->(\@upp_cl);
1026 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1030 } elsif ($ty eq 'BreakwaterStart') {
1031 $last_anchor = $cur;
1032 $build_start->('FirstPackaging', $cur);
1033 } elsif ($ty eq 'Upstream') {
1037 } elsif ($ty eq 'Mixed') {
1040 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1043 $queue->(\@brw_cl, "debian");
1044 $queue->(\@upp_cl, "upstream");
1045 $rewrite_from_here->(\@brw_cl);
1048 } elsif ($ty eq 'Pseudomerge') {
1049 my $contrib = $cl->{Contributor}{CommitId};
1050 print $report " Contributor=$contrib" if $report;
1051 push @pseudomerges, $cl;
1052 $rewrite_from_here->(\@upp_cl);
1055 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1056 $last_anchor = $cur;
1057 $build_start->("Anchor", $cur);
1058 } elsif ($ty eq 'DgitImportUnpatched') {
1059 my $pm = $pseudomerges[-1];
1061 # To an extent, this is heuristic. Imports don't have
1062 # a useful history of the debian/ branch. We assume
1063 # that the first pseudomerge after an import has a
1064 # useful history of debian/, and ignore the histories
1065 # from later pseudomerges. Often the first pseudomerge
1066 # will be the dgit import of the upload to the actual
1067 # suite intended by the non-dgit NMUer, and later
1068 # pseudomerges may represent in-archive copies.
1069 my $ovwrs = $pm->{Overwritten};
1070 printf $report " PM=%s \@Overwr:%d",
1071 $pm->{CommitId}, (scalar @$ovwrs)
1074 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1077 my $ovwr = $ovwrs->[0]{CommitId};
1078 printf $report " Overwr=%s", $ovwr if $report;
1079 # This import has a tree which is just like a
1080 # breakwater tree, but it has the wrong history. It
1081 # ought to have the previous breakwater (which the
1082 # pseudomerge overwrote) as an ancestor. That will
1083 # make the history of the debian/ files correct. As
1084 # for the upstream version: either it's the same as
1085 # was ovewritten (ie, same as the previous
1086 # breakwater), in which case that history is precisely
1087 # right; or, otherwise, it was a non-gitish upload of a
1088 # new upstream version. We can tell these apart by
1089 # looking at the tree of the supposed upstream.
1092 SpecialMethod => 'DgitImportDebianUpdate',
1093 $xmsg->("convert dgit import: debian changes")
1096 SpecialMethod => 'DgitImportUpstreamUpdate',
1097 $xmsg->("convert dgit import: upstream update",
1100 $prline->(" Import");
1101 $rewrite_from_here->(\@brw_cl);
1102 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1106 # Everything is from this import. This kind of import
1107 # is already nearly in valid breakwater format, with the
1108 # patches as commits. Unfortunately it contains
1110 printdebug "*** WALK BOMB bare dgit import\n";
1111 $cl->{Why} = "bare dgit dsc import";
1115 } elsif ($ty eq 'VanillaMerge' or $ty eq 'MergedBreakwaters') {
1116 # User may have merged unstitched branch(es). We will
1117 # have now lost what ffq-prev was then (since the later
1118 # pseudomerge may introduce further changes). The effect
1119 # of resolving such a merge is that we may have to go back
1120 # further in history to find a merge base, since the one
1121 # which was reachable via ffq-prev is no longer findable.
1122 # This is suboptimal, but if it all works we'll have done
1124 # xxx we should warn the user in the docs about this
1128 # We expect to find a dominating anchor amongst the
1129 # inputs' anchors. That will be the new anchor.
1131 # More complicated is finding a merge base for the
1132 # breakwaters. We need a merge base that is a breakwater
1133 # commit. The ancestors of breakwater commits are more
1134 # breakwater commits and possibly upstream commits and the
1135 # ancestors of those upstream. Upstreams might have
1136 # arbitrary ancestors. But any upstream commit U is
1137 # either included in both anchors, in which case the
1138 # earlier anchor is a better merge base than any of U's
1139 # ancestors; or U is not included in the older anchor, in
1140 # which case U is not an ancestor of the vanilla merge at
1141 # all. So no upstream commit, nor any ancestor thereof,
1142 # is a best merge base. As for non-breakwater Debian
1143 # commits: these are never ancestors of any breakwater.
1145 # So any best merge base as found by git-merge-base
1146 # is a suitable breakwater anchor. Usually there will
1149 printdebug "*** MERGE\n";
1151 # xxx avoid calling walk without nogenerate when
1152 # we have a MergedBreakwater; instead call keycommits ?
1154 my @bwbcmd = (@git, qw(merge-base));
1155 my @ibcmd = (@git, qw(merge-base --all));
1156 my $might_be_in_bw = 1;
1158 my $ps = $cl->{Parents};
1160 foreach my $p (@$ps) {
1161 $prline->(" VanillaMerge ".$p->{Ix});
1163 my ($ptip, $pbw, $panchor) =
1164 walk $p->{CommitId}, 0, $report,
1165 $report_lprefix.' ';
1166 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1167 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1168 $p->{Anchor} = $panchor;
1170 $best_anchor = $panchor if
1171 !defined $best_anchor or
1172 is_fast_fwd $best_anchor, $panchor;
1174 printdebug " MERGE BA best=".($best_anchor//'-').
1178 foreach my $p (@$ps) {
1179 $prline->(" VanillaMerge ".$p->{Ix});
1180 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1181 $nomerge->('DivergentAnchor');
1182 } elsif ($p->{Anchor} eq $best_anchor) {
1183 print $report " SameAnchor" if $report;
1185 print $report " SupersededAnchor" if $report;
1187 if ($p->{Breakwater} eq $p->{CommitId}) {
1188 # this parent commit was its own breakwater,
1189 # ie it is part of the breakwater
1190 print $report " Breakwater" if $report;
1192 $might_be_in_bw = 0;
1194 push @bwbcmd, $p->{Breakwater};
1195 push @ibcmd, $p->{CommitId};
1198 if ($ok && $might_be_in_bw) {
1199 $prline->(" VanillaMerge MergedBreakwaters");
1200 $last_anchor = $best_anchor;
1201 $build_start->('MergedBreakwaters', $cur);
1204 $nomerge->("alleged merged-breakwater is not a breakwater")
1205 unless $ty eq 'VanillaMerge';
1207 my $bwb = cmdoutput @bwbcmd;
1209 # OK, now we have a breakwater base, but we need the merge
1210 # base for the interchange branch because we need the delta
1213 # This a the best merge base of our inputs which has the
1214 # breakwater merge base as an ancestor.
1217 grep { is_fast_fwd $bwb, $_ }
1222 or $nomerge->("no suitable interchange merge base");
1224 $prline->(" VanillaMerge Base");
1226 my ($btip, $bbw, $banchor) =
1227 walk $ib, 0, $report, $report_lprefix.' ';
1229 my $ibinfo = { SeriesTip => $btip,
1231 Anchor => $banchor };
1233 or $nomerge->("interchange merge-base ($ib)'s".
1234 " breakwater ($bbw)".
1235 " != breakwaters' merge-base ($bwb)");
1236 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1237 or $nomerge->("interchange merge-base ($ib)'s".
1238 " anchor ($ibinfo->{SeriesBase})".
1239 " != any merge input's anchor (".
1240 (join ' ', map { $_->{Anchor} } @$ps).
1244 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1245 $cl->{MergeBestAnchor} = $best_anchor;
1248 SpecialMethod => 'MergeCreateMergedBreakwaters',
1249 $xmsg->('constructed from vanilla merge',
1250 ' merged-breakwater'),
1254 SpecialMethod => 'MergeMergeSeries',
1256 $build_start->('MergeBreakwaters', $cur);
1258 printdebug "*** WALK BOMB unrecognised\n";
1264 printdebug "*** WALK prep done cur=$cur".
1265 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1267 return if $nogenerate;
1269 # Now we build it back up again
1275 $#upp_cl = $upp_limit if defined $upp_limit;
1277 my $committer_authline = calculate_committer_authline();
1279 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1281 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1284 mkdir $rd or $!==EEXIST or die $!;
1286 runcmd @git, qw(read-tree), $build;
1287 foreach my $cl (qw(Debian), (reverse @brw_cl),
1288 { SpecialMethod => 'RecordBreakwaterTip' },
1289 qw(Upstream), (reverse @upp_cl)) {
1291 $current_method = $cl;
1294 my $method = $cl->{SpecialMethod} // $current_method;
1295 my @parents = ($build);
1296 my $cltree = $cl->{CommitId};
1297 printdebug "WALK BUILD ".($cltree//'undef').
1298 " $method (rewriting=$rewriting)\n";
1299 if ($method eq 'Debian') {
1300 read_tree_debian($cltree);
1301 } elsif ($method eq 'Upstream') {
1302 read_tree_upstream($cltree);
1303 } elsif ($method eq 'StartRewrite') {
1306 } elsif ($method eq 'RecordBreakwaterTip') {
1307 $breakwater = $build;
1309 } elsif ($method eq 'DgitImportDebianUpdate') {
1310 read_tree_debian($cltree);
1311 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1312 confess unless $rewriting;
1313 my $differs = (get_differs $build, $cltree);
1314 next unless $differs & D_UPS;
1315 read_tree_upstream($cltree);
1316 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1317 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1318 print "Found a general merge, will try to tidy it up.\n";
1320 read_tree_upstream($cl->{MergeBestAnchor});
1321 read_tree_upstream($cl->{MergeBestAnchor});
1322 read_tree_debian($cltree);
1323 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1324 } elsif ($method eq 'MergeMergeSeries') {
1325 print "Running merge resolution for $cl->{CommitId}...\n";
1326 $build = merge_series
1328 $cl->{MergeInterchangeBaseInfo},
1329 @{ $cl->{Parents} };
1330 $last_anchor = $cl->{MergeBestAnchor};
1331 my $check_differs = get_differs $build, $cl->{CommitId};
1332 # Breakwater changes which were in each side of the
1333 # merge should be in MergeCreateMergedBreakwaters
1334 # output. Upstream changes are exactly the result
1335 # of merge_series. So the only difference should
1336 # be potential laundry results.
1338 "merge misresolved: tree is not the same (%s %s d.%#x)",
1339 $cl->{CommitId}, $build, $check_differs)
1340 if $check_differs & ~D_PAT_ADD;
1341 print "Merge resolution successful.\n";
1344 confess "$method ?";
1347 my $procd = (pop @processed) // 'UNDEF';
1348 if ($cl ne $procd) {
1350 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1353 my $newtree = cmdoutput @git, qw(write-tree);
1354 my $ch = $cl->{Hdr};
1355 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1356 $ch =~ s{^parent .*\n}{}mg;
1357 $ch =~ s{(?=^author)}{
1358 join '', map { "parent $_\n" } @parents
1359 }me or confess "$ch ?";
1361 $ch =~ s{^committer .*$}{$committer_authline}m
1364 my $cf = "$rd/m$rewriting";
1365 open CD, ">", $cf or die $!;
1366 print CD $ch, "\n", $cl->{Msg} or die $!;
1368 my @cmd = (@git, qw(hash-object));
1369 push @cmd, qw(-w) if $rewriting;
1370 push @cmd, qw(-t commit), $cf;
1371 my $newcommit = cmdoutput @cmd;
1372 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1373 $build = $newcommit;
1374 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1375 $last_anchor = $cur;
1380 my $final_check = get_differs $build, $input;
1381 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1382 if $final_check & ~D_PAT_ADD;
1384 my @r = ($build, $breakwater, $last_anchor);
1385 printdebug "*** WALK RETURN @r\n";
1390 git_check_unmodified();
1391 return git_rev_parse qw(HEAD);
1394 sub update_head ($$$) {
1395 my ($old, $new, $mrest) = @_;
1396 push @deferred_updates, "update HEAD $new $old";
1397 run_deferred_updates $mrest;
1400 sub update_head_checkout ($$$) {
1401 my ($old, $new, $mrest) = @_;
1402 update_head $old, $new, $mrest;
1403 runcmd @git, qw(reset --hard);
1406 sub update_head_postlaunder ($$$) {
1407 my ($old, $tip, $reflogmsg) = @_;
1408 return if $tip eq $old;
1409 print "git-debrebase: laundered (head was $old)\n";
1410 update_head $old, $tip, $reflogmsg;
1411 # no tree changes except debian/patches
1412 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1415 sub currently_rebasing() {
1416 foreach (qw(rebase-merge rebase-apply)) {
1417 return 1 if stat_exists "$maindir_gitdir/$_";
1422 sub bail_if_rebasing() {
1423 fail "you are in the middle of a git-rebase already"
1424 if currently_rebasing();
1427 sub do_launder_head ($) {
1428 my ($reflogmsg) = @_;
1429 my $old = get_head();
1431 my ($tip,$breakwater) = walk $old;
1433 update_head_postlaunder $old, $tip, $reflogmsg;
1434 return ($tip,$breakwater);
1437 sub cmd_launder_v0 () {
1438 badusage "no arguments to launder-v0 allowed" if @ARGV;
1439 my $old = get_head();
1440 my ($tip,$breakwater,$last_anchor) = walk $old;
1441 update_head_postlaunder $old, $tip, 'launder';
1442 printf "# breakwater tip\n%s\n", $breakwater;
1443 printf "# working tip\n%s\n", $tip;
1444 printf "# last anchor\n%s\n", $last_anchor;
1447 sub defaultcmd_rebase () {
1448 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1449 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1450 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1453 sub cmd_analyse () {
1454 badusage "analyse does not support any options"
1455 if @ARGV and $ARGV[0] =~ m/^-/;
1456 badusage "too many arguments to analyse" if @ARGV>1;
1459 $old = git_rev_parse $old;
1461 $old = git_rev_parse 'HEAD';
1463 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1464 STDOUT->error and die $!;
1467 sub ffq_prev_branchinfo () {
1468 my $current = git_get_symref();
1469 return gdr_ffq_prev_branchinfo($current);
1472 sub ffq_check ($;$$) {
1473 # calls $ff and/or $notff zero or more times
1474 # then returns either (status,message) where status is
1479 # or (undef,undef, $ffq_prev,$gdrlast)
1480 # $ff and $notff are called like this:
1481 # $ff->("message for stdout\n");
1482 # $notff->('snag-name', $message);
1483 # normally $currentval should be HEAD
1484 my ($currentval, $ff, $notff) =@_;
1486 $ff //= sub { print $_[0] or die $!; };
1489 my ($status, $message, $current, $ffq_prev, $gdrlast)
1490 = ffq_prev_branchinfo();
1491 return ($status, $message) unless $status eq 'branch';
1493 my $exists = git_get_ref $ffq_prev;
1494 return ('exists',"$ffq_prev already exists") if $exists;
1496 return ('not-branch', 'HEAD symref is not to refs/heads/')
1497 unless $current =~ m{^refs/heads/};
1500 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1503 printdebug "ffq check_specs @check_specs\n";
1506 my ($lrref, $desc) = @_;
1507 printdebug "ffq might check $lrref ($desc)\n";
1509 for my $chk (@check_specs) {
1511 $invert = $glob =~ s{^[!^]}{};
1512 last if fnmatch $glob, $lrref;
1515 my $lrval = git_get_ref $lrref;
1516 return unless length $lrval;
1518 if (is_fast_fwd $lrval, $currentval) {
1519 $ff->("OK, you are ahead of $lrref\n");
1520 $checked{$lrref} = 1;
1521 } elsif (is_fast_fwd $currentval, $lrval) {
1522 $checked{$lrref} = -1;
1523 $notff->('behind', "you are behind $lrref, divergence risk");
1525 $checked{$lrref} = -1;
1526 $notff->('diverged', "you have diverged from $lrref");
1530 my $merge = cfg "branch.$branch.merge",1;
1531 if (defined $merge and $merge =~ m{^refs/heads/}) {
1533 printdebug "ffq merge $rhs\n";
1534 my $check_remote = sub {
1535 my ($remote, $desc) = @_;
1536 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1537 return unless defined $remote;
1538 $check->("refs/remotes/$remote/$rhs", $desc);
1540 $check_remote->((scalar cfg "branch.$branch.remote",1),
1541 'remote fetch/merge branch');
1542 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1543 (scalar cfg "branch.$branch.pushDefault",1),
1544 'remote push branch');
1546 if ($branch =~ m{^dgit/}) {
1547 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1548 } elsif ($branch =~ m{^master$}) {
1549 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1551 return (undef, undef, $ffq_prev, $gdrlast);
1554 sub record_ffq_prev_deferred () {
1555 # => ('status', "message")
1557 # deferred message is undef
1562 # if not ff from some branch we should be ff from, is an snag
1563 # if "deferred", will have added something about that to
1564 # @deferred_update_messages, and also maybe printed (already)
1565 # some messages about ff checks
1567 my $currentval = get_head();
1569 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1570 return ($status,$message) if defined $status;
1574 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1575 push @deferred_updates, "delete $gdrlast";
1576 push @deferred_update_messages, "Recorded previous head for preservation";
1577 return ('deferred', undef);
1580 sub record_ffq_auto () {
1581 my ($status, $message) = record_ffq_prev_deferred();
1582 if ($status eq 'deferred' || $status eq 'exists') {
1584 snag $status, "could not record ffq-prev: $message";
1589 sub ffq_prev_info () {
1591 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1592 my ($status, $message, $current, $ffq_prev, $gdrlast)
1593 = ffq_prev_branchinfo();
1594 if ($status ne 'branch') {
1595 snag $status, "could not check ffq-prev: $message";
1598 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1599 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1602 sub stitch ($$$$$) {
1603 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1605 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1607 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1608 my $differs = get_differs $old_head, $ffq_prev_commitish;
1609 unless ($differs & ~D_PAT_ADD) {
1610 # ffq-prev is ahead of us, and the only tree changes it has
1611 # are possibly addition of things in debian/patches/.
1612 # Just wind forwards rather than making a pointless pseudomerge.
1613 push @deferred_updates,
1614 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1615 update_head_checkout $old_head, $ffq_prev_commitish,
1616 "stitch (fast forward)";
1621 # We make pseudomerges with L as the contributing parent.
1622 # This makes git rev-list --first-parent work properly.
1623 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1624 'Declare fast forward / record previous work',
1625 "[git-debrebase pseudomerge: $prose]",
1627 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1628 update_head $old_head, $new_head, "stitch: $prose";
1631 sub do_stitch ($;$) {
1632 my ($prose, $unclean) = @_;
1634 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1635 if (!$ffq_prev_commitish) {
1636 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1639 my $dangling_head = get_head();
1641 keycommits $dangling_head, $unclean,$unclean,$unclean;
1644 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1647 sub upstream_commitish_search ($$) {
1648 my ($upstream_version, $tried) = @_;
1649 # todo: at some point maybe use git-deborig to do this
1650 foreach my $tagpfx ('', 'v', 'upstream/') {
1651 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1652 my $new_upstream = git_get_ref "refs/tags/$tag";
1654 return $new_upstream if length $new_upstream;
1658 sub resolve_upstream_version ($$) {
1659 my ($new_upstream, $upstream_version) = @_;
1661 if (!defined $new_upstream) {
1663 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1664 if (!length $new_upstream) {
1665 fail "Could not determine appropriate upstream commitish.\n".
1666 " (Tried these tags: @tried)\n".
1667 " Check version, and specify upstream commitish explicitly.";
1670 $new_upstream = git_rev_parse $new_upstream;
1672 return $new_upstream;
1675 sub cmd_new_upstream () {
1676 # automatically and unconditionally launders before rebasing
1677 # if rebase --abort is used, laundering has still been done
1681 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1683 # parse args - low commitment
1684 my $spec_version = shift @ARGV;
1685 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1686 fail "bad version number \`$spec_version'" unless defined $new_version;
1687 if ($new_version->is_native()) {
1688 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1691 my $new_upstream = shift @ARGV;
1692 my $new_upstream_version = upstreamversion $new_version;
1694 resolve_upstream_version $new_upstream, $new_upstream_version;
1699 my ($n, @x) = @_; # may be ''
1700 my $pc = $pieces{$n} //= {
1702 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1704 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1709 my $newpiece = sub {
1710 my ($n, @x) = @_; # may be ''
1711 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1712 push @newpieces, $pc;
1717 New => $new_upstream,
1719 while (@ARGV && $ARGV[0] !~ m{^-}) {
1720 my $n = shift @ARGV;
1722 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1723 unless @ARGV && $ARGV[0] !~ m{^-};
1725 my $c = git_rev_parse shift @ARGV;
1726 die unless $n =~ m/^$extra_orig_namepart_re$/;
1727 $newpiece->($n, New => $c);
1730 # now we need to investigate the branch this generates the
1731 # laundered version but we don't switch to it yet
1732 my $old_head = get_head();
1733 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1735 my $old_bw_cl = classify $old_bw;
1736 my $old_anchor_cl = classify $old_anchor;
1738 if (!$old_anchor_cl->{OrigParents}) {
1739 snag 'anchor-treated',
1740 'old anchor is recognised due to --anchor, cannot check upstream';
1742 $old_upstream = parsecommit
1743 $old_anchor_cl->{OrigParents}[0]{CommitId};
1744 $piece->('', Old => $old_upstream->{CommitId});
1747 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1748 if ($old_upstream->{Msg} =~
1749 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1751 my @oldpieces = (split / /, $1);
1752 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1753 if ($old_n_parents != @oldpieces &&
1754 $old_n_parents != @oldpieces + 1) {
1755 snag 'upstream-confusing', sprintf
1756 "previous upstream combine %s".
1757 " mentions %d pieces (each implying one parent)".
1758 " but has %d parents".
1759 " (one per piece plus maybe a previous combine)",
1760 $old_upstream->{CommitId},
1761 (scalar @oldpieces),
1763 } elsif ($oldpieces[0] ne '.') {
1764 snag 'upstream-confusing', sprintf
1765 "previous upstream combine %s".
1766 " first piece is not \`.'",
1770 foreach my $i (0..$#oldpieces) {
1771 my $n = $oldpieces[$i];
1772 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1773 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1777 snag 'upstream-confusing',
1778 "previous upstream $old_upstream->{CommitId} is from".
1779 " git-debrebase but not an \`upstream-combine' commit";
1783 foreach my $pc (values %pieces) {
1784 if (!$old_upstream) {
1785 # we have complained already
1786 } elsif (!$pc->{Old}) {
1787 snag 'upstream-new-piece',
1788 "introducing upstream piece \`$pc->{Name}'";
1789 } elsif (!$pc->{New}) {
1790 snag 'upstream-rm-piece',
1791 "dropping upstream piece \`$pc->{Name}'";
1792 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1793 snag 'upstream-not-ff',
1794 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1798 printdebug "%pieces = ", (dd \%pieces), "\n";
1799 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1807 my @upstream_merge_parents;
1810 push @upstream_merge_parents, $old_upstream->{CommitId};
1813 foreach my $pc (@newpieces) { # always has '' first
1815 read_tree_subdir $pc->{Name}, $pc->{New};
1817 runcmd @git, qw(read-tree), $pc->{New};
1819 push @upstream_merge_parents, $pc->{New};
1822 # index now contains the new upstream
1824 if (@newpieces > 1) {
1825 # need to make the upstream subtree merge commit
1826 $new_upstream = make_commit \@upstream_merge_parents,
1827 [ "Combine upstreams for $new_upstream_version",
1828 ("[git-debrebase upstream-combine . ".
1829 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1834 # $new_upstream is either the single upstream commit, or the
1835 # combined commit we just made. Either way it will be the
1836 # "upstream" parent of the anchor merge.
1838 read_tree_subdir 'debian', "$old_bw:debian";
1840 # index now contains the anchor merge contents
1841 $new_bw = make_commit [ $old_bw, $new_upstream ],
1842 [ "Update to upstream $new_upstream_version",
1843 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1846 my $clogsignoff = cmdoutput qw(git show),
1847 '--pretty=format:%an <%ae> %aD',
1850 # Now we have to add a changelog stanza so the Debian version
1852 die if unlink "debian";
1853 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1854 unlink "debian/changelog" or $!==ENOENT or die $!;
1855 mkdir "debian" or die $!;
1856 open CN, ">", "debian/changelog" or die $!;
1857 my $oldclog = git_cat_file ":debian/changelog";
1858 $oldclog =~ m/^($package_re) \(\S+\) / or
1859 fail "cannot parse old changelog to get package name";
1861 print CN <<END, $oldclog or die $!;
1862 $p ($new_version) UNRELEASED; urgency=medium
1864 * Update to new upstream version $new_upstream_version.
1870 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1872 # Now we have the final new breakwater branch in the index
1873 $new_bw = make_commit [ $new_bw ],
1874 [ "Update changelog for new upstream $new_upstream_version",
1875 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1879 # we have constructed the new breakwater. we now need to commit to
1880 # the laundering output, because git-rebase can't easily be made
1881 # to make a replay list which is based on some other branch
1883 update_head_postlaunder $old_head, $old_laundered_tip,
1884 'launder for new upstream';
1886 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1887 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1888 "debrebase new-upstream $new_version: rebase";
1890 # now it's for the user to sort out
1893 sub cmd_record_ffq_prev () {
1894 badusage "no arguments allowed" if @ARGV;
1895 my ($status, $msg) = record_ffq_prev_deferred();
1896 if ($status eq 'exists' && $opt_noop_ok) {
1897 print "Previous head already recorded\n" or die $!;
1898 } elsif ($status eq 'deferred') {
1899 run_deferred_updates 'record-ffq-prev';
1901 fail "Could not preserve: $msg";
1906 badusage "no arguments allowed" if @ARGV;
1907 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1908 print "$bw\n" or die $!;
1911 sub cmd_breakwater () {
1912 badusage "no arguments allowed" if @ARGV;
1913 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1914 print "$bw\n" or die $!;
1918 badusage "no arguments allowed" if @ARGV;
1920 # todo: gdr status should print divergence info
1921 # todo: gdr status should print upstream component(s) info
1922 # todo: gdr should leave/maintain some refs with this kind of info ?
1924 my $oldest = { Badness => 0 };
1927 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1928 if ($oldest->{Badness} < $badness) {
1929 $oldest = $newest = undef;
1932 Badness => $badness,
1933 CommitId => $cl->{CommitId},
1937 $newest //= $oldest;
1939 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1940 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1941 sub { $note->(2, 'branch is unlaundered', @_); },
1942 sub { $note->(3, 'branch needs laundering', @_); },
1943 sub { $note->(4, 'branch not in git-debrebase form', @_); };
1945 my $prcommitinfo = sub {
1947 flush STDOUT or die $!;
1948 runcmd @git, qw(--no-pager log -n1),
1949 '--pretty=format: %h %s%n',
1953 print "current branch contents, in git-debrebase terms:\n";
1954 if (!$oldest->{Badness}) {
1955 print " branch is laundered\n";
1957 print " $oldest->{OurMsg}\n";
1959 foreach my $info ($oldest, $newest) {
1960 my $cid = $info->{CommitId};
1961 next if $cid eq $printed;
1963 print " $info->{KcMsg}\n";
1964 $prcommitinfo->($cid);
1969 my ($cid, $what) = @_;
1970 if (!defined $cid) {
1971 print " $what is not well-defined\n";
1974 $prcommitinfo->($cid);
1977 print "key git-debrebase commits:\n";
1978 $prab->($anchor, 'anchor');
1979 $prab->($bw, 'breakwater');
1981 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1982 ffq_prev_branchinfo();
1984 print "branch and ref status, in git-debrebase terms:\n";
1986 print " $ffq_msg\n";
1988 $ffq_prev = git_get_ref $ffq_prev;
1989 $gdrlast = git_get_ref $gdrlast;
1991 print " unstitched; previous tip was:\n";
1992 $prcommitinfo->($ffq_prev);
1993 } elsif (!$gdrlast) {
1994 print " stitched? (no record of git-debrebase work)\n";
1995 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1996 print " stitched\n";
1998 print " not git-debrebase (diverged since last stitch)\n"
2001 print "you are currently rebasing\n" if currently_rebasing();
2005 my $prose = 'stitch';
2006 getoptions("stitch",
2007 'prose=s', \$prose);
2008 badusage "no arguments allowed" if @ARGV;
2009 do_stitch $prose, 0;
2011 sub cmd_prepush () { cmd_stitch(); }
2014 badusage "no arguments allowed" if @ARGV;
2015 do_launder_head 'launder for git-debrebase quick';
2019 sub cmd_conclude () {
2020 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2021 if (!$ffq_prev_commitish) {
2022 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2025 my $dangling_head = get_head();
2027 badusage "no arguments allowed" if @ARGV;
2028 do_launder_head 'launder for git-debrebase quick';
2033 if (currently_rebasing()) {
2034 runcmd @git, qw(rebase --abort);
2036 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2037 if (!$ffq_prev_commitish) {
2038 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2041 my $scrapping_head = get_head();
2042 badusage "no arguments allowed" if @ARGV;
2043 push @deferred_updates,
2044 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2045 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2047 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2050 sub make_patches_staged ($) {
2052 # Produces the patches that would result from $head if it were
2054 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2057 gbp_pq_export 'bw', $secret_bw, $secret_head;
2061 sub make_patches ($) {
2063 keycommits $head, 0, \&snag;
2064 make_patches_staged $head;
2067 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2068 runcmd @git, qw(read-tree), $head;
2069 read_tree_subdir 'debian/patches', $ptree;
2070 $out = make_commit [$head], [
2071 'Commit patch queue (exported by git-debrebase)',
2072 '[git-debrebase: export and commit patches]',
2078 sub cmd_make_patches () {
2079 my $opt_quiet_would_amend;
2080 getoptions("make-patches",
2081 'quiet-would-amend!', \$opt_quiet_would_amend);
2082 badusage "no arguments allowed" if @ARGV;
2084 my $old_head = get_head();
2085 my $new = make_patches $old_head;
2086 my $d = get_differs $old_head, $new;
2088 fail "No (more) patches to export." unless $opt_noop_ok;
2090 } elsif ($d == D_PAT_ADD) {
2092 update_head_checkout $old_head, $new, 'make-patches';
2094 print STDERR failmsg
2095 "Patch export produced patch amendments".
2096 " (abandoned output commit $new).".
2097 " Try laundering first."
2098 unless $opt_quiet_would_amend;
2103 sub cmd_convert_from_gbp () {
2104 badusage "want only 1 optional argument, the upstream git commitish"
2107 my $clogp = parsechangelog();
2108 my $version = $clogp->{'Version'}
2109 // die "missing Version from changelog";
2111 my ($upstream_spec) = @ARGV;
2113 my $upstream_version = upstreamversion $version;
2115 resolve_upstream_version($upstream_spec, $upstream_version);
2117 my $old_head = get_head();
2119 my $upsdiff = get_differs $upstream, $old_head;
2120 if ($upsdiff & D_UPS) {
2121 runcmd @git, qw(--no-pager diff --stat),
2122 $upstream, $old_head,
2123 qw( -- :!/debian :/);
2125 upstream ($upstream_spec) and HEAD are not
2126 identical in upstream files. See diffstat above, or run
2127 git diff $upstream_spec HEAD -- :!/debian :/
2131 if (!is_fast_fwd $upstream, $old_head) {
2132 snag 'upstream-not-ancestor',
2133 "upstream ($upstream) is not an ancestor of HEAD";
2135 my $wrong = cmdoutput
2136 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2137 qw(-- :/ :!/debian));
2138 if (length $wrong) {
2139 snag 'unexpected-upstream-changes',
2140 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2141 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2145 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2146 snag 'upstream-has-debian',
2147 "upstream ($upstream) contains debian/ directory";
2150 my $previous_dgit_view = eval {
2151 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2153 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2154 my ($stz, $desc) = @_;
2155 no warnings qw(exiting);
2156 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2157 next unless $stz->{Date};
2158 next unless $stz->{Distribution} ne 'UNRELEASED';
2159 $lvsn = $stz->{Version};
2160 $suite = $stz->{Distribution};
2163 die "neither of the first two changelog entries are released\n"
2164 unless defined $lvsn;
2165 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2166 my $mtag_pat = debiantag_maintview $lvsn, '*';
2167 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2169 die "could not find suitable maintainer view tag $mtag_pat\n"
2170 unless $mtag_pat =~ m{/};
2171 is_fast_fwd $mtag, 'HEAD' or
2172 die "HEAD is not FF from maintainer tag $mtag!";
2173 my $dtag = "archive/$mtag";
2174 is_fast_fwd $mtag, $dtag or
2175 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2176 print "will stitch in dgit view, $dtag\n";
2177 git_rev_parse $dtag;
2179 if (!$previous_dgit_view) {
2182 print STDERR "cannot stitch in dgit view: $@\n";
2185 snags_maybe_bail_early();
2191 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2192 # make a branch out of the patch queue - we'll want this in a mo
2193 runcmd qw(gbp pq import);
2194 # strip the patches out
2195 runcmd @git, qw(checkout -q gdr-internal~0);
2196 rm_subdir_cached 'debian/patches';
2197 $work = make_commit ['HEAD'], [
2198 'git-debrebase convert-from-gbp: drop patches from tree',
2199 'Delete debian/patches, as part of converting to git-debrebase format.',
2200 '[git-debrebase convert-from-gbp: drop patches from tree]'
2202 # make the anchor merge
2203 # the tree is already exactly right
2204 $work = make_commit [$work, $upstream], [
2205 'git-debrebase import: declare upstream',
2206 'First breakwater merge.',
2207 '[git-debrebase anchor: declare upstream]'
2210 # rebase the patch queue onto the new breakwater
2211 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2212 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2213 $work = git_rev_parse 'HEAD';
2215 if ($previous_dgit_view) {
2216 $work = make_commit [$work, $previous_dgit_view], [
2217 'git-debrebase import: declare ff from dgit archive view',
2218 '[git-debrebase pseudomerge: import-from-gbp]',
2225 update_head_checkout $old_head, $work, 'convert-from-gbp';
2228 sub cmd_convert_to_gbp () {
2229 badusage "no arguments allowed" if @ARGV;
2230 my $head = get_head();
2231 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2232 keycommits $head, 0;
2234 make_patches_staged $head;
2236 $out = make_commit ['HEAD'], [
2237 'Commit patch queue (converted from git-debrebase format)',
2238 '[git-debrebase convert-to-gbp: commit patches]',
2242 push @deferred_updates, "delete $ffq";
2243 push @deferred_updates, "delete $gdrlast";
2246 update_head_checkout $head, $out, "convert to gbp (v0)";
2247 print <<END or die $!;
2248 git-debrebase: converted to git-buildpackage branch format
2249 git-debrebase: WARNING: do not now run "git-debrebase" any more
2250 git-debrebase: WARNING: doing so would drop all upstream patches!
2254 sub cmd_convert_from_dgit_view () {
2255 my $clogp = parsechangelog();
2257 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2263 getoptions("convert-from-dgit-view",
2264 'diagnose!', \$diagnose,
2265 'build-products-dir:s', \$bpd,
2266 'origs!', \$do_origs,
2268 'always-convert-anyway!', \$always);
2269 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2274 my $spec = shift @ARGV;
2275 my $commit = git_rev_parse "$spec^{commit}";
2276 push @upstreams, { Commit => $commit,
2277 Source => "$ARGV[0], from command line",
2282 my $head = get_head();
2286 my $trouble = sub { $troubles++; };
2287 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2288 printdebug "troubles=$troubles\n";
2291 $us: Branch already seems to be in git-debrebase format!
2292 $us: --always-convert-anyway would do the conversion operation anyway
2293 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2295 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2300 snags_maybe_bail_early();
2302 my $version = upstreamversion $clogp->{Version};
2303 print STDERR "Considering possible commits corresponding to upstream:\n";
2308 my $ups_tag = upstream_commitish_search $version, \@tried;
2310 my $this = "git tag $tried[-1]";
2311 push @upstreams, { Commit => $ups_tag,
2316 " git tag: no suitable tag found (tried %s)\n",
2321 my $p = $clogp->{'Source'};
2322 # we do a quick check to see if there are plausible origs
2324 if (!opendir BPD, $bpd) {
2325 die "$bpd: opendir: $!" unless $!==ENOENT;
2327 while ($!=0, my $f = readdir BPD) {
2328 next unless is_orig_file_of_p_v $f, $p, $version;
2330 " orig: found what looks like a .orig, %s\n",
2335 die "read $bpd: $!" if $!;
2339 my $tree = cmdoutput
2340 @dgit, qw(--build-products-dir), $bpd,
2341 qw(print-unapplied-treeish);
2344 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2345 rm_subdir_cached 'debian';
2346 $tree = cmdoutput @git, qw(write-tree);
2347 my $ups_synth = make_commit [], [ <<END, <<END,
2348 Import effective orig tree for upstream version $version
2350 This includes the contents of the .orig(s), minus any debian/ directory.
2352 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2355 push @upstreams, { Commit => $ups_synth,
2356 Source => "orig(s) imported via dgit",
2361 " orig: no suitable origs found (looked for %s in %s)\n",
2362 "${p}_".(stripeoch $version)."...", $bpd;
2367 my $some_patches = stat_exists 'debian/patches/series';
2369 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2372 foreach my $u (@upstreams) {
2376 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2377 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2378 runcmd @git, qw(clean -xdff);
2379 runcmd @git, qw(checkout), $head, qw(-- debian);
2380 if ($some_patches) {
2381 rm_subdir_cached 'debian/patches';
2382 $work = make_commit [ $work ], [
2383 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2384 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2385 "to git-debrebase format. Upstream changes will appear as commits.",
2386 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2389 $work = make_commit [ $work, $u->{Commit} ], [
2390 'git-debrebase convert-from-dgit-view: declare upstream',
2391 '(Re)constructed breakwater merge.',
2392 '[git-debrebase anchor: declare upstream]'
2394 runcmd @git, qw(checkout --quiet -b mk), $work;
2395 if ($some_patches) {
2396 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2397 runcmd @git, qw(reset --quiet);
2398 my @gbp_cmd = (qw(gbp pq import));
2400 my $gbp_err = "../gbp-pq-err";
2401 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2403 my $r = system @gbp_cmd;
2406 " %s: couldn't apply patches: gbp pq %s",
2407 $u->{Source}, waitstatusmsg();
2411 my $work = git_rev_parse qw(HEAD);
2412 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2413 if (length $diffout) {
2415 " $u->{Source}: applying patches gives different tree\n";
2416 print STDERR $diffout if $diagnose;
2420 $u->{Result} = $work;
2428 Could not find or construct a suitable upstream commit.
2429 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2430 upstream commmit explicitly or provide suitable origs.
2434 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2436 ffq_check $result->{Result};
2438 update_head_checkout $head, $result->{Result},
2439 'convert-from-dgit-view';
2442 sub cmd_downstream_rebase_launder_v0 () {
2443 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2445 $base = git_rev_parse $base;
2446 my $old_head = get_head();
2447 my $current = $old_head;
2450 if ($current eq $base) {
2451 $topmost_keep //= $current;
2452 print " $current BASE stop\n";
2455 my $cl = classify $current;
2456 print " $current $cl->{Type}";
2458 my $p0 = $cl->{Parents}[0]{CommitId};
2460 if ($cl->{Type} eq 'Pseudomerge') {
2461 print " ^".($cl->{Contributor}{Ix}+1);
2462 $next = $cl->{Contributor}{CommitId};
2463 } elsif ($cl->{Type} eq 'AddPatches' or
2464 $cl->{Type} eq 'Changelog') {
2474 $topmost_keep //= $current;
2476 die "to-be stripped changes not on top of the branch\n"
2481 if ($topmost_keep eq $old_head) {
2482 print "unchanged\n";
2484 print "updating to $topmost_keep\n";
2485 update_head_checkout
2486 $old_head, $topmost_keep,
2487 'downstream-rebase-launder-v0';
2493 "D+" => \$debuglevel,
2494 'noop-ok', => \$opt_noop_ok,
2495 'f=s' => \@snag_force_opts,
2496 'anchor=s' => \@opt_anchors,
2497 '--dgit=s' => \($dgit[0]),
2500 my ($opt,$val) = @_;
2501 badusage "git-debrebase: no cuddling to -i for git-rebase"
2503 die if $opt_defaultcmd_interactive; # should not happen
2504 $opt_defaultcmd_interactive = [ qw(-i) ];
2505 # This access to @ARGV is excessive familiarity with
2506 # Getopt::Long, but there isn't another sensible
2507 # approach. '-i=s{0,}' does not work with bundling.
2508 push @$opt_defaultcmd_interactive, @ARGV;
2511 'help' => sub { print $usage_message or die $!; finish 0; },
2514 initdebug('git-debrebase ');
2515 enabledebug if $debuglevel;
2517 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2518 chdir $toplevel or die "chdir $toplevel: $!";
2520 $rd = fresh_playground "$playprefix/misc";
2522 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2524 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2525 defaultcmd_rebase();
2527 my $cmd = shift @ARGV;
2530 $cmdfn = ${*::}{"cmd_$cmdfn"};
2532 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";