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