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