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