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 sub run_ref_updates_now ($$) {
135 my ($mrest, $updates) = @_;
136 # @$updates is a list of lines for git-update-ref, without \ns
138 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
139 debugcmd '>|', @upd_cmd;
140 open U, "|-", @upd_cmd or die $!;
141 foreach (@$updates) {
142 printdebug ">= ", $_, "\n";
143 print U $_, "\n" or die $!;
146 close U or failedcmd @upd_cmd;
149 our $snags_forced = 0;
150 our $snags_tripped = 0;
151 our $snags_summarised = 0;
152 our @deferred_updates;
153 our @deferred_update_messages;
155 sub all_snags_summarised () {
156 $snags_forced + $snags_tripped == $snags_summarised;
158 sub run_deferred_updates ($) {
161 confess 'dangerous internal error' unless all_snags_summarised();
163 run_ref_updates_now $mrest, \@deferred_updates;
164 print $_, "\n" foreach @deferred_update_messages;
166 @deferred_updates = ();
167 @deferred_update_messages = ();
170 sub get_differs ($$) {
172 # This resembles quiltify_trees_differ, in dgit, a bit.
173 # But we don't care about modes, or dpkg-source-unrepresentable
174 # changes, and we don't need the plethora of different modes.
175 # Conversely we need to distinguish different kinds of changes to
176 # debian/ and debian/patches/.
181 my ($opts, $limits, $fn) = @_;
182 my @cmd = (@git, qw(diff-tree -z --no-renames));
184 push @cmd, "$_:" foreach $x, $y;
185 push @cmd, '--', @$limits;
186 my $diffs = cmdoutput @cmd;
187 foreach (split /\0/, $diffs) { $fn->(); }
190 $rundiff->([qw(--name-only)], [], sub {
191 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
194 if ($differs & DS_DEB) {
196 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
198 m{^debian/patches/} ? D_PAT_OTH :
199 $_ eq 'debian/changelog' ? D_DEB_CLOG :
202 die "mysterious debian changes $x..$y"
203 unless $differs & (D_PAT_OTH|DS_DEB);
206 if ($differs & D_PAT_OTH) {
208 $differs &= ~D_PAT_OTH;
210 $differs |= D_PAT_OTH;
211 no warnings qw(exiting); last;
213 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
214 no warnings qw(exiting);
215 if (!defined $mode) {
218 die unless s{^debian/patches/}{};
220 if ($mode eq 'A' && !m/\.series$/s) {
222 } elsif ($mode eq 'M' && $_ eq 'series') {
223 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
224 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
225 chomp $x_s; $x_s .= "\n";
226 $ok = $x_s eq substr($y_s, 0, length $x_s);
231 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
233 die "mysterious debian/patches changes $x..$y"
234 unless $differs & (D_PAT_ADD|D_PAT_OTH);
237 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
242 sub commit_pr_info ($) {
244 return Data::Dumper->dump([$r], [qw(commit)]);
247 sub calculate_committer_authline () {
248 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
249 'DUMMY COMMIT (git-debrebase)', "HEAD:";
250 my ($h,$m) = get_commit $c;
251 $h =~ m/^committer .*$/m or confess "($h) ?";
255 sub rm_subdir_cached ($) {
257 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
260 sub read_tree_subdir ($$) {
261 my ($subdir, $new_tree_object) = @_;
262 rm_subdir_cached $subdir;
263 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
266 sub read_tree_debian ($) {
268 read_tree_subdir 'debian', "$treeish:debian";
269 rm_subdir_cached 'debian/patches';
272 sub read_tree_upstream ($;$$) {
273 my ($treeish, $keep_patches, $tree_with_debian) = @_;
274 # if $tree_with_debian is supplied, will use that for debian/
275 # otherwise will save and restore it.
277 $tree_with_debian ? "$tree_with_debian:debian"
278 : cmdoutput @git, qw(write-tree --prefix=debian/);
279 runcmd @git, qw(read-tree), $treeish;
280 read_tree_subdir 'debian', $debian;
281 rm_subdir_cached 'debian/patches' unless $keep_patches;
284 sub make_commit ($$) {
285 my ($parents, $message_paras) = @_;
286 my $tree = cmdoutput @git, qw(write-tree);
287 my @cmd = (@git, qw(commit-tree), $tree);
288 push @cmd, qw(-p), $_ foreach @$parents;
289 push @cmd, qw(-m), $_ foreach @$message_paras;
290 return cmdoutput @cmd;
293 our @snag_force_opts;
295 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
296 if (grep { $_ eq $tag } @snag_force_opts) {
298 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
301 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
305 # Important: all mainline code must call snags_maybe_bail after
306 # any point where snag might be called, but before making changes
307 # (eg before any call to run_deferred_updates). snags_maybe_bail
308 # may be called more than once if necessary (but this is not ideal
309 # because then the messages about number of snags may be confusing).
310 sub snags_maybe_bail () {
311 return if all_snags_summarised();
314 "%s: snags: %d overriden by individual -f options\n",
317 if ($snags_tripped) {
320 "%s: snags: %d overriden by global --force\n",
324 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
328 $snags_summarised = $snags_forced + $snags_tripped;
330 sub snags_maybe_bail_early () {
331 # useful to bail out early without doing a lot of work;
332 # not a substitute for snags_maybe_bail.
333 snags_maybe_bail() if $snags_tripped && !$opt_force;
336 return $snags_forced || $snags_tripped;
339 sub gbp_pq_export ($$$) {
340 my ($bname, $base, $tip) = @_;
341 # must be run in a workarea. $bname and patch-queue/$bname
342 # ought not to exist. Leaves you on patch-queue/$bname with
343 # the patches staged but not committed.
344 printdebug "gbp_pq_export $bname $base $tip\n";
345 runcmd @git, qw(checkout -q -b), $bname, $base;
346 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
347 my @gbp_cmd = (qw(gbp pq export));
348 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
350 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
353 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
357 # xxx allow merge resolution separately from laundering, before git merge
359 # xxx general gdr docs highlight forbidden things
360 # xxx general gdr docs list allowable things ?
361 # xxx general gdr docs explicitly forbid some rebase
363 # xxx provide a way for the user to help
364 # xxx (eg, provide wreckage provide way to continue)
367 # use git-format-patch?
368 # our own patch identification algorithm?
369 # this is an alternative strategy
371 sub merge_failed ($$) {
372 my ($wrecknotes, $emsg) = @_;
374 push @m, "Merge resolution failed: $emsg";
376 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
377 # ^ xxx this section does not yet exist
378 fail join '', map { "$_\n" } @m;
381 sub mwrecknote ($$$) {
382 my ($wrecknotes, $reftail, $commitish) = @_;
383 confess unless defined $commitish;
384 printdebug "mwrecknote $reftail $commitish\n";
385 $wrecknotes->{$reftail} = $commitish;
388 sub merge_series ($$$;@) {
389 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
390 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
391 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
392 # ^ specifies several patch series (currently we only support exactly 2)
393 # return value is a commit which is the result of
394 # merging the two versions of the same topic branch
395 # $input_q[0] and $input_q[1]
396 # with respect to the old version
400 # Creates, in *_q, a key MR for its private use
402 printdebug "merge_series newbase=$newbase\n";
404 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
405 $base_q->{MR}{S} = 'base';
408 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
409 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
410 # $prereq{<patch filename>} exists or not (even later)
414 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
416 local $workarea = fresh_playground "$playprefix/merge";
417 my $seriesfile = "debian/patches/series";
420 foreach my $q ($base_q, reverse @input_qs) {
422 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
424 if (open S, $seriesfile) {
425 while (my $patch = <S>) {
426 chomp $patch or die $!;
427 $prereq{$patch} //= {};
428 foreach my $earlier (@earlier) {
429 $prereq{$patch}{$earlier}{$s}++ and die;
431 push @earlier, $patch;
432 stat "debian/patches/$patch" or die "$patch ?";
434 S->error and die "$seriesfile $!";
437 die "$seriesfile $!" unless $!==ENOENT;
439 read_tree_upstream $newbase, 1;
440 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
441 "Convert $s to patch queue for merging",
442 "[git-debrebase merge-innards patch-queue import:".
445 printdebug "merge_series pec $pec ";
446 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
447 $pec = make_commit [ $pec ], [
448 "Drop series file from $s to avoid merge trouble",
449 "[git-debrebase merge-innards patch-queue prep:".
453 read_tree_debian $newbase;
455 read_tree_subdir 'debian/patches', "$pec:debian/patches";
457 rm_subdir_cached 'debian/patches';
459 $pec = make_commit [ $pec ], [
460 "Update debian/ (excluding patches) to final to avoid re-merging",
461 "debian/ was already merged and we need to just take that.",
462 "[git-debrebase merge-innards patch-queue packaging:".
466 printdebug "pec' $pec\n";
467 runcmd @git, qw(reset -q --hard), $pec;
468 $q->{MR}{PEC} = $pec;
469 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
471 # now, because of reverse, we are on $input_q->{MR}{OQC}
472 runcmd @git, qw(checkout -q -b merge);
473 printdebug "merge_series merging...\n";
474 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
475 debugcmd '+', @mergecmd;
477 if (system @mergecmd) {
481 printdebug "merge_series merge ok, series...\n";
482 # We need to construct a new series file
483 # Firstly, resolve prereq
484 foreach my $f (sort keys %prereq) {
485 printdebug "merge_series patch\t$f\t";
486 if (!stat_exists "debian/patches/$f") {
487 print DEBUG " drop\n" if $debuglevel;
488 # git merge deleted it; that's how we tell it's not wanted
492 print DEBUG " keep\n" if $debuglevel;
493 foreach my $g (sort keys %{ $prereq{$f} }) {
494 my $gfp = $prereq{$f}{$g};
495 printdebug "merge_series prereq\t$f\t-> $g\t";
496 if (!!$gfp->{0} == !!$gfp->{1}
499 print DEBUG "\tkeep\n" if $debuglevel;
501 print DEBUG "\tdrop\n" if $debuglevel;
502 delete $prereq{$f}{$g};
509 return scalar keys %{ $prereq{$f} };
512 my $nodate = time + 1;
514 # $authordate{<patch filename>};
515 my $authordate = sub {
517 $authordate{$f} //= do {
518 open PF, "<", "debian/patches/$f" or die "$f $!";
520 return $nodate if m/^$/;
521 last if s{^Date: }{};
524 return cmdoutput qw(date +%s -d), $_;
528 open NS, '>', $seriesfile or die $!;
530 while (keys %prereq) {
532 foreach my $try (sort keys %prereq) {
535 $unsat->($try) <=> $unsat->($best) or
536 $authordate->($try) <=> $authordate->($best) or
542 printdebug "merge_series series next $best\n";
543 print NS "$best\n" or die $!;
544 delete $prereq{$best};
545 foreach my $gp (values %prereq) {
550 runcmd @git, qw(add), $seriesfile;
551 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
552 $mwrecknote->('merged-patchqueue', git_rev_parse 'HEAD');
554 printdebug "merge_series series gbp pq import\n";
555 runcmd qw(gbp pq import);
557 # OK now we are on patch-queue/merge, and we need to rebase
558 # onto the intended parent and drop the patches from each one
560 printdebug "merge_series series ok, building...\n";
561 my $build = $newbase;
562 my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
563 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
564 my $commit = git_cat_file $c, 'commit';
565 printdebug "merge_series series ok, building $c\n";
566 read_tree_upstream $c, 0, $newbase;
567 my $tree = cmdoutput @git, qw(write-tree);
568 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
569 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
570 open C, ">", "../mcommit" or die $!;
571 print C $commit or die $!;
573 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
576 $mwrecknote->('merged-result', $result);
578 runcmd @git, qw(update-ref refs/heads/result), $result;
580 runcmd @git, qw(checkout -q -b debug);
581 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
582 runcmd @git, qw(add .);
583 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
584 my $mdebug = git_rev_parse 'HEAD';
585 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
586 $mwrecknote->('merged-debug', $mdebug);
588 printdebug "merge_series returns $result\n";
592 # classify returns an info hash like this
594 # Hdr => # commit headers, including 1 final newline
595 # Msg => # commit message (so one newline is dropped)
597 # Type => (see below)
599 # Ix => $index # ie 0, 1, 2, ...
601 # Differs => return value from get_differs
603 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
605 # NewMsg => # commit message, but with any [dgit import ...] edited
606 # # to say "[was: ...]"
616 # has additional entres in classification result
617 # Overwritten = [ subset of Parents ]
618 # Contributor = $the_remaining_Parent
620 # DgitImportUnpatched
621 # has additional entry in classification result
622 # OrigParents = [ subset of Parents ]
625 # has additional entry in classification result
626 # OrigParents = [ subset of Parents ] # singleton list
633 # has additional entry in classification result
636 sub parsecommit ($;$) {
637 my ($objid, $p_ref) = @_;
638 # => hash with CommitId Hdr Msg Tree Parents
639 # Parents entries have only Ix CommitId
640 # $p_ref, if provided, must be [] and is used as a base for Parents
645 my ($h,$m) = get_commit $objid;
647 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
648 my (@ph) = $h =~ m/^parent (\w+)$/mg;
658 foreach my $ph (@ph) {
660 Ix => scalar @$p_ref,
672 my $r = parsecommit($objid, \@p);
676 $p->{Differs} = (get_differs $p->{CommitId}, $t),
679 printdebug "classify $objid \$t=$t \@p",
680 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
684 my ($type, @rest) = @_;
685 $r = { %$r, Type => $type, @rest };
687 printdebug " = $type ".(dd $r)."\n";
693 $r = { %$r, Type => qw(Unknown), Why => $why };
694 printdebug " ** Unknown\n";
698 if (grep { $_ eq $objid } @opt_anchors) {
699 return $classify->('TreatAsAnchor');
702 my @identical = grep { !$_->{Differs} } @p;
703 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
704 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
706 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
707 # multi-orig upstreams are represented with an anchor merge
708 # from a single upstream commit which combines the orig tarballs
710 # Every anchor tagged this way must be a merge.
711 # We are relying on the
712 # [git-debrebase anchor: ...]
713 # commit message annotation in "declare" anchor merges (which
714 # do not have any upstream changes), to distinguish those
715 # anchor merges from ordinary pseudomerges (which we might
716 # just try to strip).
718 # However, the user is going to be doing git-rebase a lot. We
719 # really don't want them to rewrite an anchor commit.
720 # git-rebase trips up on merges, so that is a useful safety
723 # BreakwaterStart commits are also anchors in the terminology
724 # of git-debrebase(5), but they are untagged (and always
725 # manually generated).
727 # We cannot not tolerate any tagged linear commit (ie,
728 # BreakwaterStart commits tagged `[anchor:') because such a
729 # thing could result from an erroneous linearising raw git
730 # rebase of a merge anchor. That would represent a corruption
731 # of the branch. and we want to detect and reject the results
732 # of such corruption before it makes it out anywhere. If we
733 # reject it here then we avoid making the pseudomerge which
734 # would be needed to push it.
736 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
737 @p == 2 or return $badanchor->("has other than two parents");
738 $haspatches and return $badanchor->("contains debian/patches");
740 # How to decide about l/r ordering of anchors ? git
741 # --topo-order prefers to expand 2nd parent first. There's
742 # already an easy rune to look for debian/ history anyway (git log
743 # debian/) so debian breakwater branch should be 1st parent; that
744 # way also there's also an easy rune to look for the upstream
745 # patches (--topo-order).
747 # Also this makes --first-parent be slightly more likely to
748 # be useful - it makes it provide a linearised breakwater history.
750 # Of course one can say somthing like
751 # gitk -- ':/' ':!/debian'
752 # to get _just_ the commits touching upstream files, and by
753 # the TREESAME logic in git-rev-list this will leave the
754 # breakwater into upstream at the first anchor. But that
755 # doesn't report debian/ changes at all.
757 # Other observations about gitk: by default, gitk seems to
758 # produce output in a different order to git-rev-list. I
759 # can't seem to find this documented anywhere. gitk
760 # --date-order DTRT. But, gitk always seems to put the
761 # parents from left to right, in order, so it's easy to see
762 # which way round a pseudomerge is.
764 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
765 $p[1]{Differs} & ~DS_DEB and
766 $badanchor->("upstream files differ from left parent");
767 $p[0]{Differs} & ~D_UPS and
768 $badanchor->("debian/ differs from right parent");
770 return $classify->(qw(Anchor),
771 OrigParents => [ $p[1] ]);
775 my $d = $r->{Parents}[0]{Differs};
776 if ($d == D_PAT_ADD) {
777 return $classify->(qw(AddPatches));
778 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
779 return $unknown->("edits debian/patches");
780 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
781 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
783 if ($d == D_DEB_CLOG) {
784 return $classify->(qw(Changelog));
786 return $classify->(qw(Packaging));
788 } elsif ($ty eq 'missing') {
789 return $classify->(qw(BreakwaterStart));
791 return $unknown->("parent's debian is not a directory");
793 } elsif ($d == D_UPS) {
794 return $classify->(qw(Upstream));
795 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
796 return $classify->(qw(Mixed));
798 return $unknown->("no changes");
800 confess "internal error $objid ?";
804 return $unknown->("origin commit");
807 if (@p == 2 && @identical == 1) {
808 my @overwritten = grep { $_->{Differs} } @p;
809 confess "internal error $objid ?" unless @overwritten==1;
810 return $classify->(qw(Pseudomerge),
811 Overwritten => [ $overwritten[0] ],
812 Contributor => $identical[0]);
814 if (@p == 2 && @identical == 2) {
816 my ($ph,$pm) = get_commit $_[0]{CommitId};
817 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
821 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
822 if ($order > 0) { # newer first
823 } elsif ($order < 0) {
824 @bytime = reverse @bytime;
826 # same age, default to order made by -s ours
827 # that is, commit was made by someone who preferred L
829 return $classify->(qw(Pseudomerge),
830 SubType => qw(Ambiguous),
831 Contributor => $bytime[0],
832 Overwritten => [ $bytime[1] ]);
835 my ($p_h, $p_m) = get_commit $p->{CommitId};
836 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
837 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
839 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
841 if (!(grep { !$_->{IsOrigin} } @p) and
842 (@orig_ps >= @p - 1) and
843 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
845 return $classify->(qw(DgitImportUnpatched),
846 OrigParents => \@orig_ps);
850 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
851 # xxx ^ metadata tag needs adding to (5)
852 return $classify->("MergedBreakwaters");
854 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
855 return $unknown->("unknown kind of merge from $1");
858 return $unknown->("octopus merge");
861 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
862 return $unknown->("general two-parent merge");
865 return $classify->("VanillaMerge");
868 sub keycommits ($;$$$$$);
870 sub mergedbreakwaters_anchor ($) {
873 foreach my $p (@{ $cl->{Parents} }) {
874 my ($panchor, $pbw) = keycommits $p->{CommitId},
875 undef,undef,undef,undef, 1;
876 $best_anchor = $panchor
877 if !defined $best_anchor
878 or is_fast_fwd $best_anchor, $panchor;
879 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
880 unless is_fast_fwd $panchor, $best_anchor;
885 sub keycommits ($;$$$$$) {
886 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
887 # => ($anchor, $breakwater)
889 # $unclean->("unclean-$tagsfx", $msg, $cl)
890 # $furniture->("unclean-$tagsfx", $msg, $cl)
891 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
892 # is callled for each situation or commit that
893 # wouldn't be found in a laundered branch
894 # $furniture is for furniture commits such as might be found on an
895 # interchange branch (pseudomerge, d/patches, changelog)
896 # $trouble is for things whnich prevent the return of
897 # anchor and breakwater information; if that is ignored,
898 # then keycommits returns (undef, undef) instead.
899 # $fatal is for unprocessable commits, and should normally cause
900 # a failure. If ignored, agaion, (undef, undef) is returned.
902 # If $claimed_bw, this is supposed to be a breakwater commit.
904 # If a callback is undef, fail is called instead.
905 # If a callback is defined but false, the situation is ignored.
907 # no warnings qw(exiting); last;
908 # if the answer is no longer wanted.
910 my ($anchor, $breakwater);
911 $breakwater = $head if $claimed_bw;
915 $fatal //= sub { fail $_[1]; };
917 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
918 my $why = $mainwhy.$xwhy;
919 my $m = "branch needs laundering (run git-debrebase): $why";
920 fail $m unless defined $cb;
922 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
924 my $found_anchor = sub {
926 $breakwater //= $clogonly;
927 $breakwater //= $head;
928 no warnings qw(exiting);
932 $cl = classify $head;
933 my $ty = $cl->{Type};
934 if ($ty eq 'Packaging') {
935 $breakwater //= $clogonly;
936 $breakwater //= $head;
937 } elsif ($ty eq 'Changelog') {
938 # this is going to count as the tip of the breakwater
939 # only if it has no upstream stuff before it
941 } elsif ($ty eq 'Anchor' or
942 $ty eq 'TreatAsAnchor' or
943 $ty eq 'BreakwaterStart') {
944 $found_anchor->($head);
945 } elsif ($ty eq 'Upstream') {
946 $x->($unclean, 'ordering',
947 "packaging change ($breakwater) follows upstream change"," (eg $head)")
948 if defined $breakwater;
951 } elsif ($ty eq 'Mixed') {
952 $x->($unclean, 'mixed',
953 "found mixed upstream/packaging commit"," ($head)");
956 } elsif ($ty eq 'Pseudomerge' or
957 $ty eq 'AddPatches') {
959 $x->($furniture, (lc $ty),
960 "found interchange bureaucracy commit ($ty)"," ($head)");
961 } elsif ($ty eq 'DgitImportUnpatched') {
963 $x->($trouble, 'dgitimport',
964 "found dgit dsc import"," ($head)");
965 return (undef,undef);
967 $x->($fatal, 'unprocessable',
968 "found bare dgit dsc import with no prior history",
970 return (undef,undef);
972 } elsif ($ty eq 'VanillaMerge') {
973 $x->($trouble, 'vanillamerge',
974 "found vanilla merge"," ($head)");
975 return (undef,undef);
976 } elsif ($ty eq 'MergedBreakwaters') {
977 $found_anchor->(mergedbreakwaters_anchor $cl);
979 $x->($fatal, 'unprocessable',
980 "found unprocessable commit, cannot cope: $cl->{Why}",
982 return (undef,undef);
984 $head = $cl->{Parents}[0]{CommitId};
986 return ($anchor, $breakwater);
992 $nogenerate,$report, $report_lprefix) = @_;
993 # => ($tip, $breakwater_tip, $last_anchor)
994 # (or nothing, if $nogenerate)
996 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
997 $report_lprefix //= '';
999 # go through commits backwards
1000 # we generate two lists of commits to apply:
1001 # breakwater branch and upstream patches
1002 my (@brw_cl, @upp_cl, @processed);
1009 my ($prose, $info) = @_;
1010 my $ms = $cl->{Msg};
1013 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1014 return (Msg => $ms);
1016 my $rewrite_from_here = sub {
1018 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1020 push @processed, $sp_cl;
1025 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1028 return unless $report;
1029 print $report $prdelim, $report_lprefix, @_;
1033 my $bomb = sub { # usage: return $bomb->();
1034 print $report " Unprocessable" if $report;
1035 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1038 return (undef,undef);
1040 fail "found unprocessable commit, cannot cope".
1041 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1042 " (commit $cur) (d.".
1043 (join ' ', map { sprintf "%#x", $_->{Differs} }
1044 @{ $cl->{Parents} }).
1051 my $build_start = sub {
1052 my ($msg, $parent) = @_;
1055 no warnings qw(exiting); last;
1060 merge_failed $cl->{MergeWreckNotes}, $emsg;
1063 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1068 $cl = classify $cur;
1069 $cl->{MergeWreckNotes} //= {};
1070 my $ty = $cl->{Type};
1071 my $st = $cl->{SubType};
1072 $prline->("$cl->{CommitId} $cl->{Type}");
1073 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1074 push @processed, $cl;
1075 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1076 if ($ty eq 'AddPatches') {
1078 $rewrite_from_here->(\@upp_cl);
1080 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1084 } elsif ($ty eq 'BreakwaterStart') {
1085 $last_anchor = $cur;
1086 $build_start->('FirstPackaging', $cur);
1087 } elsif ($ty eq 'Upstream') {
1091 } elsif ($ty eq 'Mixed') {
1094 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1097 $queue->(\@brw_cl, "debian");
1098 $queue->(\@upp_cl, "upstream");
1099 $rewrite_from_here->(\@brw_cl);
1102 } elsif ($ty eq 'Pseudomerge') {
1103 my $contrib = $cl->{Contributor}{CommitId};
1104 print $report " Contributor=$contrib" if $report;
1105 push @pseudomerges, $cl;
1106 $rewrite_from_here->(\@upp_cl);
1109 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1110 $last_anchor = $cur;
1111 $build_start->("Anchor", $cur);
1112 } elsif ($ty eq 'DgitImportUnpatched') {
1113 my $pm = $pseudomerges[-1];
1115 # To an extent, this is heuristic. Imports don't have
1116 # a useful history of the debian/ branch. We assume
1117 # that the first pseudomerge after an import has a
1118 # useful history of debian/, and ignore the histories
1119 # from later pseudomerges. Often the first pseudomerge
1120 # will be the dgit import of the upload to the actual
1121 # suite intended by the non-dgit NMUer, and later
1122 # pseudomerges may represent in-archive copies.
1123 my $ovwrs = $pm->{Overwritten};
1124 printf $report " PM=%s \@Overwr:%d",
1125 $pm->{CommitId}, (scalar @$ovwrs)
1128 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1131 my $ovwr = $ovwrs->[0]{CommitId};
1132 printf $report " Overwr=%s", $ovwr if $report;
1133 # This import has a tree which is just like a
1134 # breakwater tree, but it has the wrong history. It
1135 # ought to have the previous breakwater (which the
1136 # pseudomerge overwrote) as an ancestor. That will
1137 # make the history of the debian/ files correct. As
1138 # for the upstream version: either it's the same as
1139 # was ovewritten (ie, same as the previous
1140 # breakwater), in which case that history is precisely
1141 # right; or, otherwise, it was a non-gitish upload of a
1142 # new upstream version. We can tell these apart by
1143 # looking at the tree of the supposed upstream.
1146 SpecialMethod => 'DgitImportDebianUpdate',
1147 $xmsg->("convert dgit import: debian changes")
1150 SpecialMethod => 'DgitImportUpstreamUpdate',
1151 $xmsg->("convert dgit import: upstream update",
1154 $prline->(" Import");
1155 $rewrite_from_here->(\@brw_cl);
1156 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1160 # Everything is from this import. This kind of import
1161 # is already nearly in valid breakwater format, with the
1162 # patches as commits. Unfortunately it contains
1164 printdebug "*** WALK BOMB bare dgit import\n";
1165 $cl->{Why} = "bare dgit dsc import";
1169 } elsif ($ty eq 'MergedBreakwaters') {
1170 $last_anchor = mergedbreakwaters_anchor $cl;
1171 $build_start->(' MergedBreakwaters', $cur);
1173 } elsif ($ty eq 'VanillaMerge') {
1174 # User may have merged unstitched branch(es). We will
1175 # have now lost what ffq-prev was then (since the later
1176 # pseudomerge may introduce further changes). The effect
1177 # of resolving such a merge is that we may have to go back
1178 # further in history to find a merge base, since the one
1179 # which was reachable via ffq-prev is no longer findable.
1180 # This is suboptimal, but if it all works we'll have done
1182 # xxx we should warn the user in the docs about this
1186 # We expect to find a dominating anchor amongst the
1187 # inputs' anchors. That will be the new anchor.
1189 # More complicated is finding a merge base for the
1190 # breakwaters. We need a merge base that is a breakwater
1191 # commit. The ancestors of breakwater commits are more
1192 # breakwater commits and possibly upstream commits and the
1193 # ancestors of those upstream. Upstreams might have
1194 # arbitrary ancestors. But any upstream commit U is
1195 # either included in both anchors, in which case the
1196 # earlier anchor is a better merge base than any of U's
1197 # ancestors; or U is not included in the older anchor, in
1198 # which case U is not an ancestor of the vanilla merge at
1199 # all. So no upstream commit, nor any ancestor thereof,
1200 # is a best merge base. As for non-breakwater Debian
1201 # commits: these are never ancestors of any breakwater.
1203 # So any best merge base as found by git-merge-base
1204 # is a suitable breakwater anchor. Usually there will
1207 printdebug "*** MERGE\n";
1209 my @bwbcmd = (@git, qw(merge-base));
1210 my @ibcmd = (@git, qw(merge-base --all));
1211 my $might_be_in_bw = 1;
1213 my $ps = $cl->{Parents};
1215 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1217 foreach my $p (@$ps) {
1218 $prline->(" VanillaMerge ".$p->{Ix});
1220 my ($ptip, $pbw, $panchor) =
1221 walk $p->{CommitId}, 0, $report,
1222 $report_lprefix.' ';
1223 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1224 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1225 $p->{Anchor} = $panchor;
1227 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1228 $mwrecknote->("$lr-input", $p->{CommitId});
1230 my $mwrecknote_parent = sub {
1232 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1234 $mwrecknote_parent->('Laundered');
1235 $mwrecknote_parent->('Breakwater');
1236 $mwrecknote_parent->('Anchor');
1238 $best_anchor = $panchor if
1239 !defined $best_anchor or
1240 is_fast_fwd $best_anchor, $panchor;
1242 printdebug " MERGE BA best=".($best_anchor//'-').
1246 $mwrecknote->('result-anchor', $best_anchor);
1248 foreach my $p (@$ps) {
1249 $prline->(" VanillaMerge ".$p->{Ix});
1250 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1251 $nomerge->('divergent anchors');
1252 } elsif ($p->{Anchor} eq $best_anchor) {
1253 print $report " SameAnchor" if $report;
1255 print $report " SupersededAnchor" if $report;
1257 if ($p->{Breakwater} eq $p->{CommitId}) {
1258 # this parent commit was its own breakwater,
1259 # ie it is part of the breakwater
1260 print $report " Breakwater" if $report;
1262 $might_be_in_bw = 0;
1264 push @bwbcmd, $p->{Breakwater};
1265 push @ibcmd, $p->{CommitId};
1268 if ($ok && $might_be_in_bw) {
1269 # We could rewrite this to contaion the metadata
1270 # declaring it to be MergedBreakwaters, but
1271 # unnecessarily rewriting a merge seems unhelpful.
1272 $prline->(" VanillaMerge MergedBreakwaters");
1273 $last_anchor = $best_anchor;
1274 $build_start->('MergedBreakwaters', $cur);
1277 my $bwb = cmdoutput @bwbcmd;
1279 # OK, now we have a breakwater base, but we need the merge
1280 # base for the interchange branch because we need the delta
1283 # This a the best merge base of our inputs which has the
1284 # breakwater merge base as an ancestor.
1291 @ibs or confess 'internal error, expected anchor at least ?';
1295 foreach my $tibix (0..$#ibs) {
1296 my $tib = $ibs[$tibix];
1297 my $ff = is_fast_fwd $bwb, $tib;
1298 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1299 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1300 $mwrecknote->($tibleaf, $tib);
1307 $ib or $nomerge->("no suitable interchange merge base");
1309 $prline->(" VanillaMerge Base");
1311 my ($btip, $bbw, $banchor) = eval {
1312 walk $ib, 0, $report, $report_lprefix.' ';
1314 $nomerge->("walking interchange branch merge base ($ibleaf): ".
1317 $mwrecknote->("mergebase-laundered", $btip);
1318 $mwrecknote->("mergebase-breakwater", $bbw);
1319 $mwrecknote->("mergebase-anchor", $banchor);
1321 my $ibinfo = { SeriesTip => $btip,
1324 LeftRight => 'mergebase' };
1327 or $nomerge->("interchange merge-base ($ib)'s".
1328 " breakwater ($bbw)".
1329 " != breakwaters' merge-base ($bwb)");
1331 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1332 or $nomerge->("interchange merge-base ($ib)'s".
1333 " anchor ($ibinfo->{SeriesBase})".
1334 " != any merge input's anchor (".
1335 (join ' ', map { $_->{Anchor} } @$ps).
1338 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1339 $cl->{MergeBestAnchor} = $best_anchor;
1342 SpecialMethod => 'MergeCreateMergedBreakwaters',
1343 $xmsg->('constructed from vanilla merge',
1344 ' merged-breakwater'),
1348 SpecialMethod => 'MergeMergeSeries',
1350 $build_start->('MergeBreakwaters', $cur);
1352 printdebug "*** WALK BOMB unrecognised\n";
1358 printdebug "*** WALK prep done cur=$cur".
1359 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1361 return if $nogenerate;
1363 # Now we build it back up again
1369 my $read_tree_upstream = sub {
1371 read_tree_upstream $treeish, 0, $build;
1374 $#upp_cl = $upp_limit if defined $upp_limit;
1376 my $committer_authline = calculate_committer_authline();
1378 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1380 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1383 mkdir $rd or $!==EEXIST or die $!;
1385 runcmd @git, qw(read-tree), $build;
1386 foreach my $cl (qw(Debian), (reverse @brw_cl),
1387 { SpecialMethod => 'RecordBreakwaterTip' },
1388 qw(Upstream), (reverse @upp_cl)) {
1390 $current_method = $cl;
1393 my $method = $cl->{SpecialMethod} // $current_method;
1394 my @parents = ($build);
1395 my $cltree = $cl->{CommitId};
1396 printdebug "WALK BUILD ".($cltree//'undef').
1397 " $method (rewriting=$rewriting)\n";
1398 if ($method eq 'Debian') {
1399 read_tree_debian($cltree);
1400 } elsif ($method eq 'Upstream') {
1401 $read_tree_upstream->($cltree);
1402 } elsif ($method eq 'StartRewrite') {
1405 } elsif ($method eq 'RecordBreakwaterTip') {
1406 $breakwater = $build;
1408 } elsif ($method eq 'DgitImportDebianUpdate') {
1409 read_tree_debian($cltree);
1410 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1411 confess unless $rewriting;
1412 my $differs = (get_differs $build, $cltree);
1413 next unless $differs & D_UPS;
1414 $read_tree_upstream->($cltree);
1415 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1416 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1417 print "Found a general merge, will try to tidy it up.\n";
1419 $read_tree_upstream->($cl->{MergeBestAnchor});
1420 $read_tree_upstream->($cl->{MergeBestAnchor});
1421 read_tree_debian($cltree);
1422 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1423 } elsif ($method eq 'MergeMergeSeries') {
1424 print "Running merge resolution for $cl->{CommitId}...\n";
1425 $build = merge_series
1426 $build, $cl->{MergeWreckNotes},
1427 $cl->{MergeInterchangeBaseInfo},
1428 @{ $cl->{Parents} };
1429 $last_anchor = $cl->{MergeBestAnchor};
1431 # Check for mismerges:
1433 my ($against, $allow, $what) = @_;
1434 my $differs = get_differs $build, $against;
1436 "merge misresolved: %s are not the same (%s %s d.%#x)",
1437 $what, $against, $build, $differs)
1438 if $differs & ~($allow | D_PAT_ADD);
1441 # Breakwater changes which were in each side of the
1442 # merge will have been incorporated into the
1443 # MergeCreateMergedBreakwaters output. Because the
1444 # upstream series was rebased onto the new breakwater,
1445 # so should all of the packaging changes which were in
1447 $check->($input, D_UPS, 'debian files');
1449 # Upstream files are merge_series, which ought to
1450 # have been identical to the original merge.
1451 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1453 print "Merge resolution successful.\n";
1456 confess "$method ?";
1459 my $procd = (pop @processed) // 'UNDEF';
1460 if ($cl ne $procd) {
1462 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1465 my $newtree = cmdoutput @git, qw(write-tree);
1466 my $ch = $cl->{Hdr};
1467 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1468 $ch =~ s{^parent .*\n}{}mg;
1469 $ch =~ s{(?=^author)}{
1470 join '', map { "parent $_\n" } @parents
1471 }me or confess "$ch ?";
1473 $ch =~ s{^committer .*$}{$committer_authline}m
1476 my $cf = "$rd/m$rewriting";
1477 open CD, ">", $cf or die $!;
1478 print CD $ch, "\n", $cl->{Msg} or die $!;
1480 my @cmd = (@git, qw(hash-object));
1481 push @cmd, qw(-w) if $rewriting;
1482 push @cmd, qw(-t commit), $cf;
1483 my $newcommit = cmdoutput @cmd;
1484 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1485 $build = $newcommit;
1486 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1487 $last_anchor = $cur;
1492 my $final_check = get_differs $build, $input;
1493 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1494 if $final_check & ~D_PAT_ADD;
1496 my @r = ($build, $breakwater, $last_anchor);
1497 printdebug "*** WALK RETURN @r\n";
1502 git_check_unmodified();
1503 return git_rev_parse qw(HEAD);
1506 sub update_head ($$$) {
1507 my ($old, $new, $mrest) = @_;
1508 push @deferred_updates, "update HEAD $new $old";
1509 run_deferred_updates $mrest;
1512 sub update_head_checkout ($$$) {
1513 my ($old, $new, $mrest) = @_;
1514 update_head $old, $new, $mrest;
1515 runcmd @git, qw(reset --hard);
1518 sub update_head_postlaunder ($$$) {
1519 my ($old, $tip, $reflogmsg) = @_;
1520 return if $tip eq $old;
1521 print "git-debrebase: laundered (head was $old)\n";
1522 update_head $old, $tip, $reflogmsg;
1523 # no tree changes except debian/patches
1524 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1527 sub currently_rebasing() {
1528 foreach (qw(rebase-merge rebase-apply)) {
1529 return 1 if stat_exists "$maindir_gitdir/$_";
1534 sub bail_if_rebasing() {
1535 fail "you are in the middle of a git-rebase already"
1536 if currently_rebasing();
1539 sub do_launder_head ($) {
1540 my ($reflogmsg) = @_;
1541 my $old = get_head();
1543 my ($tip,$breakwater) = walk $old;
1545 update_head_postlaunder $old, $tip, $reflogmsg;
1546 return ($tip,$breakwater);
1549 sub cmd_launder_v0 () {
1550 badusage "no arguments to launder-v0 allowed" if @ARGV;
1551 my $old = get_head();
1552 my ($tip,$breakwater,$last_anchor) = walk $old;
1553 update_head_postlaunder $old, $tip, 'launder';
1554 printf "# breakwater tip\n%s\n", $breakwater;
1555 printf "# working tip\n%s\n", $tip;
1556 printf "# last anchor\n%s\n", $last_anchor;
1559 sub defaultcmd_rebase () {
1560 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1561 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1562 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1565 sub cmd_analyse () {
1566 badusage "analyse does not support any options"
1567 if @ARGV and $ARGV[0] =~ m/^-/;
1568 badusage "too many arguments to analyse" if @ARGV>1;
1571 $old = git_rev_parse $old;
1573 $old = git_rev_parse 'HEAD';
1575 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1576 STDOUT->error and die $!;
1579 sub ffq_prev_branchinfo () {
1580 my $current = git_get_symref();
1581 return gdr_ffq_prev_branchinfo($current);
1584 sub ffq_check ($;$$) {
1585 # calls $ff and/or $notff zero or more times
1586 # then returns either (status,message) where status is
1591 # or (undef,undef, $ffq_prev,$gdrlast)
1592 # $ff and $notff are called like this:
1593 # $ff->("message for stdout\n");
1594 # $notff->('snag-name', $message);
1595 # normally $currentval should be HEAD
1596 my ($currentval, $ff, $notff) =@_;
1598 $ff //= sub { print $_[0] or die $!; };
1601 my ($status, $message, $current, $ffq_prev, $gdrlast)
1602 = ffq_prev_branchinfo();
1603 return ($status, $message) unless $status eq 'branch';
1605 my $exists = git_get_ref $ffq_prev;
1606 return ('exists',"$ffq_prev already exists") if $exists;
1608 return ('not-branch', 'HEAD symref is not to refs/heads/')
1609 unless $current =~ m{^refs/heads/};
1612 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1615 printdebug "ffq check_specs @check_specs\n";
1618 my ($lrref, $desc) = @_;
1619 printdebug "ffq might check $lrref ($desc)\n";
1621 for my $chk (@check_specs) {
1623 $invert = $glob =~ s{^[!^]}{};
1624 last if fnmatch $glob, $lrref;
1627 my $lrval = git_get_ref $lrref;
1628 return unless length $lrval;
1630 if (is_fast_fwd $lrval, $currentval) {
1631 $ff->("OK, you are ahead of $lrref\n");
1632 $checked{$lrref} = 1;
1633 } elsif (is_fast_fwd $currentval, $lrval) {
1634 $checked{$lrref} = -1;
1635 $notff->('behind', "you are behind $lrref, divergence risk");
1637 $checked{$lrref} = -1;
1638 $notff->('diverged', "you have diverged from $lrref");
1642 my $merge = cfg "branch.$branch.merge",1;
1643 if (defined $merge and $merge =~ m{^refs/heads/}) {
1645 printdebug "ffq merge $rhs\n";
1646 my $check_remote = sub {
1647 my ($remote, $desc) = @_;
1648 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1649 return unless defined $remote;
1650 $check->("refs/remotes/$remote/$rhs", $desc);
1652 $check_remote->((scalar cfg "branch.$branch.remote",1),
1653 'remote fetch/merge branch');
1654 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1655 (scalar cfg "branch.$branch.pushDefault",1),
1656 'remote push branch');
1658 if ($branch =~ m{^dgit/}) {
1659 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1660 } elsif ($branch =~ m{^master$}) {
1661 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1663 return (undef, undef, $ffq_prev, $gdrlast);
1666 sub record_ffq_prev_deferred () {
1667 # => ('status', "message")
1669 # deferred message is undef
1674 # if not ff from some branch we should be ff from, is an snag
1675 # if "deferred", will have added something about that to
1676 # @deferred_update_messages, and also maybe printed (already)
1677 # some messages about ff checks
1679 my $currentval = get_head();
1681 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1682 return ($status,$message) if defined $status;
1686 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1687 push @deferred_updates, "delete $gdrlast";
1688 push @deferred_update_messages, "Recorded previous head for preservation";
1689 return ('deferred', undef);
1692 sub record_ffq_auto () {
1693 my ($status, $message) = record_ffq_prev_deferred();
1694 if ($status eq 'deferred' || $status eq 'exists') {
1696 snag $status, "could not record ffq-prev: $message";
1701 sub ffq_prev_info () {
1703 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1704 my ($status, $message, $current, $ffq_prev, $gdrlast)
1705 = ffq_prev_branchinfo();
1706 if ($status ne 'branch') {
1707 snag $status, "could not check ffq-prev: $message";
1710 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1711 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1714 sub stitch ($$$$$) {
1715 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1717 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1719 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1720 my $differs = get_differs $old_head, $ffq_prev_commitish;
1721 unless ($differs & ~D_PAT_ADD) {
1722 # ffq-prev is ahead of us, and the only tree changes it has
1723 # are possibly addition of things in debian/patches/.
1724 # Just wind forwards rather than making a pointless pseudomerge.
1725 push @deferred_updates,
1726 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1727 update_head_checkout $old_head, $ffq_prev_commitish,
1728 "stitch (fast forward)";
1733 # We make pseudomerges with L as the contributing parent.
1734 # This makes git rev-list --first-parent work properly.
1735 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1736 'Declare fast forward / record previous work',
1737 "[git-debrebase pseudomerge: $prose]",
1739 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1740 update_head $old_head, $new_head, "stitch: $prose";
1743 sub do_stitch ($;$) {
1744 my ($prose, $unclean) = @_;
1746 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1747 if (!$ffq_prev_commitish) {
1748 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1751 my $dangling_head = get_head();
1753 keycommits $dangling_head, $unclean,$unclean,$unclean;
1756 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1759 sub upstream_commitish_search ($$) {
1760 my ($upstream_version, $tried) = @_;
1761 # todo: at some point maybe use git-deborig to do this
1762 foreach my $tagpfx ('', 'v', 'upstream/') {
1763 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1764 my $new_upstream = git_get_ref "refs/tags/$tag";
1766 return $new_upstream if length $new_upstream;
1770 sub resolve_upstream_version ($$) {
1771 my ($new_upstream, $upstream_version) = @_;
1773 if (!defined $new_upstream) {
1775 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1776 if (!length $new_upstream) {
1777 fail "Could not determine appropriate upstream commitish.\n".
1778 " (Tried these tags: @tried)\n".
1779 " Check version, and specify upstream commitish explicitly.";
1782 $new_upstream = git_rev_parse $new_upstream;
1784 return $new_upstream;
1787 sub cmd_new_upstream () {
1788 # automatically and unconditionally launders before rebasing
1789 # if rebase --abort is used, laundering has still been done
1793 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1795 # parse args - low commitment
1796 my $spec_version = shift @ARGV;
1797 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1798 fail "bad version number \`$spec_version'" unless defined $new_version;
1799 if ($new_version->is_native()) {
1800 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1803 my $new_upstream = shift @ARGV;
1804 my $new_upstream_version = upstreamversion $new_version;
1806 resolve_upstream_version $new_upstream, $new_upstream_version;
1811 my ($n, @x) = @_; # may be ''
1812 my $pc = $pieces{$n} //= {
1814 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1816 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1821 my $newpiece = sub {
1822 my ($n, @x) = @_; # may be ''
1823 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1824 push @newpieces, $pc;
1829 New => $new_upstream,
1831 while (@ARGV && $ARGV[0] !~ m{^-}) {
1832 my $n = shift @ARGV;
1834 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1835 unless @ARGV && $ARGV[0] !~ m{^-};
1837 my $c = git_rev_parse shift @ARGV;
1838 die unless $n =~ m/^$extra_orig_namepart_re$/;
1839 $newpiece->($n, New => $c);
1842 # now we need to investigate the branch this generates the
1843 # laundered version but we don't switch to it yet
1844 my $old_head = get_head();
1845 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1847 my $old_bw_cl = classify $old_bw;
1848 my $old_anchor_cl = classify $old_anchor;
1850 if (!$old_anchor_cl->{OrigParents}) {
1851 snag 'anchor-treated',
1852 'old anchor is recognised due to --anchor, cannot check upstream';
1854 $old_upstream = parsecommit
1855 $old_anchor_cl->{OrigParents}[0]{CommitId};
1856 $piece->('', Old => $old_upstream->{CommitId});
1859 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1860 if ($old_upstream->{Msg} =~
1861 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1863 my @oldpieces = (split / /, $1);
1864 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1865 if ($old_n_parents != @oldpieces &&
1866 $old_n_parents != @oldpieces + 1) {
1867 snag 'upstream-confusing', sprintf
1868 "previous upstream combine %s".
1869 " mentions %d pieces (each implying one parent)".
1870 " but has %d parents".
1871 " (one per piece plus maybe a previous combine)",
1872 $old_upstream->{CommitId},
1873 (scalar @oldpieces),
1875 } elsif ($oldpieces[0] ne '.') {
1876 snag 'upstream-confusing', sprintf
1877 "previous upstream combine %s".
1878 " first piece is not \`.'",
1882 foreach my $i (0..$#oldpieces) {
1883 my $n = $oldpieces[$i];
1884 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1885 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1889 snag 'upstream-confusing',
1890 "previous upstream $old_upstream->{CommitId} is from".
1891 " git-debrebase but not an \`upstream-combine' commit";
1895 foreach my $pc (values %pieces) {
1896 if (!$old_upstream) {
1897 # we have complained already
1898 } elsif (!$pc->{Old}) {
1899 snag 'upstream-new-piece',
1900 "introducing upstream piece \`$pc->{Name}'";
1901 } elsif (!$pc->{New}) {
1902 snag 'upstream-rm-piece',
1903 "dropping upstream piece \`$pc->{Name}'";
1904 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1905 snag 'upstream-not-ff',
1906 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1910 printdebug "%pieces = ", (dd \%pieces), "\n";
1911 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1919 my @upstream_merge_parents;
1922 push @upstream_merge_parents, $old_upstream->{CommitId};
1925 foreach my $pc (@newpieces) { # always has '' first
1927 read_tree_subdir $pc->{Name}, $pc->{New};
1929 runcmd @git, qw(read-tree), $pc->{New};
1931 push @upstream_merge_parents, $pc->{New};
1934 # index now contains the new upstream
1936 if (@newpieces > 1) {
1937 # need to make the upstream subtree merge commit
1938 $new_upstream = make_commit \@upstream_merge_parents,
1939 [ "Combine upstreams for $new_upstream_version",
1940 ("[git-debrebase upstream-combine . ".
1941 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1946 # $new_upstream is either the single upstream commit, or the
1947 # combined commit we just made. Either way it will be the
1948 # "upstream" parent of the anchor merge.
1950 read_tree_subdir 'debian', "$old_bw:debian";
1952 # index now contains the anchor merge contents
1953 $new_bw = make_commit [ $old_bw, $new_upstream ],
1954 [ "Update to upstream $new_upstream_version",
1955 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1958 my $clogsignoff = cmdoutput qw(git show),
1959 '--pretty=format:%an <%ae> %aD',
1962 # Now we have to add a changelog stanza so the Debian version
1964 die if unlink "debian";
1965 die $! unless $!==ENOENT or $!==ENOTEMPTY;
1966 unlink "debian/changelog" or $!==ENOENT or die $!;
1967 mkdir "debian" or die $!;
1968 open CN, ">", "debian/changelog" or die $!;
1969 my $oldclog = git_cat_file ":debian/changelog";
1970 $oldclog =~ m/^($package_re) \(\S+\) / or
1971 fail "cannot parse old changelog to get package name";
1973 print CN <<END, $oldclog or die $!;
1974 $p ($new_version) UNRELEASED; urgency=medium
1976 * Update to new upstream version $new_upstream_version.
1982 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1984 # Now we have the final new breakwater branch in the index
1985 $new_bw = make_commit [ $new_bw ],
1986 [ "Update changelog for new upstream $new_upstream_version",
1987 "[git-debrebase: new upstream $new_upstream_version, changelog]",
1991 # we have constructed the new breakwater. we now need to commit to
1992 # the laundering output, because git-rebase can't easily be made
1993 # to make a replay list which is based on some other branch
1995 update_head_postlaunder $old_head, $old_laundered_tip,
1996 'launder for new upstream';
1998 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1999 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2000 "debrebase new-upstream $new_version: rebase";
2002 # now it's for the user to sort out
2005 sub cmd_record_ffq_prev () {
2006 badusage "no arguments allowed" if @ARGV;
2007 my ($status, $msg) = record_ffq_prev_deferred();
2008 if ($status eq 'exists' && $opt_noop_ok) {
2009 print "Previous head already recorded\n" or die $!;
2010 } elsif ($status eq 'deferred') {
2011 run_deferred_updates 'record-ffq-prev';
2013 fail "Could not preserve: $msg";
2018 badusage "no arguments allowed" if @ARGV;
2019 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2020 print "$bw\n" or die $!;
2023 sub cmd_breakwater () {
2024 badusage "no arguments allowed" if @ARGV;
2025 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2026 print "$bw\n" or die $!;
2030 badusage "no arguments allowed" if @ARGV;
2032 # todo: gdr status should print divergence info
2033 # todo: gdr status should print upstream component(s) info
2034 # todo: gdr should leave/maintain some refs with this kind of info ?
2036 my $oldest = { Badness => 0 };
2039 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2040 if ($oldest->{Badness} < $badness) {
2041 $oldest = $newest = undef;
2044 Badness => $badness,
2045 CommitId => $cl->{CommitId},
2049 $newest //= $oldest;
2051 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2052 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2053 sub { $note->(2, 'branch is unlaundered', @_); },
2054 sub { $note->(3, 'branch needs laundering', @_); },
2055 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2057 my $prcommitinfo = sub {
2059 flush STDOUT or die $!;
2060 runcmd @git, qw(--no-pager log -n1),
2061 '--pretty=format: %h %s%n',
2065 print "current branch contents, in git-debrebase terms:\n";
2066 if (!$oldest->{Badness}) {
2067 print " branch is laundered\n";
2069 print " $oldest->{OurMsg}\n";
2071 foreach my $info ($oldest, $newest) {
2072 my $cid = $info->{CommitId};
2073 next if $cid eq $printed;
2075 print " $info->{KcMsg}\n";
2076 $prcommitinfo->($cid);
2081 my ($cid, $what) = @_;
2082 if (!defined $cid) {
2083 print " $what is not well-defined\n";
2086 $prcommitinfo->($cid);
2089 print "key git-debrebase commits:\n";
2090 $prab->($anchor, 'anchor');
2091 $prab->($bw, 'breakwater');
2093 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2094 ffq_prev_branchinfo();
2096 print "branch and ref status, in git-debrebase terms:\n";
2098 print " $ffq_msg\n";
2100 $ffq_prev = git_get_ref $ffq_prev;
2101 $gdrlast = git_get_ref $gdrlast;
2103 print " unstitched; previous tip was:\n";
2104 $prcommitinfo->($ffq_prev);
2105 } elsif (!$gdrlast) {
2106 print " stitched? (no record of git-debrebase work)\n";
2107 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2108 print " stitched\n";
2110 print " not git-debrebase (diverged since last stitch)\n"
2113 print "you are currently rebasing\n" if currently_rebasing();
2117 my $prose = 'stitch';
2118 getoptions("stitch",
2119 'prose=s', \$prose);
2120 badusage "no arguments allowed" if @ARGV;
2121 do_stitch $prose, 0;
2123 sub cmd_prepush () { cmd_stitch(); }
2126 badusage "no arguments allowed" if @ARGV;
2127 do_launder_head 'launder for git-debrebase quick';
2131 sub cmd_conclude () {
2132 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2133 if (!$ffq_prev_commitish) {
2134 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2137 my $dangling_head = get_head();
2139 badusage "no arguments allowed" if @ARGV;
2140 do_launder_head 'launder for git-debrebase quick';
2145 if (currently_rebasing()) {
2146 runcmd @git, qw(rebase --abort);
2148 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2149 if (!$ffq_prev_commitish) {
2150 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2153 my $scrapping_head = get_head();
2154 badusage "no arguments allowed" if @ARGV;
2155 push @deferred_updates,
2156 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2157 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2159 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2162 sub make_patches_staged ($) {
2164 # Produces the patches that would result from $head if it were
2166 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2169 gbp_pq_export 'bw', $secret_bw, $secret_head;
2173 sub make_patches ($) {
2175 keycommits $head, 0, \&snag;
2176 make_patches_staged $head;
2179 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2180 runcmd @git, qw(read-tree), $head;
2181 read_tree_subdir 'debian/patches', $ptree;
2182 $out = make_commit [$head], [
2183 'Commit patch queue (exported by git-debrebase)',
2184 '[git-debrebase: export and commit patches]',
2190 sub cmd_make_patches () {
2191 my $opt_quiet_would_amend;
2192 getoptions("make-patches",
2193 'quiet-would-amend!', \$opt_quiet_would_amend);
2194 badusage "no arguments allowed" if @ARGV;
2196 my $old_head = get_head();
2197 my $new = make_patches $old_head;
2198 my $d = get_differs $old_head, $new;
2200 fail "No (more) patches to export." unless $opt_noop_ok;
2202 } elsif ($d == D_PAT_ADD) {
2204 update_head_checkout $old_head, $new, 'make-patches';
2206 print STDERR failmsg
2207 "Patch export produced patch amendments".
2208 " (abandoned output commit $new).".
2209 " Try laundering first."
2210 unless $opt_quiet_would_amend;
2215 sub cmd_convert_from_gbp () {
2216 badusage "want only 1 optional argument, the upstream git commitish"
2219 my $clogp = parsechangelog();
2220 my $version = $clogp->{'Version'}
2221 // die "missing Version from changelog";
2223 my ($upstream_spec) = @ARGV;
2225 my $upstream_version = upstreamversion $version;
2227 resolve_upstream_version($upstream_spec, $upstream_version);
2229 my $old_head = get_head();
2231 my $upsdiff = get_differs $upstream, $old_head;
2232 if ($upsdiff & D_UPS) {
2233 runcmd @git, qw(--no-pager diff --stat),
2234 $upstream, $old_head,
2235 qw( -- :!/debian :/);
2237 upstream ($upstream_spec) and HEAD are not
2238 identical in upstream files. See diffstat above, or run
2239 git diff $upstream_spec HEAD -- :!/debian :/
2243 if (!is_fast_fwd $upstream, $old_head) {
2244 snag 'upstream-not-ancestor',
2245 "upstream ($upstream) is not an ancestor of HEAD";
2247 my $wrong = cmdoutput
2248 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2249 qw(-- :/ :!/debian));
2250 if (length $wrong) {
2251 snag 'unexpected-upstream-changes',
2252 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2253 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2257 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2258 snag 'upstream-has-debian',
2259 "upstream ($upstream) contains debian/ directory";
2262 my $previous_dgit_view = eval {
2263 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2265 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2266 my ($stz, $desc) = @_;
2267 no warnings qw(exiting);
2268 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2269 next unless $stz->{Date};
2270 next unless $stz->{Distribution} ne 'UNRELEASED';
2271 $lvsn = $stz->{Version};
2272 $suite = $stz->{Distribution};
2275 die "neither of the first two changelog entries are released\n"
2276 unless defined $lvsn;
2277 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2278 my $mtag_pat = debiantag_maintview $lvsn, '*';
2279 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2281 die "could not find suitable maintainer view tag $mtag_pat\n"
2282 unless $mtag_pat =~ m{/};
2283 is_fast_fwd $mtag, 'HEAD' or
2284 die "HEAD is not FF from maintainer tag $mtag!";
2285 my $dtag = "archive/$mtag";
2286 is_fast_fwd $mtag, $dtag or
2287 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2288 print "will stitch in dgit view, $dtag\n";
2289 git_rev_parse $dtag;
2291 if (!$previous_dgit_view) {
2294 print STDERR "cannot stitch in dgit view: $@\n";
2297 snags_maybe_bail_early();
2303 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2304 # make a branch out of the patch queue - we'll want this in a mo
2305 runcmd qw(gbp pq import);
2306 # strip the patches out
2307 runcmd @git, qw(checkout -q gdr-internal~0);
2308 rm_subdir_cached 'debian/patches';
2309 $work = make_commit ['HEAD'], [
2310 'git-debrebase convert-from-gbp: drop patches from tree',
2311 'Delete debian/patches, as part of converting to git-debrebase format.',
2312 '[git-debrebase convert-from-gbp: drop patches from tree]'
2314 # make the anchor merge
2315 # the tree is already exactly right
2316 $work = make_commit [$work, $upstream], [
2317 'git-debrebase import: declare upstream',
2318 'First breakwater merge.',
2319 '[git-debrebase anchor: declare upstream]'
2322 # rebase the patch queue onto the new breakwater
2323 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2324 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2325 $work = git_rev_parse 'HEAD';
2327 if ($previous_dgit_view) {
2328 $work = make_commit [$work, $previous_dgit_view], [
2329 'git-debrebase import: declare ff from dgit archive view',
2330 '[git-debrebase pseudomerge: import-from-gbp]',
2337 update_head_checkout $old_head, $work, 'convert-from-gbp';
2340 sub cmd_convert_to_gbp () {
2341 badusage "no arguments allowed" if @ARGV;
2342 my $head = get_head();
2343 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2344 keycommits $head, 0;
2346 make_patches_staged $head;
2348 $out = make_commit ['HEAD'], [
2349 'Commit patch queue (converted from git-debrebase format)',
2350 '[git-debrebase convert-to-gbp: commit patches]',
2354 push @deferred_updates, "delete $ffq";
2355 push @deferred_updates, "delete $gdrlast";
2358 update_head_checkout $head, $out, "convert to gbp (v0)";
2359 print <<END or die $!;
2360 git-debrebase: converted to git-buildpackage branch format
2361 git-debrebase: WARNING: do not now run "git-debrebase" any more
2362 git-debrebase: WARNING: doing so would drop all upstream patches!
2366 sub cmd_convert_from_dgit_view () {
2367 my $clogp = parsechangelog();
2369 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2375 getoptions("convert-from-dgit-view",
2376 'diagnose!', \$diagnose,
2377 'build-products-dir:s', \$bpd,
2378 'origs!', \$do_origs,
2380 'always-convert-anyway!', \$always);
2381 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2386 my $spec = shift @ARGV;
2387 my $commit = git_rev_parse "$spec^{commit}";
2388 push @upstreams, { Commit => $commit,
2389 Source => "$ARGV[0], from command line",
2394 my $head = get_head();
2398 my $trouble = sub { $troubles++; };
2399 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2400 printdebug "troubles=$troubles\n";
2403 $us: Branch already seems to be in git-debrebase format!
2404 $us: --always-convert-anyway would do the conversion operation anyway
2405 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2407 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2412 snags_maybe_bail_early();
2414 my $version = upstreamversion $clogp->{Version};
2415 print STDERR "Considering possible commits corresponding to upstream:\n";
2420 my $ups_tag = upstream_commitish_search $version, \@tried;
2422 my $this = "git tag $tried[-1]";
2423 push @upstreams, { Commit => $ups_tag,
2428 " git tag: no suitable tag found (tried %s)\n",
2433 my $p = $clogp->{'Source'};
2434 # we do a quick check to see if there are plausible origs
2436 if (!opendir BPD, $bpd) {
2437 die "$bpd: opendir: $!" unless $!==ENOENT;
2439 while ($!=0, my $f = readdir BPD) {
2440 next unless is_orig_file_of_p_v $f, $p, $version;
2442 " orig: found what looks like a .orig, %s\n",
2447 die "read $bpd: $!" if $!;
2451 my $tree = cmdoutput
2452 @dgit, qw(--build-products-dir), $bpd,
2453 qw(print-unapplied-treeish);
2456 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2457 rm_subdir_cached 'debian';
2458 $tree = cmdoutput @git, qw(write-tree);
2459 my $ups_synth = make_commit [], [ <<END, <<END,
2460 Import effective orig tree for upstream version $version
2462 This includes the contents of the .orig(s), minus any debian/ directory.
2464 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2467 push @upstreams, { Commit => $ups_synth,
2468 Source => "orig(s) imported via dgit",
2473 " orig: no suitable origs found (looked for %s in %s)\n",
2474 "${p}_".(stripeoch $version)."...", $bpd;
2479 my $some_patches = stat_exists 'debian/patches/series';
2481 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2484 foreach my $u (@upstreams) {
2488 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2489 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2490 runcmd @git, qw(clean -xdff);
2491 runcmd @git, qw(checkout), $head, qw(-- debian);
2492 if ($some_patches) {
2493 rm_subdir_cached 'debian/patches';
2494 $work = make_commit [ $work ], [
2495 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2496 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2497 "to git-debrebase format. Upstream changes will appear as commits.",
2498 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2501 $work = make_commit [ $work, $u->{Commit} ], [
2502 'git-debrebase convert-from-dgit-view: declare upstream',
2503 '(Re)constructed breakwater merge.',
2504 '[git-debrebase anchor: declare upstream]'
2506 runcmd @git, qw(checkout --quiet -b mk), $work;
2507 if ($some_patches) {
2508 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2509 runcmd @git, qw(reset --quiet);
2510 my @gbp_cmd = (qw(gbp pq import));
2512 my $gbp_err = "../gbp-pq-err";
2513 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2515 my $r = system @gbp_cmd;
2518 " %s: couldn't apply patches: gbp pq %s",
2519 $u->{Source}, waitstatusmsg();
2523 my $work = git_rev_parse qw(HEAD);
2524 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2525 if (length $diffout) {
2527 " $u->{Source}: applying patches gives different tree\n";
2528 print STDERR $diffout if $diagnose;
2532 $u->{Result} = $work;
2540 Could not find or construct a suitable upstream commit.
2541 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2542 upstream commmit explicitly or provide suitable origs.
2546 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2548 ffq_check $result->{Result};
2550 update_head_checkout $head, $result->{Result},
2551 'convert-from-dgit-view';
2554 sub cmd_downstream_rebase_launder_v0 () {
2555 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2557 $base = git_rev_parse $base;
2558 my $old_head = get_head();
2559 my $current = $old_head;
2562 if ($current eq $base) {
2563 $topmost_keep //= $current;
2564 print " $current BASE stop\n";
2567 my $cl = classify $current;
2568 print " $current $cl->{Type}";
2570 my $p0 = $cl->{Parents}[0]{CommitId};
2572 if ($cl->{Type} eq 'Pseudomerge') {
2573 print " ^".($cl->{Contributor}{Ix}+1);
2574 $next = $cl->{Contributor}{CommitId};
2575 } elsif ($cl->{Type} eq 'AddPatches' or
2576 $cl->{Type} eq 'Changelog') {
2586 $topmost_keep //= $current;
2588 die "to-be stripped changes not on top of the branch\n"
2593 if ($topmost_keep eq $old_head) {
2594 print "unchanged\n";
2596 print "updating to $topmost_keep\n";
2597 update_head_checkout
2598 $old_head, $topmost_keep,
2599 'downstream-rebase-launder-v0';
2605 "D+" => \$debuglevel,
2606 'noop-ok', => \$opt_noop_ok,
2607 'f=s' => \@snag_force_opts,
2608 'anchor=s' => \@opt_anchors,
2609 '--dgit=s' => \($dgit[0]),
2612 my ($opt,$val) = @_;
2613 badusage "git-debrebase: no cuddling to -i for git-rebase"
2615 die if $opt_defaultcmd_interactive; # should not happen
2616 $opt_defaultcmd_interactive = [ qw(-i) ];
2617 # This access to @ARGV is excessive familiarity with
2618 # Getopt::Long, but there isn't another sensible
2619 # approach. '-i=s{0,}' does not work with bundling.
2620 push @$opt_defaultcmd_interactive, @ARGV;
2623 'help' => sub { print $usage_message or die $!; finish 0; },
2626 initdebug('git-debrebase ');
2627 enabledebug if $debuglevel;
2629 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2630 chdir $toplevel or die "chdir $toplevel: $!";
2632 $rd = fresh_playground "$playprefix/misc";
2634 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2636 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2637 defaultcmd_rebase();
2639 my $cmd = shift @ARGV;
2642 $cmdfn = ${*::}{"cmd_$cmdfn"};
2644 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";