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