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