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