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