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