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_series ($$$;@) {
421 my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
422 # $base_q{SeriesBase} $input_qs[]{SeriesBase}
423 # $base_q{SeriesTip} $input_qs[]{SeriesTip}
424 # ^ specifies several patch series (currently we only support exactly 2)
425 # return value is a commit which is the result of
426 # merging the two versions of the same topic branch
427 # $input_q[0] and $input_q[1]
428 # with respect to the old version
432 # Creates, in *_q, a key MR for its private use
434 printdebug "merge_series newbase=$newbase\n";
436 $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
437 $base_q->{MR}{S} = 'base';
440 # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
441 # $prereq{<patch filename>}{<possible prereq} exists or not (later)
442 # $prereq{<patch filename>} exists or not (even later)
446 my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
448 my $attempt_cmd = sub {
452 merge_failed $wrecknotes,
453 failedcmd_waitstatus(),
454 "failed command: @_";
459 fresh_workarea "merge";
460 my $seriesfile = "debian/patches/series";
463 foreach my $q ($base_q, reverse @input_qs) {
465 gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
467 if (open S, $seriesfile) {
468 while (my $patch = <S>) {
469 chomp $patch or die $!;
470 $prereq{$patch} //= {};
471 foreach my $earlier (@earlier) {
472 $prereq{$patch}{$earlier}{$s}++ and die;
474 push @earlier, $patch;
475 stat "debian/patches/$patch" or die "$patch ?";
477 S->error and die "$seriesfile $!";
480 die "$seriesfile $!" unless $!==ENOENT;
482 read_tree_upstream $newbase, 1;
483 my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
484 "Convert $s to patch queue for merging",
485 "[git-debrebase merge-innards patch-queue import:".
488 printdebug "merge_series pec $pec ";
489 runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
490 $pec = make_commit [ $pec ], [
491 "Drop series file from $s to avoid merge trouble",
492 "[git-debrebase merge-innards patch-queue prep:".
496 read_tree_debian $newbase;
498 read_tree_subdir 'debian/patches', "$pec:debian/patches";
500 rm_subdir_cached 'debian/patches';
502 $pec = make_commit [ $pec ], [
503 "Update debian/ (excluding patches) to final to avoid re-merging",
504 "debian/ was already merged and we need to just take that.",
505 "[git-debrebase merge-innards patch-queue packaging:".
509 printdebug "pec' $pec\n";
510 runcmd @git, qw(reset -q --hard), $pec;
511 $q->{MR}{PEC} = $pec;
512 $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
514 # now, because of reverse, we are on $input_q->{MR}{OQC}
515 runcmd @git, qw(checkout -q -b merge);
516 printdebug "merge_series merging...\n";
517 my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
519 $attempt_cmd->(@mergecmd);
521 printdebug "merge_series merge ok, series...\n";
522 # We need to construct a new series file
523 # Firstly, resolve prereq
524 foreach my $f (sort keys %prereq) {
525 printdebug "merge_series patch\t$f\t";
526 if (!stat_exists "debian/patches/$f") {
527 print DEBUG " drop\n" if $debuglevel;
528 # git merge deleted it; that's how we tell it's not wanted
532 print DEBUG " keep\n" if $debuglevel;
533 foreach my $g (sort keys %{ $prereq{$f} }) {
534 my $gfp = $prereq{$f}{$g};
535 printdebug "merge_series prereq\t$f\t-> $g\t";
536 if (!!$gfp->{0} == !!$gfp->{1}
539 print DEBUG "\tkeep\n" if $debuglevel;
541 print DEBUG "\tdrop\n" if $debuglevel;
542 delete $prereq{$f}{$g};
549 return scalar keys %{ $prereq{$f} };
552 my $nodate = time + 1;
554 # $authordate{<patch filename>};
555 my $authordate = sub {
557 $authordate{$f} //= do {
558 open PF, "<", "debian/patches/$f" or die "$f $!";
560 return $nodate if m/^$/;
561 last if s{^Date: }{};
564 return cmdoutput qw(date +%s -d), $_;
568 open NS, '>', $seriesfile or die $!;
570 while (keys %prereq) {
572 foreach my $try (sort keys %prereq) {
575 $unsat->($try) <=> $unsat->($best) or
576 $authordate->($try) <=> $authordate->($best) or
582 printdebug "merge_series series next $best\n";
583 print NS "$best\n" or die $!;
584 delete $prereq{$best};
585 foreach my $gp (values %prereq) {
590 runcmd @git, qw(add), $seriesfile;
591 runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
592 $mwrecknote->('merged-patchqueue', git_rev_parse 'HEAD');
594 printdebug "merge_series series gbp pq import\n";
596 $attempt_cmd->(qw(gbp pq import));
598 # OK now we are on patch-queue/merge, and we need to rebase
599 # onto the intended parent and drop the patches from each one
601 printdebug "merge_series series ok, building...\n";
602 my $build = $newbase;
603 my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
604 foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
605 my $commit = git_cat_file $c, 'commit';
606 printdebug "merge_series series ok, building $c\n";
607 read_tree_upstream $c, 0, $newbase;
608 my $tree = cmdoutput @git, qw(write-tree);
609 $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
610 $commit =~ s{^tree (\S+)$}{tree $tree}m or confess;
611 open C, ">", "../mcommit" or die $!;
612 print C $commit or die $!;
614 $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
617 $mwrecknote->('merged-result', $result);
619 runcmd @git, qw(update-ref refs/heads/result), $result;
621 runcmd @git, qw(checkout -q -b debug);
622 runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
623 runcmd @git, qw(add .);
624 runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
625 my $mdebug = git_rev_parse 'HEAD';
626 printdebug sprintf "merge_series done debug=%s\n", $mdebug;
627 $mwrecknote->('merged-debug', $mdebug);
629 printdebug "merge_series returns $result\n";
633 # classify returns an info hash like this
635 # Hdr => # commit headers, including 1 final newline
636 # Msg => # commit message (so one newline is dropped)
638 # Type => (see below)
640 # Ix => $index # ie 0, 1, 2, ...
642 # Differs => return value from get_differs
644 # IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
646 # NewMsg => # commit message, but with any [dgit import ...] edited
647 # # to say "[was: ...]"
657 # has additional entres in classification result
658 # Overwritten = [ subset of Parents ]
659 # Contributor = $the_remaining_Parent
661 # DgitImportUnpatched
662 # has additional entry in classification result
663 # OrigParents = [ subset of Parents ]
666 # has additional entry in classification result
667 # OrigParents = [ subset of Parents ] # singleton list
674 # has additional entry in classification result
677 sub parsecommit ($;$) {
678 my ($objid, $p_ref) = @_;
679 # => hash with CommitId Hdr Msg Tree Parents
680 # Parents entries have only Ix CommitId
681 # $p_ref, if provided, must be [] and is used as a base for Parents
686 my ($h,$m) = get_commit $objid;
688 my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
689 my (@ph) = $h =~ m/^parent (\w+)$/mg;
699 foreach my $ph (@ph) {
701 Ix => scalar @$p_ref,
713 my $r = parsecommit($objid, \@p);
717 $p->{Differs} = (get_differs $p->{CommitId}, $t),
720 printdebug "classify $objid \$t=$t \@p",
721 (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
725 my ($type, @rest) = @_;
726 $r = { %$r, Type => $type, @rest };
728 printdebug " = $type ".(dd $r)."\n";
734 $r = { %$r, Type => qw(Unknown), Why => $why };
735 printdebug " ** Unknown\n";
739 if (grep { $_ eq $objid } @opt_anchors) {
740 return $classify->('TreatAsAnchor');
743 my @identical = grep { !$_->{Differs} } @p;
744 my ($stype, $series) = git_cat_file "$t:debian/patches/series";
745 my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
747 if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
748 # multi-orig upstreams are represented with an anchor merge
749 # from a single upstream commit which combines the orig tarballs
751 # Every anchor tagged this way must be a merge.
752 # We are relying on the
753 # [git-debrebase anchor: ...]
754 # commit message annotation in "declare" anchor merges (which
755 # do not have any upstream changes), to distinguish those
756 # anchor merges from ordinary pseudomerges (which we might
757 # just try to strip).
759 # However, the user is going to be doing git-rebase a lot. We
760 # really don't want them to rewrite an anchor commit.
761 # git-rebase trips up on merges, so that is a useful safety
764 # BreakwaterStart commits are also anchors in the terminology
765 # of git-debrebase(5), but they are untagged (and always
766 # manually generated).
768 # We cannot not tolerate any tagged linear commit (ie,
769 # BreakwaterStart commits tagged `[anchor:') because such a
770 # thing could result from an erroneous linearising raw git
771 # rebase of a merge anchor. That would represent a corruption
772 # of the branch. and we want to detect and reject the results
773 # of such corruption before it makes it out anywhere. If we
774 # reject it here then we avoid making the pseudomerge which
775 # would be needed to push it.
777 my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
778 @p == 2 or return $badanchor->("has other than two parents");
779 $haspatches and return $badanchor->("contains debian/patches");
781 # How to decide about l/r ordering of anchors ? git
782 # --topo-order prefers to expand 2nd parent first. There's
783 # already an easy rune to look for debian/ history anyway (git log
784 # debian/) so debian breakwater branch should be 1st parent; that
785 # way also there's also an easy rune to look for the upstream
786 # patches (--topo-order).
788 # Also this makes --first-parent be slightly more likely to
789 # be useful - it makes it provide a linearised breakwater history.
791 # Of course one can say somthing like
792 # gitk -- ':/' ':!/debian'
793 # to get _just_ the commits touching upstream files, and by
794 # the TREESAME logic in git-rev-list this will leave the
795 # breakwater into upstream at the first anchor. But that
796 # doesn't report debian/ changes at all.
798 # Other observations about gitk: by default, gitk seems to
799 # produce output in a different order to git-rev-list. I
800 # can't seem to find this documented anywhere. gitk
801 # --date-order DTRT. But, gitk always seems to put the
802 # parents from left to right, in order, so it's easy to see
803 # which way round a pseudomerge is.
805 $p[0]{IsOrigin} and $badanchor->("is an origin commit");
806 $p[1]{Differs} & ~DS_DEB and
807 $badanchor->("upstream files differ from left parent");
808 $p[0]{Differs} & ~D_UPS and
809 $badanchor->("debian/ differs from right parent");
811 return $classify->(qw(Anchor),
812 OrigParents => [ $p[1] ]);
816 my $d = $r->{Parents}[0]{Differs};
817 if ($d == D_PAT_ADD) {
818 return $classify->(qw(AddPatches));
819 } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
820 return $unknown->("edits debian/patches");
821 } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
822 my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
824 if ($d == D_DEB_CLOG) {
825 return $classify->(qw(Changelog));
827 return $classify->(qw(Packaging));
829 } elsif ($ty eq 'missing') {
830 return $classify->(qw(BreakwaterStart));
832 return $unknown->("parent's debian is not a directory");
834 } elsif ($d == D_UPS) {
835 return $classify->(qw(Upstream));
836 } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
837 return $classify->(qw(Mixed));
839 return $unknown->("no changes");
841 confess "internal error $objid ?";
845 return $unknown->("origin commit");
848 if (@p == 2 && @identical == 1) {
849 my @overwritten = grep { $_->{Differs} } @p;
850 confess "internal error $objid ?" unless @overwritten==1;
851 return $classify->(qw(Pseudomerge),
852 Overwritten => [ $overwritten[0] ],
853 Contributor => $identical[0]);
855 if (@p == 2 && @identical == 2) {
857 my ($ph,$pm) = get_commit $_[0]{CommitId};
858 $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
862 my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
863 if ($order > 0) { # newer first
864 } elsif ($order < 0) {
865 @bytime = reverse @bytime;
867 # same age, default to order made by -s ours
868 # that is, commit was made by someone who preferred L
870 return $classify->(qw(Pseudomerge),
871 SubType => qw(Ambiguous),
872 Contributor => $bytime[0],
873 Overwritten => [ $bytime[1] ]);
876 my ($p_h, $p_m) = get_commit $p->{CommitId};
877 $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
878 ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
880 my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
882 if (!(grep { !$_->{IsOrigin} } @p) and
883 (@orig_ps >= @p - 1) and
884 $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
886 return $classify->(qw(DgitImportUnpatched),
887 OrigParents => \@orig_ps);
891 $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
892 # xxx ^ metadata tag needs adding to (5)
893 return $classify->("MergedBreakwaters");
895 if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
896 return $unknown->("unknown kind of merge from $1");
899 return $unknown->("octopus merge");
902 if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
903 return $unknown->("general two-parent merge");
906 return $classify->("VanillaMerge");
909 sub keycommits ($;$$$$$);
911 sub mergedbreakwaters_anchor ($) {
914 foreach my $p (@{ $cl->{Parents} }) {
915 my ($panchor, $pbw) = keycommits $p->{CommitId},
916 undef,undef,undef,undef, 1;
917 $best_anchor = $panchor
918 if !defined $best_anchor
919 or is_fast_fwd $best_anchor, $panchor;
920 fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
921 unless is_fast_fwd $panchor, $best_anchor;
926 sub keycommits ($;$$$$$) {
927 my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
928 # => ($anchor, $breakwater)
930 # $unclean->("unclean-$tagsfx", $msg, $cl)
931 # $furniture->("unclean-$tagsfx", $msg, $cl)
932 # $dgitimport->("unclean-$tagsfx", $msg, $cl))
933 # is callled for each situation or commit that
934 # wouldn't be found in a laundered branch
935 # $furniture is for furniture commits such as might be found on an
936 # interchange branch (pseudomerge, d/patches, changelog)
937 # $trouble is for things whnich prevent the return of
938 # anchor and breakwater information; if that is ignored,
939 # then keycommits returns (undef, undef) instead.
940 # $fatal is for unprocessable commits, and should normally cause
941 # a failure. If ignored, agaion, (undef, undef) is returned.
943 # If $claimed_bw, this is supposed to be a breakwater commit.
945 # If a callback is undef, fail is called instead.
946 # If a callback is defined but false, the situation is ignored.
948 # no warnings qw(exiting); last;
949 # if the answer is no longer wanted.
951 my ($anchor, $breakwater);
952 $breakwater = $head if $claimed_bw;
956 $fatal //= sub { fail $_[1]; };
958 my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
959 my $why = $mainwhy.$xwhy;
960 my $m = "branch needs laundering (run git-debrebase): $why";
961 fail $m unless defined $cb;
963 $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
965 my $found_anchor = sub {
967 $breakwater //= $clogonly;
968 $breakwater //= $head;
969 no warnings qw(exiting);
973 $cl = classify $head;
974 my $ty = $cl->{Type};
975 if ($ty eq 'Packaging') {
976 $breakwater //= $clogonly;
977 $breakwater //= $head;
978 } elsif ($ty eq 'Changelog') {
979 # this is going to count as the tip of the breakwater
980 # only if it has no upstream stuff before it
982 } elsif ($ty eq 'Anchor' or
983 $ty eq 'TreatAsAnchor' or
984 $ty eq 'BreakwaterStart') {
985 $found_anchor->($head);
986 } elsif ($ty eq 'Upstream') {
987 $x->($unclean, 'ordering',
988 "packaging change ($breakwater) follows upstream change"," (eg $head)")
989 if defined $breakwater;
992 } elsif ($ty eq 'Mixed') {
993 $x->($unclean, 'mixed',
994 "found mixed upstream/packaging commit"," ($head)");
997 } elsif ($ty eq 'Pseudomerge' or
998 $ty eq 'AddPatches') {
1000 $x->($furniture, (lc $ty),
1001 "found interchange bureaucracy commit ($ty)"," ($head)");
1002 } elsif ($ty eq 'DgitImportUnpatched') {
1004 $x->($trouble, 'dgitimport',
1005 "found dgit dsc import"," ($head)");
1006 return (undef,undef);
1008 $x->($fatal, 'unprocessable',
1009 "found bare dgit dsc import with no prior history",
1011 return (undef,undef);
1013 } elsif ($ty eq 'VanillaMerge') {
1014 $x->($trouble, 'vanillamerge',
1015 "found vanilla merge"," ($head)");
1016 return (undef,undef);
1017 } elsif ($ty eq 'MergedBreakwaters') {
1018 $found_anchor->(mergedbreakwaters_anchor $cl);
1020 $x->($fatal, 'unprocessable',
1021 "found unprocessable commit, cannot cope: $cl->{Why}",
1023 return (undef,undef);
1025 $head = $cl->{Parents}[0]{CommitId};
1027 return ($anchor, $breakwater);
1033 $nogenerate,$report, $report_lprefix) = @_;
1034 # => ($tip, $breakwater_tip, $last_anchor)
1035 # (or nothing, if $nogenerate)
1037 printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1038 $report_lprefix //= '';
1040 # go through commits backwards
1041 # we generate two lists of commits to apply:
1042 # breakwater branch and upstream patches
1043 my (@brw_cl, @upp_cl, @processed);
1050 my ($prose, $info) = @_;
1051 my $ms = $cl->{Msg};
1054 $ms .= "\n\n[git-debrebase$info: $prose]\n";
1055 return (Msg => $ms);
1057 my $rewrite_from_here = sub {
1059 my $sp_cl = { SpecialMethod => 'StartRewrite' };
1061 push @processed, $sp_cl;
1066 my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1069 return unless $report;
1070 print $report $prdelim, $report_lprefix, @_;
1074 my $bomb = sub { # usage: return $bomb->();
1075 print $report " Unprocessable" if $report;
1076 print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1079 return (undef,undef);
1081 fail "found unprocessable commit, cannot cope".
1082 (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1083 " (commit $cur) (d.".
1084 (join ' ', map { sprintf "%#x", $_->{Differs} }
1085 @{ $cl->{Parents} }).
1092 my $build_start = sub {
1093 my ($msg, $parent) = @_;
1096 no warnings qw(exiting); last;
1101 merge_failed $cl->{MergeWreckNotes}, $emsg;
1104 my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1109 $cl = classify $cur;
1110 $cl->{MergeWreckNotes} //= {};
1111 my $ty = $cl->{Type};
1112 my $st = $cl->{SubType};
1113 $prline->("$cl->{CommitId} $cl->{Type}");
1114 $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1115 push @processed, $cl;
1116 my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1117 if ($ty eq 'AddPatches') {
1119 $rewrite_from_here->(\@upp_cl);
1121 } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1125 } elsif ($ty eq 'BreakwaterStart') {
1126 $last_anchor = $cur;
1127 $build_start->('FirstPackaging', $cur);
1128 } elsif ($ty eq 'Upstream') {
1132 } elsif ($ty eq 'Mixed') {
1135 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1138 $queue->(\@brw_cl, "debian");
1139 $queue->(\@upp_cl, "upstream");
1140 $rewrite_from_here->(\@brw_cl);
1143 } elsif ($ty eq 'Pseudomerge') {
1144 my $contrib = $cl->{Contributor}{CommitId};
1145 print $report " Contributor=$contrib" if $report;
1146 push @pseudomerges, $cl;
1147 $rewrite_from_here->(\@upp_cl);
1150 } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1151 $last_anchor = $cur;
1152 $build_start->("Anchor", $cur);
1153 } elsif ($ty eq 'DgitImportUnpatched') {
1154 my $pm = $pseudomerges[-1];
1156 # To an extent, this is heuristic. Imports don't have
1157 # a useful history of the debian/ branch. We assume
1158 # that the first pseudomerge after an import has a
1159 # useful history of debian/, and ignore the histories
1160 # from later pseudomerges. Often the first pseudomerge
1161 # will be the dgit import of the upload to the actual
1162 # suite intended by the non-dgit NMUer, and later
1163 # pseudomerges may represent in-archive copies.
1164 my $ovwrs = $pm->{Overwritten};
1165 printf $report " PM=%s \@Overwr:%d",
1166 $pm->{CommitId}, (scalar @$ovwrs)
1169 printdebug "*** WALK BOMB DgitImportUnpatched\n";
1172 my $ovwr = $ovwrs->[0]{CommitId};
1173 printf $report " Overwr=%s", $ovwr if $report;
1174 # This import has a tree which is just like a
1175 # breakwater tree, but it has the wrong history. It
1176 # ought to have the previous breakwater (which the
1177 # pseudomerge overwrote) as an ancestor. That will
1178 # make the history of the debian/ files correct. As
1179 # for the upstream version: either it's the same as
1180 # was ovewritten (ie, same as the previous
1181 # breakwater), in which case that history is precisely
1182 # right; or, otherwise, it was a non-gitish upload of a
1183 # new upstream version. We can tell these apart by
1184 # looking at the tree of the supposed upstream.
1187 SpecialMethod => 'DgitImportDebianUpdate',
1188 $xmsg->("convert dgit import: debian changes")
1191 SpecialMethod => 'DgitImportUpstreamUpdate',
1192 $xmsg->("convert dgit import: upstream update",
1195 $prline->(" Import");
1196 $rewrite_from_here->(\@brw_cl);
1197 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1201 # Everything is from this import. This kind of import
1202 # is already nearly in valid breakwater format, with the
1203 # patches as commits. Unfortunately it contains
1205 printdebug "*** WALK BOMB bare dgit import\n";
1206 $cl->{Why} = "bare dgit dsc import";
1210 } elsif ($ty eq 'MergedBreakwaters') {
1211 $last_anchor = mergedbreakwaters_anchor $cl;
1212 $build_start->(' MergedBreakwaters', $cur);
1214 } elsif ($ty eq 'VanillaMerge') {
1215 # User may have merged unstitched branch(es). We will
1216 # have now lost what ffq-prev was then (since the later
1217 # pseudomerge may introduce further changes). The effect
1218 # of resolving such a merge is that we may have to go back
1219 # further in history to find a merge base, since the one
1220 # which was reachable via ffq-prev is no longer findable.
1221 # This is suboptimal, but if it all works we'll have done
1223 # xxx we should warn the user in the docs about this
1227 # We expect to find a dominating anchor amongst the
1228 # inputs' anchors. That will be the new anchor.
1230 # More complicated is finding a merge base for the
1231 # breakwaters. We need a merge base that is a breakwater
1232 # commit. The ancestors of breakwater commits are more
1233 # breakwater commits and possibly upstream commits and the
1234 # ancestors of those upstream. Upstreams might have
1235 # arbitrary ancestors. But any upstream commit U is
1236 # either included in both anchors, in which case the
1237 # earlier anchor is a better merge base than any of U's
1238 # ancestors; or U is not included in the older anchor, in
1239 # which case U is not an ancestor of the vanilla merge at
1240 # all. So no upstream commit, nor any ancestor thereof,
1241 # is a best merge base. As for non-breakwater Debian
1242 # commits: these are never ancestors of any breakwater.
1244 # So any best merge base as found by git-merge-base
1245 # is a suitable breakwater anchor. Usually there will
1248 printdebug "*** MERGE\n";
1250 my @bwbcmd = (@git, qw(merge-base));
1251 my @ibcmd = (@git, qw(merge-base --all));
1252 my $might_be_in_bw = 1;
1254 my $ps = $cl->{Parents};
1256 $mwrecknote->('vanilla-merge', $cl->{CommitId});
1258 foreach my $p (@$ps) {
1259 $prline->(" VanillaMerge ".$p->{Ix});
1261 my ($ptip, $pbw, $panchor) =
1262 walk $p->{CommitId}, 0, $report,
1263 $report_lprefix.' ';
1264 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1265 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1266 $p->{Anchor} = $panchor;
1268 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1269 $mwrecknote->("$lr-input", $p->{CommitId});
1271 my $mwrecknote_parent = sub {
1273 $mwrecknote->("$lr-".(lc $which), $p->{$which});
1275 $mwrecknote_parent->('Laundered');
1276 $mwrecknote_parent->('Breakwater');
1277 $mwrecknote_parent->('Anchor');
1279 $best_anchor = $panchor if
1280 !defined $best_anchor or
1281 is_fast_fwd $best_anchor, $panchor;
1283 printdebug " MERGE BA best=".($best_anchor//'-').
1287 $mwrecknote->('result-anchor', $best_anchor);
1289 foreach my $p (@$ps) {
1290 $prline->(" VanillaMerge ".$p->{Ix});
1291 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1292 $nomerge->('divergent anchors');
1293 } elsif ($p->{Anchor} eq $best_anchor) {
1294 print $report " SameAnchor" if $report;
1296 print $report " SupersededAnchor" if $report;
1298 if ($p->{Breakwater} eq $p->{CommitId}) {
1299 # this parent commit was its own breakwater,
1300 # ie it is part of the breakwater
1301 print $report " Breakwater" if $report;
1303 $might_be_in_bw = 0;
1305 push @bwbcmd, $p->{Breakwater};
1306 push @ibcmd, $p->{CommitId};
1309 if ($ok && $might_be_in_bw) {
1310 # We could rewrite this to contaion the metadata
1311 # declaring it to be MergedBreakwaters, but
1312 # unnecessarily rewriting a merge seems unhelpful.
1313 $prline->(" VanillaMerge MergedBreakwaters");
1314 $last_anchor = $best_anchor;
1315 $build_start->('MergedBreakwaters', $cur);
1318 my $bwb = cmdoutput @bwbcmd;
1320 # OK, now we have a breakwater base, but we need the merge
1321 # base for the interchange branch because we need the delta
1324 # This a the best merge base of our inputs which has the
1325 # breakwater merge base as an ancestor.
1332 @ibs or confess 'internal error, expected anchor at least ?';
1336 foreach my $tibix (0..$#ibs) {
1337 my $tib = $ibs[$tibix];
1338 my $ff = is_fast_fwd $bwb, $tib;
1339 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1340 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1341 $mwrecknote->($tibleaf, $tib);
1348 $ib or $nomerge->("no suitable interchange merge base");
1350 $prline->(" VanillaMerge Base");
1352 my ($btip, $bbw, $banchor) = eval {
1353 walk $ib, 0, $report, $report_lprefix.' ';
1355 $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1359 $mwrecknote->("mergebase-laundered", $btip);
1360 $mwrecknote->("mergebase-breakwater", $bbw);
1361 $mwrecknote->("mergebase-anchor", $banchor);
1363 my $ibinfo = { SeriesTip => $btip,
1366 LeftRight => 'mergebase' };
1369 or $nomerge->("interchange merge-base ($ib)'s".
1370 " breakwater ($bbw)".
1371 " != breakwaters' merge-base ($bwb)");
1373 grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1374 or $nomerge->("interchange merge-base ($ib)'s".
1375 " anchor ($ibinfo->{SeriesBase})".
1376 " != any merge input's anchor (".
1377 (join ' ', map { $_->{Anchor} } @$ps).
1380 $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1381 $cl->{MergeBestAnchor} = $best_anchor;
1384 SpecialMethod => 'MergeCreateMergedBreakwaters',
1385 $xmsg->('constructed from vanilla merge',
1386 ' merged-breakwater'),
1390 SpecialMethod => 'MergeMergeSeries',
1392 $build_start->('MergeBreakwaters', $cur);
1394 printdebug "*** WALK BOMB unrecognised\n";
1400 printdebug "*** WALK prep done cur=$cur".
1401 " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1403 return if $nogenerate;
1405 # Now we build it back up again
1411 my $read_tree_upstream = sub {
1413 read_tree_upstream $treeish, 0, $build;
1416 $#upp_cl = $upp_limit if defined $upp_limit;
1418 my $committer_authline = calculate_committer_authline();
1420 printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1422 confess "internal error" unless $build eq (pop @processed)->{CommitId};
1425 mkdir $rd or $!==EEXIST or die $!;
1427 runcmd @git, qw(read-tree), $build;
1428 foreach my $cl (qw(Debian), (reverse @brw_cl),
1429 { SpecialMethod => 'RecordBreakwaterTip' },
1430 qw(Upstream), (reverse @upp_cl)) {
1432 $current_method = $cl;
1435 my $method = $cl->{SpecialMethod} // $current_method;
1436 my @parents = ($build);
1437 my $cltree = $cl->{CommitId};
1438 printdebug "WALK BUILD ".($cltree//'undef').
1439 " $method (rewriting=$rewriting)\n";
1440 if ($method eq 'Debian') {
1441 read_tree_debian($cltree);
1442 } elsif ($method eq 'Upstream') {
1443 $read_tree_upstream->($cltree);
1444 } elsif ($method eq 'StartRewrite') {
1447 } elsif ($method eq 'RecordBreakwaterTip') {
1448 $breakwater = $build;
1450 } elsif ($method eq 'DgitImportDebianUpdate') {
1451 read_tree_debian($cltree);
1452 } elsif ($method eq 'DgitImportUpstreamUpdate') {
1453 confess unless $rewriting;
1454 my $differs = (get_differs $build, $cltree);
1455 next unless $differs & D_UPS;
1456 $read_tree_upstream->($cltree);
1457 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1458 } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1459 print "Found a general merge, will try to tidy it up.\n";
1461 $read_tree_upstream->($cl->{MergeBestAnchor});
1462 $read_tree_upstream->($cl->{MergeBestAnchor});
1463 read_tree_debian($cltree);
1464 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1465 } elsif ($method eq 'MergeMergeSeries') {
1466 print "Running merge resolution for $cl->{CommitId}...\n";
1467 $build = merge_series
1468 $build, $cl->{MergeWreckNotes},
1469 $cl->{MergeInterchangeBaseInfo},
1470 @{ $cl->{Parents} };
1471 $last_anchor = $cl->{MergeBestAnchor};
1473 # Check for mismerges:
1475 my ($against, $allow, $what) = @_;
1476 my $differs = get_differs $build, $against;
1478 "merge misresolved: %s are not the same (%s %s d.%#x)",
1479 $what, $against, $build, $differs)
1480 if $differs & ~($allow | D_PAT_ADD);
1483 # Breakwater changes which were in each side of the
1484 # merge will have been incorporated into the
1485 # MergeCreateMergedBreakwaters output. Because the
1486 # upstream series was rebased onto the new breakwater,
1487 # so should all of the packaging changes which were in
1489 $check->($input, D_UPS, 'debian files');
1491 # Upstream files are merge_series, which ought to
1492 # have been identical to the original merge.
1493 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1495 print "Merge resolution successful.\n";
1498 confess "$method ?";
1501 my $procd = (pop @processed) // 'UNDEF';
1502 if ($cl ne $procd) {
1504 printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1507 my $newtree = cmdoutput @git, qw(write-tree);
1508 my $ch = $cl->{Hdr};
1509 $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1510 $ch =~ s{^parent .*\n}{}mg;
1511 $ch =~ s{(?=^author)}{
1512 join '', map { "parent $_\n" } @parents
1513 }me or confess "$ch ?";
1515 $ch =~ s{^committer .*$}{$committer_authline}m
1518 my $cf = "$rd/m$rewriting";
1519 open CD, ">", $cf or die $!;
1520 print CD $ch, "\n", $cl->{Msg} or die $!;
1522 my @cmd = (@git, qw(hash-object));
1523 push @cmd, qw(-w) if $rewriting;
1524 push @cmd, qw(-t commit), $cf;
1525 my $newcommit = cmdoutput @cmd;
1526 confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1527 $build = $newcommit;
1528 if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1529 $last_anchor = $cur;
1534 my $final_check = get_differs $build, $input;
1535 die sprintf "internal error %#x %s %s", $final_check, $input, $build
1536 if $final_check & ~D_PAT_ADD;
1538 my @r = ($build, $breakwater, $last_anchor);
1539 printdebug "*** WALK RETURN @r\n";
1544 git_check_unmodified();
1545 return git_rev_parse qw(HEAD);
1548 sub update_head ($$$) {
1549 my ($old, $new, $mrest) = @_;
1550 push @deferred_updates, "update HEAD $new $old";
1551 run_deferred_updates $mrest;
1554 sub update_head_checkout ($$$) {
1555 my ($old, $new, $mrest) = @_;
1556 update_head $old, $new, $mrest;
1557 runcmd @git, qw(reset --hard);
1560 sub update_head_postlaunder ($$$) {
1561 my ($old, $tip, $reflogmsg) = @_;
1562 return if $tip eq $old;
1563 print "git-debrebase: laundered (head was $old)\n";
1564 update_head $old, $tip, $reflogmsg;
1565 # no tree changes except debian/patches
1566 runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1569 sub currently_rebasing() {
1570 foreach (qw(rebase-merge rebase-apply)) {
1571 return 1 if stat_exists "$maindir_gitdir/$_";
1576 sub bail_if_rebasing() {
1577 fail "you are in the middle of a git-rebase already"
1578 if currently_rebasing();
1581 sub do_launder_head ($) {
1582 my ($reflogmsg) = @_;
1583 my $old = get_head();
1585 my ($tip,$breakwater) = walk $old;
1587 update_head_postlaunder $old, $tip, $reflogmsg;
1588 return ($tip,$breakwater);
1591 sub cmd_launder_v0 () {
1592 badusage "no arguments to launder-v0 allowed" if @ARGV;
1593 my $old = get_head();
1594 my ($tip,$breakwater,$last_anchor) = walk $old;
1595 update_head_postlaunder $old, $tip, 'launder';
1596 printf "# breakwater tip\n%s\n", $breakwater;
1597 printf "# working tip\n%s\n", $tip;
1598 printf "# last anchor\n%s\n", $last_anchor;
1601 sub defaultcmd_rebase () {
1602 push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1603 my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1604 runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1607 sub cmd_analyse () {
1608 badusage "analyse does not support any options"
1609 if @ARGV and $ARGV[0] =~ m/^-/;
1610 badusage "too many arguments to analyse" if @ARGV>1;
1613 $old = git_rev_parse $old;
1615 $old = git_rev_parse 'HEAD';
1617 my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1618 STDOUT->error and die $!;
1621 sub ffq_prev_branchinfo () {
1622 my $current = git_get_symref();
1623 return gdr_ffq_prev_branchinfo($current);
1626 sub ffq_check ($;$$) {
1627 # calls $ff and/or $notff zero or more times
1628 # then returns either (status,message) where status is
1633 # or (undef,undef, $ffq_prev,$gdrlast)
1634 # $ff and $notff are called like this:
1635 # $ff->("message for stdout\n");
1636 # $notff->('snag-name', $message);
1637 # normally $currentval should be HEAD
1638 my ($currentval, $ff, $notff) =@_;
1640 $ff //= sub { print $_[0] or die $!; };
1643 my ($status, $message, $current, $ffq_prev, $gdrlast)
1644 = ffq_prev_branchinfo();
1645 return ($status, $message) unless $status eq 'branch';
1647 my $exists = git_get_ref $ffq_prev;
1648 return ('exists',"$ffq_prev already exists") if $exists;
1650 return ('not-branch', 'HEAD symref is not to refs/heads/')
1651 unless $current =~ m{^refs/heads/};
1654 my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1657 printdebug "ffq check_specs @check_specs\n";
1660 my ($lrref, $desc) = @_;
1661 printdebug "ffq might check $lrref ($desc)\n";
1663 for my $chk (@check_specs) {
1665 $invert = $glob =~ s{^[!^]}{};
1666 last if fnmatch $glob, $lrref;
1669 my $lrval = git_get_ref $lrref;
1670 return unless length $lrval;
1672 if (is_fast_fwd $lrval, $currentval) {
1673 $ff->("OK, you are ahead of $lrref\n");
1674 $checked{$lrref} = 1;
1675 } elsif (is_fast_fwd $currentval, $lrval) {
1676 $checked{$lrref} = -1;
1677 $notff->('behind', "you are behind $lrref, divergence risk");
1679 $checked{$lrref} = -1;
1680 $notff->('diverged', "you have diverged from $lrref");
1684 my $merge = cfg "branch.$branch.merge",1;
1685 if (defined $merge and $merge =~ m{^refs/heads/}) {
1687 printdebug "ffq merge $rhs\n";
1688 my $check_remote = sub {
1689 my ($remote, $desc) = @_;
1690 printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1691 return unless defined $remote;
1692 $check->("refs/remotes/$remote/$rhs", $desc);
1694 $check_remote->((scalar cfg "branch.$branch.remote",1),
1695 'remote fetch/merge branch');
1696 $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1697 (scalar cfg "branch.$branch.pushDefault",1),
1698 'remote push branch');
1700 if ($branch =~ m{^dgit/}) {
1701 $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1702 } elsif ($branch =~ m{^master$}) {
1703 $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1705 return (undef, undef, $ffq_prev, $gdrlast);
1708 sub record_ffq_prev_deferred () {
1709 # => ('status', "message")
1711 # deferred message is undef
1716 # if not ff from some branch we should be ff from, is an snag
1717 # if "deferred", will have added something about that to
1718 # @deferred_update_messages, and also maybe printed (already)
1719 # some messages about ff checks
1721 my $currentval = get_head();
1723 my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1724 return ($status,$message) if defined $status;
1728 push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1729 push @deferred_updates, "delete $gdrlast";
1730 push @deferred_update_messages, "Recorded previous head for preservation";
1731 return ('deferred', undef);
1734 sub record_ffq_auto () {
1735 my ($status, $message) = record_ffq_prev_deferred();
1736 if ($status eq 'deferred' || $status eq 'exists') {
1738 snag $status, "could not record ffq-prev: $message";
1743 sub ffq_prev_info () {
1745 # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1746 my ($status, $message, $current, $ffq_prev, $gdrlast)
1747 = ffq_prev_branchinfo();
1748 if ($status ne 'branch') {
1749 snag $status, "could not check ffq-prev: $message";
1752 my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1753 return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1756 sub stitch ($$$$$) {
1757 my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1759 push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1761 if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1762 my $differs = get_differs $old_head, $ffq_prev_commitish;
1763 unless ($differs & ~D_PAT_ADD) {
1764 # ffq-prev is ahead of us, and the only tree changes it has
1765 # are possibly addition of things in debian/patches/.
1766 # Just wind forwards rather than making a pointless pseudomerge.
1767 push @deferred_updates,
1768 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1769 update_head_checkout $old_head, $ffq_prev_commitish,
1770 "stitch (fast forward)";
1775 # We make pseudomerges with L as the contributing parent.
1776 # This makes git rev-list --first-parent work properly.
1777 my $new_head = make_commit [ $old_head, $ffq_prev ], [
1778 'Declare fast forward / record previous work',
1779 "[git-debrebase pseudomerge: $prose]",
1781 push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1782 update_head $old_head, $new_head, "stitch: $prose";
1785 sub do_stitch ($;$) {
1786 my ($prose, $unclean) = @_;
1788 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1789 if (!$ffq_prev_commitish) {
1790 fail "No ffq-prev to stitch." unless $opt_noop_ok;
1793 my $dangling_head = get_head();
1795 keycommits $dangling_head, $unclean,$unclean,$unclean;
1798 stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1801 sub upstream_commitish_search ($$) {
1802 my ($upstream_version, $tried) = @_;
1803 # todo: at some point maybe use git-deborig to do this
1804 foreach my $tagpfx ('', 'v', 'upstream/') {
1805 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1806 my $new_upstream = git_get_ref "refs/tags/$tag";
1808 return $new_upstream if length $new_upstream;
1812 sub resolve_upstream_version ($$) {
1813 my ($new_upstream, $upstream_version) = @_;
1815 if (!defined $new_upstream) {
1817 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1818 if (!length $new_upstream) {
1819 fail "Could not determine appropriate upstream commitish.\n".
1820 " (Tried these tags: @tried)\n".
1821 " Check version, and specify upstream commitish explicitly.";
1824 $new_upstream = git_rev_parse $new_upstream;
1826 return $new_upstream;
1829 sub cmd_new_upstream () {
1830 # automatically and unconditionally launders before rebasing
1831 # if rebase --abort is used, laundering has still been done
1835 badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1837 # parse args - low commitment
1838 my $spec_version = shift @ARGV;
1839 my $new_version = (new Dpkg::Version $spec_version, check => 1);
1840 fail "bad version number \`$spec_version'" unless defined $new_version;
1841 if ($new_version->is_native()) {
1842 $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1845 my $new_upstream = shift @ARGV;
1846 my $new_upstream_version = upstreamversion $new_version;
1848 resolve_upstream_version $new_upstream, $new_upstream_version;
1853 my ($n, @x) = @_; # may be ''
1854 my $pc = $pieces{$n} //= {
1856 Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1858 while (my $k = shift @x) { $pc->{$k} = shift @x; }
1863 my $newpiece = sub {
1864 my ($n, @x) = @_; # may be ''
1865 my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1866 push @newpieces, $pc;
1871 New => $new_upstream,
1873 while (@ARGV && $ARGV[0] !~ m{^-}) {
1874 my $n = shift @ARGV;
1876 badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1877 unless @ARGV && $ARGV[0] !~ m{^-};
1879 my $c = git_rev_parse shift @ARGV;
1880 die unless $n =~ m/^$extra_orig_namepart_re$/;
1881 $newpiece->($n, New => $c);
1884 # now we need to investigate the branch this generates the
1885 # laundered version but we don't switch to it yet
1886 my $old_head = get_head();
1887 my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1889 my $old_bw_cl = classify $old_bw;
1890 my $old_anchor_cl = classify $old_anchor;
1892 if (!$old_anchor_cl->{OrigParents}) {
1893 snag 'anchor-treated',
1894 'old anchor is recognised due to --anchor, cannot check upstream';
1896 $old_upstream = parsecommit
1897 $old_anchor_cl->{OrigParents}[0]{CommitId};
1898 $piece->('', Old => $old_upstream->{CommitId});
1901 if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1902 if ($old_upstream->{Msg} =~
1903 m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1905 my @oldpieces = (split / /, $1);
1906 my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1907 if ($old_n_parents != @oldpieces &&
1908 $old_n_parents != @oldpieces + 1) {
1909 snag 'upstream-confusing', sprintf
1910 "previous upstream combine %s".
1911 " mentions %d pieces (each implying one parent)".
1912 " but has %d parents".
1913 " (one per piece plus maybe a previous combine)",
1914 $old_upstream->{CommitId},
1915 (scalar @oldpieces),
1917 } elsif ($oldpieces[0] ne '.') {
1918 snag 'upstream-confusing', sprintf
1919 "previous upstream combine %s".
1920 " first piece is not \`.'",
1924 foreach my $i (0..$#oldpieces) {
1925 my $n = $oldpieces[$i];
1926 my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1927 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1931 snag 'upstream-confusing',
1932 "previous upstream $old_upstream->{CommitId} is from".
1933 " git-debrebase but not an \`upstream-combine' commit";
1937 foreach my $pc (values %pieces) {
1938 if (!$old_upstream) {
1939 # we have complained already
1940 } elsif (!$pc->{Old}) {
1941 snag 'upstream-new-piece',
1942 "introducing upstream piece \`$pc->{Name}'";
1943 } elsif (!$pc->{New}) {
1944 snag 'upstream-rm-piece',
1945 "dropping upstream piece \`$pc->{Name}'";
1946 } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1947 snag 'upstream-not-ff',
1948 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1952 printdebug "%pieces = ", (dd \%pieces), "\n";
1953 printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1961 my @upstream_merge_parents;
1964 push @upstream_merge_parents, $old_upstream->{CommitId};
1967 foreach my $pc (@newpieces) { # always has '' first
1969 read_tree_subdir $pc->{Name}, $pc->{New};
1971 runcmd @git, qw(read-tree), $pc->{New};
1973 push @upstream_merge_parents, $pc->{New};
1976 # index now contains the new upstream
1978 if (@newpieces > 1) {
1979 # need to make the upstream subtree merge commit
1980 $new_upstream = make_commit \@upstream_merge_parents,
1981 [ "Combine upstreams for $new_upstream_version",
1982 ("[git-debrebase upstream-combine . ".
1983 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1988 # $new_upstream is either the single upstream commit, or the
1989 # combined commit we just made. Either way it will be the
1990 # "upstream" parent of the anchor merge.
1992 read_tree_subdir 'debian', "$old_bw:debian";
1994 # index now contains the anchor merge contents
1995 $new_bw = make_commit [ $old_bw, $new_upstream ],
1996 [ "Update to upstream $new_upstream_version",
1997 "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2000 my $clogsignoff = cmdoutput qw(git show),
2001 '--pretty=format:%an <%ae> %aD',
2004 # Now we have to add a changelog stanza so the Debian version
2006 die if unlink "debian";
2007 die $! unless $!==ENOENT or $!==ENOTEMPTY;
2008 unlink "debian/changelog" or $!==ENOENT or die $!;
2009 mkdir "debian" or die $!;
2010 open CN, ">", "debian/changelog" or die $!;
2011 my $oldclog = git_cat_file ":debian/changelog";
2012 $oldclog =~ m/^($package_re) \(\S+\) / or
2013 fail "cannot parse old changelog to get package name";
2015 print CN <<END, $oldclog or die $!;
2016 $p ($new_version) UNRELEASED; urgency=medium
2018 * Update to new upstream version $new_upstream_version.
2024 runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2026 # Now we have the final new breakwater branch in the index
2027 $new_bw = make_commit [ $new_bw ],
2028 [ "Update changelog for new upstream $new_upstream_version",
2029 "[git-debrebase: new upstream $new_upstream_version, changelog]",
2033 # we have constructed the new breakwater. we now need to commit to
2034 # the laundering output, because git-rebase can't easily be made
2035 # to make a replay list which is based on some other branch
2037 update_head_postlaunder $old_head, $old_laundered_tip,
2038 'launder for new upstream';
2040 my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2041 local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2042 "debrebase new-upstream $new_version: rebase";
2044 # now it's for the user to sort out
2047 sub cmd_record_ffq_prev () {
2048 badusage "no arguments allowed" if @ARGV;
2049 my ($status, $msg) = record_ffq_prev_deferred();
2050 if ($status eq 'exists' && $opt_noop_ok) {
2051 print "Previous head already recorded\n" or die $!;
2052 } elsif ($status eq 'deferred') {
2053 run_deferred_updates 'record-ffq-prev';
2055 fail "Could not preserve: $msg";
2060 badusage "no arguments allowed" if @ARGV;
2061 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2062 print "$bw\n" or die $!;
2065 sub cmd_breakwater () {
2066 badusage "no arguments allowed" if @ARGV;
2067 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2068 print "$bw\n" or die $!;
2072 badusage "no arguments allowed" if @ARGV;
2074 # todo: gdr status should print divergence info
2075 # todo: gdr status should print upstream component(s) info
2076 # todo: gdr should leave/maintain some refs with this kind of info ?
2078 my $oldest = { Badness => 0 };
2081 my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2082 if ($oldest->{Badness} < $badness) {
2083 $oldest = $newest = undef;
2086 Badness => $badness,
2087 CommitId => $cl->{CommitId},
2091 $newest //= $oldest;
2093 my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2094 sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2095 sub { $note->(2, 'branch is unlaundered', @_); },
2096 sub { $note->(3, 'branch needs laundering', @_); },
2097 sub { $note->(4, 'branch not in git-debrebase form', @_); };
2099 my $prcommitinfo = sub {
2101 flush STDOUT or die $!;
2102 runcmd @git, qw(--no-pager log -n1),
2103 '--pretty=format: %h %s%n',
2107 print "current branch contents, in git-debrebase terms:\n";
2108 if (!$oldest->{Badness}) {
2109 print " branch is laundered\n";
2111 print " $oldest->{OurMsg}\n";
2113 foreach my $info ($oldest, $newest) {
2114 my $cid = $info->{CommitId};
2115 next if $cid eq $printed;
2117 print " $info->{KcMsg}\n";
2118 $prcommitinfo->($cid);
2123 my ($cid, $what) = @_;
2124 if (!defined $cid) {
2125 print " $what is not well-defined\n";
2128 $prcommitinfo->($cid);
2131 print "key git-debrebase commits:\n";
2132 $prab->($anchor, 'anchor');
2133 $prab->($bw, 'breakwater');
2135 my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2136 ffq_prev_branchinfo();
2138 print "branch and ref status, in git-debrebase terms:\n";
2140 print " $ffq_msg\n";
2142 $ffq_prev = git_get_ref $ffq_prev;
2143 $gdrlast = git_get_ref $gdrlast;
2145 print " unstitched; previous tip was:\n";
2146 $prcommitinfo->($ffq_prev);
2147 } elsif (!$gdrlast) {
2148 print " stitched? (no record of git-debrebase work)\n";
2149 } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2150 print " stitched\n";
2152 print " not git-debrebase (diverged since last stitch)\n"
2155 print "you are currently rebasing\n" if currently_rebasing();
2159 my $prose = 'stitch';
2160 getoptions("stitch",
2161 'prose=s', \$prose);
2162 badusage "no arguments allowed" if @ARGV;
2163 do_stitch $prose, 0;
2165 sub cmd_prepush () { cmd_stitch(); }
2168 badusage "no arguments allowed" if @ARGV;
2169 do_launder_head 'launder for git-debrebase quick';
2173 sub cmd_conclude () {
2174 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2175 if (!$ffq_prev_commitish) {
2176 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2179 my $dangling_head = get_head();
2181 badusage "no arguments allowed" if @ARGV;
2182 do_launder_head 'launder for git-debrebase quick';
2187 if (currently_rebasing()) {
2188 runcmd @git, qw(rebase --abort);
2190 my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2191 if (!$ffq_prev_commitish) {
2192 fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2195 my $scrapping_head = get_head();
2196 badusage "no arguments allowed" if @ARGV;
2197 push @deferred_updates,
2198 "update $gdrlast $ffq_prev_commitish $git_null_obj",
2199 "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2201 update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2204 sub make_patches_staged ($) {
2206 # Produces the patches that would result from $head if it were
2208 my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2211 gbp_pq_export 'bw', $secret_bw, $secret_head;
2215 sub make_patches ($) {
2217 keycommits $head, 0, \&snag;
2218 make_patches_staged $head;
2221 my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2222 runcmd @git, qw(read-tree), $head;
2223 read_tree_subdir 'debian/patches', $ptree;
2224 $out = make_commit [$head], [
2225 'Commit patch queue (exported by git-debrebase)',
2226 '[git-debrebase: export and commit patches]',
2232 sub cmd_make_patches () {
2233 my $opt_quiet_would_amend;
2234 getoptions("make-patches",
2235 'quiet-would-amend!', \$opt_quiet_would_amend);
2236 badusage "no arguments allowed" if @ARGV;
2238 my $old_head = get_head();
2239 my $new = make_patches $old_head;
2240 my $d = get_differs $old_head, $new;
2242 fail "No (more) patches to export." unless $opt_noop_ok;
2244 } elsif ($d == D_PAT_ADD) {
2246 update_head_checkout $old_head, $new, 'make-patches';
2248 print STDERR failmsg
2249 "Patch export produced patch amendments".
2250 " (abandoned output commit $new).".
2251 " Try laundering first."
2252 unless $opt_quiet_would_amend;
2257 sub cmd_convert_from_gbp () {
2258 badusage "want only 1 optional argument, the upstream git commitish"
2261 my $clogp = parsechangelog();
2262 my $version = $clogp->{'Version'}
2263 // die "missing Version from changelog";
2265 my ($upstream_spec) = @ARGV;
2267 my $upstream_version = upstreamversion $version;
2269 resolve_upstream_version($upstream_spec, $upstream_version);
2271 my $old_head = get_head();
2273 my $upsdiff = get_differs $upstream, $old_head;
2274 if ($upsdiff & D_UPS) {
2275 runcmd @git, qw(--no-pager diff --stat),
2276 $upstream, $old_head,
2277 qw( -- :!/debian :/);
2279 upstream ($upstream_spec) and HEAD are not
2280 identical in upstream files. See diffstat above, or run
2281 git diff $upstream_spec HEAD -- :!/debian :/
2285 if (!is_fast_fwd $upstream, $old_head) {
2286 snag 'upstream-not-ancestor',
2287 "upstream ($upstream) is not an ancestor of HEAD";
2289 my $wrong = cmdoutput
2290 (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2291 qw(-- :/ :!/debian));
2292 if (length $wrong) {
2293 snag 'unexpected-upstream-changes',
2294 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2295 print STDERR "list expected changes with: git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2299 if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2300 snag 'upstream-has-debian',
2301 "upstream ($upstream) contains debian/ directory";
2304 my $previous_dgit_view = eval {
2305 my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2307 parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2308 my ($stz, $desc) = @_;
2309 no warnings qw(exiting);
2310 printdebug 'CHANGELOG ', Dumper($desc, $stz);
2311 next unless $stz->{Date};
2312 next unless $stz->{Distribution} ne 'UNRELEASED';
2313 $lvsn = $stz->{Version};
2314 $suite = $stz->{Distribution};
2317 die "neither of the first two changelog entries are released\n"
2318 unless defined $lvsn;
2319 print "last finished-looking changelog entry: ($lvsn) $suite\n";
2320 my $mtag_pat = debiantag_maintview $lvsn, '*';
2321 my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2323 die "could not find suitable maintainer view tag $mtag_pat\n"
2324 unless $mtag_pat =~ m{/};
2325 is_fast_fwd $mtag, 'HEAD' or
2326 die "HEAD is not FF from maintainer tag $mtag!";
2327 my $dtag = "archive/$mtag";
2328 is_fast_fwd $mtag, $dtag or
2329 die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2330 print "will stitch in dgit view, $dtag\n";
2331 git_rev_parse $dtag;
2333 if (!$previous_dgit_view) {
2336 print STDERR "cannot stitch in dgit view: $@\n";
2339 snags_maybe_bail_early();
2345 runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2346 # make a branch out of the patch queue - we'll want this in a mo
2347 runcmd qw(gbp pq import);
2348 # strip the patches out
2349 runcmd @git, qw(checkout -q gdr-internal~0);
2350 rm_subdir_cached 'debian/patches';
2351 $work = make_commit ['HEAD'], [
2352 'git-debrebase convert-from-gbp: drop patches from tree',
2353 'Delete debian/patches, as part of converting to git-debrebase format.',
2354 '[git-debrebase convert-from-gbp: drop patches from tree]'
2356 # make the anchor merge
2357 # the tree is already exactly right
2358 $work = make_commit [$work, $upstream], [
2359 'git-debrebase import: declare upstream',
2360 'First breakwater merge.',
2361 '[git-debrebase anchor: declare upstream]'
2364 # rebase the patch queue onto the new breakwater
2365 runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2366 runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2367 $work = git_rev_parse 'HEAD';
2369 if ($previous_dgit_view) {
2370 $work = make_commit [$work, $previous_dgit_view], [
2371 'git-debrebase import: declare ff from dgit archive view',
2372 '[git-debrebase pseudomerge: import-from-gbp]',
2379 update_head_checkout $old_head, $work, 'convert-from-gbp';
2382 sub cmd_convert_to_gbp () {
2383 badusage "no arguments allowed" if @ARGV;
2384 my $head = get_head();
2385 my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2386 keycommits $head, 0;
2388 make_patches_staged $head;
2390 $out = make_commit ['HEAD'], [
2391 'Commit patch queue (converted from git-debrebase format)',
2392 '[git-debrebase convert-to-gbp: commit patches]',
2396 push @deferred_updates, "delete $ffq";
2397 push @deferred_updates, "delete $gdrlast";
2400 update_head_checkout $head, $out, "convert to gbp (v0)";
2401 print <<END or die $!;
2402 git-debrebase: converted to git-buildpackage branch format
2403 git-debrebase: WARNING: do not now run "git-debrebase" any more
2404 git-debrebase: WARNING: doing so would drop all upstream patches!
2408 sub cmd_convert_from_dgit_view () {
2409 my $clogp = parsechangelog();
2411 my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2417 getoptions("convert-from-dgit-view",
2418 'diagnose!', \$diagnose,
2419 'build-products-dir:s', \$bpd,
2420 'origs!', \$do_origs,
2422 'always-convert-anyway!', \$always);
2423 fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2428 my $spec = shift @ARGV;
2429 my $commit = git_rev_parse "$spec^{commit}";
2430 push @upstreams, { Commit => $commit,
2431 Source => "$ARGV[0], from command line",
2436 my $head = get_head();
2440 my $trouble = sub { $troubles++; };
2441 keycommits $head, sub{}, sub{}, $trouble, $trouble;
2442 printdebug "troubles=$troubles\n";
2445 $us: Branch already seems to be in git-debrebase format!
2446 $us: --always-convert-anyway would do the conversion operation anyway
2447 $us: but is probably a bad idea. Probably, you wanted to do nothing.
2449 fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2454 snags_maybe_bail_early();
2456 my $version = upstreamversion $clogp->{Version};
2457 print STDERR "Considering possible commits corresponding to upstream:\n";
2462 my $ups_tag = upstream_commitish_search $version, \@tried;
2464 my $this = "git tag $tried[-1]";
2465 push @upstreams, { Commit => $ups_tag,
2470 " git tag: no suitable tag found (tried %s)\n",
2475 my $p = $clogp->{'Source'};
2476 # we do a quick check to see if there are plausible origs
2478 if (!opendir BPD, $bpd) {
2479 die "$bpd: opendir: $!" unless $!==ENOENT;
2481 while ($!=0, my $f = readdir BPD) {
2482 next unless is_orig_file_of_p_v $f, $p, $version;
2484 " orig: found what looks like a .orig, %s\n",
2489 die "read $bpd: $!" if $!;
2493 my $tree = cmdoutput
2494 @dgit, qw(--build-products-dir), $bpd,
2495 qw(print-unapplied-treeish);
2498 runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2499 rm_subdir_cached 'debian';
2500 $tree = cmdoutput @git, qw(write-tree);
2501 my $ups_synth = make_commit [], [ <<END, <<END,
2502 Import effective orig tree for upstream version $version
2504 This includes the contents of the .orig(s), minus any debian/ directory.
2506 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2509 push @upstreams, { Commit => $ups_synth,
2510 Source => "orig(s) imported via dgit",
2515 " orig: no suitable origs found (looked for %s in %s)\n",
2516 "${p}_".(stripeoch $version)."...", $bpd;
2521 my $some_patches = stat_exists 'debian/patches/series';
2523 print STDERR "Evaluating possible commits corresponding to upstream:\n";
2526 foreach my $u (@upstreams) {
2530 runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2531 runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2532 runcmd @git, qw(clean -xdff);
2533 runcmd @git, qw(checkout), $head, qw(-- debian);
2534 if ($some_patches) {
2535 rm_subdir_cached 'debian/patches';
2536 $work = make_commit [ $work ], [
2537 'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2538 "Drop upstream changes, and delete debian/patches, as part of converting\n".
2539 "to git-debrebase format. Upstream changes will appear as commits.",
2540 '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2543 $work = make_commit [ $work, $u->{Commit} ], [
2544 'git-debrebase convert-from-dgit-view: declare upstream',
2545 '(Re)constructed breakwater merge.',
2546 '[git-debrebase anchor: declare upstream]'
2548 runcmd @git, qw(checkout --quiet -b mk), $work;
2549 if ($some_patches) {
2550 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2551 runcmd @git, qw(reset --quiet);
2552 my @gbp_cmd = (qw(gbp pq import));
2554 my $gbp_err = "../gbp-pq-err";
2555 @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2557 my $r = system @gbp_cmd;
2560 " %s: couldn't apply patches: gbp pq %s",
2561 $u->{Source}, waitstatusmsg();
2565 my $work = git_rev_parse qw(HEAD);
2566 my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2567 if (length $diffout) {
2569 " $u->{Source}: applying patches gives different tree\n";
2570 print STDERR $diffout if $diagnose;
2574 $u->{Result} = $work;
2582 Could not find or construct a suitable upstream commit.
2583 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2584 upstream commmit explicitly or provide suitable origs.
2588 printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2590 ffq_check $result->{Result};
2592 update_head_checkout $head, $result->{Result},
2593 'convert-from-dgit-view';
2596 sub cmd_downstream_rebase_launder_v0 () {
2597 badusage "needs 1 argument, the baseline" unless @ARGV==1;
2599 $base = git_rev_parse $base;
2600 my $old_head = get_head();
2601 my $current = $old_head;
2604 if ($current eq $base) {
2605 $topmost_keep //= $current;
2606 print " $current BASE stop\n";
2609 my $cl = classify $current;
2610 print " $current $cl->{Type}";
2612 my $p0 = $cl->{Parents}[0]{CommitId};
2614 if ($cl->{Type} eq 'Pseudomerge') {
2615 print " ^".($cl->{Contributor}{Ix}+1);
2616 $next = $cl->{Contributor}{CommitId};
2617 } elsif ($cl->{Type} eq 'AddPatches' or
2618 $cl->{Type} eq 'Changelog') {
2628 $topmost_keep //= $current;
2630 die "to-be stripped changes not on top of the branch\n"
2635 if ($topmost_keep eq $old_head) {
2636 print "unchanged\n";
2638 print "updating to $topmost_keep\n";
2639 update_head_checkout
2640 $old_head, $topmost_keep,
2641 'downstream-rebase-launder-v0';
2647 "D+" => \$debuglevel,
2648 'noop-ok', => \$opt_noop_ok,
2649 'f=s' => \@snag_force_opts,
2650 'anchor=s' => \@opt_anchors,
2651 '--dgit=s' => \($dgit[0]),
2654 my ($opt,$val) = @_;
2655 badusage "git-debrebase: no cuddling to -i for git-rebase"
2657 die if $opt_defaultcmd_interactive; # should not happen
2658 $opt_defaultcmd_interactive = [ qw(-i) ];
2659 # This access to @ARGV is excessive familiarity with
2660 # Getopt::Long, but there isn't another sensible
2661 # approach. '-i=s{0,}' does not work with bundling.
2662 push @$opt_defaultcmd_interactive, @ARGV;
2665 'help' => sub { print $usage_message or die $!; finish 0; },
2668 initdebug('git-debrebase ');
2669 enabledebug if $debuglevel;
2671 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2672 chdir $toplevel or die "chdir $toplevel: $!";
2674 $rd = fresh_playground "$playprefix/misc";
2676 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2678 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2679 defaultcmd_rebase();
2681 my $cmd = shift @ARGV;
2684 $cmdfn = ${*::}{"cmd_$cmdfn"};
2686 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";