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