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