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