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