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