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