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);
58 our $wrecknoteprefix = 'refs/debrebase-wreckage';
64 print STDERR "$us: bad usage: $m\n";
70 local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
71 GetOptions @_ or badusage $m;
75 getoptions_main "bad options follow \`git-debrebase $sc'", @_;
79 my ($k, $optional) = @_;
81 my @cmd = qw(git config -z);
82 push @cmd, qw(--get-all) if wantarray;
84 my $out = cmdoutput_errok @cmd;
86 fail "missing required git config $k" unless $optional;
89 my @l = split /\0/, $out;
90 return wantarray ? @l : $l[0];
97 my $dd = new Data::Dumper [ $v ];
98 Terse $dd 1; Indent $dd 0; Useqq $dd 1;
104 my $data = (git_cat_file $objid, 'commit');
105 $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
109 sub D_UPS () { 0x02; } # upstream files
110 sub D_PAT_ADD () { 0x04; } # debian/patches/ extra patches at end
111 sub D_PAT_OTH () { 0x08; } # debian/patches other changes
112 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
113 sub D_DEB_OTH () { 0x20; } # debian/changelog
114 sub DS_DEB () { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
116 our $playprefix = 'debrebase';
121 our @dgit = qw(dgit);
123 sub in_workarea ($) {
126 my $r = eval { $sub->(); };
127 { local $@; changedir $maindir; }
131 sub fresh_workarea (;$) {
134 $workarea = fresh_playground "$playprefix/$subdir";
135 in_workarea sub { playtree_setup };
138 sub run_ref_updates_now ($$) {
139 my ($mrest, $updates) = @_;
140 # @$updates is a list of lines for git-update-ref, without \ns
142 my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
143 debugcmd '>|', @upd_cmd;
144 open U, "|-", @upd_cmd or die $!;
145 foreach (@$updates) {
146 printdebug ">= ", $_, "\n";
147 print U $_, "\n" or die $!;
150 close U or failedcmd @upd_cmd;
153 our $snags_forced = 0;
154 our $snags_tripped = 0;
155 our $snags_summarised = 0;
156 our @deferred_updates;
157 our @deferred_update_messages;
159 sub merge_wreckage_cleaning ($) {
161 git_for_each_ref("$wrecknoteprefix/*", sub {
162 my ($objid,$objtype,$fullrefname,$reftail) = @_;
163 push @$updates, "delete $fullrefname";
167 sub all_snags_summarised () {
168 $snags_forced + $snags_tripped == $snags_summarised;
170 sub run_deferred_updates ($) {
173 confess 'dangerous internal error' unless all_snags_summarised();
175 merge_wreckage_cleaning \@deferred_updates;
176 run_ref_updates_now $mrest, \@deferred_updates;
177 print $_, "\n" foreach @deferred_update_messages;
179 @deferred_updates = ();
180 @deferred_update_messages = ();
183 sub get_differs ($$) {
185 # This resembles quiltify_trees_differ, in dgit, a bit.
186 # But we don't care about modes, or dpkg-source-unrepresentable
187 # changes, and we don't need the plethora of different modes.
188 # Conversely we need to distinguish different kinds of changes to
189 # debian/ and debian/patches/.
194 my ($opts, $limits, $fn) = @_;
195 my @cmd = (@git, qw(diff-tree -z --no-renames));
197 push @cmd, "$_:" foreach $x, $y;
198 push @cmd, '--', @$limits;
199 my $diffs = cmdoutput @cmd;
200 foreach (split /\0/, $diffs) { $fn->(); }
203 $rundiff->([qw(--name-only)], [], sub {
204 $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
207 if ($differs & DS_DEB) {
209 $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
211 m{^debian/patches/} ? D_PAT_OTH :
212 $_ eq 'debian/changelog' ? D_DEB_CLOG :
215 die "mysterious debian changes $x..$y"
216 unless $differs & (D_PAT_OTH|DS_DEB);
219 if ($differs & D_PAT_OTH) {
221 $differs &= ~D_PAT_OTH;
223 $differs |= D_PAT_OTH;
224 no warnings qw(exiting); last;
226 $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
227 no warnings qw(exiting);
228 if (!defined $mode) {
231 die unless s{^debian/patches/}{};
233 if ($mode eq 'A' && !m/\.series$/s) {
235 } elsif ($mode eq 'M' && $_ eq 'series') {
236 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
237 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
238 chomp $x_s; $x_s .= "\n";
239 $ok = $x_s eq substr($y_s, 0, length $x_s);
244 $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
246 die "mysterious debian/patches changes $x..$y"
247 unless $differs & (D_PAT_ADD|D_PAT_OTH);
250 printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
255 sub commit_pr_info ($) {
257 return Data::Dumper->dump([$r], [qw(commit)]);
260 sub calculate_committer_authline () {
261 my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
262 'DUMMY COMMIT (git-debrebase)', "HEAD:";
263 my ($h,$m) = get_commit $c;
264 $h =~ m/^committer .*$/m or confess "($h) ?";
268 sub rm_subdir_cached ($) {
270 runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
273 sub read_tree_subdir ($$) {
274 my ($subdir, $new_tree_object) = @_;
275 rm_subdir_cached $subdir;
276 runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
279 sub read_tree_debian ($) {
281 read_tree_subdir 'debian', "$treeish:debian";
282 rm_subdir_cached 'debian/patches';
285 sub read_tree_upstream ($;$$) {
286 my ($treeish, $keep_patches, $tree_with_debian) = @_;
287 # if $tree_with_debian is supplied, will use that for debian/
288 # otherwise will save and restore it.
290 $tree_with_debian ? "$tree_with_debian:debian"
291 : cmdoutput @git, qw(write-tree --prefix=debian/);
292 runcmd @git, qw(read-tree), $treeish;
293 read_tree_subdir 'debian', $debian;
294 rm_subdir_cached 'debian/patches' unless $keep_patches;
297 sub make_commit ($$) {
298 my ($parents, $message_paras) = @_;
299 my $tree = cmdoutput @git, qw(write-tree);
300 my @cmd = (@git, qw(commit-tree), $tree);
301 push @cmd, qw(-p), $_ foreach @$parents;
302 push @cmd, qw(-m), $_ foreach @$message_paras;
303 return cmdoutput @cmd;
306 our @snag_force_opts;
308 my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
309 if (grep { $_ eq $tag } @snag_force_opts) {
311 print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
314 print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
318 # Important: all mainline code must call snags_maybe_bail after
319 # any point where snag might be called, but before making changes
320 # (eg before any call to run_deferred_updates). snags_maybe_bail
321 # may be called more than once if necessary (but this is not ideal
322 # because then the messages about number of snags may be confusing).
323 sub snags_maybe_bail () {
324 return if all_snags_summarised();
327 "%s: snags: %d overriden by individual -f options\n",
330 if ($snags_tripped) {
333 "%s: snags: %d overriden by global --force\n",
337 "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
341 $snags_summarised = $snags_forced + $snags_tripped;
343 sub snags_maybe_bail_early () {
344 # useful to bail out early without doing a lot of work;
345 # not a substitute for snags_maybe_bail.
346 snags_maybe_bail() if $snags_tripped && !$opt_force;
349 return $snags_forced || $snags_tripped;
352 sub gbp_pq_export ($$$) {
353 my ($bname, $base, $tip) = @_;
354 # must be run in a workarea. $bname and patch-queue/$bname
355 # ought not to exist. Leaves you on patch-queue/$bname with
356 # the patches staged but not committed.
357 printdebug "gbp_pq_export $bname $base $tip\n";
358 runcmd @git, qw(checkout -q -b), $bname, $base;
359 runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
360 my @gbp_cmd = (qw(gbp pq export));
361 my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
363 { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
366 runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
370 # xxx allow merge resolution separately from laundering, before git merge
372 # xxx general gdr docs highlight forbidden things
373 # xxx general gdr docs list allowable things ?
374 # xxx general gdr docs explicitly forbid some rebase
376 # xxx provide a way for the user to help
377 # xxx (eg, provide wreckage provide way to continue)
380 # use git-format-patch?
381 # our own patch identification algorithm?
382 # this is an alternative strategy
384 sub merge_failed ($$;@) {
385 my ($wrecknotes, $emsg, @xmsgs) = @_;
387 push @m, "Merge resolution failed: $emsg";
393 merge_wreckage_cleaning \@updates;
395 while (my ($k,$v) = each %$wrecknotes) {
396 push @updates, "create $wrecknoteprefix/$k $v";
398 run_ref_updates_now "merge failed", \@updates;
399 push @m, "Wreckage left in $wrecknoteprefix/*.";
401 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
403 # use finish rather than fail, in case we are within an eval
404 # (that can happen inside walk!)
406 print STDERR "$us: $_\n" foreach @m;
410 sub mwrecknote ($$$) {
411 my ($wrecknotes, $reftail, $commitish) = @_;
412 confess unless defined $commitish;
413 printdebug "mwrecknote $reftail $commitish\n";
414 $wrecknotes->{$reftail} = $commitish;
417 sub merge_series ($$$;@) {
418 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
419 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
420 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
421 # ^ specifies several patch series (currently we only support exactly 2)
422 # return value is a commit which is the result of
423 # merging the two versions of the same topic branch
424 # $input_q[0] and $input_q[1]
425 # with respect to the old version
429 # Creates, in *_q, a key MR for its private use
431 printdebug "merge_series newbase=$newbase\n";
433 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
434 $base_q->{MR}{S} = 'base';
437 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
438 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
439 # $prereq{<patch filename>} exists or not (even later)
443 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
445 my $attempt_cmd = sub {
449 merge_failed $wrecknotes,
450 failedcmd_waitstatus(),
451 "failed command: @_";
456 fresh_workarea "merge";
457 my $seriesfile = "debian/patches/series";
460 foreach my $q ($base_q, reverse @input_qs) {
462 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
464 if (open S, $seriesfile) {
465 while (my $patch = <S>) {
466 chomp $patch or die $!;
467 $prereq{$patch} //= {};
468 foreach my $earlier (@earlier) {
469 $prereq{$patch}{$earlier}{$s}++ and die;
471 push @earlier, $patch;
472 stat "debian/patches/$patch" or die "$patch ?";
474 S->error and die "$seriesfile $!";
477 die "$seriesfile $!" unless $!==ENOENT;
479 read_tree_upstream $newbase, 1;
480 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
481 "Convert $s to patch queue for merging",
482 "[git-debrebase merge-innards patch-queue import:".
485 printdebug "merge_series pec $pec ";
486 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
487 $pec = make_commit [ $pec ], [
488 "Drop series file from $s to avoid merge trouble",
489 "[git-debrebase merge-innards patch-queue prep:".
493 read_tree_debian $newbase;
495 read_tree_subdir 'debian/patches', "$pec:debian/patches";
497 rm_subdir_cached 'debian/patches';
499 $pec = make_commit [ $pec ], [
500 "Update debian/ (excluding patches) to final to avoid re-merging",
501 "debian/ was already merged and we need to just take that.",
502 "[git-debrebase merge-innards patch-queue packaging:".
506 printdebug "pec' $pec\n";
507 runcmd @git, qw(reset -q --hard), $pec;
508 $q->{MR}{PEC} = $pec;
509 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
511 # now, because of reverse, we are on $input_q->{MR}{OQC}
512 runcmd @git, qw(checkout -q -b merge);
513 printdebug "merge_series merging...\n";
514 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
516 $attempt_cmd->(@mergecmd);
518 printdebug "merge_series merge ok, series...\n";
519 # We need to construct a new series file
520 # Firstly, resolve prereq
521 foreach my $f (sort keys %prereq) {
522 printdebug "merge_series patch\t$f\t";
523 if (!stat_exists "debian/patches/$f") {
524 print DEBUG " drop\n" if $debuglevel;
525 # git merge deleted it; that's how we tell it's not wanted
529 print DEBUG " keep\n" if $debuglevel;
530 foreach my $g (sort keys %{ $prereq{$f} }) {
531 my $gfp = $prereq{$f}{$g};
532 printdebug "merge_series prereq\t$f\t-> $g\t";
533 if (!!$gfp->{0} == !!$gfp->{1}
536 print DEBUG "\tkeep\n" if $debuglevel;
538 print DEBUG "\tdrop\n" if $debuglevel;
539 delete $prereq{$f}{$g};
546 return scalar keys %{ $prereq{$f} };
549 my $nodate = time + 1;
551 # $authordate{<patch filename>};
552 my $authordate = sub {
554 $authordate{$f} //= do {
555 open PF, "<", "debian/patches/$f" or die "$f $!";
557 return $nodate if m/^$/;
558 last if s{^Date: }{};
561 return cmdoutput qw(date +%s -d), $_;
565 open NS, '>', $seriesfile or die $!;
567 while (keys %prereq) {
569 foreach my $try (sort keys %prereq) {
572 $unsat->($try) <=> $unsat->($best) or
573 $authordate->($try) <=> $authordate->($best) or
579 printdebug "merge_series series next $best\n";
580 print NS "$best\n" or die $!;
581 delete $prereq{$best};
582 foreach my $gp (values %prereq) {
587 runcmd @git, qw(add), $seriesfile;
588 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
589 $mwrecknote->('merged-patchqueue', git_rev_parse 'HEAD');
591 printdebug "merge_series series gbp pq import\n";
593 $attempt_cmd->(qw(gbp pq import));
595 # OK now we are on patch-queue/merge, and we need to rebase
596 # onto the intended parent and drop the patches from each one
598 printdebug "merge_series series ok, building...\n";
599 my $build = $newbase;
600 my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
601 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
602 my $commit = git_cat_file $c, 'commit';
603 printdebug "merge_series series ok, building $c\n";
604 read_tree_upstream $c, 0, $newbase;
605 my $tree = cmdoutput @git, qw(write-tree);
606 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
607 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
608 open C, ">", "../mcommit" or die $!;
609 print C $commit or die $!;
611 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
614 $mwrecknote->('merged-result', $result);
616 runcmd @git, qw(update-ref refs/heads/result), $result;
618 runcmd @git, qw(checkout -q -b debug);
619 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
620 runcmd @git, qw(add .);
621 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
622 my $mdebug = git_rev_parse 'HEAD';
623 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
624 $mwrecknote->('merged-debug', $mdebug);
626 printdebug "merge_series returns $result\n";
630 # classify returns an info hash like this
632 # Hdr => # commit headers, including 1 final newline
633 # Msg => # commit message (so one newline is dropped)
635 # Type => (see below)
637 # Ix => $index # ie 0, 1, 2, ...
639 # Differs => return value from get_differs
641 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
643 # NewMsg => # commit message, but with any [dgit import ...] edited
644 # # to say "[was: ...]"
654 # has additional entres in classification result
655 # Overwritten = [ subset of Parents ]
656 # Contributor = $the_remaining_Parent
658 # DgitImportUnpatched
659 # has additional entry in classification result
660 # OrigParents = [ subset of Parents ]
663 # has additional entry in classification result
664 # OrigParents = [ subset of Parents ] # singleton list
671 # has additional entry in classification result
674 sub parsecommit ($;$) {
675 my ($objid, $p_ref) = @_;
676 # => hash with CommitId Hdr Msg Tree Parents
677 # Parents entries have only Ix CommitId
678 # $p_ref, if provided, must be [] and is used as a base for Parents
683 my ($h,$m) = get_commit $objid;
685 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
686 my (@ph) = $h =~ m/^parent (\w+)$/mg;
696 foreach my $ph (@ph) {
698 Ix => scalar @$p_ref,
710 my $r = parsecommit($objid, \@p);
714 $p->{Differs} = (get_differs $p->{CommitId}, $t),
717 printdebug "classify $objid \$t=$t \@p",
718 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
722 my ($type, @rest) = @_;
723 $r = { %$r, Type => $type, @rest };
725 printdebug " = $type ".(dd $r)."\n";
731 $r = { %$r, Type => qw(Unknown), Why => $why };
732 printdebug " ** Unknown\n";
736 if (grep { $_ eq $objid } @opt_anchors) {
737 return $classify->('TreatAsAnchor');
740 my @identical = grep { !$_->{Differs} } @p;
741 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
742 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
744 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
745 # multi-orig upstreams are represented with an anchor merge
746 # from a single upstream commit which combines the orig tarballs
748 # Every anchor tagged this way must be a merge.
749 # We are relying on the
750 # [git-debrebase anchor: ...]
751 # commit message annotation in "declare" anchor merges (which
752 # do not have any upstream changes), to distinguish those
753 # anchor merges from ordinary pseudomerges (which we might
754 # just try to strip).
756 # However, the user is going to be doing git-rebase a lot. We
757 # really don't want them to rewrite an anchor commit.
758 # git-rebase trips up on merges, so that is a useful safety
761 # BreakwaterStart commits are also anchors in the terminology
762 # of git-debrebase(5), but they are untagged (and always
763 # manually generated).
765 # We cannot not tolerate any tagged linear commit (ie,
766 # BreakwaterStart commits tagged `[anchor:') because such a
767 # thing could result from an erroneous linearising raw git
768 # rebase of a merge anchor. That would represent a corruption
769 # of the branch. and we want to detect and reject the results
770 # of such corruption before it makes it out anywhere. If we
771 # reject it here then we avoid making the pseudomerge which
772 # would be needed to push it.
774 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
775 @p == 2 or return $badanchor->("has other than two parents");
776 $haspatches and return $badanchor->("contains debian/patches");
778 # How to decide about l/r ordering of anchors ? git
779 # --topo-order prefers to expand 2nd parent first. There's
780 # already an easy rune to look for debian/ history anyway (git log
781 # debian/) so debian breakwater branch should be 1st parent; that
782 # way also there's also an easy rune to look for the upstream
783 # patches (--topo-order).
785 # Also this makes --first-parent be slightly more likely to
786 # be useful - it makes it provide a linearised breakwater history.
788 # Of course one can say somthing like
789 # gitk -- ':/' ':!/debian'
790 # to get _just_ the commits touching upstream files, and by
791 # the TREESAME logic in git-rev-list this will leave the
792 # breakwater into upstream at the first anchor. But that
793 # doesn't report debian/ changes at all.
795 # Other observations about gitk: by default, gitk seems to
796 # produce output in a different order to git-rev-list. I
797 # can't seem to find this documented anywhere. gitk
798 # --date-order DTRT. But, gitk always seems to put the
799 # parents from left to right, in order, so it's easy to see
800 # which way round a pseudomerge is.
802 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
803 $p[1]{Differs} & ~DS_DEB and
804 $badanchor->("upstream files differ from left parent");
805 $p[0]{Differs} & ~D_UPS and
806 $badanchor->("debian/ differs from right parent");
808 return $classify->(qw(Anchor),
809 OrigParents => [ $p[1] ]);
813 my $d = $r->{Parents}[0]{Differs};
814 if ($d == D_PAT_ADD) {
815 return $classify->(qw(AddPatches));
816 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
817 return $unknown->("edits debian/patches");
818 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
819 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
821 if ($d == D_DEB_CLOG) {
822 return $classify->(qw(Changelog));
824 return $classify->(qw(Packaging));
826 } elsif ($ty eq 'missing') {
827 return $classify->(qw(BreakwaterStart));
829 return $unknown->("parent's debian is not a directory");
831 } elsif ($d == D_UPS) {
832 return $classify->(qw(Upstream));
833 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
834 return $classify->(qw(Mixed));
836 return $unknown->("no changes");
838 confess "internal error $objid ?";
842 return $unknown->("origin commit");
845 if (@p == 2 && @identical == 1) {
846 my @overwritten = grep { $_->{Differs} } @p;
847 confess "internal error $objid ?" unless @overwritten==1;
848 return $classify->(qw(Pseudomerge),
849 Overwritten => [ $overwritten[0] ],
850 Contributor => $identical[0]);
852 if (@p == 2 && @identical == 2) {
854 my ($ph,$pm) = get_commit $_[0]{CommitId};
855 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
859 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
860 if ($order > 0) { # newer first
861 } elsif ($order < 0) {
862 @bytime = reverse @bytime;
864 # same age, default to order made by -s ours
865 # that is, commit was made by someone who preferred L
867 return $classify->(qw(Pseudomerge),
868 SubType => qw(Ambiguous),
869 Contributor => $bytime[0],
870 Overwritten => [ $bytime[1] ]);
873 my ($p_h, $p_m) = get_commit $p->{CommitId};
874 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
875 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
877 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
879 if (!(grep { !$_->{IsOrigin} } @p) and
880 (@orig_ps >= @p - 1) and
881 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
883 return $classify->(qw(DgitImportUnpatched),
884 OrigParents => \@orig_ps);
888 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
889 # xxx ^ metadata tag needs adding to (5)
890 return $classify->("MergedBreakwaters");
892 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
893 return $unknown->("unknown kind of merge from $1");
896 return $unknown->("octopus merge");
899 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
900 return $unknown->("general two-parent merge");
903 return $classify->("VanillaMerge");
906 sub keycommits ($;$$$$$);
908 sub mergedbreakwaters_anchor ($) {
911 foreach my $p (@{ $cl->{Parents} }) {
912 my ($panchor, $pbw) = keycommits $p->{CommitId},
913 undef,undef,undef,undef, 1;
914 $best_anchor = $panchor
915 if !defined $best_anchor
916 or is_fast_fwd $best_anchor, $panchor;
917 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
918 unless is_fast_fwd $panchor, $best_anchor;
923 sub keycommits ($;$$$$$) {
924 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
925 # => ($anchor, $breakwater)
927 # $unclean->("unclean-$tagsfx", $msg, $cl)
928 # $furniture->("unclean-$tagsfx", $msg, $cl)
929 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
930 # is callled for each situation or commit that
931 # wouldn't be found in a laundered branch
932 # $furniture is for furniture commits such as might be found on an
933 # interchange branch (pseudomerge, d/patches, changelog)
934 # $trouble is for things whnich prevent the return of
935 # anchor and breakwater information; if that is ignored,
936 # then keycommits returns (undef, undef) instead.
937 # $fatal is for unprocessable commits, and should normally cause
938 # a failure. If ignored, agaion, (undef, undef) is returned.
940 # If $claimed_bw, this is supposed to be a breakwater commit.
942 # If a callback is undef, fail is called instead.
943 # If a callback is defined but false, the situation is ignored.
945 # no warnings qw(exiting); last;
946 # if the answer is no longer wanted.
948 my ($anchor, $breakwater);
949 $breakwater = $head if $claimed_bw;
953 $fatal //= sub { fail $_[1]; };
955 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
956 my $why = $mainwhy.$xwhy;
957 my $m = "branch needs laundering (run git-debrebase): $why";
958 fail $m unless defined $cb;
960 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
962 my $found_anchor = sub {
964 $breakwater //= $clogonly;
965 $breakwater //= $head;
966 no warnings qw(exiting);
970 $cl = classify $head;
971 my $ty = $cl->{Type};
972 if ($ty eq 'Packaging') {
973 $breakwater //= $clogonly;
974 $breakwater //= $head;
975 } elsif ($ty eq 'Changelog') {
976 # this is going to count as the tip of the breakwater
977 # only if it has no upstream stuff before it
979 } elsif ($ty eq 'Anchor' or
980 $ty eq 'TreatAsAnchor' or
981 $ty eq 'BreakwaterStart') {
982 $found_anchor->($head);
983 } elsif ($ty eq 'Upstream') {
984 $x->($unclean, 'ordering',
985 "packaging change ($breakwater) follows upstream change"," (eg $head)")
986 if defined $breakwater;
989 } elsif ($ty eq 'Mixed') {
990 $x->($unclean, 'mixed',
991 "found mixed upstream/packaging commit"," ($head)");
994 } elsif ($ty eq 'Pseudomerge' or
995 $ty eq 'AddPatches') {
997 $x->($furniture, (lc $ty),
998 "found interchange bureaucracy commit ($ty)"," ($head)");
999 } elsif ($ty eq 'DgitImportUnpatched') {
1001 $x->($trouble, 'dgitimport',
1002 "found dgit dsc import"," ($head)");
1003 return (undef,undef);
1005 $x->($fatal, 'unprocessable',
1006 "found bare dgit dsc import with no prior history",
1008 return (undef,undef);
1010 } elsif ($ty eq 'VanillaMerge') {
1011 $x->($trouble, 'vanillamerge',
1012 "found vanilla merge"," ($head)");
1013 return (undef,undef);
1014 } elsif ($ty eq 'MergedBreakwaters') {
1015 $found_anchor->(mergedbreakwaters_anchor $cl);
1017 $x->($fatal, 'unprocessable',
1018 "found unprocessable commit, cannot cope: $cl->{Why}",
1020 return (undef,undef);
1022 $head = $cl->{Parents}[0]{CommitId};
1024 return ($anchor, $breakwater);
1030 $nogenerate,$report, $report_lprefix) = @_;
1031 # => ($tip, $breakwater_tip, $last_anchor)
1032 # (or nothing, if $nogenerate)
1034 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1035 $report_lprefix //= '';
1037 # go through commits backwards
1038 # we generate two lists of commits to apply:
1039 # breakwater branch and upstream patches
1040 my (@brw_cl, @upp_cl, @processed);
1047 my ($prose, $info) = @_;
1048 my $ms = $cl->{Msg};
1051 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1052 return (Msg => $ms);
1054 my $rewrite_from_here = sub {
1056 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1058 push @processed, $sp_cl;
1063 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1066 return unless $report;
1067 print $report $prdelim, $report_lprefix, @_;
1071 my $bomb = sub { # usage: return $bomb->();
1072 print $report " Unprocessable" if $report;
1073 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1076 return (undef,undef);
1078 fail "found unprocessable commit, cannot cope".
1079 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1080 " (commit $cur) (d.".
1081 (join ' ', map { sprintf "%#x", $_->{Differs} }
1082 @{ $cl->{Parents} }).
1089 my $build_start = sub {
1090 my ($msg, $parent) = @_;
1093 no warnings qw(exiting); last;
1098 merge_failed $cl->{MergeWreckNotes}, $emsg;
1101 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1106 $cl = classify $cur;
1107 $cl->{MergeWreckNotes} //= {};
1108 my $ty = $cl->{Type};
1109 my $st = $cl->{SubType};
1110 $prline->("$cl->{CommitId} $cl->{Type}");
1111 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1112 push @processed, $cl;
1113 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1114 if ($ty eq 'AddPatches') {
1116 $rewrite_from_here->(\@upp_cl);
1118 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1122 } elsif ($ty eq 'BreakwaterStart') {
1123 $last_anchor = $cur;
1124 $build_start->('FirstPackaging', $cur);
1125 } elsif ($ty eq 'Upstream') {
1129 } elsif ($ty eq 'Mixed') {
1132 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1135 $queue->(\@brw_cl, "debian");
1136 $queue->(\@upp_cl, "upstream");
1137 $rewrite_from_here->(\@brw_cl);
1140 } elsif ($ty eq 'Pseudomerge') {
1141 my $contrib = $cl->{Contributor}{CommitId};
1142 print $report " Contributor=$contrib" if $report;
1143 push @pseudomerges, $cl;
1144 $rewrite_from_here->(\@upp_cl);
1147 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1148 $last_anchor = $cur;
1149 $build_start->("Anchor", $cur);
1150 } elsif ($ty eq 'DgitImportUnpatched') {
1151 my $pm = $pseudomerges[-1];
1153 # To an extent, this is heuristic. Imports don't have
1154 # a useful history of the debian/ branch. We assume
1155 # that the first pseudomerge after an import has a
1156 # useful history of debian/, and ignore the histories
1157 # from later pseudomerges. Often the first pseudomerge
1158 # will be the dgit import of the upload to the actual
1159 # suite intended by the non-dgit NMUer, and later
1160 # pseudomerges may represent in-archive copies.
1161 my $ovwrs = $pm->{Overwritten};
1162 printf $report " PM=%s \@Overwr:%d",
1163 $pm->{CommitId}, (scalar @$ovwrs)
1166 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1169 my $ovwr = $ovwrs->[0]{CommitId};
1170 printf $report " Overwr=%s", $ovwr if $report;
1171 # This import has a tree which is just like a
1172 # breakwater tree, but it has the wrong history. It
1173 # ought to have the previous breakwater (which the
1174 # pseudomerge overwrote) as an ancestor. That will
1175 # make the history of the debian/ files correct. As
1176 # for the upstream version: either it's the same as
1177 # was ovewritten (ie, same as the previous
1178 # breakwater), in which case that history is precisely
1179 # right; or, otherwise, it was a non-gitish upload of a
1180 # new upstream version. We can tell these apart by
1181 # looking at the tree of the supposed upstream.
1184 SpecialMethod => 'DgitImportDebianUpdate',
1185 $xmsg->("convert dgit import: debian changes")
1188 SpecialMethod => 'DgitImportUpstreamUpdate',
1189 $xmsg->("convert dgit import: upstream update",
1192 $prline->(" Import");
1193 $rewrite_from_here->(\@brw_cl);
1194 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1198 # Everything is from this import. This kind of import
1199 # is already nearly in valid breakwater format, with the
1200 # patches as commits. Unfortunately it contains
1202 printdebug "*** WALK BOMB bare dgit import\n";
1203 $cl->{Why} = "bare dgit dsc import";
1207 } elsif ($ty eq 'MergedBreakwaters') {
1208 $last_anchor = mergedbreakwaters_anchor $cl;
1209 $build_start->(' MergedBreakwaters', $cur);
1211 } elsif ($ty eq 'VanillaMerge') {
1212 # User may have merged unstitched branch(es). We will
1213 # have now lost what ffq-prev was then (since the later
1214 # pseudomerge may introduce further changes). The effect
1215 # of resolving such a merge is that we may have to go back
1216 # further in history to find a merge base, since the one
1217 # which was reachable via ffq-prev is no longer findable.
1218 # This is suboptimal, but if it all works we'll have done
1220 # xxx we should warn the user in the docs about this
1224 # We expect to find a dominating anchor amongst the
1225 # inputs' anchors. That will be the new anchor.
1227 # More complicated is finding a merge base for the
1228 # breakwaters. We need a merge base that is a breakwater
1229 # commit. The ancestors of breakwater commits are more
1230 # breakwater commits and possibly upstream commits and the
1231 # ancestors of those upstream. Upstreams might have
1232 # arbitrary ancestors. But any upstream commit U is
1233 # either included in both anchors, in which case the
1234 # earlier anchor is a better merge base than any of U's
1235 # ancestors; or U is not included in the older anchor, in
1236 # which case U is not an ancestor of the vanilla merge at
1237 # all. So no upstream commit, nor any ancestor thereof,
1238 # is a best merge base. As for non-breakwater Debian
1239 # commits: these are never ancestors of any breakwater.
1241 # So any best merge base as found by git-merge-base
1242 # is a suitable breakwater anchor. Usually there will
1245 printdebug "*** MERGE\n";
1247 my @bwbcmd = (@git, qw(merge-base));
1248 my @ibcmd = (@git, qw(merge-base --all));
1249 my $might_be_in_bw = 1;
1251 my $ps = $cl->{Parents};
1253 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1255 foreach my $p (@$ps) {
1256 $prline->(" VanillaMerge ".$p->{Ix});
1258 my ($ptip, $pbw, $panchor) =
1259 walk $p->{CommitId}, 0, $report,
1260 $report_lprefix.' ';
1261 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1262 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1263 $p->{Anchor} = $panchor;
1265 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1266 $mwrecknote->("$lr-input", $p->{CommitId});
1268 my $mwrecknote_parent = sub {
1270 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1272 $mwrecknote_parent->('Laundered');
1273 $mwrecknote_parent->('Breakwater');
1274 $mwrecknote_parent->('Anchor');
1276 $best_anchor = $panchor if
1277 !defined $best_anchor or
1278 is_fast_fwd $best_anchor, $panchor;
1280 printdebug " MERGE BA best=".($best_anchor//'-').
1284 $mwrecknote->('result-anchor', $best_anchor);
1286 foreach my $p (@$ps) {
1287 $prline->(" VanillaMerge ".$p->{Ix});
1288 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1289 $nomerge->('divergent anchors');
1290 } elsif ($p->{Anchor} eq $best_anchor) {
1291 print $report " SameAnchor" if $report;
1293 print $report " SupersededAnchor" if $report;
1295 if ($p->{Breakwater} eq $p->{CommitId}) {
1296 # this parent commit was its own breakwater,
1297 # ie it is part of the breakwater
1298 print $report " Breakwater" if $report;
1300 $might_be_in_bw = 0;
1302 push @bwbcmd, $p->{Breakwater};
1303 push @ibcmd, $p->{CommitId};
1306 if ($ok && $might_be_in_bw) {
1307 # We could rewrite this to contaion the metadata
1308 # declaring it to be MergedBreakwaters, but
1309 # unnecessarily rewriting a merge seems unhelpful.
1310 $prline->(" VanillaMerge MergedBreakwaters");
1311 $last_anchor = $best_anchor;
1312 $build_start->('MergedBreakwaters', $cur);
1315 my $bwb = cmdoutput @bwbcmd;
1317 # OK, now we have a breakwater base, but we need the merge
1318 # base for the interchange branch because we need the delta
1321 # This a the best merge base of our inputs which has the
1322 # breakwater merge base as an ancestor.
1329 @ibs or confess 'internal error, expected anchor at least ?';
1333 foreach my $tibix (0..$#ibs) {
1334 my $tib = $ibs[$tibix];
1335 my $ff = is_fast_fwd $bwb, $tib;
1336 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1337 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1338 $mwrecknote->($tibleaf, $tib);
1345 $ib or $nomerge->("no suitable interchange merge base");
1347 $prline->(" VanillaMerge Base");
1349 my ($btip, $bbw, $banchor) = eval {
1350 walk $ib, 0, $report, $report_lprefix.' ';
1352 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1356 $mwrecknote->("mergebase-laundered", $btip);
1357 $mwrecknote->("mergebase-breakwater", $bbw);
1358 $mwrecknote->("mergebase-anchor", $banchor);
1360 my $ibinfo = { SeriesTip => $btip,
1363 LeftRight => 'mergebase' };
1366 or $nomerge->("interchange merge-base ($ib)'s".
1367 " breakwater ($bbw)".
1368 " != breakwaters' merge-base ($bwb)");
1370 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1371 or $nomerge->("interchange merge-base ($ib)'s".
1372 " anchor ($ibinfo->{SeriesBase})".
1373 " != any merge input's anchor (".
1374 (join ' ', map { $_->{Anchor} } @$ps).
1377 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1378 $cl->{MergeBestAnchor} = $best_anchor;
1381 SpecialMethod => 'MergeCreateMergedBreakwaters',
1382 $xmsg->('constructed from vanilla merge',
1383 ' merged-breakwater'),
1387 SpecialMethod => 'MergeMergeSeries',
1389 $build_start->('MergeBreakwaters', $cur);
1391 printdebug "*** WALK BOMB unrecognised\n";
1397 printdebug "*** WALK prep done cur=$cur".
1398 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1400 return if $nogenerate;
1402 # Now we build it back up again
1408 my $read_tree_upstream = sub {
1410 read_tree_upstream $treeish, 0, $build;
1413 $#upp_cl = $upp_limit if defined $upp_limit;
1415 my $committer_authline = calculate_committer_authline();
1417 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1419 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1422 mkdir $rd or $!==EEXIST or die $!;
1424 runcmd @git, qw(read-tree), $build;
1425 foreach my $cl (qw(Debian), (reverse @brw_cl),
1426 { SpecialMethod => 'RecordBreakwaterTip' },
1427 qw(Upstream), (reverse @upp_cl)) {
1429 $current_method = $cl;
1432 my $method = $cl->{SpecialMethod} // $current_method;
1433 my @parents = ($build);
1434 my $cltree = $cl->{CommitId};
1435 printdebug "WALK BUILD ".($cltree//'undef').
1436 " $method (rewriting=$rewriting)\n";
1437 if ($method eq 'Debian') {
1438 read_tree_debian($cltree);
1439 } elsif ($method eq 'Upstream') {
1440 $read_tree_upstream->($cltree);
1441 } elsif ($method eq 'StartRewrite') {
1444 } elsif ($method eq 'RecordBreakwaterTip') {
1445 $breakwater = $build;
1447 } elsif ($method eq 'DgitImportDebianUpdate') {
1448 read_tree_debian($cltree);
1449 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1450 confess unless $rewriting;
1451 my $differs = (get_differs $build, $cltree);
1452 next unless $differs & D_UPS;
1453 $read_tree_upstream->($cltree);
1454 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1455 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1456 print "Found a general merge, will try to tidy it up.\n";
1458 $read_tree_upstream->($cl->{MergeBestAnchor});
1459 $read_tree_upstream->($cl->{MergeBestAnchor});
1460 read_tree_debian($cltree);
1461 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1462 } elsif ($method eq 'MergeMergeSeries') {
1463 print "Running merge resolution for $cl->{CommitId}...\n";
1464 $build = merge_series
1465 $build, $cl->{MergeWreckNotes},
1466 $cl->{MergeInterchangeBaseInfo},
1467 @{ $cl->{Parents} };
1468 $last_anchor = $cl->{MergeBestAnchor};
1470 # Check for mismerges:
1472 my ($against, $allow, $what) = @_;
1473 my $differs = get_differs $build, $against;
1475 "merge misresolved: %s are not the same (%s %s d.%#x)",
1476 $what, $against, $build, $differs)
1477 if $differs & ~($allow | D_PAT_ADD);
1480 # Breakwater changes which were in each side of the
1481 # merge will have been incorporated into the
1482 # MergeCreateMergedBreakwaters output. Because the
1483 # upstream series was rebased onto the new breakwater,
1484 # so should all of the packaging changes which were in
1486 $check->($input, D_UPS, 'debian files');
1488 # Upstream files are merge_series, which ought to
1489 # have been identical to the original merge.
1490 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1492 print "Merge resolution successful.\n";
1495 confess "$method ?";
1498 my $procd = (pop @processed) // 'UNDEF';
1499 if ($cl ne $procd) {
1501 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1504 my $newtree = cmdoutput @git, qw(write-tree);
1505 my $ch = $cl->{Hdr};
1506 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1507 $ch =~ s{^parent .*\n}{}mg;
1508 $ch =~ s{(?=^author)}{
1509 join '', map { "parent $_\n" } @parents
1510 }me or confess "$ch ?";
1512 $ch =~ s{^committer .*$}{$committer_authline}m
1515 my $cf = "$rd/m$rewriting";
1516 open CD, ">", $cf or die $!;
1517 print CD $ch, "\n", $cl->{Msg} or die $!;
1519 my @cmd = (@git, qw(hash-object));
1520 push @cmd, qw(-w) if $rewriting;
1521 push @cmd, qw(-t commit), $cf;
1522 my $newcommit = cmdoutput @cmd;
1523 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1524 $build = $newcommit;
1525 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1526 $last_anchor = $cur;
1531 my $final_check = get_differs $build, $input;
1532 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1533 if $final_check & ~D_PAT_ADD;
1535 my @r = ($build, $breakwater, $last_anchor);
1536 printdebug "*** WALK RETURN @r\n";
1541 git_check_unmodified();
1542 return git_rev_parse qw(HEAD);
1545 sub update_head ($$$) {
1546 my ($old, $new, $mrest) = @_;
1547 push @deferred_updates, "update HEAD $new $old";
1548 run_deferred_updates $mrest;
1551 sub update_head_checkout ($$$) {
1552 my ($old, $new, $mrest) = @_;
1553 update_head $old, $new, $mrest;
1554 runcmd @git, qw(reset --hard);
1557 sub update_head_postlaunder ($$$) {
1558 my ($old, $tip, $reflogmsg) = @_;
1559 return if $tip eq $old;
1560 print "git-debrebase: laundered (head was $old)\n";
1561 update_head $old, $tip, $reflogmsg;
1562 # no tree changes except debian/patches
1563 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1566 sub currently_rebasing() {
1567 foreach (qw(rebase-merge rebase-apply)) {
1568 return 1 if stat_exists "$maindir_gitdir/$_";
1573 sub bail_if_rebasing() {
1574 fail "you are in the middle of a git-rebase already"
1575 if currently_rebasing();
1578 sub do_launder_head ($) {
1579 my ($reflogmsg) = @_;
1580 my $old = get_head();
1582 my ($tip,$breakwater) = walk $old;
1584 update_head_postlaunder $old, $tip, $reflogmsg;
1585 return ($tip,$breakwater);
1588 sub cmd_launder_v0 () {
1589 badusage "no arguments to launder-v0 allowed" if @ARGV;
1590 my $old = get_head();
1591 my ($tip,$breakwater,$last_anchor) = walk $old;
1592 update_head_postlaunder $old, $tip, 'launder';
1593 printf "# breakwater tip\n%s\n", $breakwater;
1594 printf "# working tip\n%s\n", $tip;
1595 printf "# last anchor\n%s\n", $last_anchor;
1598 sub defaultcmd_rebase () {
1599 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1600 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1601 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1604 sub cmd_analyse () {
1605 badusage "analyse does not support any options"
1606 if @ARGV and $ARGV[0] =~ m/^-/;
1607 badusage "too many arguments to analyse" if @ARGV>1;
1610 $old = git_rev_parse $old;
1612 $old = git_rev_parse 'HEAD';
1614 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1615 STDOUT->error and die $!;
1618 sub ffq_prev_branchinfo () {
1619 my $current = git_get_symref();
1620 return gdr_ffq_prev_branchinfo($current);
1623 sub ffq_check ($;$$) {
1624 # calls $ff and/or $notff zero or more times
1625 # then returns either (status,message) where status is
1630 # or (undef,undef, $ffq_prev,$gdrlast)
1631 # $ff and $notff are called like this:
1632 # $ff->("message for stdout\n");
1633 # $notff->('snag-name', $message);
1634 # normally $currentval should be HEAD
1635 my ($currentval, $ff, $notff) =@_;
1637 $ff //= sub { print $_[0] or die $!; };
1640 my ($status, $message, $current, $ffq_prev, $gdrlast)
1641 = ffq_prev_branchinfo();
1642 return ($status, $message) unless $status eq 'branch';
1644 my $exists = git_get_ref $ffq_prev;
1645 return ('exists',"$ffq_prev already exists") if $exists;
1647 return ('not-branch', 'HEAD symref is not to refs/heads/')
1648 unless $current =~ m{^refs/heads/};
1651 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1654 printdebug "ffq check_specs @check_specs\n";
1657 my ($lrref, $desc) = @_;
1658 printdebug "ffq might check $lrref ($desc)\n";
1660 for my $chk (@check_specs) {
1662 $invert = $glob =~ s{^[!^]}{};
1663 last if fnmatch $glob, $lrref;
1666 my $lrval = git_get_ref $lrref;
1667 return unless length $lrval;
1669 if (is_fast_fwd $lrval, $currentval) {
1670 $ff->("OK, you are ahead of $lrref\n");
1671 $checked{$lrref} = 1;
1672 } elsif (is_fast_fwd $currentval, $lrval) {
1673 $checked{$lrref} = -1;
1674 $notff->('behind', "you are behind $lrref, divergence risk");
1676 $checked{$lrref} = -1;
1677 $notff->('diverged', "you have diverged from $lrref");
1681 my $merge = cfg "branch.$branch.merge",1;
1682 if (defined $merge and $merge =~ m{^refs/heads/}) {
1684 printdebug "ffq merge $rhs\n";
1685 my $check_remote = sub {
1686 my ($remote, $desc) = @_;
1687 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1688 return unless defined $remote;
1689 $check->("refs/remotes/$remote/$rhs", $desc);
1691 $check_remote->((scalar cfg "branch.$branch.remote",1),
1692 'remote fetch/merge branch');
1693 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1694 (scalar cfg "branch.$branch.pushDefault",1),
1695 'remote push branch');
1697 if ($branch =~ m{^dgit/}) {
1698 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1699 } elsif ($branch =~ m{^master$}) {
1700 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1702 return (undef, undef, $ffq_prev, $gdrlast);
1705 sub record_ffq_prev_deferred () {
1706 # => ('status', "message")
1708 # deferred message is undef
1713 # if not ff from some branch we should be ff from, is an snag
1714 # if "deferred", will have added something about that to
1715 # @deferred_update_messages, and also maybe printed (already)
1716 # some messages about ff checks
1718 my $currentval = get_head();
1720 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1721 return ($status,$message) if defined $status;
1725 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1726 push @deferred_updates, "delete $gdrlast";
1727 push @deferred_update_messages, "Recorded previous head for preservation";
1728 return ('deferred', undef);
1731 sub record_ffq_auto () {
1732 my ($status, $message) = record_ffq_prev_deferred();
1733 if ($status eq 'deferred' || $status eq 'exists') {
1735 snag $status, "could not record ffq-prev: $message";
1740 sub ffq_prev_info () {
1742 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1743 my ($status, $message, $current, $ffq_prev, $gdrlast)
1744 = ffq_prev_branchinfo();
1745 if ($status ne 'branch') {
1746 snag $status, "could not check ffq-prev: $message";
1749 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1750 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1753 sub stitch ($$$$$) {
1754 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1756 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1758 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1759 my $differs = get_differs $old_head, $ffq_prev_commitish;
1760 unless ($differs & ~D_PAT_ADD) {
1761 # ffq-prev is ahead of us, and the only tree changes it has
1762 # are possibly addition of things in debian/patches/.
1763 # Just wind forwards rather than making a pointless pseudomerge.
1764 push @deferred_updates,
1765 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1766 update_head_checkout $old_head, $ffq_prev_commitish,
1767 "stitch (fast forward)";
1772 # We make pseudomerges with L as the contributing parent.
1773 # This makes git rev-list --first-parent work properly.
1774 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1775 'Declare fast forward / record previous work',
1776 "[git-debrebase pseudomerge: $prose]",
1778 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1779 update_head $old_head, $new_head, "stitch: $prose";
1782 sub do_stitch ($;$) {
1783 my ($prose, $unclean) = @_;
1785 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1786 if (!$ffq_prev_commitish) {
1787 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1790 my $dangling_head = get_head();
1792 keycommits $dangling_head, $unclean,$unclean,$unclean;
1795 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1798 sub upstream_commitish_search ($$) {
1799 my ($upstream_version, $tried) = @_;
1800 # todo: at some point maybe use git-deborig to do this
1801 foreach my $tagpfx ('', 'v', 'upstream/') {
1802 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1803 my $new_upstream = git_get_ref "refs/tags/$tag";
1805 return $new_upstream if length $new_upstream;
1809 sub resolve_upstream_version ($$) {
1810 my ($new_upstream, $upstream_version) = @_;
1812 if (!defined $new_upstream) {
1814 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1815 if (!length $new_upstream) {
1816 fail "Could not determine appropriate upstream commitish.\n".
1817 " (Tried these tags: @tried)\n".
1818 " Check version, and specify upstream commitish explicitly.";
1821 $new_upstream = git_rev_parse $new_upstream;
1823 return $new_upstream;
1826 sub cmd_new_upstream () {
1827 # automatically and unconditionally launders before rebasing
1828 # if rebase --abort is used, laundering has still been done
1832 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1834 # parse args - low commitment
1835 my $spec_version = shift @ARGV;
1836 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1837 fail "bad version number \`$spec_version'" unless defined $new_version;
1838 if ($new_version->is_native()) {
1839 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1842 my $new_upstream = shift @ARGV;
1843 my $new_upstream_version = upstreamversion $new_version;
1845 resolve_upstream_version $new_upstream, $new_upstream_version;
1850 my ($n, @x) = @_; # may be ''
1851 my $pc = $pieces{$n} //= {
1853 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1855 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1860 my $newpiece = sub {
1861 my ($n, @x) = @_; # may be ''
1862 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1863 push @newpieces, $pc;
1868 New => $new_upstream,
1870 while (@ARGV && $ARGV[0] !~ m{^-}) {
1871 my $n = shift @ARGV;
1873 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1874 unless @ARGV && $ARGV[0] !~ m{^-};
1876 my $c = git_rev_parse shift @ARGV;
1877 die unless $n =~ m/^$extra_orig_namepart_re$/;
1878 $newpiece->($n, New => $c);
1881 # now we need to investigate the branch this generates the
1882 # laundered version but we don't switch to it yet
1883 my $old_head = get_head();
1884 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1886 my $old_bw_cl = classify $old_bw;
1887 my $old_anchor_cl = classify $old_anchor;
1889 if (!$old_anchor_cl->{OrigParents}) {
1890 snag 'anchor-treated',
1891 'old anchor is recognised due to --anchor, cannot check upstream';
1893 $old_upstream = parsecommit
1894 $old_anchor_cl->{OrigParents}[0]{CommitId};
1895 $piece->('', Old => $old_upstream->{CommitId});
1898 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1899 if ($old_upstream->{Msg} =~
1900 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1902 my @oldpieces = (split / /, $1);
1903 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1904 if ($old_n_parents != @oldpieces &&
1905 $old_n_parents != @oldpieces + 1) {
1906 snag 'upstream-confusing', sprintf
1907 "previous upstream combine %s".
1908 " mentions %d pieces (each implying one parent)".
1909 " but has %d parents".
1910 " (one per piece plus maybe a previous combine)",
1911 $old_upstream->{CommitId},
1912 (scalar @oldpieces),
1914 } elsif ($oldpieces[0] ne '.') {
1915 snag 'upstream-confusing', sprintf
1916 "previous upstream combine %s".
1917 " first piece is not \`.'",
1921 foreach my $i (0..$#oldpieces) {
1922 my $n = $oldpieces[$i];
1923 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1924 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1928 snag 'upstream-confusing',
1929 "previous upstream $old_upstream->{CommitId} is from".
1930 " git-debrebase but not an \`upstream-combine' commit";
1934 foreach my $pc (values %pieces) {
1935 if (!$old_upstream) {
1936 # we have complained already
1937 } elsif (!$pc->{Old}) {
1938 snag 'upstream-new-piece',
1939 "introducing upstream piece \`$pc->{Name}'";
1940 } elsif (!$pc->{New}) {
1941 snag 'upstream-rm-piece',
1942 "dropping upstream piece \`$pc->{Name}'";
1943 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1944 snag 'upstream-not-ff',
1945 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1949 printdebug "%pieces = ", (dd \%pieces), "\n";
1950 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1958 my @upstream_merge_parents;
1961 push @upstream_merge_parents, $old_upstream->{CommitId};
1964 foreach my $pc (@newpieces) { # always has '' first
1966 read_tree_subdir $pc->{Name}, $pc->{New};
1968 runcmd @git, qw(read-tree), $pc->{New};
1970 push @upstream_merge_parents, $pc->{New};
1973 # index now contains the new upstream
1975 if (@newpieces > 1) {
1976 # need to make the upstream subtree merge commit
1977 $new_upstream = make_commit \@upstream_merge_parents,
1978 [ "Combine upstreams for $new_upstream_version",
1979 ("[git-debrebase upstream-combine . ".
1980 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1985 # $new_upstream is either the single upstream commit, or the
1986 # combined commit we just made. Either way it will be the
1987 # "upstream" parent of the anchor merge.
1989 read_tree_subdir 'debian', "$old_bw:debian";
1991 # index now contains the anchor merge contents
1992 $new_bw = make_commit [ $old_bw, $new_upstream ],
1993 [ "Update to upstream $new_upstream_version",
1994 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1997 my $clogsignoff = cmdoutput qw(git show),
1998 '--pretty=format:%an <%ae> %aD',
2001 # Now we have to add a changelog stanza so the Debian version
2003 die if unlink "debian";
2004 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2005 unlink "debian/changelog" or $!==ENOENT or die $!;
2006 mkdir "debian" or die $!;
2007 open CN, ">", "debian/changelog" or die $!;
2008 my $oldclog = git_cat_file ":debian/changelog";
2009 $oldclog =~ m/^($package_re) \(\S+\) / or
2010 fail "cannot parse old changelog to get package name";
2012 print CN <<END, $oldclog or die $!;
2013 $p ($new_version) UNRELEASED; urgency=medium
2015 * Update to new upstream version $new_upstream_version.
2021 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2023 # Now we have the final new breakwater branch in the index
2024 $new_bw = make_commit [ $new_bw ],
2025 [ "Update changelog for new upstream $new_upstream_version",
2026 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2030 # we have constructed the new breakwater. we now need to commit to
2031 # the laundering output, because git-rebase can't easily be made
2032 # to make a replay list which is based on some other branch
2034 update_head_postlaunder $old_head, $old_laundered_tip,
2035 'launder for new upstream';
2037 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2038 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2039 "debrebase new-upstream $new_version: rebase";
2041 # now it's for the user to sort out
2044 sub cmd_record_ffq_prev () {
2045 badusage "no arguments allowed" if @ARGV;
2046 my ($status, $msg) = record_ffq_prev_deferred();
2047 if ($status eq 'exists' && $opt_noop_ok) {
2048 print "Previous head already recorded\n" or die $!;
2049 } elsif ($status eq 'deferred') {
2050 run_deferred_updates 'record-ffq-prev';
2052 fail "Could not preserve: $msg";
2057 badusage "no arguments allowed" if @ARGV;
2058 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2059 print "$bw\n" or die $!;
2062 sub cmd_breakwater () {
2063 badusage "no arguments allowed" if @ARGV;
2064 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2065 print "$bw\n" or die $!;
2069 badusage "no arguments allowed" if @ARGV;
2071 # todo: gdr status should print divergence info
2072 # todo: gdr status should print upstream component(s) info
2073 # todo: gdr should leave/maintain some refs with this kind of info ?
2075 my $oldest = { Badness => 0 };
2078 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2079 if ($oldest->{Badness} < $badness) {
2080 $oldest = $newest = undef;
2083 Badness => $badness,
2084 CommitId => $cl->{CommitId},
2088 $newest //= $oldest;
2090 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2091 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2092 sub { $note->(2, 'branch is unlaundered', @_); },
2093 sub { $note->(3, 'branch needs laundering', @_); },
2094 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2096 my $prcommitinfo = sub {
2098 flush STDOUT or die $!;
2099 runcmd @git, qw(--no-pager log -n1),
2100 '--pretty=format: %h %s%n',
2104 print "current branch contents, in git-debrebase terms:\n";
2105 if (!$oldest->{Badness}) {
2106 print " branch is laundered\n";
2108 print " $oldest->{OurMsg}\n";
2110 foreach my $info ($oldest, $newest) {
2111 my $cid = $info->{CommitId};
2112 next if $cid eq $printed;
2114 print " $info->{KcMsg}\n";
2115 $prcommitinfo->($cid);
2120 my ($cid, $what) = @_;
2121 if (!defined $cid) {
2122 print " $what is not well-defined\n";
2125 $prcommitinfo->($cid);
2128 print "key git-debrebase commits:\n";
2129 $prab->($anchor, 'anchor');
2130 $prab->($bw, 'breakwater');
2132 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2133 ffq_prev_branchinfo();
2135 print "branch and ref status, in git-debrebase terms:\n";
2137 print " $ffq_msg\n";
2139 $ffq_prev = git_get_ref $ffq_prev;
2140 $gdrlast = git_get_ref $gdrlast;
2142 print " unstitched; previous tip was:\n";
2143 $prcommitinfo->($ffq_prev);
2144 } elsif (!$gdrlast) {
2145 print " stitched? (no record of git-debrebase work)\n";
2146 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2147 print " stitched\n";
2149 print " not git-debrebase (diverged since last stitch)\n"
2152 print "you are currently rebasing\n" if currently_rebasing();
2156 my $prose = 'stitch';
2157 getoptions("stitch",
2158 'prose=s', \$prose);
2159 badusage "no arguments allowed" if @ARGV;
2160 do_stitch $prose, 0;
2162 sub cmd_prepush () { cmd_stitch(); }
2165 badusage "no arguments allowed" if @ARGV;
2166 do_launder_head 'launder for git-debrebase quick';
2170 sub cmd_conclude () {
2171 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2172 if (!$ffq_prev_commitish) {
2173 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2176 my $dangling_head = get_head();
2178 badusage "no arguments allowed" if @ARGV;
2179 do_launder_head 'launder for git-debrebase quick';
2184 if (currently_rebasing()) {
2185 runcmd @git, qw(rebase --abort);
2187 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2188 if (!$ffq_prev_commitish) {
2189 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2192 my $scrapping_head = get_head();
2193 badusage "no arguments allowed" if @ARGV;
2194 push @deferred_updates,
2195 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2196 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2198 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2201 sub make_patches_staged ($) {
2203 # Produces the patches that would result from $head if it were
2205 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2208 gbp_pq_export 'bw', $secret_bw, $secret_head;
2212 sub make_patches ($) {
2214 keycommits $head, 0, \&snag;
2215 make_patches_staged $head;
2218 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2219 runcmd @git, qw(read-tree), $head;
2220 read_tree_subdir 'debian/patches', $ptree;
2221 $out = make_commit [$head], [
2222 'Commit patch queue (exported by git-debrebase)',
2223 '[git-debrebase: export and commit patches]',
2229 sub cmd_make_patches () {
2230 my $opt_quiet_would_amend;
2231 getoptions("make-patches",
2232 'quiet-would-amend!', \$opt_quiet_would_amend);
2233 badusage "no arguments allowed" if @ARGV;
2235 my $old_head = get_head();
2236 my $new = make_patches $old_head;
2237 my $d = get_differs $old_head, $new;
2239 fail "No (more) patches to export." unless $opt_noop_ok;
2241 } elsif ($d == D_PAT_ADD) {
2243 update_head_checkout $old_head, $new, 'make-patches';
2245 print STDERR failmsg
2246 "Patch export produced patch amendments".
2247 " (abandoned output commit $new).".
2248 " Try laundering first."
2249 unless $opt_quiet_would_amend;
2254 sub cmd_convert_from_gbp () {
2255 badusage "want only 1 optional argument, the upstream git commitish"
2258 my $clogp = parsechangelog();
2259 my $version = $clogp->{'Version'}
2260 // die "missing Version from changelog";
2262 my ($upstream_spec) = @ARGV;
2264 my $upstream_version = upstreamversion $version;
2266 resolve_upstream_version($upstream_spec, $upstream_version);
2268 my $old_head = get_head();
2270 my $upsdiff = get_differs $upstream, $old_head;
2271 if ($upsdiff & D_UPS) {
2272 runcmd @git, qw(--no-pager diff --stat),
2273 $upstream, $old_head,
2274 qw( -- :!/debian :/);
2276 upstream ($upstream_spec) and HEAD are not
2277 identical in upstream files. See diffstat above, or run
2278 git diff $upstream_spec HEAD -- :!/debian :/
2282 if (!is_fast_fwd $upstream, $old_head) {
2283 snag 'upstream-not-ancestor',
2284 "upstream ($upstream) is not an ancestor of HEAD";
2286 my $wrong = cmdoutput
2287 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2288 qw(-- :/ :!/debian));
2289 if (length $wrong) {
2290 snag 'unexpected-upstream-changes',
2291 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2292 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2296 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2297 snag 'upstream-has-debian',
2298 "upstream ($upstream) contains debian/ directory";
2301 my $previous_dgit_view = eval {
2302 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2304 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2305 my ($stz, $desc) = @_;
2306 no warnings qw(exiting);
2307 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2308 next unless $stz->{Date};
2309 next unless $stz->{Distribution} ne 'UNRELEASED';
2310 $lvsn = $stz->{Version};
2311 $suite = $stz->{Distribution};
2314 die "neither of the first two changelog entries are released\n"
2315 unless defined $lvsn;
2316 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2317 my $mtag_pat = debiantag_maintview $lvsn, '*';
2318 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2320 die "could not find suitable maintainer view tag $mtag_pat\n"
2321 unless $mtag_pat =~ m{/};
2322 is_fast_fwd $mtag, 'HEAD' or
2323 die "HEAD is not FF from maintainer tag $mtag!";
2324 my $dtag = "archive/$mtag";
2325 is_fast_fwd $mtag, $dtag or
2326 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2327 print "will stitch in dgit view, $dtag\n";
2328 git_rev_parse $dtag;
2330 if (!$previous_dgit_view) {
2333 print STDERR "cannot stitch in dgit view: $@\n";
2336 snags_maybe_bail_early();
2342 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2343 # make a branch out of the patch queue - we'll want this in a mo
2344 runcmd qw(gbp pq import);
2345 # strip the patches out
2346 runcmd @git, qw(checkout -q gdr-internal~0);
2347 rm_subdir_cached 'debian/patches';
2348 $work = make_commit ['HEAD'], [
2349 'git-debrebase convert-from-gbp: drop patches from tree',
2350 'Delete debian/patches, as part of converting to git-debrebase format.',
2351 '[git-debrebase convert-from-gbp: drop patches from tree]'
2353 # make the anchor merge
2354 # the tree is already exactly right
2355 $work = make_commit [$work, $upstream], [
2356 'git-debrebase import: declare upstream',
2357 'First breakwater merge.',
2358 '[git-debrebase anchor: declare upstream]'
2361 # rebase the patch queue onto the new breakwater
2362 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2363 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2364 $work = git_rev_parse 'HEAD';
2366 if ($previous_dgit_view) {
2367 $work = make_commit [$work, $previous_dgit_view], [
2368 'git-debrebase import: declare ff from dgit archive view',
2369 '[git-debrebase pseudomerge: import-from-gbp]',
2376 update_head_checkout $old_head, $work, 'convert-from-gbp';
2379 sub cmd_convert_to_gbp () {
2380 badusage "no arguments allowed" if @ARGV;
2381 my $head = get_head();
2382 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2383 keycommits $head, 0;
2385 make_patches_staged $head;
2387 $out = make_commit ['HEAD'], [
2388 'Commit patch queue (converted from git-debrebase format)',
2389 '[git-debrebase convert-to-gbp: commit patches]',
2393 push @deferred_updates, "delete $ffq";
2394 push @deferred_updates, "delete $gdrlast";
2397 update_head_checkout $head, $out, "convert to gbp (v0)";
2398 print <<END or die $!;
2399 git-debrebase: converted to git-buildpackage branch format
2400 git-debrebase: WARNING: do not now run "git-debrebase" any more
2401 git-debrebase: WARNING: doing so would drop all upstream patches!
2405 sub cmd_convert_from_dgit_view () {
2406 my $clogp = parsechangelog();
2408 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2414 getoptions("convert-from-dgit-view",
2415 'diagnose!', \$diagnose,
2416 'build-products-dir:s', \$bpd,
2417 'origs!', \$do_origs,
2419 'always-convert-anyway!', \$always);
2420 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2425 my $spec = shift @ARGV;
2426 my $commit = git_rev_parse "$spec^{commit}";
2427 push @upstreams, { Commit => $commit,
2428 Source => "$ARGV[0], from command line",
2433 my $head = get_head();
2437 my $trouble = sub { $troubles++; };
2438 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2439 printdebug "troubles=$troubles\n";
2442 $us: Branch already seems to be in git-debrebase format!
2443 $us: --always-convert-anyway would do the conversion operation anyway
2444 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2446 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2451 snags_maybe_bail_early();
2453 my $version = upstreamversion $clogp->{Version};
2454 print STDERR "Considering possible commits corresponding to upstream:\n";
2459 my $ups_tag = upstream_commitish_search $version, \@tried;
2461 my $this = "git tag $tried[-1]";
2462 push @upstreams, { Commit => $ups_tag,
2467 " git tag: no suitable tag found (tried %s)\n",
2472 my $p = $clogp->{'Source'};
2473 # we do a quick check to see if there are plausible origs
2475 if (!opendir BPD, $bpd) {
2476 die "$bpd: opendir: $!" unless $!==ENOENT;
2478 while ($!=0, my $f = readdir BPD) {
2479 next unless is_orig_file_of_p_v $f, $p, $version;
2481 " orig: found what looks like a .orig, %s\n",
2486 die "read $bpd: $!" if $!;
2490 my $tree = cmdoutput
2491 @dgit, qw(--build-products-dir), $bpd,
2492 qw(print-unapplied-treeish);
2495 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2496 rm_subdir_cached 'debian';
2497 $tree = cmdoutput @git, qw(write-tree);
2498 my $ups_synth = make_commit [], [ <<END, <<END,
2499 Import effective orig tree for upstream version $version
2501 This includes the contents of the .orig(s), minus any debian/ directory.
2503 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2506 push @upstreams, { Commit => $ups_synth,
2507 Source => "orig(s) imported via dgit",
2512 " orig: no suitable origs found (looked for %s in %s)\n",
2513 "${p}_".(stripeoch $version)."...", $bpd;
2518 my $some_patches = stat_exists 'debian/patches/series';
2520 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2523 foreach my $u (@upstreams) {
2527 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2528 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2529 runcmd @git, qw(clean -xdff);
2530 runcmd @git, qw(checkout), $head, qw(-- debian);
2531 if ($some_patches) {
2532 rm_subdir_cached 'debian/patches';
2533 $work = make_commit [ $work ], [
2534 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2535 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2536 "to git-debrebase format. Upstream changes will appear as commits.",
2537 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2540 $work = make_commit [ $work, $u->{Commit} ], [
2541 'git-debrebase convert-from-dgit-view: declare upstream',
2542 '(Re)constructed breakwater merge.',
2543 '[git-debrebase anchor: declare upstream]'
2545 runcmd @git, qw(checkout --quiet -b mk), $work;
2546 if ($some_patches) {
2547 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2548 runcmd @git, qw(reset --quiet);
2549 my @gbp_cmd = (qw(gbp pq import));
2551 my $gbp_err = "../gbp-pq-err";
2552 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2554 my $r = system @gbp_cmd;
2557 " %s: couldn't apply patches: gbp pq %s",
2558 $u->{Source}, waitstatusmsg();
2562 my $work = git_rev_parse qw(HEAD);
2563 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2564 if (length $diffout) {
2566 " $u->{Source}: applying patches gives different tree\n";
2567 print STDERR $diffout if $diagnose;
2571 $u->{Result} = $work;
2579 Could not find or construct a suitable upstream commit.
2580 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2581 upstream commmit explicitly or provide suitable origs.
2585 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2587 ffq_check $result->{Result};
2589 update_head_checkout $head, $result->{Result},
2590 'convert-from-dgit-view';
2593 sub cmd_downstream_rebase_launder_v0 () {
2594 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2596 $base = git_rev_parse $base;
2597 my $old_head = get_head();
2598 my $current = $old_head;
2601 if ($current eq $base) {
2602 $topmost_keep //= $current;
2603 print " $current BASE stop\n";
2606 my $cl = classify $current;
2607 print " $current $cl->{Type}";
2609 my $p0 = $cl->{Parents}[0]{CommitId};
2611 if ($cl->{Type} eq 'Pseudomerge') {
2612 print " ^".($cl->{Contributor}{Ix}+1);
2613 $next = $cl->{Contributor}{CommitId};
2614 } elsif ($cl->{Type} eq 'AddPatches' or
2615 $cl->{Type} eq 'Changelog') {
2625 $topmost_keep //= $current;
2627 die "to-be stripped changes not on top of the branch\n"
2632 if ($topmost_keep eq $old_head) {
2633 print "unchanged\n";
2635 print "updating to $topmost_keep\n";
2636 update_head_checkout
2637 $old_head, $topmost_keep,
2638 'downstream-rebase-launder-v0';
2644 "D+" => \$debuglevel,
2645 'noop-ok', => \$opt_noop_ok,
2646 'f=s' => \@snag_force_opts,
2647 'anchor=s' => \@opt_anchors,
2648 '--dgit=s' => \($dgit[0]),
2651 my ($opt,$val) = @_;
2652 badusage "git-debrebase: no cuddling to -i for git-rebase"
2654 die if $opt_defaultcmd_interactive; # should not happen
2655 $opt_defaultcmd_interactive = [ qw(-i) ];
2656 # This access to @ARGV is excessive familiarity with
2657 # Getopt::Long, but there isn't another sensible
2658 # approach. '-i=s{0,}' does not work with bundling.
2659 push @$opt_defaultcmd_interactive, @ARGV;
2662 'help' => sub { print $usage_message or die $!; finish 0; },
2665 initdebug('git-debrebase ');
2666 enabledebug if $debuglevel;
2668 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2669 chdir $toplevel or die "chdir $toplevel: $!";
2671 $rd = fresh_playground "$playprefix/misc";
2673 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2675 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2676 defaultcmd_rebase();
2678 my $cmd = shift @ARGV;
2681 $cmdfn = ${*::}{"cmd_$cmdfn"};
2683 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";