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