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;
394 run_ref_updates_now "merge failed", \@updates;
398 while (my ($k,$v) = each %$wrecknotes) {
399 push @updates, "create $wrecknoteprefix/$k $v";
401 run_ref_updates_now "merge failed", \@updates;
402 push @m, "Wreckage left in $wrecknoteprefix/*.";
404 push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
406 # use finish rather than fail, in case we are within an eval
407 # (that can happen inside walk!)
409 print STDERR "$us: $_\n" foreach @m;
413 sub mwrecknote ($$$) {
414 my ($wrecknotes, $reftail, $commitish) = @_;
415 confess unless defined $commitish;
416 printdebug "mwrecknote $reftail $commitish\n";
417 $wrecknotes->{$reftail} = $commitish;
420 sub merge_attempt_cmd {
421 my $wrecknotes = shift @_;
425 merge_failed $wrecknotes,
426 failedcmd_waitstatus(),
427 "failed command: @_";
431 sub merge_series ($$$;@) {
432 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
433 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
434 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
435 # ^ specifies several patch series (currently we only support exactly 2)
436 # return value is a commit which is the result of
437 # merging the two versions of the same topic branch
438 # $input_q[0] and $input_q[1]
439 # with respect to the old version
443 # Creates, in *_q, a key MR for its private use
445 printdebug "merge_series newbase=$newbase\n";
447 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
448 $base_q->{MR}{S} = 'base';
451 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
452 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
453 # $prereq{<patch filename>} exists or not (even later)
457 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
459 my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
462 fresh_workarea "merge";
463 my $seriesfile = "debian/patches/series";
466 foreach my $q ($base_q, reverse @input_qs) {
468 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
470 if (open S, $seriesfile) {
471 while (my $patch = <S>) {
472 chomp $patch or die $!;
473 $prereq{$patch} //= {};
474 foreach my $earlier (@earlier) {
475 $prereq{$patch}{$earlier}{$s}++ and die;
477 push @earlier, $patch;
478 stat "debian/patches/$patch" or die "$patch ?";
480 S->error and die "$seriesfile $!";
483 die "$seriesfile $!" unless $!==ENOENT;
485 read_tree_upstream $newbase, 1;
486 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
487 "Convert $s to patch queue for merging",
488 "[git-debrebase merge-innards patch-queue import:".
491 printdebug "merge_series pec $pec ";
492 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
493 $pec = make_commit [ $pec ], [
494 "Drop series file from $s to avoid merge trouble",
495 "[git-debrebase merge-innards patch-queue prep:".
499 read_tree_debian $newbase;
501 read_tree_subdir 'debian/patches', "$pec:debian/patches";
503 rm_subdir_cached 'debian/patches';
505 $pec = make_commit [ $pec ], [
506 "Update debian/ (excluding patches) to final to avoid re-merging",
507 "debian/ was already merged and we need to just take that.",
508 "[git-debrebase merge-innards patch-queue packaging:".
512 printdebug "pec' $pec\n";
513 runcmd @git, qw(reset -q --hard), $pec;
514 $q->{MR}{PEC} = $pec;
515 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
517 # now, because of reverse, we are on $input_q->{MR}{OQC}
518 runcmd @git, qw(checkout -q -b merge);
519 printdebug "merge_series merging...\n";
520 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
522 $attempt_cmd->(@mergecmd);
524 printdebug "merge_series merge ok, series...\n";
525 # We need to construct a new series file
526 # Firstly, resolve prereq
527 foreach my $f (sort keys %prereq) {
528 printdebug "merge_series patch\t$f\t";
529 if (!stat_exists "debian/patches/$f") {
530 print DEBUG " drop\n" if $debuglevel;
531 # git merge deleted it; that's how we tell it's not wanted
535 print DEBUG " keep\n" if $debuglevel;
536 foreach my $g (sort keys %{ $prereq{$f} }) {
537 my $gfp = $prereq{$f}{$g};
538 printdebug "merge_series prereq\t$f\t-> $g\t";
539 if (!!$gfp->{0} == !!$gfp->{1}
542 print DEBUG "\tkeep\n" if $debuglevel;
544 print DEBUG "\tdrop\n" if $debuglevel;
545 delete $prereq{$f}{$g};
552 return scalar keys %{ $prereq{$f} };
555 my $nodate = time + 1;
557 # $authordate{<patch filename>};
558 my $authordate = sub {
560 $authordate{$f} //= do {
561 open PF, "<", "debian/patches/$f" or die "$f $!";
563 return $nodate if m/^$/;
564 last if s{^Date: }{};
567 return cmdoutput qw(date +%s -d), $_;
571 open NS, '>', $seriesfile or die $!;
573 while (keys %prereq) {
575 foreach my $try (sort keys %prereq) {
578 $unsat->($try) <=> $unsat->($best) or
579 $authordate->($try) <=> $authordate->($best) or
585 printdebug "merge_series series next $best\n";
586 print NS "$best\n" or die $!;
587 delete $prereq{$best};
588 foreach my $gp (values %prereq) {
593 runcmd @git, qw(add), $seriesfile;
594 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
595 $mwrecknote->('merged-patchqueue', git_rev_parse 'HEAD');
597 printdebug "merge_series series gbp pq import\n";
599 $attempt_cmd->(qw(gbp pq import));
601 # OK now we are on patch-queue/merge, and we need to rebase
602 # onto the intended parent and drop the patches from each one
604 printdebug "merge_series series ok, building...\n";
605 my $build = $newbase;
606 my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
607 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
608 my $commit = git_cat_file $c, 'commit';
609 printdebug "merge_series series ok, building $c\n";
610 read_tree_upstream $c, 0, $newbase;
611 my $tree = cmdoutput @git, qw(write-tree);
612 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
613 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
614 open C, ">", "../mcommit" or die $!;
615 print C $commit or die $!;
617 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
620 $mwrecknote->('merged-result', $result);
622 runcmd @git, qw(update-ref refs/heads/result), $result;
624 runcmd @git, qw(checkout -q -b debug);
625 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
626 runcmd @git, qw(add .);
627 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
628 my $mdebug = git_rev_parse 'HEAD';
629 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
630 $mwrecknote->('merged-debug', $mdebug);
632 printdebug "merge_series returns $result\n";
636 # classify returns an info hash like this
638 # Hdr => # commit headers, including 1 final newline
639 # Msg => # commit message (so one newline is dropped)
641 # Type => (see below)
643 # Ix => $index # ie 0, 1, 2, ...
645 # Differs => return value from get_differs
647 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
649 # NewMsg => # commit message, but with any [dgit import ...] edited
650 # # to say "[was: ...]"
660 # has additional entres in classification result
661 # Overwritten = [ subset of Parents ]
662 # Contributor = $the_remaining_Parent
664 # DgitImportUnpatched
665 # has additional entry in classification result
666 # OrigParents = [ subset of Parents ]
669 # has additional entry in classification result
670 # OrigParents = [ subset of Parents ] # singleton list
677 # has additional entry in classification result
680 sub parsecommit ($;$) {
681 my ($objid, $p_ref) = @_;
682 # => hash with CommitId Hdr Msg Tree Parents
683 # Parents entries have only Ix CommitId
684 # $p_ref, if provided, must be [] and is used as a base for Parents
689 my ($h,$m) = get_commit $objid;
691 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
692 my (@ph) = $h =~ m/^parent (\w+)$/mg;
702 foreach my $ph (@ph) {
704 Ix => scalar @$p_ref,
716 my $r = parsecommit($objid, \@p);
720 $p->{Differs} = (get_differs $p->{CommitId}, $t),
723 printdebug "classify $objid \$t=$t \@p",
724 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
728 my ($type, @rest) = @_;
729 $r = { %$r, Type => $type, @rest };
731 printdebug " = $type ".(dd $r)."\n";
737 $r = { %$r, Type => qw(Unknown), Why => $why };
738 printdebug " ** Unknown\n";
742 if (grep { $_ eq $objid } @opt_anchors) {
743 return $classify->('TreatAsAnchor');
746 my @identical = grep { !$_->{Differs} } @p;
747 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
748 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
750 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
751 # multi-orig upstreams are represented with an anchor merge
752 # from a single upstream commit which combines the orig tarballs
754 # Every anchor tagged this way must be a merge.
755 # We are relying on the
756 # [git-debrebase anchor: ...]
757 # commit message annotation in "declare" anchor merges (which
758 # do not have any upstream changes), to distinguish those
759 # anchor merges from ordinary pseudomerges (which we might
760 # just try to strip).
762 # However, the user is going to be doing git-rebase a lot. We
763 # really don't want them to rewrite an anchor commit.
764 # git-rebase trips up on merges, so that is a useful safety
767 # BreakwaterStart commits are also anchors in the terminology
768 # of git-debrebase(5), but they are untagged (and always
769 # manually generated).
771 # We cannot not tolerate any tagged linear commit (ie,
772 # BreakwaterStart commits tagged `[anchor:') because such a
773 # thing could result from an erroneous linearising raw git
774 # rebase of a merge anchor. That would represent a corruption
775 # of the branch. and we want to detect and reject the results
776 # of such corruption before it makes it out anywhere. If we
777 # reject it here then we avoid making the pseudomerge which
778 # would be needed to push it.
780 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
781 @p == 2 or return $badanchor->("has other than two parents");
782 $haspatches and return $badanchor->("contains debian/patches");
784 # How to decide about l/r ordering of anchors ? git
785 # --topo-order prefers to expand 2nd parent first. There's
786 # already an easy rune to look for debian/ history anyway (git log
787 # debian/) so debian breakwater branch should be 1st parent; that
788 # way also there's also an easy rune to look for the upstream
789 # patches (--topo-order).
791 # Also this makes --first-parent be slightly more likely to
792 # be useful - it makes it provide a linearised breakwater history.
794 # Of course one can say somthing like
795 # gitk -- ':/' ':!/debian'
796 # to get _just_ the commits touching upstream files, and by
797 # the TREESAME logic in git-rev-list this will leave the
798 # breakwater into upstream at the first anchor. But that
799 # doesn't report debian/ changes at all.
801 # Other observations about gitk: by default, gitk seems to
802 # produce output in a different order to git-rev-list. I
803 # can't seem to find this documented anywhere. gitk
804 # --date-order DTRT. But, gitk always seems to put the
805 # parents from left to right, in order, so it's easy to see
806 # which way round a pseudomerge is.
808 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
809 $p[1]{Differs} & ~DS_DEB and
810 $badanchor->("upstream files differ from left parent");
811 $p[0]{Differs} & ~D_UPS and
812 $badanchor->("debian/ differs from right parent");
814 return $classify->(qw(Anchor),
815 OrigParents => [ $p[1] ]);
819 my $d = $r->{Parents}[0]{Differs};
820 if ($d == D_PAT_ADD) {
821 return $classify->(qw(AddPatches));
822 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
823 return $unknown->("edits debian/patches");
824 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
825 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
827 if ($d == D_DEB_CLOG) {
828 return $classify->(qw(Changelog));
830 return $classify->(qw(Packaging));
832 } elsif ($ty eq 'missing') {
833 return $classify->(qw(BreakwaterStart));
835 return $unknown->("parent's debian is not a directory");
837 } elsif ($d == D_UPS) {
838 return $classify->(qw(Upstream));
839 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
840 return $classify->(qw(Mixed));
842 return $unknown->("no changes");
844 confess "internal error $objid ?";
848 return $unknown->("origin commit");
851 if (@p == 2 && @identical == 1) {
852 my @overwritten = grep { $_->{Differs} } @p;
853 confess "internal error $objid ?" unless @overwritten==1;
854 return $classify->(qw(Pseudomerge),
855 Overwritten => [ $overwritten[0] ],
856 Contributor => $identical[0]);
858 if (@p == 2 && @identical == 2) {
860 my ($ph,$pm) = get_commit $_[0]{CommitId};
861 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
865 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
866 if ($order > 0) { # newer first
867 } elsif ($order < 0) {
868 @bytime = reverse @bytime;
870 # same age, default to order made by -s ours
871 # that is, commit was made by someone who preferred L
873 return $classify->(qw(Pseudomerge),
874 SubType => qw(Ambiguous),
875 Contributor => $bytime[0],
876 Overwritten => [ $bytime[1] ]);
879 my ($p_h, $p_m) = get_commit $p->{CommitId};
880 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
881 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
883 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
885 if (!(grep { !$_->{IsOrigin} } @p) and
886 (@orig_ps >= @p - 1) and
887 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
889 return $classify->(qw(DgitImportUnpatched),
890 OrigParents => \@orig_ps);
894 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
895 # xxx ^ metadata tag needs adding to (5)
896 return $classify->("MergedBreakwaters");
898 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
899 return $unknown->("unknown kind of merge from $1");
902 return $unknown->("octopus merge");
905 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
906 return $unknown->("general two-parent merge");
909 return $classify->("VanillaMerge");
912 sub keycommits ($;$$$$$);
914 sub mergedbreakwaters_anchor ($) {
917 foreach my $p (@{ $cl->{Parents} }) {
918 my ($panchor, $pbw) = keycommits $p->{CommitId},
919 undef,undef,undef,undef, 1;
920 $best_anchor = $panchor
921 if !defined $best_anchor
922 or is_fast_fwd $best_anchor, $panchor;
923 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
924 unless is_fast_fwd $panchor, $best_anchor;
929 sub keycommits ($;$$$$$) {
930 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
931 # => ($anchor, $breakwater)
933 # $unclean->("unclean-$tagsfx", $msg, $cl)
934 # $furniture->("unclean-$tagsfx", $msg, $cl)
935 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
936 # is callled for each situation or commit that
937 # wouldn't be found in a laundered branch
938 # $furniture is for furniture commits such as might be found on an
939 # interchange branch (pseudomerge, d/patches, changelog)
940 # $trouble is for things whnich prevent the return of
941 # anchor and breakwater information; if that is ignored,
942 # then keycommits returns (undef, undef) instead.
943 # $fatal is for unprocessable commits, and should normally cause
944 # a failure. If ignored, agaion, (undef, undef) is returned.
946 # If $claimed_bw, this is supposed to be a breakwater commit.
948 # If a callback is undef, fail is called instead.
949 # If a callback is defined but false, the situation is ignored.
951 # no warnings qw(exiting); last;
952 # if the answer is no longer wanted.
954 my ($anchor, $breakwater);
955 $breakwater = $head if $claimed_bw;
959 $fatal //= sub { fail $_[1]; };
961 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
962 my $why = $mainwhy.$xwhy;
963 my $m = "branch needs laundering (run git-debrebase): $why";
964 fail $m unless defined $cb;
966 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
968 my $found_anchor = sub {
970 $breakwater //= $clogonly;
971 $breakwater //= $head;
972 no warnings qw(exiting);
976 $cl = classify $head;
977 my $ty = $cl->{Type};
978 if ($ty eq 'Packaging') {
979 $breakwater //= $clogonly;
980 $breakwater //= $head;
981 } elsif ($ty eq 'Changelog') {
982 # this is going to count as the tip of the breakwater
983 # only if it has no upstream stuff before it
985 } elsif ($ty eq 'Anchor' or
986 $ty eq 'TreatAsAnchor' or
987 $ty eq 'BreakwaterStart') {
988 $found_anchor->($head);
989 } elsif ($ty eq 'Upstream') {
990 $x->($unclean, 'ordering',
991 "packaging change ($breakwater) follows upstream change"," (eg $head)")
992 if defined $breakwater;
995 } elsif ($ty eq 'Mixed') {
996 $x->($unclean, 'mixed',
997 "found mixed upstream/packaging commit"," ($head)");
1000 } elsif ($ty eq 'Pseudomerge' or
1001 $ty eq 'AddPatches') {
1003 $x->($furniture, (lc $ty),
1004 "found interchange bureaucracy commit ($ty)"," ($head)");
1005 } elsif ($ty eq 'DgitImportUnpatched') {
1007 $x->($trouble, 'dgitimport',
1008 "found dgit dsc import"," ($head)");
1009 return (undef,undef);
1011 $x->($fatal, 'unprocessable',
1012 "found bare dgit dsc import with no prior history",
1014 return (undef,undef);
1016 } elsif ($ty eq 'VanillaMerge') {
1017 $x->($trouble, 'vanillamerge',
1018 "found vanilla merge"," ($head)");
1019 return (undef,undef);
1020 } elsif ($ty eq 'MergedBreakwaters') {
1021 $found_anchor->(mergedbreakwaters_anchor $cl);
1023 $x->($fatal, 'unprocessable',
1024 "found unprocessable commit, cannot cope: $cl->{Why}",
1026 return (undef,undef);
1028 $head = $cl->{Parents}[0]{CommitId};
1030 return ($anchor, $breakwater);
1036 $nogenerate,$report, $report_lprefix) = @_;
1037 # => ($tip, $breakwater_tip, $last_anchor)
1038 # (or nothing, if $nogenerate)
1040 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1041 $report_lprefix //= '';
1043 # go through commits backwards
1044 # we generate two lists of commits to apply:
1045 # breakwater branch and upstream patches
1046 my (@brw_cl, @upp_cl, @processed);
1053 my ($prose, $info) = @_;
1054 my $ms = $cl->{Msg};
1057 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1058 return (Msg => $ms);
1060 my $rewrite_from_here = sub {
1062 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1064 push @processed, $sp_cl;
1069 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1072 return unless $report;
1073 print $report $prdelim, $report_lprefix, @_;
1077 my $bomb = sub { # usage: return $bomb->();
1078 print $report " Unprocessable" if $report;
1079 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1082 return (undef,undef);
1084 fail "found unprocessable commit, cannot cope".
1085 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1086 " (commit $cur) (d.".
1087 (join ' ', map { sprintf "%#x", $_->{Differs} }
1088 @{ $cl->{Parents} }).
1095 my $build_start = sub {
1096 my ($msg, $parent) = @_;
1099 no warnings qw(exiting); last;
1104 merge_failed $cl->{MergeWreckNotes}, $emsg;
1107 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1112 $cl = classify $cur;
1113 $cl->{MergeWreckNotes} //= {};
1114 my $ty = $cl->{Type};
1115 my $st = $cl->{SubType};
1116 $prline->("$cl->{CommitId} $cl->{Type}");
1117 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1118 push @processed, $cl;
1119 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1120 if ($ty eq 'AddPatches') {
1122 $rewrite_from_here->(\@upp_cl);
1124 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1128 } elsif ($ty eq 'BreakwaterStart') {
1129 $last_anchor = $cur;
1130 $build_start->('FirstPackaging', $cur);
1131 } elsif ($ty eq 'Upstream') {
1135 } elsif ($ty eq 'Mixed') {
1138 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1141 $queue->(\@brw_cl, "debian");
1142 $queue->(\@upp_cl, "upstream");
1143 $rewrite_from_here->(\@brw_cl);
1146 } elsif ($ty eq 'Pseudomerge') {
1147 my $contrib = $cl->{Contributor}{CommitId};
1148 print $report " Contributor=$contrib" if $report;
1149 push @pseudomerges, $cl;
1150 $rewrite_from_here->(\@upp_cl);
1153 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1154 $last_anchor = $cur;
1155 $build_start->("Anchor", $cur);
1156 } elsif ($ty eq 'DgitImportUnpatched') {
1157 my $pm = $pseudomerges[-1];
1159 # To an extent, this is heuristic. Imports don't have
1160 # a useful history of the debian/ branch. We assume
1161 # that the first pseudomerge after an import has a
1162 # useful history of debian/, and ignore the histories
1163 # from later pseudomerges. Often the first pseudomerge
1164 # will be the dgit import of the upload to the actual
1165 # suite intended by the non-dgit NMUer, and later
1166 # pseudomerges may represent in-archive copies.
1167 my $ovwrs = $pm->{Overwritten};
1168 printf $report " PM=%s \@Overwr:%d",
1169 $pm->{CommitId}, (scalar @$ovwrs)
1172 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1175 my $ovwr = $ovwrs->[0]{CommitId};
1176 printf $report " Overwr=%s", $ovwr if $report;
1177 # This import has a tree which is just like a
1178 # breakwater tree, but it has the wrong history. It
1179 # ought to have the previous breakwater (which the
1180 # pseudomerge overwrote) as an ancestor. That will
1181 # make the history of the debian/ files correct. As
1182 # for the upstream version: either it's the same as
1183 # was ovewritten (ie, same as the previous
1184 # breakwater), in which case that history is precisely
1185 # right; or, otherwise, it was a non-gitish upload of a
1186 # new upstream version. We can tell these apart by
1187 # looking at the tree of the supposed upstream.
1190 SpecialMethod => 'DgitImportDebianUpdate',
1191 $xmsg->("convert dgit import: debian changes")
1194 SpecialMethod => 'DgitImportUpstreamUpdate',
1195 $xmsg->("convert dgit import: upstream update",
1198 $prline->(" Import");
1199 $rewrite_from_here->(\@brw_cl);
1200 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1204 # Everything is from this import. This kind of import
1205 # is already nearly in valid breakwater format, with the
1206 # patches as commits. Unfortunately it contains
1208 printdebug "*** WALK BOMB bare dgit import\n";
1209 $cl->{Why} = "bare dgit dsc import";
1213 } elsif ($ty eq 'MergedBreakwaters') {
1214 $last_anchor = mergedbreakwaters_anchor $cl;
1215 $build_start->(' MergedBreakwaters', $cur);
1217 } elsif ($ty eq 'VanillaMerge') {
1218 # User may have merged unstitched branch(es). We will
1219 # have now lost what ffq-prev was then (since the later
1220 # pseudomerge may introduce further changes). The effect
1221 # of resolving such a merge is that we may have to go back
1222 # further in history to find a merge base, since the one
1223 # which was reachable via ffq-prev is no longer findable.
1224 # This is suboptimal, but if it all works we'll have done
1226 # xxx we should warn the user in the docs about this
1230 # We expect to find a dominating anchor amongst the
1231 # inputs' anchors. That will be the new anchor.
1233 # More complicated is finding a merge base for the
1234 # breakwaters. We need a merge base that is a breakwater
1235 # commit. The ancestors of breakwater commits are more
1236 # breakwater commits and possibly upstream commits and the
1237 # ancestors of those upstream. Upstreams might have
1238 # arbitrary ancestors. But any upstream commit U is
1239 # either included in both anchors, in which case the
1240 # earlier anchor is a better merge base than any of U's
1241 # ancestors; or U is not included in the older anchor, in
1242 # which case U is not an ancestor of the vanilla merge at
1243 # all. So no upstream commit, nor any ancestor thereof,
1244 # is a best merge base. As for non-breakwater Debian
1245 # commits: these are never ancestors of any breakwater.
1247 # So any best merge base as found by git-merge-base
1248 # is a suitable breakwater anchor. Usually there will
1251 printdebug "*** MERGE\n";
1253 my @bwbcmd = (@git, qw(merge-base));
1254 my @ibcmd = (@git, qw(merge-base --all));
1255 my $might_be_in_bw = 1;
1257 my $ps = $cl->{Parents};
1259 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1261 foreach my $p (@$ps) {
1262 $prline->(" VanillaMerge ".$p->{Ix});
1264 my ($ptip, $pbw, $panchor) =
1265 walk $p->{CommitId}, 0, $report,
1266 $report_lprefix.' ';
1267 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1268 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1269 $p->{Anchor} = $panchor;
1271 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1272 $mwrecknote->("$lr-input", $p->{CommitId});
1274 my $mwrecknote_parent = sub {
1276 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1278 $mwrecknote_parent->('Laundered');
1279 $mwrecknote_parent->('Breakwater');
1280 $mwrecknote_parent->('Anchor');
1282 $best_anchor = $panchor if
1283 !defined $best_anchor or
1284 is_fast_fwd $best_anchor, $panchor;
1286 printdebug " MERGE BA best=".($best_anchor//'-').
1290 $mwrecknote->('result-anchor', $best_anchor);
1292 foreach my $p (@$ps) {
1293 $prline->(" VanillaMerge ".$p->{Ix});
1294 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1295 $nomerge->('divergent anchors');
1296 } elsif ($p->{Anchor} eq $best_anchor) {
1297 print $report " SameAnchor" if $report;
1299 print $report " SupersededAnchor" if $report;
1301 if ($p->{Breakwater} eq $p->{CommitId}) {
1302 # this parent commit was its own breakwater,
1303 # ie it is part of the breakwater
1304 print $report " Breakwater" if $report;
1306 $might_be_in_bw = 0;
1308 push @bwbcmd, $p->{Breakwater};
1309 push @ibcmd, $p->{CommitId};
1312 if ($ok && $might_be_in_bw) {
1313 # We could rewrite this to contaion the metadata
1314 # declaring it to be MergedBreakwaters, but
1315 # unnecessarily rewriting a merge seems unhelpful.
1316 $prline->(" VanillaMerge MergedBreakwaters");
1317 $last_anchor = $best_anchor;
1318 $build_start->('MergedBreakwaters', $cur);
1321 my $bwb = cmdoutput @bwbcmd;
1323 # OK, now we have a breakwater base, but we need the merge
1324 # base for the interchange branch because we need the delta
1327 # This a the best merge base of our inputs which has the
1328 # breakwater merge base as an ancestor.
1335 @ibs or confess 'internal error, expected anchor at least ?';
1339 foreach my $tibix (0..$#ibs) {
1340 my $tib = $ibs[$tibix];
1341 my $ff = is_fast_fwd $bwb, $tib;
1342 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1343 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1344 $mwrecknote->($tibleaf, $tib);
1351 $ib or $nomerge->("no suitable interchange merge base");
1353 $prline->(" VanillaMerge Base");
1355 my ($btip, $bbw, $banchor) = eval {
1356 walk $ib, 0, $report, $report_lprefix.' ';
1358 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1362 $mwrecknote->("mergebase-laundered", $btip);
1363 $mwrecknote->("mergebase-breakwater", $bbw);
1364 $mwrecknote->("mergebase-anchor", $banchor);
1366 my $ibinfo = { SeriesTip => $btip,
1369 LeftRight => 'mergebase' };
1372 or $nomerge->("interchange merge-base ($ib)'s".
1373 " breakwater ($bbw)".
1374 " != breakwaters' merge-base ($bwb)");
1376 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1377 or $nomerge->("interchange merge-base ($ib)'s".
1378 " anchor ($ibinfo->{SeriesBase})".
1379 " != any merge input's anchor (".
1380 (join ' ', map { $_->{Anchor} } @$ps).
1383 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1384 $cl->{MergeBestAnchor} = $best_anchor;
1387 SpecialMethod => 'MergeCreateMergedBreakwaters',
1388 $xmsg->('constructed from vanilla merge',
1389 ' merged-breakwater'),
1393 SpecialMethod => 'MergeMergeSeries',
1395 $build_start->('MergeBreakwaters', $cur);
1397 printdebug "*** WALK BOMB unrecognised\n";
1403 printdebug "*** WALK prep done cur=$cur".
1404 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1406 return if $nogenerate;
1408 # Now we build it back up again
1414 my $read_tree_upstream = sub {
1416 read_tree_upstream $treeish, 0, $build;
1419 $#upp_cl = $upp_limit if defined $upp_limit;
1421 my $committer_authline = calculate_committer_authline();
1423 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1425 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1428 mkdir $rd or $!==EEXIST or die $!;
1430 runcmd @git, qw(read-tree), $build;
1431 foreach my $cl (qw(Debian), (reverse @brw_cl),
1432 { SpecialMethod => 'RecordBreakwaterTip' },
1433 qw(Upstream), (reverse @upp_cl)) {
1435 $current_method = $cl;
1438 my $method = $cl->{SpecialMethod} // $current_method;
1439 my @parents = ($build);
1440 my $cltree = $cl->{CommitId};
1441 printdebug "WALK BUILD ".($cltree//'undef').
1442 " $method (rewriting=$rewriting)\n";
1443 if ($method eq 'Debian') {
1444 read_tree_debian($cltree);
1445 } elsif ($method eq 'Upstream') {
1446 $read_tree_upstream->($cltree);
1447 } elsif ($method eq 'StartRewrite') {
1450 } elsif ($method eq 'RecordBreakwaterTip') {
1451 $breakwater = $build;
1453 } elsif ($method eq 'DgitImportDebianUpdate') {
1454 read_tree_debian($cltree);
1455 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1456 confess unless $rewriting;
1457 my $differs = (get_differs $build, $cltree);
1458 next unless $differs & D_UPS;
1459 $read_tree_upstream->($cltree);
1460 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1461 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1462 print "Found a general merge, will try to tidy it up.\n";
1464 $read_tree_upstream->($cl->{MergeBestAnchor});
1465 $read_tree_upstream->($cl->{MergeBestAnchor});
1466 read_tree_debian($cltree);
1467 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1468 } elsif ($method eq 'MergeMergeSeries') {
1469 print "Running merge resolution for $cl->{CommitId}...\n";
1470 $build = merge_series
1471 $build, $cl->{MergeWreckNotes},
1472 $cl->{MergeInterchangeBaseInfo},
1473 @{ $cl->{Parents} };
1474 $last_anchor = $cl->{MergeBestAnchor};
1476 # Check for mismerges:
1478 my ($against, $allow, $what) = @_;
1479 my $differs = get_differs $build, $against;
1481 "merge misresolved: %s are not the same (%s %s d.%#x)",
1482 $what, $against, $build, $differs)
1483 if $differs & ~($allow | D_PAT_ADD);
1486 # Breakwater changes which were in each side of the
1487 # merge will have been incorporated into the
1488 # MergeCreateMergedBreakwaters output. Because the
1489 # upstream series was rebased onto the new breakwater,
1490 # so should all of the packaging changes which were in
1492 $check->($input, D_UPS, 'debian files');
1494 # Upstream files are merge_series, which ought to
1495 # have been identical to the original merge.
1496 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1498 print "Merge resolution successful.\n";
1501 confess "$method ?";
1504 my $procd = (pop @processed) // 'UNDEF';
1505 if ($cl ne $procd) {
1507 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1510 my $newtree = cmdoutput @git, qw(write-tree);
1511 my $ch = $cl->{Hdr};
1512 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1513 $ch =~ s{^parent .*\n}{}mg;
1514 $ch =~ s{(?=^author)}{
1515 join '', map { "parent $_\n" } @parents
1516 }me or confess "$ch ?";
1518 $ch =~ s{^committer .*$}{$committer_authline}m
1521 my $cf = "$rd/m$rewriting";
1522 open CD, ">", $cf or die $!;
1523 print CD $ch, "\n", $cl->{Msg} or die $!;
1525 my @cmd = (@git, qw(hash-object));
1526 push @cmd, qw(-w) if $rewriting;
1527 push @cmd, qw(-t commit), $cf;
1528 my $newcommit = cmdoutput @cmd;
1529 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1530 $build = $newcommit;
1531 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1532 $last_anchor = $cur;
1537 my $final_check = get_differs $build, $input;
1538 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1539 if $final_check & ~D_PAT_ADD;
1541 my @r = ($build, $breakwater, $last_anchor);
1542 printdebug "*** WALK RETURN @r\n";
1547 git_check_unmodified();
1548 return git_rev_parse qw(HEAD);
1551 sub update_head ($$$) {
1552 my ($old, $new, $mrest) = @_;
1553 push @deferred_updates, "update HEAD $new $old";
1554 run_deferred_updates $mrest;
1557 sub update_head_checkout ($$$) {
1558 my ($old, $new, $mrest) = @_;
1559 update_head $old, $new, $mrest;
1560 runcmd @git, qw(reset --hard);
1563 sub update_head_postlaunder ($$$) {
1564 my ($old, $tip, $reflogmsg) = @_;
1565 return if $tip eq $old;
1566 print "git-debrebase: laundered (head was $old)\n";
1567 update_head $old, $tip, $reflogmsg;
1568 # no tree changes except debian/patches
1569 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1572 sub currently_rebasing() {
1573 foreach (qw(rebase-merge rebase-apply)) {
1574 return 1 if stat_exists "$maindir_gitdir/$_";
1579 sub bail_if_rebasing() {
1580 fail "you are in the middle of a git-rebase already"
1581 if currently_rebasing();
1584 sub do_launder_head ($) {
1585 my ($reflogmsg) = @_;
1586 my $old = get_head();
1588 my ($tip,$breakwater) = walk $old;
1590 update_head_postlaunder $old, $tip, $reflogmsg;
1591 return ($tip,$breakwater);
1594 sub cmd_launder_v0 () {
1595 badusage "no arguments to launder-v0 allowed" if @ARGV;
1596 my $old = get_head();
1597 my ($tip,$breakwater,$last_anchor) = walk $old;
1598 update_head_postlaunder $old, $tip, 'launder';
1599 printf "# breakwater tip\n%s\n", $breakwater;
1600 printf "# working tip\n%s\n", $tip;
1601 printf "# last anchor\n%s\n", $last_anchor;
1604 sub defaultcmd_rebase () {
1605 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1606 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1607 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1610 sub cmd_analyse () {
1611 badusage "analyse does not support any options"
1612 if @ARGV and $ARGV[0] =~ m/^-/;
1613 badusage "too many arguments to analyse" if @ARGV>1;
1616 $old = git_rev_parse $old;
1618 $old = git_rev_parse 'HEAD';
1620 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1621 STDOUT->error and die $!;
1624 sub ffq_prev_branchinfo () {
1625 my $current = git_get_symref();
1626 return gdr_ffq_prev_branchinfo($current);
1629 sub ffq_check ($;$$) {
1630 # calls $ff and/or $notff zero or more times
1631 # then returns either (status,message) where status is
1636 # or (undef,undef, $ffq_prev,$gdrlast)
1637 # $ff and $notff are called like this:
1638 # $ff->("message for stdout\n");
1639 # $notff->('snag-name', $message);
1640 # normally $currentval should be HEAD
1641 my ($currentval, $ff, $notff) =@_;
1643 $ff //= sub { print $_[0] or die $!; };
1646 my ($status, $message, $current, $ffq_prev, $gdrlast)
1647 = ffq_prev_branchinfo();
1648 return ($status, $message) unless $status eq 'branch';
1650 my $exists = git_get_ref $ffq_prev;
1651 return ('exists',"$ffq_prev already exists") if $exists;
1653 return ('not-branch', 'HEAD symref is not to refs/heads/')
1654 unless $current =~ m{^refs/heads/};
1657 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1660 printdebug "ffq check_specs @check_specs\n";
1663 my ($lrref, $desc) = @_;
1664 printdebug "ffq might check $lrref ($desc)\n";
1666 for my $chk (@check_specs) {
1668 $invert = $glob =~ s{^[!^]}{};
1669 last if fnmatch $glob, $lrref;
1672 my $lrval = git_get_ref $lrref;
1673 return unless length $lrval;
1675 if (is_fast_fwd $lrval, $currentval) {
1676 $ff->("OK, you are ahead of $lrref\n");
1677 $checked{$lrref} = 1;
1678 } elsif (is_fast_fwd $currentval, $lrval) {
1679 $checked{$lrref} = -1;
1680 $notff->('behind', "you are behind $lrref, divergence risk");
1682 $checked{$lrref} = -1;
1683 $notff->('diverged', "you have diverged from $lrref");
1687 my $merge = cfg "branch.$branch.merge",1;
1688 if (defined $merge and $merge =~ m{^refs/heads/}) {
1690 printdebug "ffq merge $rhs\n";
1691 my $check_remote = sub {
1692 my ($remote, $desc) = @_;
1693 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1694 return unless defined $remote;
1695 $check->("refs/remotes/$remote/$rhs", $desc);
1697 $check_remote->((scalar cfg "branch.$branch.remote",1),
1698 'remote fetch/merge branch');
1699 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1700 (scalar cfg "branch.$branch.pushDefault",1),
1701 'remote push branch');
1703 if ($branch =~ m{^dgit/}) {
1704 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1705 } elsif ($branch =~ m{^master$}) {
1706 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1708 return (undef, undef, $ffq_prev, $gdrlast);
1711 sub record_ffq_prev_deferred () {
1712 # => ('status', "message")
1714 # deferred message is undef
1719 # if not ff from some branch we should be ff from, is an snag
1720 # if "deferred", will have added something about that to
1721 # @deferred_update_messages, and also maybe printed (already)
1722 # some messages about ff checks
1724 my $currentval = get_head();
1726 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1727 return ($status,$message) if defined $status;
1731 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1732 push @deferred_updates, "delete $gdrlast";
1733 push @deferred_update_messages, "Recorded previous head for preservation";
1734 return ('deferred', undef);
1737 sub record_ffq_auto () {
1738 my ($status, $message) = record_ffq_prev_deferred();
1739 if ($status eq 'deferred' || $status eq 'exists') {
1741 snag $status, "could not record ffq-prev: $message";
1746 sub ffq_prev_info () {
1748 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1749 my ($status, $message, $current, $ffq_prev, $gdrlast)
1750 = ffq_prev_branchinfo();
1751 if ($status ne 'branch') {
1752 snag $status, "could not check ffq-prev: $message";
1755 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1756 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1759 sub stitch ($$$$$) {
1760 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1762 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1764 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1765 my $differs = get_differs $old_head, $ffq_prev_commitish;
1766 unless ($differs & ~D_PAT_ADD) {
1767 # ffq-prev is ahead of us, and the only tree changes it has
1768 # are possibly addition of things in debian/patches/.
1769 # Just wind forwards rather than making a pointless pseudomerge.
1770 push @deferred_updates,
1771 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1772 update_head_checkout $old_head, $ffq_prev_commitish,
1773 "stitch (fast forward)";
1778 # We make pseudomerges with L as the contributing parent.
1779 # This makes git rev-list --first-parent work properly.
1780 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1781 'Declare fast forward / record previous work',
1782 "[git-debrebase pseudomerge: $prose]",
1784 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1785 update_head $old_head, $new_head, "stitch: $prose";
1788 sub do_stitch ($;$) {
1789 my ($prose, $unclean) = @_;
1791 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1792 if (!$ffq_prev_commitish) {
1793 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1796 my $dangling_head = get_head();
1798 keycommits $dangling_head, $unclean,$unclean,$unclean;
1801 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1804 sub upstream_commitish_search ($$) {
1805 my ($upstream_version, $tried) = @_;
1806 # todo: at some point maybe use git-deborig to do this
1807 foreach my $tagpfx ('', 'v', 'upstream/') {
1808 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1809 my $new_upstream = git_get_ref "refs/tags/$tag";
1811 return $new_upstream if length $new_upstream;
1815 sub resolve_upstream_version ($$) {
1816 my ($new_upstream, $upstream_version) = @_;
1818 if (!defined $new_upstream) {
1820 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1821 if (!length $new_upstream) {
1822 fail "Could not determine appropriate upstream commitish.\n".
1823 " (Tried these tags: @tried)\n".
1824 " Check version, and specify upstream commitish explicitly.";
1827 $new_upstream = git_rev_parse $new_upstream;
1829 return $new_upstream;
1832 sub cmd_new_upstream () {
1833 # automatically and unconditionally launders before rebasing
1834 # if rebase --abort is used, laundering has still been done
1838 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1840 # parse args - low commitment
1841 my $spec_version = shift @ARGV;
1842 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1843 fail "bad version number \`$spec_version'" unless defined $new_version;
1844 if ($new_version->is_native()) {
1845 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1848 my $new_upstream = shift @ARGV;
1849 my $new_upstream_version = upstreamversion $new_version;
1851 resolve_upstream_version $new_upstream, $new_upstream_version;
1856 my ($n, @x) = @_; # may be ''
1857 my $pc = $pieces{$n} //= {
1859 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1861 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1866 my $newpiece = sub {
1867 my ($n, @x) = @_; # may be ''
1868 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1869 push @newpieces, $pc;
1874 New => $new_upstream,
1876 while (@ARGV && $ARGV[0] !~ m{^-}) {
1877 my $n = shift @ARGV;
1879 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1880 unless @ARGV && $ARGV[0] !~ m{^-};
1882 my $c = git_rev_parse shift @ARGV;
1883 die unless $n =~ m/^$extra_orig_namepart_re$/;
1884 $newpiece->($n, New => $c);
1887 # now we need to investigate the branch this generates the
1888 # laundered version but we don't switch to it yet
1889 my $old_head = get_head();
1890 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1892 my $old_bw_cl = classify $old_bw;
1893 my $old_anchor_cl = classify $old_anchor;
1895 if (!$old_anchor_cl->{OrigParents}) {
1896 snag 'anchor-treated',
1897 'old anchor is recognised due to --anchor, cannot check upstream';
1899 $old_upstream = parsecommit
1900 $old_anchor_cl->{OrigParents}[0]{CommitId};
1901 $piece->('', Old => $old_upstream->{CommitId});
1904 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1905 if ($old_upstream->{Msg} =~
1906 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1908 my @oldpieces = (split / /, $1);
1909 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1910 if ($old_n_parents != @oldpieces &&
1911 $old_n_parents != @oldpieces + 1) {
1912 snag 'upstream-confusing', sprintf
1913 "previous upstream combine %s".
1914 " mentions %d pieces (each implying one parent)".
1915 " but has %d parents".
1916 " (one per piece plus maybe a previous combine)",
1917 $old_upstream->{CommitId},
1918 (scalar @oldpieces),
1920 } elsif ($oldpieces[0] ne '.') {
1921 snag 'upstream-confusing', sprintf
1922 "previous upstream combine %s".
1923 " first piece is not \`.'",
1927 foreach my $i (0..$#oldpieces) {
1928 my $n = $oldpieces[$i];
1929 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1930 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1934 snag 'upstream-confusing',
1935 "previous upstream $old_upstream->{CommitId} is from".
1936 " git-debrebase but not an \`upstream-combine' commit";
1940 foreach my $pc (values %pieces) {
1941 if (!$old_upstream) {
1942 # we have complained already
1943 } elsif (!$pc->{Old}) {
1944 snag 'upstream-new-piece',
1945 "introducing upstream piece \`$pc->{Name}'";
1946 } elsif (!$pc->{New}) {
1947 snag 'upstream-rm-piece',
1948 "dropping upstream piece \`$pc->{Name}'";
1949 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1950 snag 'upstream-not-ff',
1951 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1955 printdebug "%pieces = ", (dd \%pieces), "\n";
1956 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1964 my @upstream_merge_parents;
1967 push @upstream_merge_parents, $old_upstream->{CommitId};
1970 foreach my $pc (@newpieces) { # always has '' first
1972 read_tree_subdir $pc->{Name}, $pc->{New};
1974 runcmd @git, qw(read-tree), $pc->{New};
1976 push @upstream_merge_parents, $pc->{New};
1979 # index now contains the new upstream
1981 if (@newpieces > 1) {
1982 # need to make the upstream subtree merge commit
1983 $new_upstream = make_commit \@upstream_merge_parents,
1984 [ "Combine upstreams for $new_upstream_version",
1985 ("[git-debrebase upstream-combine . ".
1986 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1991 # $new_upstream is either the single upstream commit, or the
1992 # combined commit we just made. Either way it will be the
1993 # "upstream" parent of the anchor merge.
1995 read_tree_subdir 'debian', "$old_bw:debian";
1997 # index now contains the anchor merge contents
1998 $new_bw = make_commit [ $old_bw, $new_upstream ],
1999 [ "Update to upstream $new_upstream_version",
2000 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2003 my $clogsignoff = cmdoutput qw(git show),
2004 '--pretty=format:%an <%ae> %aD',
2007 # Now we have to add a changelog stanza so the Debian version
2009 die if unlink "debian";
2010 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2011 unlink "debian/changelog" or $!==ENOENT or die $!;
2012 mkdir "debian" or die $!;
2013 open CN, ">", "debian/changelog" or die $!;
2014 my $oldclog = git_cat_file ":debian/changelog";
2015 $oldclog =~ m/^($package_re) \(\S+\) / or
2016 fail "cannot parse old changelog to get package name";
2018 print CN <<END, $oldclog or die $!;
2019 $p ($new_version) UNRELEASED; urgency=medium
2021 * Update to new upstream version $new_upstream_version.
2027 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2029 # Now we have the final new breakwater branch in the index
2030 $new_bw = make_commit [ $new_bw ],
2031 [ "Update changelog for new upstream $new_upstream_version",
2032 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2036 # we have constructed the new breakwater. we now need to commit to
2037 # the laundering output, because git-rebase can't easily be made
2038 # to make a replay list which is based on some other branch
2040 update_head_postlaunder $old_head, $old_laundered_tip,
2041 'launder for new upstream';
2043 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2044 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2045 "debrebase new-upstream $new_version: rebase";
2047 # now it's for the user to sort out
2050 sub cmd_record_ffq_prev () {
2051 badusage "no arguments allowed" if @ARGV;
2052 my ($status, $msg) = record_ffq_prev_deferred();
2053 if ($status eq 'exists' && $opt_noop_ok) {
2054 print "Previous head already recorded\n" or die $!;
2055 } elsif ($status eq 'deferred') {
2056 run_deferred_updates 'record-ffq-prev';
2058 fail "Could not preserve: $msg";
2063 badusage "no arguments allowed" if @ARGV;
2064 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2065 print "$bw\n" or die $!;
2068 sub cmd_breakwater () {
2069 badusage "no arguments allowed" if @ARGV;
2070 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2071 print "$bw\n" or die $!;
2075 badusage "no arguments allowed" if @ARGV;
2077 # todo: gdr status should print divergence info
2078 # todo: gdr status should print upstream component(s) info
2079 # todo: gdr should leave/maintain some refs with this kind of info ?
2081 my $oldest = { Badness => 0 };
2084 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2085 if ($oldest->{Badness} < $badness) {
2086 $oldest = $newest = undef;
2089 Badness => $badness,
2090 CommitId => $cl->{CommitId},
2094 $newest //= $oldest;
2096 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2097 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2098 sub { $note->(2, 'branch is unlaundered', @_); },
2099 sub { $note->(3, 'branch needs laundering', @_); },
2100 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2102 my $prcommitinfo = sub {
2104 flush STDOUT or die $!;
2105 runcmd @git, qw(--no-pager log -n1),
2106 '--pretty=format: %h %s%n',
2110 print "current branch contents, in git-debrebase terms:\n";
2111 if (!$oldest->{Badness}) {
2112 print " branch is laundered\n";
2114 print " $oldest->{OurMsg}\n";
2116 foreach my $info ($oldest, $newest) {
2117 my $cid = $info->{CommitId};
2118 next if $cid eq $printed;
2120 print " $info->{KcMsg}\n";
2121 $prcommitinfo->($cid);
2126 my ($cid, $what) = @_;
2127 if (!defined $cid) {
2128 print " $what is not well-defined\n";
2131 $prcommitinfo->($cid);
2134 print "key git-debrebase commits:\n";
2135 $prab->($anchor, 'anchor');
2136 $prab->($bw, 'breakwater');
2138 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2139 ffq_prev_branchinfo();
2141 print "branch and ref status, in git-debrebase terms:\n";
2143 print " $ffq_msg\n";
2145 $ffq_prev = git_get_ref $ffq_prev;
2146 $gdrlast = git_get_ref $gdrlast;
2148 print " unstitched; previous tip was:\n";
2149 $prcommitinfo->($ffq_prev);
2150 } elsif (!$gdrlast) {
2151 print " stitched? (no record of git-debrebase work)\n";
2152 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2153 print " stitched\n";
2155 print " not git-debrebase (diverged since last stitch)\n"
2158 print "you are currently rebasing\n" if currently_rebasing();
2162 my $prose = 'stitch';
2163 getoptions("stitch",
2164 'prose=s', \$prose);
2165 badusage "no arguments allowed" if @ARGV;
2166 do_stitch $prose, 0;
2168 sub cmd_prepush () { cmd_stitch(); }
2171 badusage "no arguments allowed" if @ARGV;
2172 do_launder_head 'launder for git-debrebase quick';
2176 sub cmd_conclude () {
2177 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2178 if (!$ffq_prev_commitish) {
2179 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2182 my $dangling_head = get_head();
2184 badusage "no arguments allowed" if @ARGV;
2185 do_launder_head 'launder for git-debrebase quick';
2190 if (currently_rebasing()) {
2191 runcmd @git, qw(rebase --abort);
2193 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2194 if (!$ffq_prev_commitish) {
2195 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2198 my $scrapping_head = get_head();
2199 badusage "no arguments allowed" if @ARGV;
2200 push @deferred_updates,
2201 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2202 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2204 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2207 sub make_patches_staged ($) {
2209 # Produces the patches that would result from $head if it were
2211 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2214 gbp_pq_export 'bw', $secret_bw, $secret_head;
2218 sub make_patches ($) {
2220 keycommits $head, 0, \&snag;
2221 make_patches_staged $head;
2224 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2225 runcmd @git, qw(read-tree), $head;
2226 read_tree_subdir 'debian/patches', $ptree;
2227 $out = make_commit [$head], [
2228 'Commit patch queue (exported by git-debrebase)',
2229 '[git-debrebase: export and commit patches]',
2235 sub cmd_make_patches () {
2236 my $opt_quiet_would_amend;
2237 getoptions("make-patches",
2238 'quiet-would-amend!', \$opt_quiet_would_amend);
2239 badusage "no arguments allowed" if @ARGV;
2241 my $old_head = get_head();
2242 my $new = make_patches $old_head;
2243 my $d = get_differs $old_head, $new;
2245 fail "No (more) patches to export." unless $opt_noop_ok;
2247 } elsif ($d == D_PAT_ADD) {
2249 update_head_checkout $old_head, $new, 'make-patches';
2251 print STDERR failmsg
2252 "Patch export produced patch amendments".
2253 " (abandoned output commit $new).".
2254 " Try laundering first."
2255 unless $opt_quiet_would_amend;
2260 sub cmd_convert_from_gbp () {
2261 badusage "want only 1 optional argument, the upstream git commitish"
2264 my $clogp = parsechangelog();
2265 my $version = $clogp->{'Version'}
2266 // die "missing Version from changelog";
2268 my ($upstream_spec) = @ARGV;
2270 my $upstream_version = upstreamversion $version;
2272 resolve_upstream_version($upstream_spec, $upstream_version);
2274 my $old_head = get_head();
2276 my $upsdiff = get_differs $upstream, $old_head;
2277 if ($upsdiff & D_UPS) {
2278 runcmd @git, qw(--no-pager diff --stat),
2279 $upstream, $old_head,
2280 qw( -- :!/debian :/);
2282 upstream ($upstream_spec) and HEAD are not
2283 identical in upstream files. See diffstat above, or run
2284 git diff $upstream_spec HEAD -- :!/debian :/
2288 if (!is_fast_fwd $upstream, $old_head) {
2289 snag 'upstream-not-ancestor',
2290 "upstream ($upstream) is not an ancestor of HEAD";
2292 my $wrong = cmdoutput
2293 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2294 qw(-- :/ :!/debian));
2295 if (length $wrong) {
2296 snag 'unexpected-upstream-changes',
2297 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2298 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2302 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2303 snag 'upstream-has-debian',
2304 "upstream ($upstream) contains debian/ directory";
2307 my $previous_dgit_view = eval {
2308 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2310 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2311 my ($stz, $desc) = @_;
2312 no warnings qw(exiting);
2313 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2314 next unless $stz->{Date};
2315 next unless $stz->{Distribution} ne 'UNRELEASED';
2316 $lvsn = $stz->{Version};
2317 $suite = $stz->{Distribution};
2320 die "neither of the first two changelog entries are released\n"
2321 unless defined $lvsn;
2322 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2323 my $mtag_pat = debiantag_maintview $lvsn, '*';
2324 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2326 die "could not find suitable maintainer view tag $mtag_pat\n"
2327 unless $mtag_pat =~ m{/};
2328 is_fast_fwd $mtag, 'HEAD' or
2329 die "HEAD is not FF from maintainer tag $mtag!";
2330 my $dtag = "archive/$mtag";
2331 is_fast_fwd $mtag, $dtag or
2332 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2333 print "will stitch in dgit view, $dtag\n";
2334 git_rev_parse $dtag;
2336 if (!$previous_dgit_view) {
2339 print STDERR "cannot stitch in dgit view: $@\n";
2342 snags_maybe_bail_early();
2348 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2349 # make a branch out of the patch queue - we'll want this in a mo
2350 runcmd qw(gbp pq import);
2351 # strip the patches out
2352 runcmd @git, qw(checkout -q gdr-internal~0);
2353 rm_subdir_cached 'debian/patches';
2354 $work = make_commit ['HEAD'], [
2355 'git-debrebase convert-from-gbp: drop patches from tree',
2356 'Delete debian/patches, as part of converting to git-debrebase format.',
2357 '[git-debrebase convert-from-gbp: drop patches from tree]'
2359 # make the anchor merge
2360 # the tree is already exactly right
2361 $work = make_commit [$work, $upstream], [
2362 'git-debrebase import: declare upstream',
2363 'First breakwater merge.',
2364 '[git-debrebase anchor: declare upstream]'
2367 # rebase the patch queue onto the new breakwater
2368 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2369 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2370 $work = git_rev_parse 'HEAD';
2372 if ($previous_dgit_view) {
2373 $work = make_commit [$work, $previous_dgit_view], [
2374 'git-debrebase import: declare ff from dgit archive view',
2375 '[git-debrebase pseudomerge: import-from-gbp]',
2382 update_head_checkout $old_head, $work, 'convert-from-gbp';
2385 sub cmd_convert_to_gbp () {
2386 badusage "no arguments allowed" if @ARGV;
2387 my $head = get_head();
2388 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2389 keycommits $head, 0;
2391 make_patches_staged $head;
2393 $out = make_commit ['HEAD'], [
2394 'Commit patch queue (converted from git-debrebase format)',
2395 '[git-debrebase convert-to-gbp: commit patches]',
2399 push @deferred_updates, "delete $ffq";
2400 push @deferred_updates, "delete $gdrlast";
2403 update_head_checkout $head, $out, "convert to gbp (v0)";
2404 print <<END or die $!;
2405 git-debrebase: converted to git-buildpackage branch format
2406 git-debrebase: WARNING: do not now run "git-debrebase" any more
2407 git-debrebase: WARNING: doing so would drop all upstream patches!
2411 sub cmd_convert_from_dgit_view () {
2412 my $clogp = parsechangelog();
2414 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2420 getoptions("convert-from-dgit-view",
2421 'diagnose!', \$diagnose,
2422 'build-products-dir:s', \$bpd,
2423 'origs!', \$do_origs,
2425 'always-convert-anyway!', \$always);
2426 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2431 my $spec = shift @ARGV;
2432 my $commit = git_rev_parse "$spec^{commit}";
2433 push @upstreams, { Commit => $commit,
2434 Source => "$ARGV[0], from command line",
2439 my $head = get_head();
2443 my $trouble = sub { $troubles++; };
2444 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2445 printdebug "troubles=$troubles\n";
2448 $us: Branch already seems to be in git-debrebase format!
2449 $us: --always-convert-anyway would do the conversion operation anyway
2450 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2452 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2457 snags_maybe_bail_early();
2459 my $version = upstreamversion $clogp->{Version};
2460 print STDERR "Considering possible commits corresponding to upstream:\n";
2465 my $ups_tag = upstream_commitish_search $version, \@tried;
2467 my $this = "git tag $tried[-1]";
2468 push @upstreams, { Commit => $ups_tag,
2473 " git tag: no suitable tag found (tried %s)\n",
2478 my $p = $clogp->{'Source'};
2479 # we do a quick check to see if there are plausible origs
2481 if (!opendir BPD, $bpd) {
2482 die "$bpd: opendir: $!" unless $!==ENOENT;
2484 while ($!=0, my $f = readdir BPD) {
2485 next unless is_orig_file_of_p_v $f, $p, $version;
2487 " orig: found what looks like a .orig, %s\n",
2492 die "read $bpd: $!" if $!;
2496 my $tree = cmdoutput
2497 @dgit, qw(--build-products-dir), $bpd,
2498 qw(print-unapplied-treeish);
2501 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2502 rm_subdir_cached 'debian';
2503 $tree = cmdoutput @git, qw(write-tree);
2504 my $ups_synth = make_commit [], [ <<END, <<END,
2505 Import effective orig tree for upstream version $version
2507 This includes the contents of the .orig(s), minus any debian/ directory.
2509 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2512 push @upstreams, { Commit => $ups_synth,
2513 Source => "orig(s) imported via dgit",
2518 " orig: no suitable origs found (looked for %s in %s)\n",
2519 "${p}_".(stripeoch $version)."...", $bpd;
2524 my $some_patches = stat_exists 'debian/patches/series';
2526 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2529 foreach my $u (@upstreams) {
2533 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2534 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2535 runcmd @git, qw(clean -xdff);
2536 runcmd @git, qw(checkout), $head, qw(-- debian);
2537 if ($some_patches) {
2538 rm_subdir_cached 'debian/patches';
2539 $work = make_commit [ $work ], [
2540 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2541 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2542 "to git-debrebase format. Upstream changes will appear as commits.",
2543 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2546 $work = make_commit [ $work, $u->{Commit} ], [
2547 'git-debrebase convert-from-dgit-view: declare upstream',
2548 '(Re)constructed breakwater merge.',
2549 '[git-debrebase anchor: declare upstream]'
2551 runcmd @git, qw(checkout --quiet -b mk), $work;
2552 if ($some_patches) {
2553 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2554 runcmd @git, qw(reset --quiet);
2555 my @gbp_cmd = (qw(gbp pq import));
2557 my $gbp_err = "../gbp-pq-err";
2558 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2560 my $r = system @gbp_cmd;
2563 " %s: couldn't apply patches: gbp pq %s",
2564 $u->{Source}, waitstatusmsg();
2568 my $work = git_rev_parse qw(HEAD);
2569 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2570 if (length $diffout) {
2572 " $u->{Source}: applying patches gives different tree\n";
2573 print STDERR $diffout if $diagnose;
2577 $u->{Result} = $work;
2585 Could not find or construct a suitable upstream commit.
2586 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2587 upstream commmit explicitly or provide suitable origs.
2591 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2593 ffq_check $result->{Result};
2595 update_head_checkout $head, $result->{Result},
2596 'convert-from-dgit-view';
2599 sub cmd_downstream_rebase_launder_v0 () {
2600 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2602 $base = git_rev_parse $base;
2603 my $old_head = get_head();
2604 my $current = $old_head;
2607 if ($current eq $base) {
2608 $topmost_keep //= $current;
2609 print " $current BASE stop\n";
2612 my $cl = classify $current;
2613 print " $current $cl->{Type}";
2615 my $p0 = $cl->{Parents}[0]{CommitId};
2617 if ($cl->{Type} eq 'Pseudomerge') {
2618 print " ^".($cl->{Contributor}{Ix}+1);
2619 $next = $cl->{Contributor}{CommitId};
2620 } elsif ($cl->{Type} eq 'AddPatches' or
2621 $cl->{Type} eq 'Changelog') {
2631 $topmost_keep //= $current;
2633 die "to-be stripped changes not on top of the branch\n"
2638 if ($topmost_keep eq $old_head) {
2639 print "unchanged\n";
2641 print "updating to $topmost_keep\n";
2642 update_head_checkout
2643 $old_head, $topmost_keep,
2644 'downstream-rebase-launder-v0';
2650 "D+" => \$debuglevel,
2651 'noop-ok', => \$opt_noop_ok,
2652 'f=s' => \@snag_force_opts,
2653 'anchor=s' => \@opt_anchors,
2654 '--dgit=s' => \($dgit[0]),
2657 my ($opt,$val) = @_;
2658 badusage "git-debrebase: no cuddling to -i for git-rebase"
2660 die if $opt_defaultcmd_interactive; # should not happen
2661 $opt_defaultcmd_interactive = [ qw(-i) ];
2662 # This access to @ARGV is excessive familiarity with
2663 # Getopt::Long, but there isn't another sensible
2664 # approach. '-i=s{0,}' does not work with bundling.
2665 push @$opt_defaultcmd_interactive, @ARGV;
2668 'help' => sub { print $usage_message or die $!; finish 0; },
2671 initdebug('git-debrebase ');
2672 enabledebug if $debuglevel;
2674 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2675 chdir $toplevel or die "chdir $toplevel: $!";
2677 $rd = fresh_playground "$playprefix/misc";
2679 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2681 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2682 defaultcmd_rebase();
2684 my $cmd = shift @ARGV;
2687 $cmdfn = ${*::}{"cmd_$cmdfn"};
2689 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";