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