chiark / gitweb /
git-debrebase: merge: Miscellaneous mwrecknote fixes
[dgit.git] / git-debrebase
1 #!/usr/bin/perl -w
2 # git-debrebase
3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
5 #
6 # Copyright (C)2017,2018 Ian Jackson
7 #
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.
12 #
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.
17 #
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/>.
20
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::GDR;
23 use Debian::Dgit::ExitStatus;
24
25 use strict;
26
27 use Debian::Dgit qw(:DEFAULT :playground);
28 setup_sigwarn();
29
30 use Memoize;
31 use Carp;
32 use POSIX;
33 use Data::Dumper;
34 use Getopt::Long qw(:config posix_default gnu_compat bundling);
35 use Dpkg::Version;
36 use File::FnMatch qw(:fnmatch);
37 use File::Copy;
38
39 $debugcmd_when_debuglevel = 2;
40
41 our ($usage_message) = <<'END';
42 usages:
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>]
49   ...
50 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
51 END
52
53 our ($opt_force, $opt_noop_ok, @opt_anchors);
54 our ($opt_defaultcmd_interactive);
55
56 our $us = qw(git-debrebase);
57
58 $|=1;
59
60 sub badusage ($) {
61     my ($m) = @_;
62     print STDERR "$us: bad usage: $m\n";
63     finish 8;
64 }
65
66 sub getoptions_main {
67     my $m = shift;
68     local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
69     GetOptions @_ or badusage $m;
70 }
71 sub getoptions {
72     my $sc = shift;
73     getoptions_main "bad options follow \`git-debrebase $sc'", @_;
74 }
75
76 sub cfg ($;$) {
77     my ($k, $optional) = @_;
78     local $/ = "\0";
79     my @cmd = qw(git config -z);
80     push @cmd, qw(--get-all) if wantarray;
81     push @cmd, $k;
82     my $out = cmdoutput_errok @cmd;
83     if (!defined $out) {
84         fail "missing required git config $k" unless $optional;
85         return ();
86     }
87     my @l = split /\0/, $out;
88     return wantarray ? @l : $l[0];
89 }
90
91 memoize('cfg');
92
93 sub dd ($) {
94     my ($v) = @_;
95     my $dd = new Data::Dumper [ $v ];
96     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
97     return Dump $dd;
98 }
99
100 sub get_commit ($) {
101     my ($objid) = @_;
102     my $data = (git_cat_file $objid, 'commit');
103     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
104     return ($`,$');
105 }
106
107 sub D_UPS ()      { 0x02; } # upstream files
108 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
109 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
110 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
111 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
112 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
113
114 our $playprefix = 'debrebase';
115 our $rd;
116 our $workarea;
117
118 our @git = qw(git);
119 our @dgit = qw(dgit);
120
121 sub in_workarea ($) {
122     my ($sub) = @_;
123     changedir $workarea;
124     my $r = eval { $sub->(); };
125     { local $@; changedir $maindir; }
126     die $@ if $@;
127 }
128
129 sub fresh_workarea () {
130     $workarea = fresh_playground "$playprefix/work";
131     in_workarea sub { playtree_setup };
132 }
133
134 sub run_ref_updates_now ($$) {
135     my ($mrest, $updates) = @_;
136     # @$updates is a list of lines for git-update-ref, without \ns
137
138     my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
139     debugcmd '>|', @upd_cmd;
140     open U, "|-", @upd_cmd or die $!;
141     foreach (@$updates) {
142         printdebug ">= ", $_, "\n";
143         print U $_, "\n" or die $!;
144     }
145     printdebug ">\$\n";
146     close U or failedcmd @upd_cmd;
147 }
148
149 our $snags_forced = 0;
150 our $snags_tripped = 0;
151 our $snags_summarised = 0;
152 our @deferred_updates;
153 our @deferred_update_messages;
154
155 sub all_snags_summarised () {
156     $snags_forced + $snags_tripped == $snags_summarised;
157 }
158 sub run_deferred_updates ($) {
159     my ($mrest) = @_;
160
161     confess 'dangerous internal error' unless all_snags_summarised();
162
163     run_ref_updates_now $mrest, \@deferred_updates;
164     print $_, "\n" foreach @deferred_update_messages;
165
166     @deferred_updates = ();
167     @deferred_update_messages = ();
168 }
169
170 sub get_differs ($$) {
171     my ($x,$y) = @_;
172     # This resembles quiltify_trees_differ, in dgit, a bit.
173     # But we don't care about modes, or dpkg-source-unrepresentable
174     # changes, and we don't need the plethora of different modes.
175     # Conversely we need to distinguish different kinds of changes to
176     # debian/ and debian/patches/.
177
178     my $differs = 0;
179
180     my $rundiff = sub {
181         my ($opts, $limits, $fn) = @_;
182         my @cmd = (@git, qw(diff-tree -z --no-renames));
183         push @cmd, @$opts;
184         push @cmd, "$_:" foreach $x, $y;
185         push @cmd, '--', @$limits;
186         my $diffs = cmdoutput @cmd;
187         foreach (split /\0/, $diffs) { $fn->(); }
188     };
189
190     $rundiff->([qw(--name-only)], [], sub {
191         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
192     });
193
194     if ($differs & DS_DEB) {
195         $differs &= ~DS_DEB;
196         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
197             $differs |=
198                 m{^debian/patches/}      ? D_PAT_OTH  :
199                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
200                                            D_DEB_OTH;
201         });
202         die "mysterious debian changes $x..$y"
203             unless $differs & (D_PAT_OTH|DS_DEB);
204     }
205
206     if ($differs & D_PAT_OTH) {
207         my $mode;
208         $differs &= ~D_PAT_OTH;
209         my $pat_oth = sub {
210             $differs |= D_PAT_OTH;
211             no warnings qw(exiting);  last;
212         };
213         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
214             no warnings qw(exiting);
215             if (!defined $mode) {
216                 $mode = $_;  next;
217             }
218             die unless s{^debian/patches/}{};
219             my $ok;
220             if ($mode eq 'A' && !m/\.series$/s) {
221                 $ok = 1;
222             } elsif ($mode eq 'M' && $_ eq 'series') {
223                 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
224                 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
225                 chomp $x_s;  $x_s .= "\n";
226                 $ok = $x_s eq substr($y_s, 0, length $x_s);
227             } else {
228                 # nope
229             }
230             $mode = undef;
231             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
232         });
233         die "mysterious debian/patches changes $x..$y"
234             unless $differs & (D_PAT_ADD|D_PAT_OTH);
235     }
236
237     printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
238
239     return $differs;
240 }
241
242 sub commit_pr_info ($) {
243     my ($r) = @_;
244     return Data::Dumper->dump([$r], [qw(commit)]);
245 }
246
247 sub calculate_committer_authline () {
248     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
249         'DUMMY COMMIT (git-debrebase)', "HEAD:";
250     my ($h,$m) = get_commit $c;
251     $h =~ m/^committer .*$/m or confess "($h) ?";
252     return $&;
253 }
254
255 sub rm_subdir_cached ($) {
256     my ($subdir) = @_;
257     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
258 }
259
260 sub read_tree_subdir ($$) {
261     my ($subdir, $new_tree_object) = @_;
262     rm_subdir_cached $subdir;
263     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
264 }
265
266 sub read_tree_debian ($) {
267     my ($treeish) = @_;
268     read_tree_subdir 'debian', "$treeish:debian";
269     rm_subdir_cached 'debian/patches';
270 }
271
272 sub read_tree_upstream ($;$$) {
273     my ($treeish, $keep_patches, $tree_with_debian) = @_;
274     # if $tree_with_debian is supplied, will use that for debian/
275     # otherwise will save and restore it.
276     my $debian =
277         $tree_with_debian ? "$tree_with_debian:debian"
278         : cmdoutput @git, qw(write-tree --prefix=debian/);
279     runcmd @git, qw(read-tree), $treeish;
280     read_tree_subdir 'debian', $debian;
281     rm_subdir_cached 'debian/patches' unless $keep_patches;
282 };
283
284 sub make_commit ($$) {
285     my ($parents, $message_paras) = @_;
286     my $tree = cmdoutput @git, qw(write-tree);
287     my @cmd = (@git, qw(commit-tree), $tree);
288     push @cmd, qw(-p), $_ foreach @$parents;
289     push @cmd, qw(-m), $_ foreach @$message_paras;
290     return cmdoutput @cmd;
291 }
292
293 our @snag_force_opts;
294 sub snag ($$;@) {
295     my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
296     if (grep { $_ eq $tag } @snag_force_opts) {
297         $snags_forced++;
298         print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
299     } else {
300         $snags_tripped++;
301         print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
302     }
303 }
304
305 # Important: all mainline code must call snags_maybe_bail after
306 # any point where snag might be called, but before making changes
307 # (eg before any call to run_deferred_updates).  snags_maybe_bail
308 # may be called more than once if necessary (but this is not ideal
309 # because then the messages about number of snags may be confusing).
310 sub snags_maybe_bail () {
311     return if all_snags_summarised();
312     if ($snags_forced) {
313         printf STDERR
314             "%s: snags: %d overriden by individual -f options\n",
315             $us, $snags_forced;
316     }
317     if ($snags_tripped) {
318         if ($opt_force) {
319             printf STDERR
320                 "%s: snags: %d overriden by global --force\n",
321                 $us, $snags_tripped;
322         } else {
323             fail sprintf
324   "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
325                 $us, $snags_tripped;
326         }
327     }
328     $snags_summarised = $snags_forced + $snags_tripped;
329 }
330 sub snags_maybe_bail_early () {
331     # useful to bail out early without doing a lot of work;
332     # not a substitute for snags_maybe_bail.
333     snags_maybe_bail() if $snags_tripped && !$opt_force;
334 }
335 sub any_snags () {
336     return $snags_forced || $snags_tripped;
337 }
338
339 sub gbp_pq_export ($$$) {
340     my ($bname, $base, $tip) = @_;
341     # must be run in a workarea.  $bname and patch-queue/$bname
342     # ought not to exist.  Leaves you on patch-queue/$bname with
343     # the patches staged but not committed.
344     printdebug "gbp_pq_export $bname $base $tip\n";
345     runcmd @git, qw(checkout -q -b), $bname, $base;
346     runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
347     my @gbp_cmd = (qw(gbp pq export));
348     my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
349     if ($r) {
350         { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
351         failedcmd @gbp_cmd;
352     }
353     runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
354 }
355
356
357 # xxx allow merge resolution separately from laundering, before git merge
358 #
359 # xxx general gdr docs highlight forbidden things
360 # xxx general gdr docs list allowable things ?
361 # xxx general gdr docs explicitly forbid some rebase
362 #
363 # xxx provide a way for the user to help
364 # xxx (eg, provide wreckage provide way to continue)
365
366 # later/rework?
367 #  use git-format-patch?
368 #  our own patch identification algorithm?
369 #  this is an alternative strategy
370
371 sub mwrecknote ($$$) {
372     my ($wrecknotes, $reftail, $commitish) = @_;
373     confess unless defined $commitish;
374     $wrecknotes->{$reftail} = $commitish;
375 }
376
377 sub merge_series ($$$;@) {
378     my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
379     # $base_q{SeriesBase}  $input_qs[]{SeriesBase}
380     # $base_q{SeriesTip}   $input_qs[]{SeriesTip}
381     # ^ specifies several patch series (currently we only support exactly 2)
382     # return value is a commit which is the result of
383     # merging the two versions of the same topic branch
384     #   $input_q[0] and $input_q[1]
385     # with respect to the old version
386     #   $base_q
387     # all onto $newbase.
388
389     # Creates, in *_q, a key MR for its private use
390
391     printdebug "merge_series newbase=$newbase\n";
392
393     $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
394     $base_q->{MR}{S} = 'base';
395
396     my %prereq;
397     # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
398     # $prereq{<patch filename>}{<possible prereq}  exists or not (later)
399     # $prereq{<patch filename>}               exists or not (even later)
400
401     my $result;
402
403     my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
404
405     local $workarea = fresh_playground "$playprefix/merge";
406     my $seriesfile = "debian/patches/series";
407     in_workarea sub {
408         playtree_setup();
409         foreach my $q ($base_q, reverse @input_qs) {
410             my $s = $q->{MR}{S};
411             gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
412             my @earlier;
413             if (open S, $seriesfile) {
414                 while (my $patch = <S>) {
415                     chomp $patch or die $!;
416                     $prereq{$patch} //= {};
417                     foreach my $earlier (@earlier) {
418                         $prereq{$patch}{$earlier}{$s}++ and die;
419                     }
420                     push @earlier, $patch;
421                     stat "debian/patches/$patch" or die "$patch ?";
422                 }
423                 S->error and die "$seriesfile $!";
424                 close S;
425             } else {
426                 die "$seriesfile $!" unless $!==ENOENT;
427             }
428             read_tree_upstream $newbase, 1;
429             my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
430                 "Convert $s to patch queue for merging",
431                 "[git-debrebase merge-innards patch-queue import:".
432                 " $q->{SeriesTip}]"
433             ];
434             printdebug "merge_series  pec $pec ";
435             runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
436             $pec = make_commit [ $pec ], [
437                 "Drop series file from $s to avoid merge trouble",
438                 "[git-debrebase merge-innards patch-queue prep:".
439                 " $q->{SeriesTip}]"
440             ];
441
442             read_tree_debian $newbase;
443             if (@earlier) {
444                 read_tree_subdir 'debian/patches', "$pec:debian/patches";
445             } else {
446                 rm_subdir_cached 'debian/patches';
447             }
448             $pec = make_commit [ $pec ], [
449  "Update debian/ (excluding patches) to final to avoid re-merging",
450  "debian/ was already merged and we need to just take that.",
451                 "[git-debrebase merge-innards patch-queue packaging:".
452                 " $q->{SeriesTip}]"
453             ];
454
455             printdebug "pec' $pec\n";
456             runcmd @git, qw(reset -q --hard), $pec;
457             $q->{MR}{PEC} = $pec;
458             $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
459         }
460         # now, because of reverse, we are on $input_q->{MR}{OQC}
461         runcmd @git, qw(checkout -q -b merge);
462         printdebug "merge_series merging...\n";
463         my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
464         debugcmd '+', @mergecmd;
465         $!=0; $?=-1;
466         if (system @mergecmd) {
467             failedcmd @mergecmd;
468         }
469
470         printdebug "merge_series merge ok, series...\n";
471         # We need to construct a new series file
472         # Firstly, resolve prereq
473         foreach my $f (sort keys %prereq) {
474             printdebug "merge_series  patch\t$f\t";
475             if (!stat_exists "debian/patches/$f") {
476                 print DEBUG " drop\n" if $debuglevel;
477                 # git merge deleted it; that's how we tell it's not wanted
478                 delete $prereq{$f};
479                 next;
480             }
481             print DEBUG " keep\n" if $debuglevel;
482             foreach my $g (sort keys %{ $prereq{$f} }) {
483                 my $gfp = $prereq{$f}{$g};
484                 printdebug "merge_series  prereq\t$f\t-> $g\t";
485                 if (!!$gfp->{0} == !!$gfp->{1}
486                     ? $gfp->{0}
487                     : !$gfp->{base}) {
488                     print DEBUG "\tkeep\n" if $debuglevel;
489                 } else {
490                     print DEBUG "\tdrop\n" if $debuglevel;
491                     delete $prereq{$f}{$g};
492                 }
493             }
494         }
495
496         my $unsat = sub {
497             my ($f) = @_;
498             return scalar keys %{ $prereq{$f} };
499         };
500
501         my $nodate = time + 1;
502         my %authordate;
503         # $authordate{<patch filename>};
504         my $authordate = sub {
505             my ($f) = @_;
506             $authordate{$f} //= do {
507                 open PF, "<", "debian/patches/$f" or die "$f $!";
508                 while (<PF>) {
509                     return $nodate if m/^$/;
510                     last if s{^Date: }{};
511                 }
512                 chomp;
513                 return cmdoutput qw(date +%s -d), $_;
514             };
515         };
516
517         open NS, '>', $seriesfile or die $!;
518
519         while (keys %prereq) {
520             my $best;
521             foreach my $try (sort keys %prereq) {
522                 if ($best) {
523                     next if (
524                              $unsat->($try) <=> $unsat->($best) or
525                              $authordate->($try) <=> $authordate->($best) or
526                              $try cmp $best
527                             ) >= 0;
528                 }
529                 $best = $try;
530             }
531             printdebug "merge_series series next $best\n";
532             print NS "$best\n" or die $!;
533             delete $prereq{$best};
534             foreach my $gp (values %prereq) {
535                 delete $gp->{$best};
536             }
537         }
538
539         runcmd @git, qw(add), $seriesfile;
540         runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
541         $mwrecknote->('merged-patchqueue', git_rev_parse 'HEAD');
542
543         printdebug "merge_series series gbp pq import\n";
544         runcmd qw(gbp pq import);
545
546         # OK now we are on patch-queue/merge, and we need to rebase
547         # onto the intended parent and drop the patches from each one
548
549         printdebug "merge_series series ok, building...\n";
550         my $build = $newbase;
551         my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
552         foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
553             my $commit = git_cat_file $c, 'commit';
554             printdebug "merge_series series ok, building $c\n";
555             read_tree_upstream $c, 0, $newbase;
556             my $tree = cmdoutput @git, qw(write-tree);
557             $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
558             $commit =~ s{^tree (\S+)$}{tree $tree}m      or confess;
559             open C, ">", "../mcommit" or die $!;
560             print C $commit or die $!;
561             close C or die $!;
562             $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
563         }
564         $result = $build;
565         $mwrecknote->('merged-result', $result);
566
567         runcmd @git, qw(update-ref refs/heads/result), $result;
568
569         runcmd @git, qw(checkout -q -b debug);
570         runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
571         runcmd @git, qw(add .);
572         runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
573         my $mdebug = git_rev_parse 'HEAD';
574         printdebug sprintf "merge_series done debug=%s\n", $mdebug;
575         $mwrecknote->('merged-debug', $mdebug);
576     };
577     printdebug "merge_series returns $result\n";
578     return $result;
579 }
580
581 # classify returns an info hash like this
582 #   CommitId => $objid
583 #   Hdr => # commit headers, including 1 final newline
584 #   Msg => # commit message (so one newline is dropped)
585 #   Tree => $treeobjid
586 #   Type => (see below)
587 #   Parents = [ {
588 #       Ix => $index # ie 0, 1, 2, ...
589 #       CommitId
590 #       Differs => return value from get_differs
591 #       IsOrigin
592 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
593 #     } ...]
594 #   NewMsg => # commit message, but with any [dgit import ...] edited
595 #             # to say "[was: ...]"
596 #
597 # Types:
598 #   Packaging
599 #   Changelog
600 #   Upstream
601 #   AddPatches
602 #   Mixed
603 #
604 #   Pseudomerge
605 #     has additional entres in classification result
606 #       Overwritten = [ subset of Parents ]
607 #       Contributor = $the_remaining_Parent
608 #
609 #   DgitImportUnpatched
610 #     has additional entry in classification result
611 #       OrigParents = [ subset of Parents ]
612 #
613 #   Anchor
614 #     has additional entry in classification result
615 #       OrigParents = [ subset of Parents ]  # singleton list
616 #
617 #   TreatAsAnchor
618 #
619 #   BreakwaterStart
620 #
621 #   Unknown
622 #     has additional entry in classification result
623 #       Why => "prose"
624
625 sub parsecommit ($;$) {
626     my ($objid, $p_ref) = @_;
627     # => hash with                   CommitId Hdr Msg Tree Parents
628     #    Parents entries have only   Ix CommitId
629     #    $p_ref, if provided, must be [] and is used as a base for Parents
630
631     $p_ref //= [];
632     die if @$p_ref;
633
634     my ($h,$m) = get_commit $objid;
635
636     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
637     my (@ph) = $h =~ m/^parent (\w+)$/mg;
638
639     my $r = {
640         CommitId => $objid,
641         Hdr => $h,
642         Msg => $m,
643         Tree => $t,
644         Parents => $p_ref,
645     };
646
647     foreach my $ph (@ph) {
648         push @$p_ref, {
649             Ix => scalar @$p_ref,
650             CommitId => $ph,
651         };
652     }
653
654     return $r;
655 }    
656
657 sub classify ($) {
658     my ($objid) = @_;
659
660     my @p;
661     my $r = parsecommit($objid, \@p);
662     my $t = $r->{Tree};
663
664     foreach my $p (@p) {
665         $p->{Differs} = (get_differs $p->{CommitId}, $t),
666     }
667
668     printdebug "classify $objid \$t=$t \@p",
669         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
670         "\n";
671
672     my $classify = sub {
673         my ($type, @rest) = @_;
674         $r = { %$r, Type => $type, @rest };
675         if ($debuglevel) {
676             printdebug " = $type ".(dd $r)."\n";
677         }
678         return $r;
679     };
680     my $unknown = sub {
681         my ($why) = @_;
682         $r = { %$r, Type => qw(Unknown), Why => $why };
683         printdebug " ** Unknown\n";
684         return $r;
685     };
686
687     if (grep { $_ eq $objid } @opt_anchors) {
688         return $classify->('TreatAsAnchor');
689     }
690
691     my @identical = grep { !$_->{Differs} } @p;
692     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
693     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
694
695     if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
696         # multi-orig upstreams are represented with an anchor merge
697         # from a single upstream commit which combines the orig tarballs
698
699         # Every anchor tagged this way must be a merge.
700         # We are relying on the
701         #     [git-debrebase anchor: ...]
702         # commit message annotation in "declare" anchor merges (which
703         # do not have any upstream changes), to distinguish those
704         # anchor merges from ordinary pseudomerges (which we might
705         # just try to strip).
706         #
707         # However, the user is going to be doing git-rebase a lot.  We
708         # really don't want them to rewrite an anchor commit.
709         # git-rebase trips up on merges, so that is a useful safety
710         # catch.
711         #
712         # BreakwaterStart commits are also anchors in the terminology
713         # of git-debrebase(5), but they are untagged (and always
714         # manually generated).
715         #
716         # We cannot not tolerate any tagged linear commit (ie,
717         # BreakwaterStart commits tagged `[anchor:') because such a
718         # thing could result from an erroneous linearising raw git
719         # rebase of a merge anchor.  That would represent a corruption
720         # of the branch. and we want to detect and reject the results
721         # of such corruption before it makes it out anywhere.  If we
722         # reject it here then we avoid making the pseudomerge which
723         # would be needed to push it.
724
725         my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
726         @p == 2 or return $badanchor->("has other than two parents");
727         $haspatches and return $badanchor->("contains debian/patches");
728
729         # How to decide about l/r ordering of anchors ?  git
730         # --topo-order prefers to expand 2nd parent first.  There's
731         # already an easy rune to look for debian/ history anyway (git log
732         # debian/) so debian breakwater branch should be 1st parent; that
733         # way also there's also an easy rune to look for the upstream
734         # patches (--topo-order).
735
736         # Also this makes --first-parent be slightly more likely to
737         # be useful - it makes it provide a linearised breakwater history.
738
739         # Of course one can say somthing like
740         #  gitk -- ':/' ':!/debian'
741         # to get _just_ the commits touching upstream files, and by
742         # the TREESAME logic in git-rev-list this will leave the
743         # breakwater into upstream at the first anchor.  But that
744         # doesn't report debian/ changes at all.
745
746         # Other observations about gitk: by default, gitk seems to
747         # produce output in a different order to git-rev-list.  I
748         # can't seem to find this documented anywhere.  gitk
749         # --date-order DTRT.  But, gitk always seems to put the
750         # parents from left to right, in order, so it's easy to see
751         # which way round a pseudomerge is.
752
753         $p[0]{IsOrigin} and $badanchor->("is an origin commit");
754         $p[1]{Differs} & ~DS_DEB and
755             $badanchor->("upstream files differ from left parent");
756         $p[0]{Differs} & ~D_UPS and
757             $badanchor->("debian/ differs from right parent");
758
759         return $classify->(qw(Anchor),
760                            OrigParents => [ $p[1] ]);
761     }
762
763     if (@p == 1) {
764         my $d = $r->{Parents}[0]{Differs};
765         if ($d == D_PAT_ADD) {
766             return $classify->(qw(AddPatches));
767         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
768             return $unknown->("edits debian/patches");
769         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
770             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
771             if ($ty eq 'tree') {
772                 if ($d == D_DEB_CLOG) {
773                     return $classify->(qw(Changelog));
774                 } else {
775                     return $classify->(qw(Packaging));
776                 }
777             } elsif ($ty eq 'missing') {
778                 return $classify->(qw(BreakwaterStart));
779             } else {
780                 return $unknown->("parent's debian is not a directory");
781             }
782         } elsif ($d == D_UPS) {
783             return $classify->(qw(Upstream));
784         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
785             return $classify->(qw(Mixed));
786         } elsif ($d == 0) {
787             return $unknown->("no changes");
788         } else {
789             confess "internal error $objid ?";
790         }
791     }
792     if (!@p) {
793         return $unknown->("origin commit");
794     }
795
796     if (@p == 2 && @identical == 1) {
797         my @overwritten = grep { $_->{Differs} } @p;
798         confess "internal error $objid ?" unless @overwritten==1;
799         return $classify->(qw(Pseudomerge),
800                            Overwritten => [ $overwritten[0] ],
801                            Contributor => $identical[0]);
802     }
803     if (@p == 2 && @identical == 2) {
804         my $get_t = sub {
805             my ($ph,$pm) = get_commit $_[0]{CommitId};
806             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
807             $1;
808         };
809         my @bytime = @p;
810         my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
811         if ($order > 0) { # newer first
812         } elsif ($order < 0) {
813             @bytime = reverse @bytime;
814         } else {
815             # same age, default to order made by -s ours
816             # that is, commit was made by someone who preferred L
817         }
818         return $classify->(qw(Pseudomerge),
819                            SubType => qw(Ambiguous),
820                            Contributor => $bytime[0],
821                            Overwritten => [ $bytime[1] ]);
822     }
823     foreach my $p (@p) {
824         my ($p_h, $p_m) = get_commit $p->{CommitId};
825         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
826         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
827     }
828     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
829     my $m2 = $r->{Msg};
830     if (!(grep { !$_->{IsOrigin} } @p) and
831         (@orig_ps >= @p - 1) and
832         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
833         $r->{NewMsg} = $m2;
834         return $classify->(qw(DgitImportUnpatched),
835                            OrigParents => \@orig_ps);
836     }
837
838     if (@p == 2 and
839         $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
840         # xxx ^ metadata tag needs adding to (5)
841         return $classify->("MergedBreakwaters");
842     }
843     if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
844         return $unknown->("unknown kind of merge from $1");
845     }
846     if (@p > 2) {
847         return $unknown->("octopus merge");
848     }
849
850     if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
851         return $unknown->("general two-parent merge");
852     }
853
854     return $classify->("VanillaMerge");
855 }
856
857 sub keycommits ($;$$$$$);
858
859 sub mergedbreakwaters_anchor ($) {
860     my ($cl) = @_;
861     my $best_anchor;
862     foreach my $p (@{ $cl->{Parents} }) {
863         my ($panchor, $pbw) = keycommits $p->{CommitId},
864             undef,undef,undef,undef, 1;
865         $best_anchor = $panchor
866             if !defined $best_anchor
867             or is_fast_fwd $best_anchor, $panchor;
868         fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
869             unless is_fast_fwd $panchor, $best_anchor;
870     }
871     return $best_anchor;
872 }
873
874 sub keycommits ($;$$$$$) {
875     my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
876     # => ($anchor, $breakwater)
877
878     # $unclean->("unclean-$tagsfx", $msg, $cl)
879     # $furniture->("unclean-$tagsfx", $msg, $cl)
880     # $dgitimport->("unclean-$tagsfx", $msg, $cl))
881     #   is callled for each situation or commit that
882     #   wouldn't be found in a laundered branch
883     # $furniture is for furniture commits such as might be found on an
884     #   interchange branch (pseudomerge, d/patches, changelog)
885     # $trouble is for things whnich prevent the return of
886     #   anchor and breakwater information; if that is ignored,
887     #   then keycommits returns (undef, undef) instead.
888     # $fatal is for unprocessable commits, and should normally cause
889     #    a failure.  If ignored, agaion, (undef, undef) is returned.
890     #
891     # If $claimed_bw, this is supposed to be a breakwater commit.
892     #
893     # If a callback is undef, fail is called instead.
894     # If a callback is defined but false, the situation is ignored.
895     # Callbacks may say:
896     #   no warnings qw(exiting); last;
897     # if the answer is no longer wanted.
898
899     my ($anchor, $breakwater);
900     $breakwater = $head if $claimed_bw;
901     my $clogonly;
902     my $cl;
903     my $found_pm;
904     $fatal //= sub { fail $_[1]; };
905     my $x = sub {
906         my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
907         my $why = $mainwhy.$xwhy;
908         my $m = "branch needs laundering (run git-debrebase): $why";
909         fail $m unless defined $cb;
910         return unless $cb;
911         $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
912     };
913     my $found_anchor = sub {
914         ($anchor) = @_;
915         $breakwater //= $clogonly;
916         $breakwater //= $head;
917         no warnings qw(exiting);
918         last;
919     };
920     for (;;) {
921         $cl = classify $head;
922         my $ty = $cl->{Type};
923         if ($ty eq 'Packaging') {
924             $breakwater //= $clogonly;
925             $breakwater //= $head;
926         } elsif ($ty eq 'Changelog') {
927             # this is going to count as the tip of the breakwater
928             # only if it has no upstream stuff before it
929             $clogonly //= $head;
930         } elsif ($ty eq 'Anchor' or
931                  $ty eq 'TreatAsAnchor' or
932                  $ty eq 'BreakwaterStart') {
933             $found_anchor->($head);
934         } elsif ($ty eq 'Upstream') {
935             $x->($unclean, 'ordering',
936  "packaging change ($breakwater) follows upstream change"," (eg $head)")
937                 if defined $breakwater;
938             $clogonly = undef;
939             $breakwater = undef;
940         } elsif ($ty eq 'Mixed') {
941             $x->($unclean, 'mixed',
942                  "found mixed upstream/packaging commit"," ($head)");
943             $clogonly = undef;
944             $breakwater = undef;
945         } elsif ($ty eq 'Pseudomerge' or
946                  $ty eq 'AddPatches') {
947             my $found_pm = 1;
948             $x->($furniture, (lc $ty),
949                  "found interchange bureaucracy commit ($ty)"," ($head)");
950         } elsif ($ty eq 'DgitImportUnpatched') {
951             if ($found_pm) {
952                 $x->($trouble, 'dgitimport',
953                      "found dgit dsc import"," ($head)");
954                 return (undef,undef);
955             } else {
956                 $x->($fatal, 'unprocessable',
957                      "found bare dgit dsc import with no prior history",
958                      " ($head)");
959                 return (undef,undef);
960             }
961         } elsif ($ty eq 'VanillaMerge') {
962             $x->($trouble, 'vanillamerge',
963                  "found vanilla merge"," ($head)");
964             return (undef,undef);
965         } elsif ($ty eq 'MergedBreakwaters') {
966             $found_anchor->(mergedbreakwaters_anchor $cl);
967         } else {
968             $x->($fatal, 'unprocessable',
969                  "found unprocessable commit, cannot cope: $cl->{Why}",
970                  " ($head)");
971             return (undef,undef);
972         }
973         $head = $cl->{Parents}[0]{CommitId};
974     }
975     return ($anchor, $breakwater);
976 }
977
978 sub walk ($;$$$);
979 sub walk ($;$$$) {
980     my ($input,
981         $nogenerate,$report, $report_lprefix) = @_;
982     # => ($tip, $breakwater_tip, $last_anchor)
983     # (or nothing, if $nogenerate)
984
985     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
986     $report_lprefix //= '';
987
988     # go through commits backwards
989     # we generate two lists of commits to apply:
990     # breakwater branch and upstream patches
991     my (@brw_cl, @upp_cl, @processed);
992     my %found;
993     my $upp_limit;
994     my @pseudomerges;
995
996     my $cl;
997     my $xmsg = sub {
998         my ($prose, $info) = @_;
999         my $ms = $cl->{Msg};
1000         chomp $ms;
1001         $info //= '';
1002         $ms .= "\n\n[git-debrebase$info: $prose]\n";
1003         return (Msg => $ms);
1004     };
1005     my $rewrite_from_here = sub {
1006         my ($cl) = @_;
1007         my $sp_cl = { SpecialMethod => 'StartRewrite' };
1008         push @$cl, $sp_cl;
1009         push @processed, $sp_cl;
1010     };
1011     my $cur = $input;
1012
1013     my $prdelim = "";
1014     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1015
1016     my $prline = sub {
1017         return unless $report;
1018         print $report $prdelim, $report_lprefix, @_;
1019         $prdelim = "\n";
1020     };
1021
1022     my $bomb = sub { # usage: return $bomb->();
1023         print $report " Unprocessable" if $report;
1024         print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1025         $prprdelim->();
1026         if ($nogenerate) {
1027             return (undef,undef);
1028         }
1029         fail "found unprocessable commit, cannot cope".
1030             (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1031             " (commit $cur) (d.".
1032             (join ' ', map { sprintf "%#x", $_->{Differs} }
1033              @{ $cl->{Parents} }).
1034                  ")";
1035     };
1036
1037     my $build;
1038     my $breakwater;
1039
1040     my $build_start = sub {
1041         my ($msg, $parent) = @_;
1042         $prline->(" $msg");
1043         $build = $parent;
1044         no warnings qw(exiting); last;
1045     };
1046
1047     my $nomerge = sub {
1048         fail "something useful about failed merge attempt @_ xxx".Dumper($cl);
1049     };
1050
1051     my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1052
1053     my $last_anchor;
1054
1055     for (;;) {
1056         $cl = classify $cur;
1057         $cl->{MergeWreckNotes} //= {};
1058         my $ty = $cl->{Type};
1059         my $st = $cl->{SubType};
1060         $prline->("$cl->{CommitId} $cl->{Type}");
1061         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1062         push @processed, $cl;
1063         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1064         if ($ty eq 'AddPatches') {
1065             $cur = $p0;
1066             $rewrite_from_here->(\@upp_cl);
1067             next;
1068         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1069             push @brw_cl, $cl;
1070             $cur = $p0;
1071             next;
1072         } elsif ($ty eq 'BreakwaterStart') {
1073             $last_anchor = $cur;
1074             $build_start->('FirstPackaging', $cur);
1075         } elsif ($ty eq 'Upstream') {
1076             push @upp_cl, $cl;
1077             $cur = $p0;
1078             next;
1079         } elsif ($ty eq 'Mixed') {
1080             my $queue = sub {
1081                 my ($q, $wh) = @_;
1082                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1083                 push @$q, $cls;
1084             };
1085             $queue->(\@brw_cl, "debian");
1086             $queue->(\@upp_cl, "upstream");
1087             $rewrite_from_here->(\@brw_cl);
1088             $cur = $p0;
1089             next;
1090         } elsif ($ty eq 'Pseudomerge') {
1091             my $contrib = $cl->{Contributor}{CommitId};
1092             print $report " Contributor=$contrib" if $report;
1093             push @pseudomerges, $cl;
1094             $rewrite_from_here->(\@upp_cl);
1095             $cur = $contrib;
1096             next;
1097         } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1098             $last_anchor = $cur;
1099             $build_start->("Anchor", $cur);
1100         } elsif ($ty eq 'DgitImportUnpatched') {
1101             my $pm = $pseudomerges[-1];
1102             if (defined $pm) {
1103                 # To an extent, this is heuristic.  Imports don't have
1104                 # a useful history of the debian/ branch.  We assume
1105                 # that the first pseudomerge after an import has a
1106                 # useful history of debian/, and ignore the histories
1107                 # from later pseudomerges.  Often the first pseudomerge
1108                 # will be the dgit import of the upload to the actual
1109                 # suite intended by the non-dgit NMUer, and later
1110                 # pseudomerges may represent in-archive copies.
1111                 my $ovwrs = $pm->{Overwritten};
1112                 printf $report " PM=%s \@Overwr:%d",
1113                     $pm->{CommitId}, (scalar @$ovwrs)
1114                     if $report;
1115                 if (@$ovwrs != 1) {
1116                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
1117                     return $bomb->();
1118                 }
1119                 my $ovwr = $ovwrs->[0]{CommitId};
1120                 printf $report " Overwr=%s", $ovwr if $report;
1121                 # This import has a tree which is just like a
1122                 # breakwater tree, but it has the wrong history.  It
1123                 # ought to have the previous breakwater (which the
1124                 # pseudomerge overwrote) as an ancestor.  That will
1125                 # make the history of the debian/ files correct.  As
1126                 # for the upstream version: either it's the same as
1127                 # was ovewritten (ie, same as the previous
1128                 # breakwater), in which case that history is precisely
1129                 # right; or, otherwise, it was a non-gitish upload of a
1130                 # new upstream version.  We can tell these apart by
1131                 # looking at the tree of the supposed upstream.
1132                 push @brw_cl, {
1133                     %$cl,
1134                     SpecialMethod => 'DgitImportDebianUpdate',
1135                     $xmsg->("convert dgit import: debian changes")
1136                 }, {
1137                     %$cl,
1138                     SpecialMethod => 'DgitImportUpstreamUpdate',
1139                     $xmsg->("convert dgit import: upstream update",
1140                             " anchor")
1141                 };
1142                 $prline->(" Import");
1143                 $rewrite_from_here->(\@brw_cl);
1144                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1145                 $cur = $ovwr;
1146                 next;
1147             } else {
1148                 # Everything is from this import.  This kind of import
1149                 # is already nearly in valid breakwater format, with the
1150                 # patches as commits.  Unfortunately it contains
1151                 # debian/patches/.
1152                 printdebug "*** WALK BOMB bare dgit import\n";
1153                 $cl->{Why} = "bare dgit dsc import";
1154                 return $bomb->();
1155             }
1156             die "$ty ?";
1157         } elsif ($ty eq 'MergedBreakwaters') {
1158             $last_anchor = mergedbreakwaters_anchor $cl;
1159             $build_start->(' MergedBreakwaters', $cur);
1160             last;
1161         } elsif ($ty eq 'VanillaMerge') {
1162             # User may have merged unstitched branch(es).  We will
1163             # have now lost what ffq-prev was then (since the later
1164             # pseudomerge may introduce further changes).  The effect
1165             # of resolving such a merge is that we may have to go back
1166             # further in history to find a merge base, since the one
1167             # which was reachable via ffq-prev is no longer findable.
1168             # This is suboptimal, but if it all works we'll have done
1169             # the right thing.
1170             # xxx we should warn the user in the docs about this
1171
1172             my $ok=1;
1173             my $best_anchor;
1174             # We expect to find a dominating anchor amongst the
1175             # inputs' anchors.  That will be the new anchor.
1176             #
1177             # More complicated is finding a merge base for the
1178             # breakwaters.  We need a merge base that is a breakwater
1179             # commit.  The ancestors of breakwater commits are more
1180             # breakwater commits and possibly upstream commits and the
1181             # ancestors of those upstream.  Upstreams might have
1182             # arbitrary ancestors.  But any upstream commit U is
1183             # either included in both anchors, in which case the
1184             # earlier anchor is a better merge base than any of U's
1185             # ancestors; or U is not included in the older anchor, in
1186             # which case U is not an ancestor of the vanilla merge at
1187             # all.  So no upstream commit, nor any ancestor thereof,
1188             # is a best merge base.  As for non-breakwater Debian
1189             # commits: these are never ancestors of any breakwater.
1190             #
1191             # So any best merge base as found by git-merge-base
1192             # is a suitable breakwater anchor.  Usually there will
1193             # be only one.
1194
1195             printdebug "*** MERGE\n";
1196
1197             my @bwbcmd = (@git, qw(merge-base));
1198             my @ibcmd = (@git, qw(merge-base --all));
1199             my $might_be_in_bw = 1;
1200
1201             my $ps = $cl->{Parents};
1202
1203             $mwrecknote->('vanilla-merge', $cl->{CommitId});
1204
1205             foreach my $p (@$ps) {
1206                 $prline->(" VanillaMerge ".$p->{Ix});
1207                 $prprdelim->();
1208                 my ($ptip, $pbw, $panchor) =
1209                     walk $p->{CommitId}, 0, $report,
1210                          $report_lprefix.'  ';
1211                 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1212                 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1213                 $p->{Anchor} = $panchor;
1214
1215                 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1216                 $mwrecknote->("$lr-input", $p->{CommitId});
1217
1218                 my $mwrecknote_parent = sub {
1219                     my ($which) = @_;
1220                     $mwrecknote->("$lr-".(lc $which), $p->{$which});
1221                 };
1222                 $mwrecknote_parent->('Laundered');
1223                 $mwrecknote_parent->('Breakwater');
1224                 $mwrecknote_parent->('Anchor');
1225
1226                 $best_anchor = $panchor if
1227                     !defined $best_anchor or
1228                     is_fast_fwd $best_anchor, $panchor;
1229
1230                 printdebug " MERGE BA best=".($best_anchor//'-').
1231                     " p=$panchor\n";
1232             }
1233
1234             $mwrecknote->('result-anchor', $best_anchor);
1235
1236             foreach my $p (@$ps) {
1237                 $prline->(" VanillaMerge ".$p->{Ix});
1238                 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1239                     $nomerge->('divergent anchors');
1240                 } elsif ($p->{Anchor} eq $best_anchor) {
1241                     print $report " SameAnchor" if $report;
1242                 } else {
1243                     print $report " SupersededAnchor" if $report;
1244                 }
1245                 if ($p->{Breakwater} eq $p->{CommitId}) {
1246                     # this parent commit was its own breakwater,
1247                     # ie it is part of the breakwater
1248                     print $report " Breakwater" if $report;
1249                 } else {
1250                     $might_be_in_bw = 0;
1251                 }
1252                 push @bwbcmd, $p->{Breakwater};
1253                 push @ibcmd, $p->{CommitId};
1254             }
1255
1256             if ($ok && $might_be_in_bw) {
1257                 # We could rewrite this to contaion the metadata
1258                 # declaring it to be MergedBreakwaters, but
1259                 # unnecessarily rewriting a merge seems unhelpful.
1260                 $prline->(" VanillaMerge MergedBreakwaters");
1261                 $last_anchor = $best_anchor;
1262                 $build_start->('MergedBreakwaters', $cur);
1263             }
1264
1265             my $bwb = cmdoutput @bwbcmd;
1266
1267             # OK, now we have a breakwater base, but we need the merge
1268             # base for the interchange branch because we need the delta
1269             # queue.
1270             #
1271             # This a the best merge base of our inputs which has the
1272             # breakwater merge base as an ancestor.
1273
1274             my @ibs =
1275                 grep /./,
1276                 split /\n/,
1277                 cmdoutput @ibcmd;
1278
1279             @ibs or confess 'internal error, expected anchor at least ?';
1280
1281             my $ib;
1282             my $ibleaf;
1283             foreach my $tibix (0..$#ibs) {
1284                 my $tib = $ibs[$tibix];
1285                 my $ff = is_fast_fwd $bwb, $tib;
1286                 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1287                 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1288                 $mwrecknote->($tibleaf, $tib);
1289                 next unless $ff;
1290                 next if $ib;
1291                 $ib = $tib;
1292                 $ibleaf = $tibleaf;
1293             }
1294
1295             $ib or $nomerge->("no suitable interchange merge base");
1296
1297             $prline->("  VanillaMerge Base");
1298             $prprdelim->();
1299             my ($btip, $bbw, $banchor) = eval {
1300                 walk $ib, 0, $report, $report_lprefix.'  ';
1301             };
1302             $nomerge->("walking interchange branch merge base ($ibleaf): ".
1303                        $@) if length $@;
1304
1305             $mwrecknote->("mergebase-laundered", $btip);
1306             $mwrecknote->("mergebase-breakwater", $bbw);
1307             $mwrecknote->("mergebase-anchor", $banchor);
1308
1309             my $ibinfo = { SeriesTip => $btip,
1310                            SeriesBase => $bbw,
1311                            Anchor => $banchor,
1312                            LeftRight => 'mergebase' };
1313
1314             $bbw eq $bwb
1315                 or $nomerge->("interchange merge-base ($ib)'s".
1316                               " breakwater ($bbw)".
1317                               " != breakwaters' merge-base ($bwb)");
1318
1319             grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1320                  or $nomerge->("interchange merge-base ($ib)'s".
1321                                " anchor ($ibinfo->{SeriesBase})".
1322                                " != any merge input's anchor (".
1323                                (join ' ', map { $_->{Anchor} } @$ps).
1324                                ")");
1325
1326             $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1327             $cl->{MergeBestAnchor} = $best_anchor;
1328             push @brw_cl, {
1329                 %$cl,
1330                 SpecialMethod => 'MergeCreateMergedBreakwaters',
1331                 $xmsg->('constructed from vanilla merge',
1332                         ' merged-breakwater'),
1333             };
1334             push @upp_cl, {
1335                 %$cl,
1336                 SpecialMethod => 'MergeMergeSeries',
1337             };
1338             $build_start->('MergeBreakwaters', $cur);
1339         } else {
1340             printdebug "*** WALK BOMB unrecognised\n";
1341             return $bomb->();
1342         }
1343     }
1344     $prprdelim->();
1345
1346     printdebug "*** WALK prep done cur=$cur".
1347         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1348
1349     return if $nogenerate;
1350
1351     # Now we build it back up again
1352
1353     fresh_workarea();
1354
1355     my $rewriting = 0;
1356
1357     my $read_tree_upstream = sub {
1358         my ($treeish) = @_;
1359         read_tree_upstream $treeish, 0, $build;
1360     };
1361
1362     $#upp_cl = $upp_limit if defined $upp_limit;
1363  
1364     my $committer_authline = calculate_committer_authline();
1365
1366     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1367
1368     confess "internal error" unless $build eq (pop @processed)->{CommitId};
1369
1370     in_workarea sub {
1371         mkdir $rd or $!==EEXIST or die $!;
1372         my $current_method;
1373         runcmd @git, qw(read-tree), $build;
1374         foreach my $cl (qw(Debian), (reverse @brw_cl),
1375                         { SpecialMethod => 'RecordBreakwaterTip' },
1376                         qw(Upstream), (reverse @upp_cl)) {
1377             if (!ref $cl) {
1378                 $current_method = $cl;
1379                 next;
1380             }
1381             my $method = $cl->{SpecialMethod} // $current_method;
1382             my @parents = ($build);
1383             my $cltree = $cl->{CommitId};
1384             printdebug "WALK BUILD ".($cltree//'undef').
1385                 " $method (rewriting=$rewriting)\n";
1386             if ($method eq 'Debian') {
1387                 read_tree_debian($cltree);
1388             } elsif ($method eq 'Upstream') {
1389                 $read_tree_upstream->($cltree);
1390             } elsif ($method eq 'StartRewrite') {
1391                 $rewriting = 1;
1392                 next;
1393             } elsif ($method eq 'RecordBreakwaterTip') {
1394                 $breakwater = $build;
1395                 next;
1396             } elsif ($method eq 'DgitImportDebianUpdate') {
1397                 read_tree_debian($cltree);
1398             } elsif ($method eq 'DgitImportUpstreamUpdate') {
1399                 confess unless $rewriting;
1400                 my $differs = (get_differs $build, $cltree);
1401                 next unless $differs & D_UPS;
1402                 $read_tree_upstream->($cltree);
1403                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1404             } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1405                 print "Found a general merge, will try to tidy it up.\n";
1406                 $rewriting = 1;
1407                 $read_tree_upstream->($cl->{MergeBestAnchor});
1408                 $read_tree_upstream->($cl->{MergeBestAnchor});
1409                 read_tree_debian($cltree);
1410                 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1411             } elsif ($method eq 'MergeMergeSeries') {
1412                 print "Running merge resolution for $cl->{CommitId}...\n";
1413                 $build = merge_series
1414                     $build, $cl->{MergeWreckNotes},
1415                     $cl->{MergeInterchangeBaseInfo},
1416                     @{ $cl->{Parents} };
1417                 $last_anchor = $cl->{MergeBestAnchor};
1418
1419                 # Check for mismerges:
1420                 my $check = sub {
1421                     my ($against, $allow, $what) = @_;
1422                     my $differs = get_differs $build, $against;
1423                     $nomerge->(sprintf
1424        "merge misresolved: %s are not the same (%s %s d.%#x)",
1425                                $what, $against, $build, $differs)
1426                         if $differs & ~($allow | D_PAT_ADD);
1427                 };
1428
1429                 # Breakwater changes which were in each side of the
1430                 # merge will have been incorporated into the
1431                 # MergeCreateMergedBreakwaters output.  Because the
1432                 # upstream series was rebased onto the new breakwater,
1433                 # so should all of the packaging changes which were in
1434                 # the input.
1435                 $check->($input, D_UPS, 'debian files');
1436
1437                 # Upstream files are merge_series, which ought to
1438                 # have been identical to the original merge.
1439                 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1440
1441                 print "Merge resolution successful.\n";
1442                 next;
1443             } else {
1444                 confess "$method ?";
1445             }
1446             if (!$rewriting) {
1447                 my $procd = (pop @processed) // 'UNDEF';
1448                 if ($cl ne $procd) {
1449                     $rewriting = 1;
1450                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1451                 }
1452             }
1453             my $newtree = cmdoutput @git, qw(write-tree);
1454             my $ch = $cl->{Hdr};
1455             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1456             $ch =~ s{^parent .*\n}{}mg;
1457             $ch =~ s{(?=^author)}{
1458                 join '', map { "parent $_\n" } @parents
1459             }me or confess "$ch ?";
1460             if ($rewriting) {
1461                 $ch =~ s{^committer .*$}{$committer_authline}m
1462                     or confess "$ch ?";
1463             }
1464             my $cf = "$rd/m$rewriting";
1465             open CD, ">", $cf or die $!;
1466             print CD $ch, "\n", $cl->{Msg} or die $!;
1467             close CD or die $!;
1468             my @cmd = (@git, qw(hash-object));
1469             push @cmd, qw(-w) if $rewriting;
1470             push @cmd, qw(-t commit), $cf;
1471             my $newcommit = cmdoutput @cmd;
1472             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1473             $build = $newcommit;
1474             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1475                 $last_anchor = $cur;
1476             }
1477         }
1478     };
1479
1480     my $final_check = get_differs $build, $input;
1481     die sprintf "internal error %#x %s %s", $final_check, $input, $build
1482         if $final_check & ~D_PAT_ADD;
1483
1484     my @r = ($build, $breakwater, $last_anchor);
1485     printdebug "*** WALK RETURN @r\n";
1486     return @r
1487 }
1488
1489 sub get_head () {
1490     git_check_unmodified();
1491     return git_rev_parse qw(HEAD);
1492 }
1493
1494 sub update_head ($$$) {
1495     my ($old, $new, $mrest) = @_;
1496     push @deferred_updates, "update HEAD $new $old";
1497     run_deferred_updates $mrest;
1498 }
1499
1500 sub update_head_checkout ($$$) {
1501     my ($old, $new, $mrest) = @_;
1502     update_head $old, $new, $mrest;
1503     runcmd @git, qw(reset --hard);
1504 }
1505
1506 sub update_head_postlaunder ($$$) {
1507     my ($old, $tip, $reflogmsg) = @_;
1508     return if $tip eq $old;
1509     print "git-debrebase: laundered (head was $old)\n";
1510     update_head $old, $tip, $reflogmsg;
1511     # no tree changes except debian/patches
1512     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1513 }
1514
1515 sub currently_rebasing() {
1516     foreach (qw(rebase-merge rebase-apply)) {
1517         return 1 if stat_exists "$maindir_gitdir/$_";
1518     }
1519     return 0;
1520 }
1521
1522 sub bail_if_rebasing() {
1523     fail "you are in the middle of a git-rebase already"
1524         if currently_rebasing();
1525 }
1526
1527 sub do_launder_head ($) {
1528     my ($reflogmsg) = @_;
1529     my $old = get_head();
1530     record_ffq_auto();
1531     my ($tip,$breakwater) = walk $old;
1532     snags_maybe_bail();
1533     update_head_postlaunder $old, $tip, $reflogmsg;
1534     return ($tip,$breakwater);
1535 }
1536
1537 sub cmd_launder_v0 () {
1538     badusage "no arguments to launder-v0 allowed" if @ARGV;
1539     my $old = get_head();
1540     my ($tip,$breakwater,$last_anchor) = walk $old;
1541     update_head_postlaunder $old, $tip, 'launder';
1542     printf "# breakwater tip\n%s\n", $breakwater;
1543     printf "# working tip\n%s\n", $tip;
1544     printf "# last anchor\n%s\n", $last_anchor;
1545 }
1546
1547 sub defaultcmd_rebase () {
1548     push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1549     my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1550     runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1551 }
1552
1553 sub cmd_analyse () {
1554     badusage "analyse does not support any options"
1555         if @ARGV and $ARGV[0] =~ m/^-/;
1556     badusage "too many arguments to analyse" if @ARGV>1;
1557     my ($old) = @ARGV;
1558     if (defined $old) {
1559         $old = git_rev_parse $old;
1560     } else {
1561         $old = git_rev_parse 'HEAD';
1562     }
1563     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1564     STDOUT->error and die $!;
1565 }
1566
1567 sub ffq_prev_branchinfo () {
1568     my $current = git_get_symref();
1569     return gdr_ffq_prev_branchinfo($current);
1570 }
1571
1572 sub ffq_check ($;$$) {
1573     # calls $ff and/or $notff zero or more times
1574     # then returns either (status,message) where status is
1575     #    exists
1576     #    detached
1577     #    weird-symref
1578     #    notbranch
1579     # or (undef,undef, $ffq_prev,$gdrlast)
1580     # $ff and $notff are called like this:
1581     #   $ff->("message for stdout\n");
1582     #   $notff->('snag-name', $message);
1583     # normally $currentval should be HEAD
1584     my ($currentval, $ff, $notff) =@_;
1585
1586     $ff //= sub { print $_[0] or die $!; };
1587     $notff //= \&snag;
1588
1589     my ($status, $message, $current, $ffq_prev, $gdrlast)
1590         = ffq_prev_branchinfo();
1591     return ($status, $message) unless $status eq 'branch';
1592
1593     my $exists = git_get_ref $ffq_prev;
1594     return ('exists',"$ffq_prev already exists") if $exists;
1595
1596     return ('not-branch', 'HEAD symref is not to refs/heads/')
1597         unless $current =~ m{^refs/heads/};
1598     my $branch = $';
1599
1600     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1601     my %checked;
1602
1603     printdebug "ffq check_specs @check_specs\n";
1604
1605     my $check = sub {
1606         my ($lrref, $desc) = @_;
1607         printdebug "ffq might check $lrref ($desc)\n";
1608         my $invert;
1609         for my $chk (@check_specs) {
1610             my $glob = $chk;
1611             $invert = $glob =~ s{^[!^]}{};
1612             last if fnmatch $glob, $lrref;
1613         }
1614         return if $invert;
1615         my $lrval = git_get_ref $lrref;
1616         return unless length $lrval;
1617
1618         if (is_fast_fwd $lrval, $currentval) {
1619             $ff->("OK, you are ahead of $lrref\n");
1620             $checked{$lrref} = 1;
1621         } elsif (is_fast_fwd $currentval, $lrval) {
1622             $checked{$lrref} = -1;
1623             $notff->('behind', "you are behind $lrref, divergence risk");
1624         } else {
1625             $checked{$lrref} = -1;
1626             $notff->('diverged', "you have diverged from $lrref");
1627         }
1628     };
1629
1630     my $merge = cfg "branch.$branch.merge",1;
1631     if (defined $merge and $merge =~ m{^refs/heads/}) {
1632         my $rhs = $';
1633         printdebug "ffq merge $rhs\n";
1634         my $check_remote = sub {
1635             my ($remote, $desc) = @_;
1636             printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1637             return unless defined $remote;
1638             $check->("refs/remotes/$remote/$rhs", $desc);
1639         };
1640         $check_remote->((scalar cfg "branch.$branch.remote",1),
1641                         'remote fetch/merge branch');
1642         $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1643                         (scalar cfg "branch.$branch.pushDefault",1),
1644                         'remote push branch');
1645     }
1646     if ($branch =~ m{^dgit/}) {
1647         $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1648     } elsif ($branch =~ m{^master$}) {
1649         $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1650     }
1651     return (undef, undef, $ffq_prev, $gdrlast);
1652 }
1653
1654 sub record_ffq_prev_deferred () {
1655     # => ('status', "message")
1656     # 'status' may be
1657     #    deferred          message is undef
1658     #    exists
1659     #    detached
1660     #    weird-symref
1661     #    notbranch
1662     # if not ff from some branch we should be ff from, is an snag
1663     # if "deferred", will have added something about that to
1664     #   @deferred_update_messages, and also maybe printed (already)
1665     #   some messages about ff checks
1666     bail_if_rebasing();
1667     my $currentval = get_head();
1668
1669     my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1670     return ($status,$message) if defined $status;
1671
1672     snags_maybe_bail();
1673
1674     push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1675     push @deferred_updates, "delete $gdrlast";
1676     push @deferred_update_messages, "Recorded previous head for preservation";
1677     return ('deferred', undef);
1678 }
1679
1680 sub record_ffq_auto () {
1681     my ($status, $message) = record_ffq_prev_deferred();
1682     if ($status eq 'deferred' || $status eq 'exists') {
1683     } else {
1684         snag $status, "could not record ffq-prev: $message";
1685         snags_maybe_bail();
1686     }
1687 }
1688
1689 sub ffq_prev_info () {
1690     bail_if_rebasing();
1691     # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1692     my ($status, $message, $current, $ffq_prev, $gdrlast)
1693         = ffq_prev_branchinfo();
1694     if ($status ne 'branch') {
1695         snag $status, "could not check ffq-prev: $message";
1696         snags_maybe_bail();
1697     }
1698     my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1699     return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1700 }
1701
1702 sub stitch ($$$$$) {
1703     my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1704
1705     push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1706
1707     if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1708         my $differs = get_differs $old_head, $ffq_prev_commitish;
1709         unless ($differs & ~D_PAT_ADD) {
1710             # ffq-prev is ahead of us, and the only tree changes it has
1711             # are possibly addition of things in debian/patches/.
1712             # Just wind forwards rather than making a pointless pseudomerge.
1713             push @deferred_updates,
1714                 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1715             update_head_checkout $old_head, $ffq_prev_commitish,
1716                 "stitch (fast forward)";
1717             return;
1718         }
1719     }
1720     fresh_workarea();
1721     # We make pseudomerges with L as the contributing parent.
1722     # This makes git rev-list --first-parent work properly.
1723     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1724         'Declare fast forward / record previous work',
1725         "[git-debrebase pseudomerge: $prose]",
1726     ];
1727     push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1728     update_head $old_head, $new_head, "stitch: $prose";
1729 }
1730
1731 sub do_stitch ($;$) {
1732     my ($prose, $unclean) = @_;
1733
1734     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1735     if (!$ffq_prev_commitish) {
1736         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1737         return;
1738     }
1739     my $dangling_head = get_head();
1740
1741     keycommits $dangling_head, $unclean,$unclean,$unclean;
1742     snags_maybe_bail();
1743
1744     stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1745 }
1746
1747 sub upstream_commitish_search ($$) {
1748     my ($upstream_version, $tried) = @_;
1749     # todo: at some point maybe use git-deborig to do this
1750     foreach my $tagpfx ('', 'v', 'upstream/') {
1751         my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1752         my $new_upstream = git_get_ref "refs/tags/$tag";
1753         push @$tried, $tag;
1754         return $new_upstream if length $new_upstream;
1755     }
1756 }
1757
1758 sub resolve_upstream_version ($$) {
1759     my ($new_upstream, $upstream_version) = @_;
1760
1761     if (!defined $new_upstream) {
1762         my @tried;
1763         $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1764         if (!length $new_upstream) {
1765             fail "Could not determine appropriate upstream commitish.\n".
1766                 " (Tried these tags: @tried)\n".
1767                 " Check version, and specify upstream commitish explicitly.";
1768         }
1769     }
1770     $new_upstream = git_rev_parse $new_upstream;
1771
1772     return $new_upstream;
1773 }
1774
1775 sub cmd_new_upstream () {
1776     # automatically and unconditionally launders before rebasing
1777     # if rebase --abort is used, laundering has still been done
1778
1779     my %pieces;
1780
1781     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1782
1783     # parse args - low commitment
1784     my $spec_version = shift @ARGV;
1785     my $new_version = (new Dpkg::Version $spec_version, check => 1);
1786     fail "bad version number \`$spec_version'" unless defined $new_version;
1787     if ($new_version->is_native()) {
1788         $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1789     }
1790
1791     my $new_upstream = shift @ARGV;
1792     my $new_upstream_version = upstreamversion  $new_version;
1793     $new_upstream =
1794         resolve_upstream_version $new_upstream, $new_upstream_version;
1795
1796     record_ffq_auto();
1797
1798     my $piece = sub {
1799         my ($n, @x) = @_; # may be ''
1800         my $pc = $pieces{$n} //= {
1801             Name => $n,
1802             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1803         };
1804         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1805         $pc;
1806     };
1807
1808     my @newpieces;
1809     my $newpiece = sub {
1810         my ($n, @x) = @_; # may be ''
1811         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1812         push @newpieces, $pc;
1813     };
1814
1815     $newpiece->('',
1816         OldIx => 0,
1817         New => $new_upstream,
1818     );
1819     while (@ARGV && $ARGV[0] !~ m{^-}) {
1820         my $n = shift @ARGV;
1821
1822         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1823             unless @ARGV && $ARGV[0] !~ m{^-};
1824
1825         my $c = git_rev_parse shift @ARGV;
1826         die unless $n =~ m/^$extra_orig_namepart_re$/;
1827         $newpiece->($n, New => $c);
1828     }
1829
1830     # now we need to investigate the branch this generates the
1831     # laundered version but we don't switch to it yet
1832     my $old_head = get_head();
1833     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1834
1835     my $old_bw_cl = classify $old_bw;
1836     my $old_anchor_cl = classify $old_anchor;
1837     my $old_upstream;
1838     if (!$old_anchor_cl->{OrigParents}) {
1839         snag 'anchor-treated',
1840             'old anchor is recognised due to --anchor, cannot check upstream';
1841     } else {
1842         $old_upstream = parsecommit
1843             $old_anchor_cl->{OrigParents}[0]{CommitId};
1844         $piece->('', Old => $old_upstream->{CommitId});
1845     }
1846
1847     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1848         if ($old_upstream->{Msg} =~
1849  m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1850            ) {
1851             my @oldpieces = (split / /, $1);
1852             my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1853             if ($old_n_parents != @oldpieces &&
1854                 $old_n_parents != @oldpieces + 1) {
1855                 snag 'upstream-confusing', sprintf
1856                     "previous upstream combine %s".
1857                     " mentions %d pieces (each implying one parent)".
1858                     " but has %d parents".
1859                     " (one per piece plus maybe a previous combine)",
1860                     $old_upstream->{CommitId},
1861                     (scalar @oldpieces),
1862                     $old_n_parents;
1863             } elsif ($oldpieces[0] ne '.') {
1864                 snag 'upstream-confusing', sprintf
1865                     "previous upstream combine %s".
1866                     " first piece is not \`.'",
1867                     $oldpieces[0];
1868             } else {
1869                 $oldpieces[0] = '';
1870                 foreach my $i (0..$#oldpieces) {
1871                     my $n = $oldpieces[$i];
1872                     my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1873                     $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1874                 }
1875             }
1876         } else {
1877             snag 'upstream-confusing',
1878                 "previous upstream $old_upstream->{CommitId} is from".
1879                " git-debrebase but not an \`upstream-combine' commit";
1880         }
1881     }
1882
1883     foreach my $pc (values %pieces) {
1884         if (!$old_upstream) {
1885             # we have complained already
1886         } elsif (!$pc->{Old}) {
1887             snag 'upstream-new-piece',
1888                 "introducing upstream piece \`$pc->{Name}'";
1889         } elsif (!$pc->{New}) {
1890             snag 'upstream-rm-piece',
1891                 "dropping upstream piece \`$pc->{Name}'";
1892         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1893             snag 'upstream-not-ff',
1894                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1895         }
1896     }
1897
1898     printdebug "%pieces = ", (dd \%pieces), "\n";
1899     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1900
1901     snags_maybe_bail();
1902
1903     my $new_bw;
1904
1905     fresh_workarea();
1906     in_workarea sub {
1907         my @upstream_merge_parents;
1908
1909         if (!any_snags()) {
1910             push @upstream_merge_parents, $old_upstream->{CommitId};
1911         }
1912
1913         foreach my $pc (@newpieces) { # always has '' first
1914             if ($pc->{Name}) {
1915                 read_tree_subdir $pc->{Name}, $pc->{New};
1916             } else {
1917                 runcmd @git, qw(read-tree), $pc->{New};
1918             }
1919             push @upstream_merge_parents, $pc->{New};
1920         }
1921
1922         # index now contains the new upstream
1923
1924         if (@newpieces > 1) {
1925             # need to make the upstream subtree merge commit
1926             $new_upstream = make_commit \@upstream_merge_parents,
1927                 [ "Combine upstreams for $new_upstream_version",
1928  ("[git-debrebase upstream-combine . ".
1929  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1930  ": new upstream]"),
1931                 ];
1932         }
1933
1934         # $new_upstream is either the single upstream commit, or the
1935         # combined commit we just made.  Either way it will be the
1936         # "upstream" parent of the anchor merge.
1937
1938         read_tree_subdir 'debian', "$old_bw:debian";
1939
1940         # index now contains the anchor merge contents
1941         $new_bw = make_commit [ $old_bw, $new_upstream ],
1942             [ "Update to upstream $new_upstream_version",
1943  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1944             ];
1945
1946         my $clogsignoff = cmdoutput qw(git show),
1947             '--pretty=format:%an <%ae>  %aD',
1948             $new_bw;
1949
1950         # Now we have to add a changelog stanza so the Debian version
1951         # is right.
1952         die if unlink "debian";
1953         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1954         unlink "debian/changelog" or $!==ENOENT or die $!;
1955         mkdir "debian" or die $!;
1956         open CN, ">", "debian/changelog" or die $!;
1957         my $oldclog = git_cat_file ":debian/changelog";
1958         $oldclog =~ m/^($package_re) \(\S+\) / or
1959             fail "cannot parse old changelog to get package name";
1960         my $p = $1;
1961         print CN <<END, $oldclog or die $!;
1962 $p ($new_version) UNRELEASED; urgency=medium
1963
1964   * Update to new upstream version $new_upstream_version.
1965
1966  -- $clogsignoff
1967
1968 END
1969         close CN or die $!;
1970         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1971
1972         # Now we have the final new breakwater branch in the index
1973         $new_bw = make_commit [ $new_bw ],
1974             [ "Update changelog for new upstream $new_upstream_version",
1975               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1976             ];
1977     };
1978
1979     # we have constructed the new breakwater. we now need to commit to
1980     # the laundering output, because git-rebase can't easily be made
1981     # to make a replay list which is based on some other branch
1982
1983     update_head_postlaunder $old_head, $old_laundered_tip,
1984         'launder for new upstream';
1985
1986     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1987     local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1988         "debrebase new-upstream $new_version: rebase";
1989     runcmd @cmd;
1990     # now it's for the user to sort out
1991 }
1992
1993 sub cmd_record_ffq_prev () {
1994     badusage "no arguments allowed" if @ARGV;
1995     my ($status, $msg) = record_ffq_prev_deferred();
1996     if ($status eq 'exists' && $opt_noop_ok) {
1997         print "Previous head already recorded\n" or die $!;
1998     } elsif ($status eq 'deferred') {
1999         run_deferred_updates 'record-ffq-prev';
2000     } else {
2001         fail "Could not preserve: $msg";
2002     }
2003 }
2004
2005 sub cmd_anchor () {
2006     badusage "no arguments allowed" if @ARGV;
2007     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2008     print "$bw\n" or die $!;
2009 }
2010
2011 sub cmd_breakwater () {
2012     badusage "no arguments allowed" if @ARGV;
2013     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2014     print "$bw\n" or die $!;
2015 }
2016
2017 sub cmd_status () {
2018     badusage "no arguments allowed" if @ARGV;
2019
2020     # todo: gdr status should print divergence info
2021     # todo: gdr status should print upstream component(s) info
2022     # todo: gdr should leave/maintain some refs with this kind of info ?
2023
2024     my $oldest = { Badness => 0 };
2025     my $newest;
2026     my $note = sub {
2027         my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2028         if ($oldest->{Badness} < $badness) {
2029             $oldest = $newest = undef;
2030         }
2031         $oldest = {
2032                    Badness => $badness,
2033                    CommitId => $cl->{CommitId},
2034                    OurMsg => $ourmsg,
2035                    KcMsg => $kcmsg,
2036                   };
2037         $newest //= $oldest;
2038     };
2039     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2040         sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2041         sub { $note->(2, 'branch is unlaundered', @_); },
2042         sub { $note->(3, 'branch needs laundering', @_); },
2043         sub { $note->(4, 'branch not in git-debrebase form', @_); };
2044
2045     my $prcommitinfo = sub {
2046         my ($cid) = @_;
2047         flush STDOUT or die $!;
2048         runcmd @git, qw(--no-pager log -n1),
2049             '--pretty=format:    %h %s%n',
2050             $cid;
2051     };
2052
2053     print "current branch contents, in git-debrebase terms:\n";
2054     if (!$oldest->{Badness}) {
2055         print "  branch is laundered\n";
2056     } else {
2057         print "  $oldest->{OurMsg}\n";
2058         my $printed = '';
2059         foreach my $info ($oldest, $newest) {
2060             my $cid = $info->{CommitId};
2061             next if $cid eq $printed;
2062             $printed = $cid;
2063             print "  $info->{KcMsg}\n";
2064             $prcommitinfo->($cid);
2065         }
2066     }
2067
2068     my $prab = sub {
2069         my ($cid, $what) = @_;
2070         if (!defined $cid) {
2071             print "  $what is not well-defined\n";
2072         } else {
2073             print "  $what\n";
2074             $prcommitinfo->($cid);
2075         }
2076     };
2077     print "key git-debrebase commits:\n";
2078     $prab->($anchor, 'anchor');
2079     $prab->($bw, 'breakwater');
2080
2081     my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2082         ffq_prev_branchinfo();
2083
2084     print "branch and ref status, in git-debrebase terms:\n";
2085     if ($ffq_msg) {
2086         print "  $ffq_msg\n";
2087     } else {
2088         $ffq_prev = git_get_ref $ffq_prev;
2089         $gdrlast = git_get_ref $gdrlast;
2090         if ($ffq_prev) {
2091             print "  unstitched; previous tip was:\n";
2092             $prcommitinfo->($ffq_prev);
2093         } elsif (!$gdrlast) {
2094             print "  stitched? (no record of git-debrebase work)\n";
2095         } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2096             print "  stitched\n";
2097         } else {
2098             print "  not git-debrebase (diverged since last stitch)\n"
2099         }
2100     }
2101     print "you are currently rebasing\n" if currently_rebasing();
2102 }
2103
2104 sub cmd_stitch () {
2105     my $prose = 'stitch';
2106     getoptions("stitch",
2107                'prose=s', \$prose);
2108     badusage "no arguments allowed" if @ARGV;
2109     do_stitch $prose, 0;
2110 }
2111 sub cmd_prepush () { cmd_stitch(); }
2112
2113 sub cmd_quick () {
2114     badusage "no arguments allowed" if @ARGV;
2115     do_launder_head 'launder for git-debrebase quick';
2116     do_stitch 'quick';
2117 }
2118
2119 sub cmd_conclude () {
2120     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2121     if (!$ffq_prev_commitish) {
2122         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2123         return;
2124     }
2125     my $dangling_head = get_head();
2126     
2127     badusage "no arguments allowed" if @ARGV;
2128     do_launder_head 'launder for git-debrebase quick';
2129     do_stitch 'quick';
2130 }
2131
2132 sub cmd_scrap () {
2133     if (currently_rebasing()) {
2134         runcmd @git, qw(rebase --abort);
2135     }
2136     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2137     if (!$ffq_prev_commitish) {
2138         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2139         finish 0;
2140     }
2141     my $scrapping_head = get_head();
2142     badusage "no arguments allowed" if @ARGV;
2143     push @deferred_updates,
2144         "update $gdrlast $ffq_prev_commitish $git_null_obj",
2145         "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2146     snags_maybe_bail();
2147     update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2148 }
2149
2150 sub make_patches_staged ($) {
2151     my ($head) = @_;
2152     # Produces the patches that would result from $head if it were
2153     # laundered.
2154     my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2155     fresh_workarea();
2156     in_workarea sub {
2157         gbp_pq_export 'bw', $secret_bw, $secret_head;
2158     };
2159 }
2160
2161 sub make_patches ($) {
2162     my ($head) = @_;
2163     keycommits $head, 0, \&snag;
2164     make_patches_staged $head;
2165     my $out;
2166     in_workarea sub {
2167         my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2168         runcmd @git, qw(read-tree), $head;
2169         read_tree_subdir 'debian/patches', $ptree;
2170         $out = make_commit [$head], [
2171             'Commit patch queue (exported by git-debrebase)',
2172             '[git-debrebase: export and commit patches]',
2173         ];
2174     };
2175     return $out;
2176 }
2177
2178 sub cmd_make_patches () {
2179     my $opt_quiet_would_amend;
2180     getoptions("make-patches",
2181                'quiet-would-amend!', \$opt_quiet_would_amend);
2182     badusage "no arguments allowed" if @ARGV;
2183     bail_if_rebasing();
2184     my $old_head = get_head();
2185     my $new = make_patches $old_head;
2186     my $d = get_differs $old_head, $new;
2187     if ($d == 0) {
2188         fail "No (more) patches to export." unless $opt_noop_ok;
2189         return;
2190     } elsif ($d == D_PAT_ADD) {
2191         snags_maybe_bail();
2192         update_head_checkout $old_head, $new, 'make-patches';
2193     } else {
2194         print STDERR failmsg
2195             "Patch export produced patch amendments".
2196             " (abandoned output commit $new).".
2197             "  Try laundering first."
2198             unless $opt_quiet_would_amend;
2199         finish 7;
2200     }
2201 }
2202
2203 sub cmd_convert_from_gbp () {
2204     badusage "want only 1 optional argument, the upstream git commitish"
2205         unless @ARGV<=1;
2206
2207     my $clogp = parsechangelog();
2208     my $version = $clogp->{'Version'}
2209         // die "missing Version from changelog";
2210
2211     my ($upstream_spec) = @ARGV;
2212
2213     my $upstream_version = upstreamversion $version;
2214     my $upstream =
2215         resolve_upstream_version($upstream_spec, $upstream_version);
2216
2217     my $old_head = get_head();
2218
2219     my $upsdiff = get_differs $upstream, $old_head;
2220     if ($upsdiff & D_UPS) {
2221         runcmd @git, qw(--no-pager diff --stat),
2222             $upstream, $old_head,
2223             qw( -- :!/debian :/);
2224         fail <<END;
2225 upstream ($upstream_spec) and HEAD are not
2226 identical in upstream files.  See diffstat above, or run
2227   git diff $upstream_spec HEAD -- :!/debian :/
2228 END
2229     }
2230
2231     if (!is_fast_fwd $upstream, $old_head) {
2232         snag 'upstream-not-ancestor',
2233             "upstream ($upstream) is not an ancestor of HEAD";
2234     } else {
2235         my $wrong = cmdoutput
2236             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2237              qw(-- :/ :!/debian));
2238         if (length $wrong) {
2239             snag 'unexpected-upstream-changes',
2240                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2241             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2242         }
2243     }
2244
2245     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2246         snag 'upstream-has-debian',
2247             "upstream ($upstream) contains debian/ directory";
2248     }
2249
2250     my $previous_dgit_view = eval {
2251         my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2252         my ($lvsn, $suite);
2253         parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2254             my ($stz, $desc) = @_;
2255             no warnings qw(exiting);
2256             printdebug 'CHANGELOG ', Dumper($desc, $stz);
2257             next unless $stz->{Date};
2258             next unless $stz->{Distribution} ne 'UNRELEASED';
2259             $lvsn = $stz->{Version};
2260             $suite = $stz->{Distribution};
2261             last;
2262         };
2263         die "neither of the first two changelog entries are released\n"
2264             unless defined $lvsn;
2265         print "last finished-looking changelog entry: ($lvsn) $suite\n";
2266         my $mtag_pat = debiantag_maintview $lvsn, '*';
2267         my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2268             $mtag_pat;
2269         die "could not find suitable maintainer view tag $mtag_pat\n"
2270             unless $mtag_pat =~ m{/};
2271         is_fast_fwd $mtag, 'HEAD' or
2272             die "HEAD is not FF from maintainer tag $mtag!";
2273         my $dtag = "archive/$mtag";
2274         is_fast_fwd $mtag, $dtag or
2275             die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2276         print "will stitch in dgit view, $dtag\n";
2277         git_rev_parse $dtag;
2278     };
2279     if (!$previous_dgit_view) {
2280         $@ =~ s/^\n+//;
2281         chomp $@;
2282         print STDERR "cannot stitch in dgit view: $@\n";
2283     }
2284
2285     snags_maybe_bail_early();
2286
2287     my $work;
2288
2289     fresh_workarea();
2290     in_workarea sub {
2291         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2292         # make a branch out of the patch queue - we'll want this in a mo
2293         runcmd qw(gbp pq import);
2294         # strip the patches out
2295         runcmd @git, qw(checkout -q gdr-internal~0);
2296         rm_subdir_cached 'debian/patches';
2297         $work = make_commit ['HEAD'], [
2298  'git-debrebase convert-from-gbp: drop patches from tree',
2299  'Delete debian/patches, as part of converting to git-debrebase format.',
2300  '[git-debrebase convert-from-gbp: drop patches from tree]'
2301                               ];
2302         # make the anchor merge
2303         # the tree is already exactly right
2304         $work = make_commit [$work, $upstream], [
2305  'git-debrebase import: declare upstream',
2306  'First breakwater merge.',
2307  '[git-debrebase anchor: declare upstream]'
2308                               ];
2309
2310         # rebase the patch queue onto the new breakwater
2311         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2312         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2313         $work = git_rev_parse 'HEAD';
2314
2315         if ($previous_dgit_view) {
2316             $work = make_commit [$work, $previous_dgit_view], [
2317  'git-debrebase import: declare ff from dgit archive view',
2318  '[git-debrebase pseudomerge: import-from-gbp]',
2319             ];
2320         }
2321     };
2322
2323     ffq_check $work;
2324     snags_maybe_bail();
2325     update_head_checkout $old_head, $work, 'convert-from-gbp';
2326 }
2327
2328 sub cmd_convert_to_gbp () {
2329     badusage "no arguments allowed" if @ARGV;
2330     my $head = get_head();
2331     my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2332     keycommits $head, 0;
2333     my $out;
2334     make_patches_staged $head;
2335     in_workarea sub {
2336         $out = make_commit ['HEAD'], [
2337             'Commit patch queue (converted from git-debrebase format)',
2338             '[git-debrebase convert-to-gbp: commit patches]',
2339         ];
2340     };
2341     if (defined $ffq) {
2342         push @deferred_updates, "delete $ffq";
2343         push @deferred_updates, "delete $gdrlast";
2344     }
2345     snags_maybe_bail();
2346     update_head_checkout $head, $out, "convert to gbp (v0)";
2347     print <<END or die $!;
2348 git-debrebase: converted to git-buildpackage branch format
2349 git-debrebase: WARNING: do not now run "git-debrebase" any more
2350 git-debrebase: WARNING: doing so would drop all upstream patches!
2351 END
2352 }
2353
2354 sub cmd_convert_from_dgit_view () { 
2355     my $clogp = parsechangelog();
2356
2357     my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2358     my $do_origs = 1;
2359     my $do_tags = 1;
2360     my $always = 0;
2361     my $diagnose = 0;
2362
2363     getoptions("convert-from-dgit-view",
2364                'diagnose!', \$diagnose,
2365                'build-products-dir:s', \$bpd,
2366                'origs!', \$do_origs,
2367                'tags!', \$do_tags,
2368                'always-convert-anyway!', \$always);
2369     fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2370
2371     my @upstreams;
2372
2373     if (@ARGV) {
2374         my $spec = shift @ARGV;
2375         my $commit = git_rev_parse "$spec^{commit}";
2376         push @upstreams, { Commit => $commit,
2377                            Source => "$ARGV[0], from command line",
2378                            Only => 1,
2379                          };
2380     }
2381
2382     my $head = get_head();
2383
2384     if (!$always) {
2385         my $troubles = 0;
2386         my $trouble = sub { $troubles++; };
2387         keycommits $head, sub{}, sub{}, $trouble, $trouble;
2388         printdebug "troubles=$troubles\n";
2389         if (!$troubles) {
2390             print STDERR <<END;
2391 $us: Branch already seems to be in git-debrebase format!
2392 $us: --always-convert-anyway would do the conversion operation anyway
2393 $us: but is probably a bad idea.  Probably, you wanted to do nothing.
2394 END
2395             fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2396             finish 0;
2397         }
2398     }
2399
2400     snags_maybe_bail_early();
2401
2402     my $version = upstreamversion $clogp->{Version};
2403     print STDERR "Considering possible commits corresponding to upstream:\n";
2404
2405     if (!@upstreams) {
2406         if ($do_tags) {
2407             my @tried;
2408             my $ups_tag = upstream_commitish_search $version, \@tried;
2409             if ($ups_tag) {
2410                 my $this = "git tag $tried[-1]";
2411                 push @upstreams, { Commit => $ups_tag,
2412                                    Source => $this,
2413                                  };
2414             } else {
2415                 printf STDERR
2416                     " git tag: no suitable tag found (tried %s)\n",
2417                     "@tried";
2418             }
2419         }
2420         if ($do_origs) {
2421             my $p = $clogp->{'Source'};
2422             # we do a quick check to see if there are plausible origs
2423             my $something=0;
2424             if (!opendir BPD, $bpd) {
2425                 die "$bpd: opendir: $!" unless $!==ENOENT;
2426             } else {
2427                 while ($!=0, my $f = readdir BPD) {
2428                     next unless is_orig_file_of_p_v $f, $p, $version;
2429                     printf STDERR
2430                         " orig: found what looks like a .orig, %s\n",
2431                         "$bpd/$f";
2432                     $something=1;
2433                     last;
2434                 }
2435                 die "read $bpd: $!" if $!;
2436                 closedir BPD;
2437             }
2438             if ($something) {
2439                 my $tree = cmdoutput
2440                     @dgit, qw(--build-products-dir), $bpd,
2441                     qw(print-unapplied-treeish);
2442                 fresh_workarea();
2443                 in_workarea sub {
2444                     runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2445                     rm_subdir_cached 'debian';
2446                     $tree = cmdoutput @git, qw(write-tree);
2447                     my $ups_synth = make_commit [], [ <<END, <<END,
2448 Import effective orig tree for upstream version $version
2449 END
2450 This includes the contents of the .orig(s), minus any debian/ directory.
2451
2452 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2453 END
2454                                                     ];
2455                     push @upstreams, { Commit => $ups_synth,
2456                                        Source => "orig(s) imported via dgit",
2457                                      };
2458                 }
2459             } else {
2460                 printf STDERR
2461                     " orig: no suitable origs found (looked for %s in %s)\n",
2462                     "${p}_".(stripeoch $version)."...", $bpd;
2463             }
2464         }
2465     }
2466
2467     my $some_patches = stat_exists 'debian/patches/series';
2468
2469     print STDERR "Evaluating possible commits corresponding to upstream:\n";
2470
2471     my $result;
2472     foreach my $u (@upstreams) {
2473         my $work = $head;
2474         fresh_workarea();
2475         in_workarea sub {
2476             runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2477             runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2478             runcmd @git, qw(clean -xdff);
2479             runcmd @git, qw(checkout), $head, qw(-- debian);
2480             if ($some_patches) {
2481                 rm_subdir_cached 'debian/patches';
2482                 $work = make_commit [ $work ], [
2483  'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2484  "Drop upstream changes, and delete debian/patches, as part of converting\n".
2485  "to git-debrebase format.  Upstream changes will appear as commits.",
2486  '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2487                                            ];
2488             }
2489             $work = make_commit [ $work, $u->{Commit} ], [
2490  'git-debrebase convert-from-dgit-view: declare upstream',
2491  '(Re)constructed breakwater merge.',
2492  '[git-debrebase anchor: declare upstream]'
2493                                                          ];
2494             runcmd @git, qw(checkout --quiet -b mk), $work;
2495             if ($some_patches) {
2496                 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2497                 runcmd @git, qw(reset --quiet);
2498                 my @gbp_cmd = (qw(gbp pq import));
2499                 if (!$diagnose) {
2500                     my $gbp_err = "../gbp-pq-err";
2501                     @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2502                 }
2503                 my $r = system @gbp_cmd;
2504                 if ($r) {
2505                     printf STDERR
2506                         " %s: couldn't apply patches: gbp pq %s",
2507                         $u->{Source}, waitstatusmsg();
2508                     return;
2509                 }
2510             }
2511             my $work = git_rev_parse qw(HEAD);
2512             my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2513             if (length $diffout) {
2514                 print STDERR
2515                     " $u->{Source}: applying patches gives different tree\n";
2516                 print STDERR $diffout if $diagnose;
2517                 return;
2518             }
2519             # OMG!
2520             $u->{Result} = $work;
2521             $result = $u;
2522         };
2523         last if $result;
2524     }
2525
2526     if (!$result) {
2527         fail <<END;
2528 Could not find or construct a suitable upstream commit.
2529 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2530 upstream commmit explicitly or provide suitable origs.
2531 END
2532     }
2533
2534     printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2535
2536     ffq_check $result->{Result};
2537     snags_maybe_bail();
2538     update_head_checkout $head, $result->{Result},
2539         'convert-from-dgit-view';
2540 }
2541
2542 sub cmd_downstream_rebase_launder_v0 () {
2543     badusage "needs 1 argument, the baseline" unless @ARGV==1;
2544     my ($base) = @ARGV;
2545     $base = git_rev_parse $base;
2546     my $old_head = get_head();
2547     my $current = $old_head;
2548     my $topmost_keep;
2549     for (;;) {
2550         if ($current eq $base) {
2551             $topmost_keep //= $current;
2552             print " $current BASE stop\n";
2553             last;
2554         }
2555         my $cl = classify $current;
2556         print " $current $cl->{Type}";
2557         my $keep = 0;
2558         my $p0 = $cl->{Parents}[0]{CommitId};
2559         my $next;
2560         if ($cl->{Type} eq 'Pseudomerge') {
2561             print " ^".($cl->{Contributor}{Ix}+1);
2562             $next = $cl->{Contributor}{CommitId};
2563         } elsif ($cl->{Type} eq 'AddPatches' or
2564                  $cl->{Type} eq 'Changelog') {
2565             print " strip";
2566             $next = $p0;
2567         } else {
2568             print " keep";
2569             $next = $p0;
2570             $keep = 1;
2571         }
2572         print "\n";
2573         if ($keep) {
2574             $topmost_keep //= $current;
2575         } else {
2576             die "to-be stripped changes not on top of the branch\n"
2577                 if $topmost_keep;
2578         }
2579         $current = $next;
2580     }
2581     if ($topmost_keep eq $old_head) {
2582         print "unchanged\n";
2583     } else {
2584         print "updating to $topmost_keep\n";
2585         update_head_checkout
2586             $old_head, $topmost_keep,
2587             'downstream-rebase-launder-v0';
2588     }
2589 }
2590
2591 getoptions_main
2592           ("bad options\n",
2593            "D+" => \$debuglevel,
2594            'noop-ok', => \$opt_noop_ok,
2595            'f=s' => \@snag_force_opts,
2596            'anchor=s' => \@opt_anchors,
2597            '--dgit=s' => \($dgit[0]),
2598            'force!',
2599            '-i:s' => sub {
2600                my ($opt,$val) = @_;
2601                badusage "git-debrebase: no cuddling to -i for git-rebase"
2602                    if length $val;
2603                die if $opt_defaultcmd_interactive; # should not happen
2604                $opt_defaultcmd_interactive = [ qw(-i) ];
2605                # This access to @ARGV is excessive familiarity with
2606                # Getopt::Long, but there isn't another sensible
2607                # approach.  '-i=s{0,}' does not work with bundling.
2608                push @$opt_defaultcmd_interactive, @ARGV;
2609                @ARGV=();
2610            },
2611            'help' => sub { print $usage_message or die $!; finish 0; },
2612            );
2613
2614 initdebug('git-debrebase ');
2615 enabledebug if $debuglevel;
2616
2617 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2618 chdir $toplevel or die "chdir $toplevel: $!";
2619
2620 $rd = fresh_playground "$playprefix/misc";
2621
2622 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2623
2624 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2625     defaultcmd_rebase();
2626 } else {
2627     my $cmd = shift @ARGV;
2628     my $cmdfn = $cmd;
2629     $cmdfn =~ y/-/_/;
2630     $cmdfn = ${*::}{"cmd_$cmdfn"};
2631
2632     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
2633     $cmdfn->();
2634 }
2635
2636 finish 0;