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