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