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