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