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