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