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