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