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