chiark / gitweb /
git-debrebase: Improve error message for convert-from-gbp upstream discrepancy
[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 our ($opt_force, $opt_noop_ok, @opt_anchors);
40 our ($opt_defaultcmd_interactive);
41
42 our $us = qw(git-debrebase);
43
44 $|=1;
45
46 sub badusage ($) {
47     my ($m) = @_;
48     print STDERR "$us: bad usage: $m\n";
49     finish 8;
50 }
51
52 sub getoptions {
53     my $m = shift;
54     local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
55     GetOptions @_ or badusage $m;
56 }
57
58 sub cfg ($;$) {
59     my ($k, $optional) = @_;
60     local $/ = "\0";
61     my @cmd = qw(git config -z);
62     push @cmd, qw(--get-all) if wantarray;
63     push @cmd, $k;
64     my $out = cmdoutput_errok @cmd;
65     if (!defined $out) {
66         fail "missing required git config $k" unless $optional;
67         return ();
68     }
69     my @l = split /\0/, $out;
70     return wantarray ? @l : $l[0];
71 }
72
73 memoize('cfg');
74
75 sub dd ($) {
76     my ($v) = @_;
77     my $dd = new Data::Dumper [ $v ];
78     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
79     return Dump $dd;
80 }
81
82 sub get_commit ($) {
83     my ($objid) = @_;
84     my $data = (git_cat_file $objid, 'commit');
85     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
86     return ($`,$');
87 }
88
89 sub D_UPS ()      { 0x02; } # upstream files
90 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
91 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
92 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
93 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
94 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
95
96 our $playprefix = 'debrebase';
97 our $rd;
98 our $workarea;
99
100 our @git = qw(git);
101
102 sub in_workarea ($) {
103     my ($sub) = @_;
104     changedir $workarea;
105     my $r = eval { $sub->(); };
106     { local $@; changedir $maindir; }
107     die $@ if $@;
108 }
109
110 sub fresh_workarea () {
111     $workarea = fresh_playground "$playprefix/work";
112     in_workarea sub { playtree_setup };
113 }
114
115 our $snags_forced = 0;
116 our $snags_tripped = 0;
117 our $snags_summarised = 0;
118 our @deferred_updates;
119 our @deferred_update_messages;
120
121 sub all_snags_summarised () {
122     $snags_forced + $snags_tripped == $snags_summarised;
123 }
124 sub run_deferred_updates ($) {
125     my ($mrest) = @_;
126
127     confess 'dangerous internal error' unless all_snags_summarised();
128
129     my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
130     debugcmd '>|', @upd_cmd;
131     open U, "|-", @upd_cmd or die $!;
132     foreach (@deferred_updates) {
133         printdebug ">= ", $_, "\n";
134         print U $_, "\n" or die $!;
135     }
136     printdebug ">\$\n";
137     close U or failedcmd @upd_cmd;
138
139     print $_, "\n" foreach @deferred_update_messages;
140
141     @deferred_updates = ();
142     @deferred_update_messages = ();
143 }
144
145 sub get_differs ($$) {
146     my ($x,$y) = @_;
147     # This resembles quiltify_trees_differ, in dgit, a bit.
148     # But we don't care about modes, or dpkg-source-unrepresentable
149     # changes, and we don't need the plethora of different modes.
150     # Conversely we need to distinguish different kinds of changes to
151     # debian/ and debian/patches/.
152
153     my $differs = 0;
154
155     my $rundiff = sub {
156         my ($opts, $limits, $fn) = @_;
157         my @cmd = (@git, qw(diff-tree -z --no-renames));
158         push @cmd, @$opts;
159         push @cmd, "$_:" foreach $x, $y;
160         push @cmd, '--', @$limits;
161         my $diffs = cmdoutput @cmd;
162         foreach (split /\0/, $diffs) { $fn->(); }
163     };
164
165     $rundiff->([qw(--name-only)], [], sub {
166         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
167     });
168
169     if ($differs & DS_DEB) {
170         $differs &= ~DS_DEB;
171         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
172             $differs |=
173                 m{^debian/patches/}      ? D_PAT_OTH  :
174                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
175                                            D_DEB_OTH;
176         });
177         die "mysterious debian changes $x..$y"
178             unless $differs & (D_PAT_OTH|DS_DEB);
179     }
180
181     if ($differs & D_PAT_OTH) {
182         my $mode;
183         $differs &= ~D_PAT_OTH;
184         my $pat_oth = sub {
185             $differs |= D_PAT_OTH;
186             no warnings qw(exiting);  last;
187         };
188         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
189             no warnings qw(exiting);
190             if (!defined $mode) {
191                 $mode = $_;  next;
192             }
193             die unless s{^debian/patches/}{};
194             my $ok;
195             if ($mode eq 'A' && !m/\.series$/s) {
196                 $ok = 1;
197             } elsif ($mode eq 'M' && $_ eq 'series') {
198                 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
199                 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
200                 chomp $x_s;  $x_s .= "\n";
201                 $ok = $x_s eq substr($y_s, 0, length $x_s);
202             } else {
203                 # nope
204             }
205             $mode = undef;
206             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
207         });
208         die "mysterious debian/patches changes $x..$y"
209             unless $differs & (D_PAT_ADD|D_PAT_OTH);
210     }
211
212     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
213
214     return $differs;
215 }
216
217 sub commit_pr_info ($) {
218     my ($r) = @_;
219     return Data::Dumper->dump([$r], [qw(commit)]);
220 }
221
222 sub calculate_committer_authline () {
223     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
224         'DUMMY COMMIT (git-debrebase)', "HEAD:";
225     my ($h,$m) = get_commit $c;
226     $h =~ m/^committer .*$/m or confess "($h) ?";
227     return $&;
228 }
229
230 sub rm_subdir_cached ($) {
231     my ($subdir) = @_;
232     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
233 }
234
235 sub read_tree_subdir ($$) {
236     my ($subdir, $new_tree_object) = @_;
237     rm_subdir_cached $subdir;
238     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
239 }
240
241 sub make_commit ($$) {
242     my ($parents, $message_paras) = @_;
243     my $tree = cmdoutput @git, qw(write-tree);
244     my @cmd = (@git, qw(commit-tree), $tree);
245     push @cmd, qw(-p), $_ foreach @$parents;
246     push @cmd, qw(-m), $_ foreach @$message_paras;
247     return cmdoutput @cmd;
248 }
249
250 our @snag_force_opts;
251 sub snag ($$;@) {
252     my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
253     if (grep { $_ eq $tag } @snag_force_opts) {
254         $snags_forced++;
255         print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
256     } else {
257         $snags_tripped++;
258         print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
259     }
260 }
261
262 # Important: all mainline code must call snags_maybe_bail after
263 # any point where snag might be called, but before making changes
264 # (eg before any call to run_deferred_updates).  snags_maybe_bail
265 # may be called more than once if necessary (but this is not ideal
266 # because then the messages about number of snags may be confusing).
267 sub snags_maybe_bail () {
268     return if all_snags_summarised();
269     if ($snags_forced) {
270         printf STDERR
271             "%s: snags: %d overriden by individual -f options\n",
272             $us, $snags_forced;
273     }
274     if ($snags_tripped) {
275         if ($opt_force) {
276             printf STDERR
277                 "%s: snags: %d overriden by global --force\n",
278                 $us, $snags_tripped;
279         } else {
280             fail sprintf
281   "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
282                 $us, $snags_tripped;
283         }
284     }
285     $snags_summarised = $snags_forced + $snags_tripped;
286 }
287 sub snags_maybe_bail_early () {
288     # useful to bail out early without doing a lot of work;
289     # not a substitute for snags_maybe_bail.
290     snags_maybe_bail() if $snags_tripped && !$opt_force;
291 }
292 sub any_snags () {
293     return $snags_forced || $snags_tripped;
294 }
295
296 # classify returns an info hash like this
297 #   CommitId => $objid
298 #   Hdr => # commit headers, including 1 final newline
299 #   Msg => # commit message (so one newline is dropped)
300 #   Tree => $treeobjid
301 #   Type => (see below)
302 #   Parents = [ {
303 #       Ix => $index # ie 0, 1, 2, ...
304 #       CommitId
305 #       Differs => return value from get_differs
306 #       IsOrigin
307 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
308 #     } ...]
309 #   NewMsg => # commit message, but with any [dgit import ...] edited
310 #             # to say "[was: ...]"
311 #
312 # Types:
313 #   Packaging
314 #   Changelog
315 #   Upstream
316 #   AddPatches
317 #   Mixed
318 #
319 #   Pseudomerge
320 #     has additional entres in classification result
321 #       Overwritten = [ subset of Parents ]
322 #       Contributor = $the_remaining_Parent
323 #
324 #   DgitImportUnpatched
325 #     has additional entry in classification result
326 #       OrigParents = [ subset of Parents ]
327 #
328 #   Anchor
329 #     has additional entry in classification result
330 #       OrigParents = [ subset of Parents ]  # singleton list
331 #
332 #   TreatAsAnchor
333 #
334 #   BreakwaterStart
335 #
336 #   Unknown
337 #     has additional entry in classification result
338 #       Why => "prose"
339
340 sub parsecommit ($;$) {
341     my ($objid, $p_ref) = @_;
342     # => hash with                   CommitId Hdr Msg Tree Parents
343     #    Parents entries have only   Ix CommitId
344     #    $p_ref, if provided, must be [] and is used as a base for Parents
345
346     $p_ref //= [];
347     die if @$p_ref;
348
349     my ($h,$m) = get_commit $objid;
350
351     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
352     my (@ph) = $h =~ m/^parent (\w+)$/mg;
353
354     my $r = {
355         CommitId => $objid,
356         Hdr => $h,
357         Msg => $m,
358         Tree => $t,
359         Parents => $p_ref,
360     };
361
362     foreach my $ph (@ph) {
363         push @$p_ref, {
364             Ix => scalar @$p_ref,
365             CommitId => $ph,
366         };
367     }
368
369     return $r;
370 }    
371
372 sub classify ($) {
373     my ($objid) = @_;
374
375     my @p;
376     my $r = parsecommit($objid, \@p);
377     my $t = $r->{Tree};
378
379     foreach my $p (@p) {
380         $p->{Differs} = (get_differs $p->{CommitId}, $t),
381     }
382
383     printdebug "classify $objid \$t=$t \@p",
384         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
385         "\n";
386
387     my $classify = sub {
388         my ($type, @rest) = @_;
389         $r = { %$r, Type => $type, @rest };
390         if ($debuglevel) {
391             printdebug " = $type ".(dd $r)."\n";
392         }
393         return $r;
394     };
395     my $unknown = sub {
396         my ($why) = @_;
397         $r = { %$r, Type => qw(Unknown), Why => $why };
398         printdebug " ** Unknown\n";
399         return $r;
400     };
401
402     if (grep { $_ eq $objid } @opt_anchors) {
403         return $classify->('TreatAsAnchor');
404     }
405
406     my @identical = grep { !$_->{Differs} } @p;
407     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
408     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
409
410     if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
411         # multi-orig upstreams are represented with an anchor merge
412         # from a single upstream commit which combines the orig tarballs
413
414         # Every anchor tagged this way must be a merge.
415         # We are relying on the
416         #     [git-debrebase anchor: ...]
417         # commit message annotation in "declare" anchor merges (which
418         # do not have any upstream changes), to distinguish those
419         # anchor merges from ordinary pseudomerges (which we might
420         # just try to strip).
421         #
422         # However, the user is going to be doing git-rebase a lot.  We
423         # really don't want them to rewrite an anchor commit.
424         # git-rebase trips up on merges, so that is a useful safety
425         # catch.
426         #
427         # BreakwaterStart commits are also anchors in the terminology
428         # of git-debrebase(5), but they are untagged (and always
429         # manually generated).
430         #
431         # We cannot not tolerate any tagged linear commit (ie,
432         # BreakwaterStart commits tagged `[anchor:') because such a
433         # thing could result from an erroneous linearising raw git
434         # rebase of a merge anchor.  That would represent a corruption
435         # of the branch. and we want to detect and reject the results
436         # of such corruption before it makes it out anywhere.  If we
437         # reject it here then we avoid making the pseudomerge which
438         # would be needed to push it.
439
440         my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
441         @p == 2 or return $badanchor->("has other than two parents");
442         $haspatches and return $badanchor->("contains debian/patches");
443
444         # How to decide about l/r ordering of anchors ?  git
445         # --topo-order prefers to expand 2nd parent first.  There's
446         # already an easy rune to look for debian/ history anyway (git log
447         # debian/) so debian breakwater branch should be 1st parent; that
448         # way also there's also an easy rune to look for the upstream
449         # patches (--topo-order).
450
451         # Also this makes --first-parent be slightly more likely to
452         # be useful - it makes it provide a linearised breakwater history.
453
454         # Of course one can say somthing like
455         #  gitk -- ':/' ':!/debian'
456         # to get _just_ the commits touching upstream files, and by
457         # the TREESAME logic in git-rev-list this will leave the
458         # breakwater into upstream at the first anchor.  But that
459         # doesn't report debian/ changes at all.
460
461         # Other observations about gitk: by default, gitk seems to
462         # produce output in a different order to git-rev-list.  I
463         # can't seem to find this documented anywhere.  gitk
464         # --date-order DTRT.  But, gitk always seems to put the
465         # parents from left to right, in order, so it's easy to see
466         # which way round a pseudomerge is.
467
468         $p[0]{IsOrigin} and $badanchor->("is an origin commit");
469         $p[1]{Differs} & ~DS_DEB and
470             $badanchor->("upstream files differ from left parent");
471         $p[0]{Differs} & ~D_UPS and
472             $badanchor->("debian/ differs from right parent");
473
474         return $classify->(qw(Anchor),
475                            OrigParents => [ $p[1] ]);
476     }
477
478     if (@p == 1) {
479         my $d = $r->{Parents}[0]{Differs};
480         if ($d == D_PAT_ADD) {
481             return $classify->(qw(AddPatches));
482         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
483             return $unknown->("edits debian/patches");
484         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
485             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
486             if ($ty eq 'tree') {
487                 if ($d == D_DEB_CLOG) {
488                     return $classify->(qw(Changelog));
489                 } else {
490                     return $classify->(qw(Packaging));
491                 }
492             } elsif ($ty eq 'missing') {
493                 return $classify->(qw(BreakwaterStart));
494             } else {
495                 return $unknown->("parent's debian is not a directory");
496             }
497         } elsif ($d == D_UPS) {
498             return $classify->(qw(Upstream));
499         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
500             return $classify->(qw(Mixed));
501         } elsif ($d == 0) {
502             return $unknown->("no changes");
503         } else {
504             confess "internal error $objid ?";
505         }
506     }
507     if (!@p) {
508         return $unknown->("origin commit");
509     }
510
511     if (@p == 2 && @identical == 1) {
512         my @overwritten = grep { $_->{Differs} } @p;
513         confess "internal error $objid ?" unless @overwritten==1;
514         return $classify->(qw(Pseudomerge),
515                            Overwritten => [ $overwritten[0] ],
516                            Contributor => $identical[0]);
517     }
518     if (@p == 2 && @identical == 2) {
519         my $get_t = sub {
520             my ($ph,$pm) = get_commit $_[0]{CommitId};
521             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
522             $1;
523         };
524         my @bytime = @p;
525         my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
526         if ($order > 0) { # newer first
527         } elsif ($order < 0) {
528             @bytime = reverse @bytime;
529         } else {
530             # same age, default to order made by -s ours
531             # that is, commit was made by someone who preferred L
532         }
533         return $classify->(qw(Pseudomerge),
534                            SubType => qw(Ambiguous),
535                            Contributor => $bytime[0],
536                            Overwritten => [ $bytime[1] ]);
537     }
538     foreach my $p (@p) {
539         my ($p_h, $p_m) = get_commit $p->{CommitId};
540         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
541         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
542     }
543     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
544     my $m2 = $r->{Msg};
545     if (!(grep { !$_->{IsOrigin} } @p) and
546         (@orig_ps >= @p - 1) and
547         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
548         $r->{NewMsg} = $m2;
549         return $classify->(qw(DgitImportUnpatched),
550                            OrigParents => \@orig_ps);
551     }
552
553     return $unknown->("complex merge");
554 }
555
556 sub keycommits ($;$$$$) {
557     my ($head, $furniture, $unclean, $trouble, $fatal) = @_;
558     # => ($anchor, $breakwater)
559
560     # $unclean->("unclean-$tagsfx", $msg, $cl)
561     # $furniture->("unclean-$tagsfx", $msg, $cl)
562     # $dgitimport->("unclean-$tagsfx", $msg, $cl))
563     #   is callled for each situation or commit that
564     #   wouldn't be found in a laundered branch
565     # $furniture is for furniture commits such as might be found on an
566     #   interchange branch (pseudomerge, d/patches, changelog)
567     # $trouble is for things whnich prevent the return of
568     #   anchor and breakwater information; if that is ignored,
569     #   then keycommits returns (undef, undef) instead.
570     # $fatal is for unprocessable commits, and should normally cause
571     #    a failure.  If ignored, agaion, (undef, undef) is returned.
572     #
573     # If a callback is undef, fail is called instead.
574     # If a callback is defined but false, the situation is ignored.
575     # Callbacks may say:
576     #   no warnings qw(exiting); last;
577     # if the answer is no longer wanted.
578
579     my ($anchor, $breakwater);
580     my $clogonly;
581     my $cl;
582     $fatal //= sub { fail $_[1]; };
583     my $x = sub {
584         my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
585         my $why = $mainwhy.$xwhy;
586         my $m = "branch needs laundering (run git-debrebase): $why";
587         fail $m unless defined $cb;
588         return unless $cb;
589         $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
590     };
591     for (;;) {
592         $cl = classify $head;
593         my $ty = $cl->{Type};
594         if ($ty eq 'Packaging') {
595             $breakwater //= $clogonly;
596             $breakwater //= $head;
597         } elsif ($ty eq 'Changelog') {
598             # this is going to count as the tip of the breakwater
599             # only if it has no upstream stuff before it
600             $clogonly //= $head;
601         } elsif ($ty eq 'Anchor' or
602                  $ty eq 'TreatAsAnchor' or
603                  $ty eq 'BreakwaterStart') {
604             $anchor = $head;
605             $breakwater //= $clogonly;
606             $breakwater //= $head;
607             last;
608         } elsif ($ty eq 'Upstream') {
609             $x->($unclean, 'ordering',
610  "packaging change ($breakwater) follows upstream change"," (eg $head)")
611                 if defined $breakwater;
612             $clogonly = undef;
613             $breakwater = undef;
614         } elsif ($ty eq 'Mixed') {
615             $x->($unclean, 'mixed',
616                  "found mixed upstream/packaging commit"," ($head)");
617             $clogonly = undef;
618             $breakwater = undef;
619         } elsif ($ty eq 'Pseudomerge' or
620                  $ty eq 'AddPatches') {
621             $x->($furniture, (lc $ty),
622                  "found interchange bureaucracy commit ($ty)"," ($head)");
623         } elsif ($ty eq 'DgitImportUnpatched') {
624             $x->($trouble, 'dgitimport',
625                  "found dgit dsc import ($head)");
626             return (undef,undef);
627         } else {
628             $x->($fatal, 'unprocessable',
629                  "found unprocessable commit, cannot cope: $cl->{Why}",
630                  " ($head)");
631             return (undef,undef);
632         }
633         $head = $cl->{Parents}[0]{CommitId};
634     }
635     return ($anchor, $breakwater);
636 }
637
638 sub walk ($;$$);
639 sub walk ($;$$) {
640     my ($input,
641         $nogenerate,$report) = @_;
642     # => ($tip, $breakwater_tip, $last_anchor)
643     # (or nothing, if $nogenerate)
644
645     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
646
647     # go through commits backwards
648     # we generate two lists of commits to apply:
649     # breakwater branch and upstream patches
650     my (@brw_cl, @upp_cl, @processed);
651     my %found;
652     my $upp_limit;
653     my @pseudomerges;
654
655     my $cl;
656     my $xmsg = sub {
657         my ($prose, $info) = @_;
658         my $ms = $cl->{Msg};
659         chomp $ms;
660         $info //= '';
661         $ms .= "\n\n[git-debrebase$info: $prose]\n";
662         return (Msg => $ms);
663     };
664     my $rewrite_from_here = sub {
665         my ($cl) = @_;
666         my $sp_cl = { SpecialMethod => 'StartRewrite' };
667         push @$cl, $sp_cl;
668         push @processed, $sp_cl;
669     };
670     my $cur = $input;
671
672     my $prdelim = "";
673     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
674
675     my $prline = sub {
676         return unless $report;
677         print $report $prdelim, @_;
678         $prdelim = "\n";
679     };
680
681     my $bomb = sub { # usage: return $bomb->();
682         print $report " Unprocessable" if $report;
683         print $report " ($cl->{Why})" if $report && defined $cl->{Why};
684         $prprdelim->();
685         if ($nogenerate) {
686             return (undef,undef);
687         }
688         fail "found unprocessable commit, cannot cope:".
689             (defined $cl->{Why} ? "; $cl->{Why}": '').
690             " (commit $cur) (d.".
691             (join ' ', map { sprintf "%#x", $_->{Differs} }
692              @{ $cl->{Parents} }).
693                  ")";
694     };
695
696     my $build;
697     my $breakwater;
698
699     my $build_start = sub {
700         my ($msg, $parent) = @_;
701         $prline->(" $msg");
702         $build = $parent;
703         no warnings qw(exiting); last;
704     };
705
706     my $last_anchor;
707
708     for (;;) {
709         $cl = classify $cur;
710         my $ty = $cl->{Type};
711         my $st = $cl->{SubType};
712         $prline->("$cl->{CommitId} $cl->{Type}");
713         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
714         push @processed, $cl;
715         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
716         if ($ty eq 'AddPatches') {
717             $cur = $p0;
718             $rewrite_from_here->(\@upp_cl);
719             next;
720         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
721             push @brw_cl, $cl;
722             $cur = $p0;
723             next;
724         } elsif ($ty eq 'BreakwaterStart') {
725             $last_anchor = $cur;
726             $build_start->('FirstPackaging', $cur);
727         } elsif ($ty eq 'Upstream') {
728             push @upp_cl, $cl;
729             $cur = $p0;
730             next;
731         } elsif ($ty eq 'Mixed') {
732             my $queue = sub {
733                 my ($q, $wh) = @_;
734                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
735                 push @$q, $cls;
736             };
737             $queue->(\@brw_cl, "debian");
738             $queue->(\@upp_cl, "upstream");
739             $rewrite_from_here->(\@brw_cl);
740             $cur = $p0;
741             next;
742         } elsif ($ty eq 'Pseudomerge') {
743             my $contrib = $cl->{Contributor}{CommitId};
744             print $report " Contributor=$contrib" if $report;
745             push @pseudomerges, $cl;
746             $rewrite_from_here->(\@upp_cl);
747             $cur = $contrib;
748             next;
749         } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
750             $last_anchor = $cur;
751             $build_start->("Anchor", $cur);
752         } elsif ($ty eq 'DgitImportUnpatched') {
753             my $pm = $pseudomerges[-1];
754             if (defined $pm) {
755                 # To an extent, this is heuristic.  Imports don't have
756                 # a useful history of the debian/ branch.  We assume
757                 # that the first pseudomerge after an import has a
758                 # useful history of debian/, and ignore the histories
759                 # from later pseudomerges.  Often the first pseudomerge
760                 # will be the dgit import of the upload to the actual
761                 # suite intended by the non-dgit NMUer, and later
762                 # pseudomerges may represent in-archive copies.
763                 my $ovwrs = $pm->{Overwritten};
764                 printf $report " PM=%s \@Overwr:%d",
765                     $pm->{CommitId}, (scalar @$ovwrs)
766                     if $report;
767                 if (@$ovwrs != 1) {
768                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
769                     return $bomb->();
770                 }
771                 my $ovwr = $ovwrs->[0]{CommitId};
772                 printf $report " Overwr=%s", $ovwr if $report;
773                 # This import has a tree which is just like a
774                 # breakwater tree, but it has the wrong history.  It
775                 # ought to have the previous breakwater (which the
776                 # pseudomerge overwrote) as an ancestor.  That will
777                 # make the history of the debian/ files correct.  As
778                 # for the upstream version: either it's the same as
779                 # was ovewritten (ie, same as the previous
780                 # breakwater), in which case that history is precisely
781                 # right; or, otherwise, it was a non-gitish upload of a
782                 # new upstream version.  We can tell these apart by
783                 # looking at the tree of the supposed upstream.
784                 push @brw_cl, {
785                     %$cl,
786                     SpecialMethod => 'DgitImportDebianUpdate',
787                     $xmsg->("convert dgit import: debian changes")
788                 }, {
789                     %$cl,
790                     SpecialMethod => 'DgitImportUpstreamUpdate',
791                     $xmsg->("convert dgit import: upstream update",
792                             " anchor")
793                 };
794                 $prline->(" Import");
795                 $rewrite_from_here->(\@brw_cl);
796                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
797                 $cur = $ovwr;
798                 next;
799             } else {
800                 # Everything is from this import.  This kind of import
801                 # is already in valid breakwater format, with the
802                 # patches as commits.
803                 printf $report " NoPM" if $report;
804                 # last thing we processed will have been the first patch,
805                 # if there is one; which is fine, so no need to rewrite
806                 # on account of this import
807                 $build_start->("ImportOrigin", $cur);
808             }
809             die "$ty ?";
810         } else {
811             printdebug "*** WALK BOMB unrecognised\n";
812             return $bomb->();
813         }
814     }
815     $prprdelim->();
816
817     printdebug "*** WALK prep done cur=$cur".
818         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
819
820     return if $nogenerate;
821
822     # Now we build it back up again
823
824     fresh_workarea();
825
826     my $rewriting = 0;
827
828     my $read_tree_debian = sub {
829         my ($treeish) = @_;
830         read_tree_subdir 'debian', "$treeish:debian";
831         rm_subdir_cached 'debian/patches';
832     };
833     my $read_tree_upstream = sub {
834         my ($treeish) = @_;
835         runcmd @git, qw(read-tree), $treeish;
836         $read_tree_debian->($build);
837     };
838
839     $#upp_cl = $upp_limit if defined $upp_limit;
840  
841     my $committer_authline = calculate_committer_authline();
842
843     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
844
845     confess "internal error" unless $build eq (pop @processed)->{CommitId};
846
847     in_workarea sub {
848         mkdir $rd or $!==EEXIST or die $!;
849         my $current_method;
850         runcmd @git, qw(read-tree), $build;
851         foreach my $cl (qw(Debian), (reverse @brw_cl),
852                         { SpecialMethod => 'RecordBreakwaterTip' },
853                         qw(Upstream), (reverse @upp_cl)) {
854             if (!ref $cl) {
855                 $current_method = $cl;
856                 next;
857             }
858             my $method = $cl->{SpecialMethod} // $current_method;
859             my @parents = ($build);
860             my $cltree = $cl->{CommitId};
861             printdebug "WALK BUILD ".($cltree//'undef').
862                 " $method (rewriting=$rewriting)\n";
863             if ($method eq 'Debian') {
864                 $read_tree_debian->($cltree);
865             } elsif ($method eq 'Upstream') {
866                 $read_tree_upstream->($cltree);
867             } elsif ($method eq 'StartRewrite') {
868                 $rewriting = 1;
869                 next;
870             } elsif ($method eq 'RecordBreakwaterTip') {
871                 $breakwater = $build;
872                 next;
873             } elsif ($method eq 'DgitImportDebianUpdate') {
874                 $read_tree_debian->($cltree);
875             } elsif ($method eq 'DgitImportUpstreamUpdate') {
876                 confess unless $rewriting;
877                 my $differs = (get_differs $build, $cltree);
878                 next unless $differs & D_UPS;
879                 $read_tree_upstream->($cltree);
880                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
881             } else {
882                 confess "$method ?";
883             }
884             if (!$rewriting) {
885                 my $procd = (pop @processed) // 'UNDEF';
886                 if ($cl ne $procd) {
887                     $rewriting = 1;
888                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
889                 }
890             }
891             my $newtree = cmdoutput @git, qw(write-tree);
892             my $ch = $cl->{Hdr};
893             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
894             $ch =~ s{^parent .*\n}{}mg;
895             $ch =~ s{(?=^author)}{
896                 join '', map { "parent $_\n" } @parents
897             }me or confess "$ch ?";
898             if ($rewriting) {
899                 $ch =~ s{^committer .*$}{$committer_authline}m
900                     or confess "$ch ?";
901             }
902             my $cf = "$rd/m$rewriting";
903             open CD, ">", $cf or die $!;
904             print CD $ch, "\n", $cl->{Msg} or die $!;
905             close CD or die $!;
906             my @cmd = (@git, qw(hash-object));
907             push @cmd, qw(-w) if $rewriting;
908             push @cmd, qw(-t commit), $cf;
909             my $newcommit = cmdoutput @cmd;
910             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
911             $build = $newcommit;
912             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
913                 $last_anchor = $cur;
914             }
915         }
916     };
917
918     my $final_check = get_differs $build, $input;
919     die sprintf "internal error %#x %s %s", $final_check, $build, $input
920         if $final_check & ~D_PAT_ADD;
921
922     my @r = ($build, $breakwater, $last_anchor);
923     printdebug "*** WALK RETURN @r\n";
924     return @r
925 }
926
927 sub get_head () {
928     git_check_unmodified();
929     return git_rev_parse qw(HEAD);
930 }
931
932 sub update_head ($$$) {
933     my ($old, $new, $mrest) = @_;
934     push @deferred_updates, "update HEAD $new $old";
935     run_deferred_updates $mrest;
936 }
937
938 sub update_head_checkout ($$$) {
939     my ($old, $new, $mrest) = @_;
940     update_head $old, $new, $mrest;
941     runcmd @git, qw(reset --hard);
942 }
943
944 sub update_head_postlaunder ($$$) {
945     my ($old, $tip, $reflogmsg) = @_;
946     return if $tip eq $old;
947     print "git-debrebase: laundered (head was $old)\n";
948     update_head $old, $tip, $reflogmsg;
949     # no tree changes except debian/patches
950     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
951 }
952
953 sub do_launder_head ($) {
954     my ($reflogmsg) = @_;
955     my $old = get_head();
956     record_ffq_auto();
957     my ($tip,$breakwater) = walk $old;
958     snags_maybe_bail();
959     update_head_postlaunder $old, $tip, $reflogmsg;
960     return ($tip,$breakwater);
961 }
962
963 sub cmd_launder_v0 () {
964     badusage "no arguments to launder-v0 allowed" if @ARGV;
965     my $old = get_head();
966     my ($tip,$breakwater,$last_anchor) = walk $old;
967     update_head_postlaunder $old, $tip, 'launder';
968     printf "# breakwater tip\n%s\n", $breakwater;
969     printf "# working tip\n%s\n", $tip;
970     printf "# last anchor\n%s\n", $last_anchor;
971 }
972
973 sub defaultcmd_rebase () {
974     push @ARGV, @{ $opt_defaultcmd_interactive // [] };
975     my ($tip,$breakwater) = do_launder_head 'launder for rebase';
976     runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
977 }
978
979 sub cmd_analyse () {
980     badusage "analyse does not support any options"
981         if @ARGV and $ARGV[0] =~ m/^-/;
982     badusage "too many arguments to analyse" if @ARGV>1;
983     my ($old) = @ARGV;
984     if (defined $old) {
985         $old = git_rev_parse $old;
986     } else {
987         $old = git_rev_parse 'HEAD';
988     }
989     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
990     STDOUT->error and die $!;
991 }
992
993 sub ffq_prev_branchinfo () {
994     my $current = git_get_symref();
995     return gdr_ffq_prev_branchinfo($current);
996 }
997
998 sub ffq_check ($;$$) {
999     # calls $ff and/or $notff zero or more times
1000     # then returns either (status,message) where status is
1001     #    exists
1002     #    detached
1003     #    weird-symref
1004     #    notbranch
1005     # or (undef,undef, $ffq_prev,$gdrlast)
1006     # $ff and $notff are called like this:
1007     #   $ff->("message for stdout\n");
1008     #   $notff->('snag-name', $message);
1009     # normally $currentval should be HEAD
1010     my ($currentval, $ff, $notff) =@_;
1011
1012     $ff //= sub { print $_[0] or die $!; };
1013     $notff //= \&snag;
1014
1015     my ($status, $message, $current, $ffq_prev, $gdrlast)
1016         = ffq_prev_branchinfo();
1017     return ($status, $message) unless $status eq 'branch';
1018
1019     my $exists = git_get_ref $ffq_prev;
1020     return ('exists',"$ffq_prev already exists") if $exists;
1021
1022     return ('not-branch', 'HEAD symref is not to refs/heads/')
1023         unless $current =~ m{^refs/heads/};
1024     my $branch = $';
1025
1026     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1027     my %checked;
1028
1029     printdebug "ffq check_specs @check_specs\n";
1030
1031     my $check = sub {
1032         my ($lrref, $desc) = @_;
1033         printdebug "ffq might check $lrref ($desc)\n";
1034         my $invert;
1035         for my $chk (@check_specs) {
1036             my $glob = $chk;
1037             $invert = $glob =~ s{^[!^]}{};
1038             last if fnmatch $glob, $lrref;
1039         }
1040         return if $invert;
1041         my $lrval = git_get_ref $lrref;
1042         return unless length $lrval;
1043
1044         if (is_fast_fwd $lrval, $currentval) {
1045             $ff->("OK, you are ahead of $lrref\n");
1046             $checked{$lrref} = 1;
1047         } elsif (is_fast_fwd $currentval, $lrval) {
1048             $checked{$lrref} = -1;
1049             $notff->('behind', "you are behind $lrref, divergence risk");
1050         } else {
1051             $checked{$lrref} = -1;
1052             $notff->('diverged', "you have diverged from $lrref");
1053         }
1054     };
1055
1056     my $merge = cfg "branch.$branch.merge",1;
1057     if (defined $merge and $merge =~ m{^refs/heads/}) {
1058         my $rhs = $';
1059         printdebug "ffq merge $rhs\n";
1060         my $check_remote = sub {
1061             my ($remote, $desc) = @_;
1062             printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1063             return unless defined $remote;
1064             $check->("refs/remotes/$remote/$rhs", $desc);
1065         };
1066         $check_remote->((scalar cfg "branch.$branch.remote",1),
1067                         'remote fetch/merge branch');
1068         $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1069                         (scalar cfg "branch.$branch.pushDefault",1),
1070                         'remote push branch');
1071     }
1072     if ($branch =~ m{^dgit/}) {
1073         $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1074     } elsif ($branch =~ m{^master$}) {
1075         $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1076     }
1077     return (undef, undef, $ffq_prev, $gdrlast);
1078 }
1079
1080 sub record_ffq_prev_deferred () {
1081     # => ('status', "message")
1082     # 'status' may be
1083     #    deferred          message is undef
1084     #    exists
1085     #    detached
1086     #    weird-symref
1087     #    notbranch
1088     # if not ff from some branch we should be ff from, is an snag
1089     # if "deferred", will have added something about that to
1090     #   @deferred_update_messages, and also maybe printed (already)
1091     #   some messages about ff checks
1092     my $currentval = get_head();
1093
1094     my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1095     return ($status,$message) if defined $status;
1096
1097     snags_maybe_bail();
1098
1099     push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1100     push @deferred_updates, "delete $gdrlast";
1101     push @deferred_update_messages, "Recorded current head for preservation";
1102     return ('deferred', undef);
1103 }
1104
1105 sub record_ffq_auto () {
1106     my ($status, $message) = record_ffq_prev_deferred();
1107     if ($status eq 'deferred' || $status eq 'exists') {
1108     } else {
1109         snag $status, "could not record ffq-prev: $message";
1110         snags_maybe_bail();
1111     }
1112 }
1113
1114 sub ffq_prev_info () {
1115     # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1116     my ($status, $message, $current, $ffq_prev, $gdrlast)
1117         = ffq_prev_branchinfo();
1118     if ($status ne 'branch') {
1119         snag $status, "could not check ffq-prev: $message";
1120         snags_maybe_bail();
1121     }
1122     my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1123     return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1124 }
1125
1126 sub stitch ($$$$$) {
1127     my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1128
1129     push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1130
1131     if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1132         my $differs = get_differs $old_head, $ffq_prev_commitish;
1133         unless ($differs & ~D_PAT_ADD) {
1134             # ffq-prev is ahead of us, and the only tree changes it has
1135             # are possibly addition of things in debian/patches/.
1136             # Just wind forwards rather than making a pointless pseudomerge.
1137             push @deferred_updates,
1138                 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1139             update_head_checkout $old_head, $ffq_prev_commitish,
1140                 "stitch (fast forward)";
1141             return;
1142         }
1143     }
1144     fresh_workarea();
1145     # We make pseudomerges with L as the contributing parent.
1146     # This makes git rev-list --first-parent work properly.
1147     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1148         'Declare fast forward / record previous work',
1149         "[git-debrebase pseudomerge: $prose]",
1150     ];
1151     push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1152     update_head $old_head, $new_head, "stitch: $prose";
1153 }
1154
1155 sub do_stitch ($;$) {
1156     my ($prose, $unclean) = @_;
1157
1158     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1159     if (!$ffq_prev_commitish) {
1160         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1161         return;
1162     }
1163     my $dangling_head = get_head();
1164
1165     keycommits $dangling_head, $unclean,$unclean,$unclean;
1166     snags_maybe_bail();
1167
1168     stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1169 }
1170
1171 sub resolve_upstream_version ($$) {
1172     my ($new_upstream, $version) = @_;
1173
1174     my $new_upstream_version = "$version";
1175     $new_upstream_version =~ s/-.*?$//;;
1176
1177     if (!defined $new_upstream) {
1178         my @tried;
1179         # todo: at some point maybe use git-deborig to do this
1180         foreach my $tagpfx ('', 'v', 'upstream/') {
1181             my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1182             $new_upstream = git_get_ref "refs/tags/$tag";
1183             last if length $new_upstream;
1184             push @tried, $tag;
1185         }
1186         if (!length $new_upstream) {
1187             fail "Could not determine appropriate upstream commitish.\n".
1188                 " (Tried these tags: @tried)\n".
1189                 " Check version, and specify upstream commitish explicitly.";
1190         }
1191     }
1192     $new_upstream = git_rev_parse $new_upstream;
1193
1194     return ($new_upstream, $new_upstream_version);
1195 }
1196
1197 sub cmd_new_upstream () {
1198     # automatically and unconditionally launders before rebasing
1199     # if rebase --abort is used, laundering has still been done
1200
1201     my %pieces;
1202
1203     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1204
1205     # parse args - low commitment
1206     my $spec_version = shift @ARGV;
1207     my $new_version = (new Dpkg::Version $spec_version, check => 1);
1208     fail "bad version number \`$spec_version'" unless defined $new_version;
1209     if ($new_version->is_native()) {
1210         $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1211     }
1212
1213     my $new_upstream = shift @ARGV;
1214     my $new_upstream_version;
1215     ($new_upstream, $new_upstream_version) =
1216         resolve_upstream_version $new_upstream, $new_version;
1217
1218     record_ffq_auto();
1219
1220     my $piece = sub {
1221         my ($n, @x) = @_; # may be ''
1222         my $pc = $pieces{$n} //= {
1223             Name => $n,
1224             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1225         };
1226         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1227         $pc;
1228     };
1229
1230     my @newpieces;
1231     my $newpiece = sub {
1232         my ($n, @x) = @_; # may be ''
1233         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1234         push @newpieces, $pc;
1235     };
1236
1237     $newpiece->('',
1238         OldIx => 0,
1239         New => $new_upstream,
1240     );
1241     while (@ARGV && $ARGV[0] !~ m{^-}) {
1242         my $n = shift @ARGV;
1243
1244         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1245             unless @ARGV && $ARGV[0] !~ m{^-};
1246
1247         my $c = git_rev_parse shift @ARGV;
1248         die unless $n =~ m/^$extra_orig_namepart_re$/;
1249         $newpiece->($n, New => $c);
1250     }
1251
1252     # now we need to investigate the branch this generates the
1253     # laundered version but we don't switch to it yet
1254     my $old_head = get_head();
1255     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1256
1257     my $old_bw_cl = classify $old_bw;
1258     my $old_anchor_cl = classify $old_anchor;
1259     my $old_upstream;
1260     if (!$old_anchor_cl->{OrigParents}) {
1261         snag 'anchor-treated',
1262             'old anchor is recognised due to --anchor, cannot check upstream';
1263     } else {
1264         $old_upstream = parsecommit
1265             $old_anchor_cl->{OrigParents}[0]{CommitId};
1266         $piece->('', Old => $old_upstream->{CommitId});
1267     }
1268
1269     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1270         if ($old_upstream->{Msg} =~
1271  m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1272            ) {
1273             my @oldpieces = (split / /, $1);
1274             my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1275             if ($old_n_parents != @oldpieces &&
1276                 $old_n_parents != @oldpieces + 1) {
1277                 snag 'upstream-confusing', sprintf
1278                     "previous upstream combine %s".
1279                     " mentions %d pieces (each implying one parent)".
1280                     " but has %d parents".
1281                     " (one per piece plus maybe a previous combine)",
1282                     $old_upstream->{CommitId},
1283                     (scalar @oldpieces),
1284                     $old_n_parents;
1285             } elsif ($oldpieces[0] ne '.') {
1286                 snag 'upstream-confusing', sprintf
1287                     "previous upstream combine %s".
1288                     " first piece is not \`.'",
1289                     $oldpieces[0];
1290             } else {
1291                 $oldpieces[0] = '';
1292                 foreach my $i (0..$#oldpieces) {
1293                     my $n = $oldpieces[$i];
1294                     my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1295                     $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1296                 }
1297             }
1298         } else {
1299             snag 'upstream-confusing',
1300                 "previous upstream $old_upstream->{CommitId} is from".
1301                " git-debrebase but not an \`upstream-combine' commit";
1302         }
1303     }
1304
1305     foreach my $pc (values %pieces) {
1306         if (!$old_upstream) {
1307             # we have complained already
1308         } elsif (!$pc->{Old}) {
1309             snag 'upstream-new-piece',
1310                 "introducing upstream piece \`$pc->{Name}'";
1311         } elsif (!$pc->{New}) {
1312             snag 'upstream-rm-piece',
1313                 "dropping upstream piece \`$pc->{Name}'";
1314         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1315             snag 'upstream-not-ff',
1316                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1317         }
1318     }
1319
1320     printdebug "%pieces = ", (dd \%pieces), "\n";
1321     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1322
1323     snags_maybe_bail();
1324
1325     my $new_bw;
1326
1327     fresh_workarea();
1328     in_workarea sub {
1329         my @upstream_merge_parents;
1330
1331         if (!any_snags()) {
1332             push @upstream_merge_parents, $old_upstream->{CommitId};
1333         }
1334
1335         foreach my $pc (@newpieces) { # always has '' first
1336             if ($pc->{Name}) {
1337                 read_tree_subdir $pc->{Name}, $pc->{New};
1338             } else {
1339                 runcmd @git, qw(read-tree), $pc->{New};
1340             }
1341             push @upstream_merge_parents, $pc->{New};
1342         }
1343
1344         # index now contains the new upstream
1345
1346         if (@newpieces > 1) {
1347             # need to make the upstream subtree merge commit
1348             $new_upstream = make_commit \@upstream_merge_parents,
1349                 [ "Combine upstreams for $new_upstream_version",
1350  ("[git-debrebase upstream-combine . ".
1351  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1352  ": new upstream]"),
1353                 ];
1354         }
1355
1356         # $new_upstream is either the single upstream commit, or the
1357         # combined commit we just made.  Either way it will be the
1358         # "upstream" parent of the anchor merge.
1359
1360         read_tree_subdir 'debian', "$old_bw:debian";
1361
1362         # index now contains the anchor merge contents
1363         $new_bw = make_commit [ $old_bw, $new_upstream ],
1364             [ "Update to upstream $new_upstream_version",
1365  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1366             ];
1367
1368         my $clogsignoff = cmdoutput qw(git show),
1369             '--pretty=format:%an <%ae>  %aD',
1370             $new_bw;
1371
1372         # Now we have to add a changelog stanza so the Debian version
1373         # is right.
1374         die if unlink "debian";
1375         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1376         unlink "debian/changelog" or $!==ENOENT or die $!;
1377         mkdir "debian" or die $!;
1378         open CN, ">", "debian/changelog" or die $!;
1379         my $oldclog = git_cat_file ":debian/changelog";
1380         $oldclog =~ m/^($package_re) \(\S+\) / or
1381             fail "cannot parse old changelog to get package name";
1382         my $p = $1;
1383         print CN <<END, $oldclog or die $!;
1384 $p ($new_version) UNRELEASED; urgency=medium
1385
1386   * Update to new upstream version $new_upstream_version.
1387
1388  -- $clogsignoff
1389
1390 END
1391         close CN or die $!;
1392         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1393
1394         # Now we have the final new breakwater branch in the index
1395         $new_bw = make_commit [ $new_bw ],
1396             [ "Update changelog for new upstream $new_upstream_version",
1397               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1398             ];
1399     };
1400
1401     # we have constructed the new breakwater. we now need to commit to
1402     # the laundering output, because git-rebase can't easily be made
1403     # to make a replay list which is based on some other branch
1404
1405     update_head_postlaunder $old_head, $old_laundered_tip,
1406         'launder for new upstream';
1407
1408     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1409     local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1410         "debrebase new-upstream $new_version: rebase";
1411     runcmd @cmd;
1412     # now it's for the user to sort out
1413 }
1414
1415 sub cmd_record_ffq_prev () {
1416     badusage "no arguments allowed" if @ARGV;
1417     my ($status, $msg) = record_ffq_prev_deferred();
1418     if ($status eq 'exists' && $opt_noop_ok) {
1419         print "Previous head already recorded\n" or die $!;
1420     } elsif ($status eq 'deferred') {
1421         run_deferred_updates 'record-ffq-prev';
1422     } else {
1423         fail "Could not preserve: $msg";
1424     }
1425 }
1426
1427 sub cmd_anchor () {
1428     badusage "no arguments allowed" if @ARGV;
1429     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1430     print "$bw\n" or die $!;
1431 }
1432
1433 sub cmd_breakwater () {
1434     badusage "no arguments allowed" if @ARGV;
1435     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1436     print "$bw\n" or die $!;
1437 }
1438
1439 sub cmd_status () {
1440     badusage "no arguments allowed" if @ARGV;
1441
1442     # todo: gdr status should print divergence info
1443     # todo: gdr status should print upstream component(s) info
1444     # todo: gdr should leave/maintain some refs with this kind of info ?
1445
1446     my $oldest = { Badness => 0 };
1447     my $newest;
1448     my $note = sub {
1449         my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1450         if ($oldest->{Badness} < $badness) {
1451             $oldest = $newest = undef;
1452         }
1453         $oldest = {
1454                    Badness => $badness,
1455                    CommitId => $cl->{CommitId},
1456                    OurMsg => $ourmsg,
1457                    KcMsg => $kcmsg,
1458                   };
1459         $newest //= $oldest;
1460     };
1461     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1462         sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1463         sub { $note->(2, 'branch is unlaundered', @_); },
1464         sub { $note->(3, 'branch needs laundering', @_); },
1465         sub { $note->(4, 'branch not in git-debrebase form', @_); };
1466
1467     my $prcommitinfo = sub {
1468         my ($cid) = @_;
1469         flush STDOUT or die $!;
1470         runcmd @git, qw(--no-pager log -n1),
1471             '--pretty=format:    %h %s%n',
1472             $cid;
1473     };
1474
1475     print "current branch contents, in git-debrebase terms:\n";
1476     if (!$oldest->{Badness}) {
1477         print "  branch is laundered\n";
1478     } else {
1479         print "  $oldest->{OurMsg}\n";
1480         my $printed = '';
1481         foreach my $info ($oldest, $newest) {
1482             my $cid = $info->{CommitId};
1483             next if $cid eq $printed;
1484             $printed = $cid;
1485             print "  $info->{KcMsg}\n";
1486             $prcommitinfo->($cid);
1487         }
1488     }
1489
1490     my $prab = sub {
1491         my ($cid, $what) = @_;
1492         if (!defined $cid) {
1493             print "  $what is not well-defined\n";
1494         } else {
1495             print "  $what\n";
1496             $prcommitinfo->($cid);
1497         }
1498     };
1499     print "key git-debrebase commits:\n";
1500     $prab->($anchor, 'anchor');
1501     $prab->($bw, 'breakwater');
1502
1503     my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1504         ffq_prev_branchinfo();
1505
1506     print "branch and ref status, in git-debrebase terms:\n";
1507     if ($ffq_msg) {
1508         print "  $ffq_msg\n";
1509     } else {
1510         $ffq_prev = git_get_ref $ffq_prev;
1511         $gdrlast = git_get_ref $gdrlast;
1512         if ($ffq_prev) {
1513             print "  unstitched; previous tip was:\n";
1514             $prcommitinfo->($ffq_prev);
1515         } elsif (!$gdrlast) {
1516             print "  stitched? (no record of git-debrebase work)\n";
1517         } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1518             print "  stitched\n";
1519         } else {
1520             print "  not git-debrebase (diverged since last stitch)\n"
1521         }
1522     }
1523 }
1524
1525 sub cmd_stitch () {
1526     my $prose = 'stitch';
1527     getoptions("bad options follow \`git-debrebase stitch'",
1528                'prose=s', \$prose);
1529     badusage "no arguments allowed" if @ARGV;
1530     do_stitch $prose, 0;
1531 }
1532 sub cmd_prepush () { cmd_stitch(); }
1533
1534 sub cmd_quick () {
1535     badusage "no arguments allowed" if @ARGV;
1536     do_launder_head 'launder for git-debrebase quick';
1537     do_stitch 'quick';
1538 }
1539
1540 sub cmd_conclude () {
1541     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1542     if (!$ffq_prev_commitish) {
1543         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1544         return;
1545     }
1546     my $dangling_head = get_head();
1547     
1548     badusage "no arguments allowed" if @ARGV;
1549     do_launder_head 'launder for git-debrebase quick';
1550     do_stitch 'quick';
1551 }
1552
1553 sub make_patches_staged ($) {
1554     my ($head) = @_;
1555     # Produces the patches that would result from $head if it were
1556     # laundered.
1557     my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1558     fresh_workarea();
1559     in_workarea sub {
1560         runcmd @git, qw(checkout -q -b bw), $secret_bw;
1561         runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1562         my @gbp_cmd = (qw(gbp pq export));
1563         my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1564         if ($r) {
1565             { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1566             failedcmd @gbp_cmd;
1567         }
1568         runcmd @git, qw(add -f debian/patches);
1569     };
1570 }
1571
1572 sub make_patches ($) {
1573     my ($head) = @_;
1574     keycommits $head, 0, \&snag;
1575     make_patches_staged $head;
1576     my $out;
1577     in_workarea sub {
1578         my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1579         runcmd @git, qw(read-tree), $head;
1580         read_tree_subdir 'debian/patches', $ptree;
1581         $out = make_commit [$head], [
1582             'Commit patch queue (exported by git-debrebase)',
1583             '[git-debrebase: export and commit patches]',
1584         ];
1585     };
1586     return $out;
1587 }
1588
1589 sub cmd_make_patches () {
1590     my $opt_quiet_would_amend;
1591     getoptions("bad options follow \`git-debrebase make-patches'",
1592                'quiet-would-amend!', \$opt_quiet_would_amend);
1593     badusage "no arguments allowed" if @ARGV;
1594     my $old_head = get_head();
1595     my $new = make_patches $old_head;
1596     my $d = get_differs $old_head, $new;
1597     if ($d == 0) {
1598         fail "No (more) patches to export." unless $opt_noop_ok;
1599         return;
1600     } elsif ($d == D_PAT_ADD) {
1601         snags_maybe_bail();
1602         update_head_checkout $old_head, $new, 'make-patches';
1603     } else {
1604         print STDERR failmsg
1605             "Patch export produced patch amendments".
1606             " (abandoned output commit $new).".
1607             "  Try laundering first."
1608             unless $opt_quiet_would_amend;
1609         finish 7;
1610     }
1611 }
1612
1613 sub cmd_convert_from_gbp () {
1614     badusage "want only 1 optional argument, the upstream git commitish"
1615         unless @ARGV<=1;
1616
1617     my $clogp = parsechangelog();
1618     my $version = $clogp->{'Version'}
1619         // die "missing Version from changelog";
1620
1621     my ($upstream_spec) = @ARGV;
1622
1623     my ($upstream, $upstream_version) =
1624         resolve_upstream_version($upstream_spec, $version);
1625
1626     my $old_head = get_head();
1627
1628     my $upsdiff = get_differs $upstream, $old_head;
1629     if ($upsdiff & D_UPS) {
1630         runcmd @git, qw(--no-pager diff --stat),
1631             $upstream, $old_head,
1632             qw( -- :!/debian :/);
1633         fail <<END;
1634 upstream ($upstream_spec) and HEAD are not
1635 identical in upstream files.  See diffstat above, or run
1636   git diff $upstream_spec HEAD -- :!/debian :/
1637 END
1638     }
1639
1640     if (!is_fast_fwd $upstream, $old_head) {
1641         snag 'upstream-not-ancestor',
1642             "upstream ($upstream) is not an ancestor of HEAD";
1643     } else {
1644         my $wrong = cmdoutput
1645             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1646              qw(-- :/ :!/debian));
1647         if (length $wrong) {
1648             snag 'unexpected-upstream-changes',
1649                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1650             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1651         }
1652     }
1653
1654     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1655         snag 'upstream-has-debian',
1656             "upstream ($upstream) contains debian/ directory";
1657     }
1658
1659     my $previous_dgit_view = eval {
1660         my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1661         my ($lvsn, $suite);
1662         parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1663             my ($stz, $desc) = @_;
1664             no warnings qw(exiting);
1665             printdebug 'CHANGELOG ', Dumper($desc, $stz);
1666             next unless $stz->{Date};
1667             next unless $stz->{Distribution} ne 'UNRELEASED';
1668             $lvsn = $stz->{Version};
1669             $suite = $stz->{Distribution};
1670             last;
1671         };
1672         die "neither of the first two changelog entries are released\n"
1673             unless defined $lvsn;
1674         print "last finished-looking changelog entry: ($lvsn) $suite\n";
1675         my $mtag_pat = debiantag_maintview $lvsn, '*';
1676         my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1677             $mtag_pat;
1678         die "could not find suitable maintainer view tag $mtag_pat\n"
1679             unless $mtag_pat =~ m{/};
1680         is_fast_fwd $mtag, 'HEAD' or
1681             die "HEAD is not FF from maintainer tag $mtag!";
1682         my $dtag = "archive/$mtag";
1683         is_fast_fwd $mtag, $dtag or
1684             die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1685         print "will stitch in dgit view, $dtag\n";
1686         git_rev_parse $dtag;
1687     };
1688     if (!$previous_dgit_view) {
1689         $@ =~ s/^\n+//;
1690         chomp $@;
1691         print STDERR "cannot stitch in dgit view: $@\n";
1692     }
1693
1694     snags_maybe_bail_early();
1695
1696     my $work;
1697
1698     fresh_workarea();
1699     in_workarea sub {
1700         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1701         # make a branch out of the patch queue - we'll want this in a mo
1702         runcmd qw(gbp pq import);
1703         # strip the patches out
1704         runcmd @git, qw(checkout -q gdr-internal~0);
1705         rm_subdir_cached 'debian/patches';
1706         $work = make_commit ['HEAD'], [
1707  'git-debrebase convert-from-gbp: drop patches from tree',
1708  'Delete debian/patches, as part of converting to git-debrebase format.',
1709  '[git-debrebase convert-from-gbp: drop patches from tree]'
1710                               ];
1711         # make the anchor merge
1712         # the tree is already exactly right
1713         $work = make_commit [$work, $upstream], [
1714  'git-debrebase import: declare upstream',
1715  'First breakwater merge.',
1716  '[git-debrebase anchor: declare upstream]'
1717                               ];
1718
1719         # rebase the patch queue onto the new breakwater
1720         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1721         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1722         $work = git_rev_parse 'HEAD';
1723
1724         if ($previous_dgit_view) {
1725             $work = make_commit [$work, $previous_dgit_view], [
1726  'git-debrebase import: declare ff from dgit archive view',
1727  '[git-debrebase pseudomerge: import-from-gbp]',
1728             ];
1729         }
1730     };
1731
1732     ffq_check $work;
1733     snags_maybe_bail();
1734     update_head_checkout $old_head, $work, 'convert-from-gbp';
1735 }
1736
1737 sub cmd_convert_to_gbp () {
1738     badusage "no arguments allowed" if @ARGV;
1739     my $head = get_head();
1740     my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1741     keycommits $head, 0;
1742     my $out;
1743     make_patches_staged $head;
1744     in_workarea sub {
1745         $out = make_commit ['HEAD'], [
1746             'Commit patch queue (converted from git-debrebase format)',
1747             '[git-debrebase convert-to-gbp: commit patches]',
1748         ];
1749     };
1750     if (defined $ffq) {
1751         push @deferred_updates, "delete $ffq";
1752         push @deferred_updates, "delete $gdrlast";
1753     }
1754     snags_maybe_bail();
1755     update_head_checkout $head, $out, "convert to gbp (v0)";
1756     print <<END or die $!;
1757 git-debrebase: converted to git-buildpackage branch format
1758 git-debrebase: WARNING: do not now run "git-debrebase" any more
1759 git-debrebase: WARNING: doing so would drop all upstream patches!
1760 END
1761 }
1762
1763 sub cmd_downstream_rebase_launder_v0 () {
1764     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1765     my ($base) = @ARGV;
1766     $base = git_rev_parse $base;
1767     my $old_head = get_head();
1768     my $current = $old_head;
1769     my $topmost_keep;
1770     for (;;) {
1771         if ($current eq $base) {
1772             $topmost_keep //= $current;
1773             print " $current BASE stop\n";
1774             last;
1775         }
1776         my $cl = classify $current;
1777         print " $current $cl->{Type}";
1778         my $keep = 0;
1779         my $p0 = $cl->{Parents}[0]{CommitId};
1780         my $next;
1781         if ($cl->{Type} eq 'Pseudomerge') {
1782             print " ^".($cl->{Contributor}{Ix}+1);
1783             $next = $cl->{Contributor}{CommitId};
1784         } elsif ($cl->{Type} eq 'AddPatches' or
1785                  $cl->{Type} eq 'Changelog') {
1786             print " strip";
1787             $next = $p0;
1788         } else {
1789             print " keep";
1790             $next = $p0;
1791             $keep = 1;
1792         }
1793         print "\n";
1794         if ($keep) {
1795             $topmost_keep //= $current;
1796         } else {
1797             die "to-be stripped changes not on top of the branch\n"
1798                 if $topmost_keep;
1799         }
1800         $current = $next;
1801     }
1802     if ($topmost_keep eq $old_head) {
1803         print "unchanged\n";
1804     } else {
1805         print "updating to $topmost_keep\n";
1806         update_head_checkout
1807             $old_head, $topmost_keep,
1808             'downstream-rebase-launder-v0';
1809     }
1810 }
1811
1812 getoptions("bad options\n",
1813            "D+" => \$debuglevel,
1814            'noop-ok', => \$opt_noop_ok,
1815            'f=s' => \@snag_force_opts,
1816            'anchor=s' => \@opt_anchors,
1817            'force!',
1818            '-i:s' => sub {
1819                my ($opt,$val) = @_;
1820                badusage "git-debrebase: no cuddling to -i for git-rebase"
1821                    if length $val;
1822                die if $opt_defaultcmd_interactive; # should not happen
1823                $opt_defaultcmd_interactive = [ qw(-i) ];
1824                # This access to @ARGV is excessive familiarity with
1825                # Getopt::Long, but there isn't another sensible
1826                # approach.  '-i=s{0,}' does not work with bundling.
1827                push @$opt_defaultcmd_interactive, @ARGV;
1828                @ARGV=();
1829            });
1830
1831 initdebug('git-debrebase ');
1832 enabledebug if $debuglevel;
1833
1834 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1835 chdir $toplevel or die "chdir $toplevel: $!";
1836
1837 $rd = fresh_playground "$playprefix/misc";
1838
1839 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1840
1841 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1842     defaultcmd_rebase();
1843 } else {
1844     my $cmd = shift @ARGV;
1845     my $cmdfn = $cmd;
1846     $cmdfn =~ y/-/_/;
1847     $cmdfn = ${*::}{"cmd_$cmdfn"};
1848
1849     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1850     $cmdfn->();
1851 }
1852
1853 finish 0;