chiark / gitweb /
changelog: 5.5+exp3 to placate version checking
[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 blockers (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, $why) = @_;
572         my $m = "branch needs laundering (run git-debrebase): $why";
573         fail $m unless defined $cb;
574         return unless $cb;
575         $cb->("unclean-$tagsfx", $why, $cl);
576     };
577     for (;;) {
578         $cl = classify $head;
579         my $ty = $cl->{Type};
580         if ($ty eq 'Packaging') {
581             $breakwater //= $clogonly;
582             $breakwater //= $head;
583         } elsif ($ty eq 'Changelog') {
584             # this is going to count as the tip of the breakwater
585             # only if it has no upstream stuff before it
586             $clogonly //= $head;
587         } elsif ($ty eq 'Anchor' or
588                  $ty eq 'TreatAsAnchor' or
589                  $ty eq 'BreakwaterStart') {
590             $anchor = $head;
591             $breakwater //= $clogonly;
592             $breakwater //= $head;
593             last;
594         } elsif ($ty eq 'Upstream') {
595             $x->($unclean, 'ordering',
596  "packaging change ($breakwater) follows upstream change (eg $head)")
597                 if defined $breakwater;
598             $clogonly = undef;
599             $breakwater = undef;
600         } elsif ($ty eq 'Mixed') {
601             $x->($unclean, 'mixed',
602                  "found mixed upstream/packaging commit ($head)");
603             $clogonly = undef;
604             $breakwater = undef;
605         } elsif ($ty eq 'Pseudomerge' or
606                  $ty eq 'AddPatches') {
607             $x->($furniture, (lc $ty),
608                  "found interchange bureaucracy commit ($ty, $head)");
609         } elsif ($ty eq 'DgitImportUnpatched') {
610             $x->($trouble, 'dgitimport',
611                  "found dgit dsc import ($head)");
612             return (undef,undef);
613         } else {
614             $x->($fatal, 'unprocessable',
615                  "found unprocessable commit, cannot cope: $head; $cl->{Why}"
616                 );
617             return (undef,undef);
618         }
619         $head = $cl->{Parents}[0]{CommitId};
620     }
621     return ($anchor, $breakwater);
622 }
623
624 sub walk ($;$$);
625 sub walk ($;$$) {
626     my ($input,
627         $nogenerate,$report) = @_;
628     # => ($tip, $breakwater_tip, $last_anchor)
629     # (or nothing, if $nogenerate)
630
631     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
632
633     # go through commits backwards
634     # we generate two lists of commits to apply:
635     # breakwater branch and upstream patches
636     my (@brw_cl, @upp_cl, @processed);
637     my %found;
638     my $upp_limit;
639     my @pseudomerges;
640
641     my $cl;
642     my $xmsg = sub {
643         my ($prose, $info) = @_;
644         my $ms = $cl->{Msg};
645         chomp $ms;
646         $info //= '';
647         $ms .= "\n\n[git-debrebase$info: $prose]\n";
648         return (Msg => $ms);
649     };
650     my $rewrite_from_here = sub {
651         my ($cl) = @_;
652         my $sp_cl = { SpecialMethod => 'StartRewrite' };
653         push @$cl, $sp_cl;
654         push @processed, $sp_cl;
655     };
656     my $cur = $input;
657
658     my $prdelim = "";
659     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
660
661     my $prline = sub {
662         return unless $report;
663         print $report $prdelim, @_;
664         $prdelim = "\n";
665     };
666
667     my $bomb = sub { # usage: return $bomb->();
668         print $report " Unprocessable" if $report;
669         print $report " ($cl->{Why})" if $report && defined $cl->{Why};
670         $prprdelim->();
671         if ($nogenerate) {
672             return (undef,undef);
673         }
674         die "commit $cur: Cannot cope with this commit (d.".
675             (join ' ', map { sprintf "%#x", $_->{Differs} }
676              @{ $cl->{Parents} }).
677             (defined $cl->{Why} ? "; $cl->{Why}": '').
678                  ")";
679     };
680
681     my $build;
682     my $breakwater;
683
684     my $build_start = sub {
685         my ($msg, $parent) = @_;
686         $prline->(" $msg");
687         $build = $parent;
688         no warnings qw(exiting); last;
689     };
690
691     my $last_anchor;
692
693     for (;;) {
694         $cl = classify $cur;
695         my $ty = $cl->{Type};
696         my $st = $cl->{SubType};
697         $prline->("$cl->{CommitId} $cl->{Type}");
698         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
699         push @processed, $cl;
700         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
701         if ($ty eq 'AddPatches') {
702             $cur = $p0;
703             $rewrite_from_here->(\@upp_cl);
704             next;
705         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
706             push @brw_cl, $cl;
707             $cur = $p0;
708             next;
709         } elsif ($ty eq 'BreakwaterStart') {
710             $last_anchor = $cur;
711             $build_start->('FirstPackaging', $cur);
712         } elsif ($ty eq 'Upstream') {
713             push @upp_cl, $cl;
714             $cur = $p0;
715             next;
716         } elsif ($ty eq 'Mixed') {
717             my $queue = sub {
718                 my ($q, $wh) = @_;
719                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
720                 push @$q, $cls;
721             };
722             $queue->(\@brw_cl, "debian");
723             $queue->(\@upp_cl, "upstream");
724             $rewrite_from_here->(\@brw_cl);
725             $cur = $p0;
726             next;
727         } elsif ($ty eq 'Pseudomerge') {
728             my $contrib = $cl->{Contributor}{CommitId};
729             print $report " Contributor=$contrib" if $report;
730             push @pseudomerges, $cl;
731             $rewrite_from_here->(\@upp_cl);
732             $cur = $contrib;
733             next;
734         } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
735             $last_anchor = $cur;
736             $build_start->("Anchor", $cur);
737         } elsif ($ty eq 'DgitImportUnpatched') {
738             my $pm = $pseudomerges[-1];
739             if (defined $pm) {
740                 # To an extent, this is heuristic.  Imports don't have
741                 # a useful history of the debian/ branch.  We assume
742                 # that the first pseudomerge after an import has a
743                 # useful history of debian/, and ignore the histories
744                 # from later pseudomerges.  Often the first pseudomerge
745                 # will be the dgit import of the upload to the actual
746                 # suite intended by the non-dgit NMUer, and later
747                 # pseudomerges may represent in-archive copies.
748                 my $ovwrs = $pm->{Overwritten};
749                 printf $report " PM=%s \@Overwr:%d",
750                     $pm->{CommitId}, (scalar @$ovwrs)
751                     if $report;
752                 if (@$ovwrs != 1) {
753                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
754                     return $bomb->();
755                 }
756                 my $ovwr = $ovwrs->[0]{CommitId};
757                 printf $report " Overwr=%s", $ovwr if $report;
758                 # This import has a tree which is just like a
759                 # breakwater tree, but it has the wrong history.  It
760                 # ought to have the previous breakwater (which the
761                 # pseudomerge overwrote) as an ancestor.  That will
762                 # make the history of the debian/ files correct.  As
763                 # for the upstream version: either it's the same as
764                 # was ovewritten (ie, same as the previous
765                 # breakwater), in which case that history is precisely
766                 # right; or, otherwise, it was a non-gitish upload of a
767                 # new upstream version.  We can tell these apart by
768                 # looking at the tree of the supposed upstream.
769                 push @brw_cl, {
770                     %$cl,
771                     SpecialMethod => 'DgitImportDebianUpdate',
772                     $xmsg->("convert dgit import: debian changes")
773                 }, {
774                     %$cl,
775                     SpecialMethod => 'DgitImportUpstreamUpdate',
776                     $xmsg->("convert dgit import: upstream update",
777                             " anchor")
778                 };
779                 $prline->(" Import");
780                 $rewrite_from_here->(\@brw_cl);
781                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
782                 $cur = $ovwr;
783                 next;
784             } else {
785                 # Everything is from this import.  This kind of import
786                 # is already in valid breakwater format, with the
787                 # patches as commits.
788                 printf $report " NoPM" if $report;
789                 # last thing we processed will have been the first patch,
790                 # if there is one; which is fine, so no need to rewrite
791                 # on account of this import
792                 $build_start->("ImportOrigin", $cur);
793             }
794             die "$ty ?";
795         } else {
796             printdebug "*** WALK BOMB unrecognised\n";
797             return $bomb->();
798         }
799     }
800     $prprdelim->();
801
802     printdebug "*** WALK prep done cur=$cur".
803         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
804
805     return if $nogenerate;
806
807     # Now we build it back up again
808
809     fresh_workarea();
810
811     my $rewriting = 0;
812
813     my $read_tree_debian = sub {
814         my ($treeish) = @_;
815         read_tree_subdir 'debian', "$treeish:debian";
816         rm_subdir_cached 'debian/patches';
817     };
818     my $read_tree_upstream = sub {
819         my ($treeish) = @_;
820         runcmd @git, qw(read-tree), $treeish;
821         $read_tree_debian->($build);
822     };
823
824     $#upp_cl = $upp_limit if defined $upp_limit;
825  
826     my $committer_authline = calculate_committer_authline();
827
828     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
829
830     confess "internal error" unless $build eq (pop @processed)->{CommitId};
831
832     in_workarea sub {
833         mkdir $rd or $!==EEXIST or die $!;
834         my $current_method;
835         runcmd @git, qw(read-tree), $build;
836         foreach my $cl (qw(Debian), (reverse @brw_cl),
837                         { SpecialMethod => 'RecordBreakwaterTip' },
838                         qw(Upstream), (reverse @upp_cl)) {
839             if (!ref $cl) {
840                 $current_method = $cl;
841                 next;
842             }
843             my $method = $cl->{SpecialMethod} // $current_method;
844             my @parents = ($build);
845             my $cltree = $cl->{CommitId};
846             printdebug "WALK BUILD ".($cltree//'undef').
847                 " $method (rewriting=$rewriting)\n";
848             if ($method eq 'Debian') {
849                 $read_tree_debian->($cltree);
850             } elsif ($method eq 'Upstream') {
851                 $read_tree_upstream->($cltree);
852             } elsif ($method eq 'StartRewrite') {
853                 $rewriting = 1;
854                 next;
855             } elsif ($method eq 'RecordBreakwaterTip') {
856                 $breakwater = $build;
857                 next;
858             } elsif ($method eq 'DgitImportDebianUpdate') {
859                 $read_tree_debian->($cltree);
860             } elsif ($method eq 'DgitImportUpstreamUpdate') {
861                 confess unless $rewriting;
862                 my $differs = (get_differs $build, $cltree);
863                 next unless $differs & D_UPS;
864                 $read_tree_upstream->($cltree);
865                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
866             } else {
867                 confess "$method ?";
868             }
869             if (!$rewriting) {
870                 my $procd = (pop @processed) // 'UNDEF';
871                 if ($cl ne $procd) {
872                     $rewriting = 1;
873                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
874                 }
875             }
876             my $newtree = cmdoutput @git, qw(write-tree);
877             my $ch = $cl->{Hdr};
878             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
879             $ch =~ s{^parent .*\n}{}mg;
880             $ch =~ s{(?=^author)}{
881                 join '', map { "parent $_\n" } @parents
882             }me or confess "$ch ?";
883             if ($rewriting) {
884                 $ch =~ s{^committer .*$}{$committer_authline}m
885                     or confess "$ch ?";
886             }
887             my $cf = "$rd/m$rewriting";
888             open CD, ">", $cf or die $!;
889             print CD $ch, "\n", $cl->{Msg} or die $!;
890             close CD or die $!;
891             my @cmd = (@git, qw(hash-object));
892             push @cmd, qw(-w) if $rewriting;
893             push @cmd, qw(-t commit), $cf;
894             my $newcommit = cmdoutput @cmd;
895             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
896             $build = $newcommit;
897             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
898                 $last_anchor = $cur;
899             }
900         }
901     };
902
903     my $final_check = get_differs $build, $input;
904     die sprintf "internal error %#x %s %s", $final_check, $build, $input
905         if $final_check & ~D_PAT_ADD;
906
907     my @r = ($build, $breakwater, $last_anchor);
908     printdebug "*** WALK RETURN @r\n";
909     return @r
910 }
911
912 sub get_head () {
913     git_check_unmodified();
914     return git_rev_parse qw(HEAD);
915 }
916
917 sub update_head ($$$) {
918     my ($old, $new, $mrest) = @_;
919     push @deferred_updates, "update HEAD $new $old";
920     run_deferred_updates $mrest;
921 }
922
923 sub update_head_checkout ($$$) {
924     my ($old, $new, $mrest) = @_;
925     update_head $old, $new, $mrest;
926     runcmd @git, qw(reset --hard);
927 }
928
929 sub update_head_postlaunder ($$$) {
930     my ($old, $tip, $reflogmsg) = @_;
931     return if $tip eq $old;
932     print "git-debrebase: laundered (head was $old)\n";
933     update_head $old, $tip, $reflogmsg;
934     # no tree changes except debian/patches
935     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
936 }
937
938 sub do_launder_head ($) {
939     my ($reflogmsg) = @_;
940     my $old = get_head();
941     record_ffq_auto();
942     my ($tip,$breakwater) = walk $old;
943     snags_maybe_bail();
944     update_head_postlaunder $old, $tip, $reflogmsg;
945     return ($tip,$breakwater);
946 }
947
948 sub cmd_launder_v0 () {
949     badusage "no arguments to launder-v0 allowed" if @ARGV;
950     my $old = get_head();
951     my ($tip,$breakwater,$last_anchor) = walk $old;
952     update_head_postlaunder $old, $tip, 'launder';
953     printf "# breakwater tip\n%s\n", $breakwater;
954     printf "# working tip\n%s\n", $tip;
955     printf "# last anchor\n%s\n", $last_anchor;
956 }
957
958 sub defaultcmd_rebase () {
959     push @ARGV, @{ $opt_defaultcmd_interactive // [] };
960     my ($tip,$breakwater) = do_launder_head 'launder for rebase';
961     runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
962 }
963
964 sub cmd_analyse () {
965     die if ($ARGV[0]//'') =~ m/^-/;
966     badusage "too many arguments to analyse" if @ARGV>1;
967     my ($old) = @ARGV;
968     if (defined $old) {
969         $old = git_rev_parse $old;
970     } else {
971         $old = git_rev_parse 'HEAD';
972     }
973     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
974     STDOUT->error and die $!;
975 }
976
977 sub ffq_prev_branchinfo () {
978     my $current = git_get_symref();
979     return gdr_ffq_prev_branchinfo($current);
980 }
981
982 sub record_ffq_prev_deferred () {
983     # => ('status', "message")
984     # 'status' may be
985     #    deferred          message is undef
986     #    exists
987     #    detached
988     #    weird-symref
989     #    notbranch
990     # if not ff from some branch we should be ff from, is an snag
991     # if "deferred", will have added something about that to
992     #   @deferred_update_messages, and also maybe printed (already)
993     #   some messages about ff checks
994     my ($status, $message, $current, $ffq_prev, $gdrlast)
995         = ffq_prev_branchinfo();
996     return ($status, $message) unless $status eq 'branch';
997
998     my $currentval = get_head();
999
1000     my $exists = git_get_ref $ffq_prev;
1001     return ('exists',"$ffq_prev already exists") if $exists;
1002
1003     return ('not-branch', 'HEAD symref is not to refs/heads/')
1004         unless $current =~ m{^refs/heads/};
1005     my $branch = $';
1006
1007     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1008     my %checked;
1009
1010     printdebug "ffq check_specs @check_specs\n";
1011
1012     my $check = sub {
1013         my ($lrref, $desc) = @_;
1014         printdebug "ffq might check $lrref ($desc)\n";
1015         my $invert;
1016         for my $chk (@check_specs) {
1017             my $glob = $chk;
1018             $invert = $glob =~ s{^[!^]}{};
1019             last if fnmatch $glob, $lrref;
1020         }
1021         return if $invert;
1022         my $lrval = git_get_ref $lrref;
1023         return unless length $lrval;
1024
1025         if (is_fast_fwd $lrval, $currentval) {
1026             print "OK, you are ahead of $lrref\n" or die $!;
1027             $checked{$lrref} = 1;
1028         } elsif (is_fast_fwd $currentval, $lrval) {
1029             $checked{$lrref} = -1;
1030             snag 'behind', "you are behind $lrref, divergence risk";
1031         } else {
1032             $checked{$lrref} = -1;
1033             snag 'diverged', "you have diverged from $lrref";
1034         }
1035     };
1036
1037     my $merge = cfg "branch.$branch.merge",1;
1038     if (defined $merge and $merge =~ m{^refs/heads/}) {
1039         my $rhs = $';
1040         printdebug "ffq merge $rhs\n";
1041         my $check_remote = sub {
1042             my ($remote, $desc) = @_;
1043             printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1044             return unless defined $remote;
1045             $check->("refs/remotes/$remote/$rhs", $desc);
1046         };
1047         $check_remote->((scalar cfg "branch.$branch.remote",1),
1048                         'remote fetch/merge branch');
1049         $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1050                         (scalar cfg "branch.$branch.pushDefault",1),
1051                         'remote push branch');
1052     }
1053     if ($branch =~ m{^dgit/}) {
1054         $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1055     } elsif ($branch =~ m{^master$}) {
1056         $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1057     }
1058
1059     snags_maybe_bail();
1060
1061     push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1062     push @deferred_updates, "delete $gdrlast";
1063     push @deferred_update_messages, "Recorded current head for preservation";
1064     return ('deferred', undef);
1065 }
1066
1067 sub record_ffq_auto () {
1068     my ($status, $message) = record_ffq_prev_deferred();
1069     if ($status eq 'deferred' || $status eq 'exists') {
1070     } else {
1071         snag $status, "could not record ffq-prev: $message";
1072         snags_maybe_bail();
1073     }
1074 }
1075
1076 sub ffq_prev_info () {
1077     # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1078     my ($status, $message, $current, $ffq_prev, $gdrlast)
1079         = ffq_prev_branchinfo();
1080     if ($status ne 'branch') {
1081         snag $status, "could not check ffq-prev: $message";
1082         snags_maybe_bail();
1083     }
1084     my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1085     return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1086 }
1087
1088 sub stitch ($$$$$) {
1089     my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1090
1091     push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1092
1093     if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1094         my $differs = get_differs $old_head, $ffq_prev_commitish;
1095         unless ($differs & ~D_PAT_ADD) {
1096             # ffq-prev is ahead of us, and the only tree changes it has
1097             # are possibly addition of things in debian/patches/.
1098             # Just wind forwards rather than making a pointless pseudomerge.
1099             push @deferred_updates,
1100                 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1101             update_head_checkout $old_head, $ffq_prev_commitish,
1102                 "stitch (fast forward)";
1103             return;
1104         }
1105     }
1106     fresh_workarea();
1107     # We make pseudomerges with L as the contributing parent.
1108     # This makes git rev-list --first-parent work properly.
1109     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1110         'Declare fast forward / record previous work',
1111         "[git-debrebase pseudomerge: $prose]",
1112     ];
1113     push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1114     update_head $old_head, $new_head, "stitch: $prose";
1115 }
1116
1117 sub do_stitch ($;$) {
1118     my ($prose, $unclean) = @_;
1119
1120     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1121     if (!$ffq_prev_commitish) {
1122         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1123         return;
1124     }
1125     my $dangling_head = get_head();
1126
1127     keycommits $dangling_head, $unclean,$unclean,$unclean;
1128     snags_maybe_bail();
1129
1130     stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1131 }
1132
1133 sub cmd_new_upstream () {
1134     # automatically and unconditionally launders before rebasing
1135     # if rebase --abort is used, laundering has still been done
1136
1137     my %pieces;
1138
1139     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1140
1141     # parse args - low commitment
1142     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1143     my $new_upstream_version = $new_version->version();
1144
1145     my $new_upstream = shift @ARGV;
1146     if (!defined $new_upstream) {
1147         my @tried;
1148         # todo: at some point maybe use git-deborig to do this
1149         foreach my $tagpfx ('', 'v', 'upstream/') {
1150             my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1151             $new_upstream = git_get_ref "refs/tags/$tag";
1152             last if length $new_upstream;
1153             push @tried, $tag;
1154         }
1155         if (!length $new_upstream) {
1156             fail "Could not determine appropriate upstream commitish.\n".
1157                 " (Tried these tags: @tried)\n".
1158                 " Check version, and specify upstream commitish explicitly.";
1159         }
1160     }
1161     $new_upstream = git_rev_parse $new_upstream;
1162
1163     record_ffq_auto();
1164
1165     my $piece = sub {
1166         my ($n, @x) = @_; # may be ''
1167         my $pc = $pieces{$n} //= {
1168             Name => $n,
1169             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1170         };
1171         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1172         $pc;
1173     };
1174
1175     my @newpieces;
1176     my $newpiece = sub {
1177         my ($n, @x) = @_; # may be ''
1178         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1179         push @newpieces, $pc;
1180     };
1181
1182     $newpiece->('',
1183         OldIx => 0,
1184         New => $new_upstream,
1185     );
1186     while (@ARGV && $ARGV[0] !~ m{^-}) {
1187         my $n = shift @ARGV;
1188
1189         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1190             unless @ARGV && $ARGV[0] !~ m{^-};
1191
1192         my $c = git_rev_parse shift @ARGV;
1193         die unless $n =~ m/^$extra_orig_namepart_re$/;
1194         $newpiece->($n, New => $c);
1195     }
1196
1197     # now we need to investigate the branch this generates the
1198     # laundered version but we don't switch to it yet
1199     my $old_head = get_head();
1200     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1201
1202     my $old_bw_cl = classify $old_bw;
1203     my $old_anchor_cl = classify $old_anchor;
1204     my $old_upstream;
1205     if (!$old_anchor_cl->{OrigParents}) {
1206         snag 'anchor-treated',
1207             'old anchor is recognised due to --anchor, cannot check upstream';
1208     } else {
1209         $old_upstream = parsecommit
1210             $old_anchor_cl->{OrigParents}[0]{CommitId};
1211         $piece->('', Old => $old_upstream->{CommitId});
1212     }
1213
1214     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1215         if ($old_upstream->{Msg} =~
1216  m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1217            ) {
1218             my @oldpieces = (split / /, $1);
1219             my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1220             if ($old_n_parents != @oldpieces &&
1221                 $old_n_parents != @oldpieces + 1) {
1222                 snag 'upstream-confusing', sprintf
1223                     "previous upstream combine %s".
1224                     " mentions %d pieces (each implying one parent)".
1225                     " but has %d parents".
1226                     " (one per piece plus maybe a previous combine)",
1227                     $old_upstream->{CommitId},
1228                     (scalar @oldpieces),
1229                     $old_n_parents;
1230             } elsif ($oldpieces[0] ne '.') {
1231                 snag 'upstream-confusing', sprintf
1232                     "previous upstream combine %s".
1233                     " first piece is not \`.'",
1234                     $oldpieces[0];
1235             } else {
1236                 $oldpieces[0] = '';
1237                 foreach my $i (0..$#oldpieces) {
1238                     my $n = $oldpieces[$i];
1239                     my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1240                     $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1241                 }
1242             }
1243         } else {
1244             snag 'upstream-confusing',
1245                 "previous upstream $old_upstream->{CommitId} is from".
1246                " git-debrebase but not an \`upstream-combine' commit";
1247         }
1248     }
1249
1250     foreach my $pc (values %pieces) {
1251         if (!$old_upstream) {
1252             # we have complained already
1253         } elsif (!$pc->{Old}) {
1254             snag 'upstream-new-piece',
1255                 "introducing upstream piece \`$pc->{Name}'";
1256         } elsif (!$pc->{New}) {
1257             snag 'upstream-rm-piece',
1258                 "dropping upstream piece \`$pc->{Name}'";
1259         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1260             snag 'upstream-not-ff',
1261                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1262         }
1263     }
1264
1265     printdebug "%pieces = ", (dd \%pieces), "\n";
1266     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1267
1268     snags_maybe_bail();
1269
1270     my $new_bw;
1271
1272     fresh_workarea();
1273     in_workarea sub {
1274         my @upstream_merge_parents;
1275
1276         if (!any_snags()) {
1277             push @upstream_merge_parents, $old_upstream->{CommitId};
1278         }
1279
1280         foreach my $pc (@newpieces) { # always has '' first
1281             if ($pc->{Name}) {
1282                 read_tree_subdir $pc->{Name}, $pc->{New};
1283             } else {
1284                 runcmd @git, qw(read-tree), $pc->{New};
1285             }
1286             push @upstream_merge_parents, $pc->{New};
1287         }
1288
1289         # index now contains the new upstream
1290
1291         if (@newpieces > 1) {
1292             # need to make the upstream subtree merge commit
1293             $new_upstream = make_commit \@upstream_merge_parents,
1294                 [ "Combine upstreams for $new_upstream_version",
1295  ("[git-debrebase upstream-combine . ".
1296  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1297  ": new upstream]"),
1298                 ];
1299         }
1300
1301         # $new_upstream is either the single upstream commit, or the
1302         # combined commit we just made.  Either way it will be the
1303         # "upstream" parent of the anchor merge.
1304
1305         read_tree_subdir 'debian', "$old_bw:debian";
1306
1307         # index now contains the anchor merge contents
1308         $new_bw = make_commit [ $old_bw, $new_upstream ],
1309             [ "Update to upstream $new_upstream_version",
1310  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1311             ];
1312
1313         my $clogsignoff = cmdoutput qw(git show),
1314             '--pretty=format:%an <%ae>  %aD',
1315             $new_bw;
1316
1317         # Now we have to add a changelog stanza so the Debian version
1318         # is right.
1319         die if unlink "debian";
1320         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1321         unlink "debian/changelog" or $!==ENOENT or die $!;
1322         mkdir "debian" or die $!;
1323         open CN, ">", "debian/changelog" or die $!;
1324         my $oldclog = git_cat_file ":debian/changelog";
1325         $oldclog =~ m/^($package_re) \(\S+\) / or
1326             fail "cannot parse old changelog to get package name";
1327         my $p = $1;
1328         print CN <<END, $oldclog or die $!;
1329 $p ($new_version) UNRELEASED; urgency=medium
1330
1331   * Update to new upstream version $new_upstream_version.
1332
1333  -- $clogsignoff
1334
1335 END
1336         close CN or die $!;
1337         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1338
1339         # Now we have the final new breakwater branch in the index
1340         $new_bw = make_commit [ $new_bw ],
1341             [ "Update changelog for new upstream $new_upstream_version",
1342               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1343             ];
1344     };
1345
1346     # we have constructed the new breakwater. we now need to commit to
1347     # the laundering output, because git-rebase can't easily be made
1348     # to make a replay list which is based on some other branch
1349
1350     update_head_postlaunder $old_head, $old_laundered_tip,
1351         'launder for new upstream';
1352
1353     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1354     local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1355         "debrebase new-upstream $new_version: rebase";
1356     runcmd @cmd;
1357     # now it's for the user to sort out
1358 }
1359
1360 sub cmd_record_ffq_prev () {
1361     badusage "no arguments allowed" if @ARGV;
1362     my ($status, $msg) = record_ffq_prev_deferred();
1363     if ($status eq 'exists' && $opt_noop_ok) {
1364         print "Previous head already recorded\n" or die $!;
1365     } elsif ($status eq 'deferred') {
1366         run_deferred_updates 'record-ffq-prev';
1367     } else {
1368         fail "Could not preserve: $msg";
1369     }
1370 }
1371
1372 sub cmd_anchor () {
1373     badusage "no arguments allowed" if @ARGV;
1374     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1375     print "$bw\n" or die $!;
1376 }
1377
1378 sub cmd_breakwater () {
1379     badusage "no arguments allowed" if @ARGV;
1380     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1381     print "$bw\n" or die $!;
1382 }
1383
1384 sub cmd_status () {
1385     badusage "no arguments allowed" if @ARGV;
1386
1387     # todo: gdr status should print divergence info
1388     # todo: gdr status should print upstream component(s) info
1389     # todo: gdr should leave/maintain some refs with this kind of info ?
1390
1391     my $oldest = [ 0 ];
1392     my $newest;
1393     my $note = sub {
1394         my ($badness, $ourmsg, $snagname, $kcmsg, $cl) = @_;
1395         if ($oldest->[0] < $badness) {
1396             $oldest = $newest = undef;
1397         }
1398         $oldest = \@_; # we're walking backwards
1399         $newest //= \@_;
1400     };
1401     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1402         sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1403         sub { $note->(2, 'branch is unlaundered', @_); },
1404         sub { $note->(3, 'branch needs laundering', @_); },
1405         sub { $note->(4, 'branch not in git-debrebase form', @_); };
1406
1407     my $prcommitinfo = sub {
1408         my ($cid) = @_;
1409         flush STDOUT or die $!;
1410         runcmd @git, qw(--no-pager log -n1),
1411             '--pretty=format:    %h %s%n',
1412             $cid;
1413     };
1414
1415     print "current branch contents, in git-debrebase terms:\n";
1416     if (!$oldest->[0]) {
1417         print "  branch is laundered\n";
1418     } else {
1419         print "  $oldest->[1]\n";
1420         my $printed = '';
1421         foreach my $info ($oldest, $newest) {
1422             my $cid = $info->[4]{CommitId};
1423             next if $cid eq $printed;
1424             $printed = $cid;
1425             print "  $info->[3]\n";
1426             $prcommitinfo->($cid);
1427         }
1428     }
1429
1430     my $prab = sub {
1431         my ($cid, $what) = @_;
1432         if (!defined $cid) {
1433             print "  $what is not well-defined\n";
1434         } else {
1435             print "  $what\n";
1436             $prcommitinfo->($cid);
1437         }
1438     };
1439     print "key git-debrebase commits:\n";
1440     $prab->($anchor, 'anchor');
1441     $prab->($bw, 'breakwater');
1442
1443     my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1444         ffq_prev_branchinfo();
1445
1446     print "branch and ref status, in git-debrebase terms:\n";
1447     if ($ffq_msg) {
1448         print "  $ffq_msg\n";
1449     } else {
1450         $ffq_prev = git_get_ref $ffq_prev;
1451         $gdrlast = git_get_ref $gdrlast;
1452         if ($ffq_prev) {
1453             print "  unstitched; previous tip was:\n";
1454             $prcommitinfo->($ffq_prev);
1455         } elsif (!$gdrlast) {
1456             print "  stitched? (no record of git-debrebase work)\n";
1457         } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1458             print "  stitched\n";
1459         } else {
1460             print "  not git-debrebase (diverged since last stitch)\n"
1461         }
1462     }
1463 }
1464
1465 sub cmd_stitch () {
1466     my $prose = 'stitch';
1467     GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1468     badusage "no arguments allowed" if @ARGV;
1469     do_stitch $prose, 0;
1470 }
1471 sub cmd_prepush () { cmd_stitch(); }
1472
1473 sub cmd_quick () {
1474     badusage "no arguments allowed" if @ARGV;
1475     do_launder_head 'launder for git-debrebase quick';
1476     do_stitch 'quick';
1477 }
1478
1479 sub cmd_conclude () {
1480     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1481     if (!$ffq_prev_commitish) {
1482         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1483         return;
1484     }
1485     my $dangling_head = get_head();
1486     
1487     badusage "no arguments allowed" if @ARGV;
1488     do_launder_head 'launder for git-debrebase quick';
1489     do_stitch 'quick';
1490 }
1491
1492 sub make_patches_staged ($) {
1493     my ($head) = @_;
1494     # Produces the patches that would result from $head if it were
1495     # laundered.
1496     my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1497     fresh_workarea();
1498     in_workarea sub {
1499         runcmd @git, qw(checkout -q -b bw), $secret_bw;
1500         runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1501         my @gbp_cmd = (qw(gbp pq export));
1502         my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1503         if ($r) {
1504             { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1505             failedcmd @gbp_cmd;
1506         }
1507         runcmd @git, qw(add debian/patches);
1508     };
1509 }
1510
1511 sub make_patches ($) {
1512     my ($head) = @_;
1513     keycommits $head, 0, \&snag;
1514     make_patches_staged $head;
1515     my $out;
1516     in_workarea sub {
1517         my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1518         runcmd @git, qw(read-tree), $head;
1519         read_tree_subdir 'debian/patches', $ptree;
1520         $out = make_commit [$head], [
1521             'Commit patch queue (exported by git-debrebase)',
1522             '[git-debrebase: export and commit patches]',
1523         ];
1524     };
1525     return $out;
1526 }
1527
1528 sub cmd_make_patches () {
1529     my $opt_quiet_would_amend;
1530     GetOptions('quiet-would-amend!', \$opt_quiet_would_amend)
1531         or die badusage("bad options to make-patches");
1532     badusage "no arguments allowed" if @ARGV;
1533     my $old_head = get_head();
1534     my $new = make_patches $old_head;
1535     my $d = get_differs $old_head, $new;
1536     if ($d == 0) {
1537         fail "No (more) patches to export." unless $opt_noop_ok;
1538         return;
1539     } elsif ($d == D_PAT_ADD) {
1540         snags_maybe_bail();
1541         update_head_checkout $old_head, $new, 'make-patches';
1542     } else {
1543         print STDERR failmsg
1544             "Patch export produced patch amendments".
1545             " (abandoned output commit $new).".
1546             "  Try laundering first."
1547             unless $opt_quiet_would_amend;
1548         finish 7;
1549     }
1550 }
1551
1552 sub cmd_convert_from_gbp () {
1553     badusage "needs 1 optional argument, the upstream git rev"
1554         unless @ARGV<=1;
1555     my ($upstream_spec) = @ARGV;
1556     $upstream_spec //= 'refs/heads/upstream';
1557     my $upstream = git_rev_parse $upstream_spec;
1558     my $old_head = get_head();
1559
1560     my $upsdiff = get_differs $upstream, $old_head;
1561     if ($upsdiff & D_UPS) {
1562         runcmd @git, qw(--no-pager diff),
1563             $upstream, $old_head,
1564             qw( -- :!/debian :/);
1565  fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1566     }
1567
1568     if (!is_fast_fwd $upstream, $old_head) {
1569         snag 'upstream-not-ancestor',
1570             "upstream ($upstream) is not an ancestor of HEAD";
1571     } else {
1572         my $wrong = cmdoutput
1573             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1574              qw(-- :/ :!/debian));
1575         if (length $wrong) {
1576             snag 'unexpected-upstream-changes',
1577                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1578             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1579         }
1580     }
1581
1582     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1583         snag 'upstream-has-debian',
1584             "upstream ($upstream) contains debian/ directory";
1585     }
1586
1587     snags_maybe_bail();
1588
1589     my $work;
1590
1591     fresh_workarea();
1592     in_workarea sub {
1593         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1594         # make a branch out of the patch queue - we'll want this in a mo
1595         runcmd qw(gbp pq import);
1596         # strip the patches out
1597         runcmd @git, qw(checkout -q gdr-internal~0);
1598         rm_subdir_cached 'debian/patches';
1599         $work = make_commit ['HEAD'], [
1600  'git-debrebase convert-from-gbp: drop patches from tree',
1601  'Delete debian/patches, as part of converting to git-debrebase format.',
1602  '[git-debrebase convert-from-gbp: drop patches from tree]'
1603                               ];
1604         # make the anchor merge
1605         # the tree is already exactly right
1606         $work = make_commit [$work, $upstream], [
1607  'git-debrebase import: declare upstream',
1608  'First breakwater merge.',
1609  '[git-debrebase anchor: declare upstream]'
1610                               ];
1611
1612         # rebase the patch queue onto the new breakwater
1613         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1614         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1615         $work = git_rev_parse 'HEAD';
1616     };
1617
1618     update_head_checkout $old_head, $work, 'convert-from-gbp';
1619 }
1620
1621 sub cmd_convert_to_gbp () {
1622     badusage "no arguments allowed" if @ARGV;
1623     my $head = get_head();
1624     my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1625     keycommits $head, 0;
1626     my $out;
1627     make_patches_staged $head;
1628     in_workarea sub {
1629         $out = make_commit ['HEAD'], [
1630             'Commit patch queue (converted from git-debrebase format)',
1631             '[git-debrebase convert-to-gbp: commit patches]',
1632         ];
1633     };
1634     if (defined $ffq) {
1635         push @deferred_updates, "delete $ffq";
1636         push @deferred_updates, "delete $gdrlast";
1637     }
1638     snags_maybe_bail();
1639     update_head_checkout $head, $out, "convert to gbp (v0)";
1640     print <<END or die $!;
1641 git-debrebase: converted to git-buildpackage branch format
1642 git-debrebase: WARNING: do not now run "git-debrebase" any more
1643 git-debrebase: WARNING: doing so would drop all upstream patches!
1644 END
1645 }
1646
1647 sub cmd_downstream_rebase_launder_v0 () {
1648     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1649     my ($base) = @ARGV;
1650     $base = git_rev_parse $base;
1651     my $old_head = get_head();
1652     my $current = $old_head;
1653     my $topmost_keep;
1654     for (;;) {
1655         if ($current eq $base) {
1656             $topmost_keep //= $current;
1657             print " $current BASE stop\n";
1658             last;
1659         }
1660         my $cl = classify $current;
1661         print " $current $cl->{Type}";
1662         my $keep = 0;
1663         my $p0 = $cl->{Parents}[0]{CommitId};
1664         my $next;
1665         if ($cl->{Type} eq 'Pseudomerge') {
1666             print " ^".($cl->{Contributor}{Ix}+1);
1667             $next = $cl->{Contributor}{CommitId};
1668         } elsif ($cl->{Type} eq 'AddPatches' or
1669                  $cl->{Type} eq 'Changelog') {
1670             print " strip";
1671             $next = $p0;
1672         } else {
1673             print " keep";
1674             $next = $p0;
1675             $keep = 1;
1676         }
1677         print "\n";
1678         if ($keep) {
1679             $topmost_keep //= $current;
1680         } else {
1681             die "to-be stripped changes not on top of the branch\n"
1682                 if $topmost_keep;
1683         }
1684         $current = $next;
1685     }
1686     if ($topmost_keep eq $old_head) {
1687         print "unchanged\n";
1688     } else {
1689         print "updating to $topmost_keep\n";
1690         update_head_checkout
1691             $old_head, $topmost_keep,
1692             'downstream-rebase-launder-v0';
1693     }
1694 }
1695
1696 GetOptions("D+" => \$debuglevel,
1697            'noop-ok', => \$opt_noop_ok,
1698            'f=s' => \@snag_force_opts,
1699            'anchor=s' => \@opt_anchors,
1700            'force!',
1701            '-i:s' => sub {
1702                my ($opt,$val) = @_;
1703                badusage "git-debrebase: no cuddling to -i for git-rebase"
1704                    if length $val;
1705                die if $opt_defaultcmd_interactive; # should not happen
1706                $opt_defaultcmd_interactive = [ qw(-i) ];
1707                # This access to @ARGV is excessive familiarity with
1708                # Getopt::Long, but there isn't another sensible
1709                # approach.  '-i=s{0,}' does not work with bundling.
1710                push @$opt_defaultcmd_interactive, @ARGV;
1711                @ARGV=();
1712            }) or die badusage "bad options\n";
1713 initdebug('git-debrebase ');
1714 enabledebug if $debuglevel;
1715
1716 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1717 chdir $toplevel or die "chdir $toplevel: $!";
1718
1719 $rd = fresh_playground "$playprefix/misc";
1720
1721 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1722
1723 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1724     defaultcmd_rebase();
1725 } else {
1726     my $cmd = shift @ARGV;
1727     my $cmdfn = $cmd;
1728     $cmdfn =~ y/-/_/;
1729     $cmdfn = ${*::}{"cmd_$cmdfn"};
1730
1731     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1732     $cmdfn->();
1733 }
1734
1735 finish 0;