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