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