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