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