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