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