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