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