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