chiark / gitweb /
git-debrebase: factor out getoptions for subcommand
[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, $version) = @_;
1189
1190     my $new_upstream_version = "$version";
1191     $new_upstream_version =~ s/-.*?$//;;
1192
1193     if (!defined $new_upstream) {
1194         my @tried;
1195         # todo: at some point maybe use git-deborig to do this
1196         foreach my $tagpfx ('', 'v', 'upstream/') {
1197             my $tag = $tagpfx.(dep14_version_mangle $new_upstream_version);
1198             $new_upstream = git_get_ref "refs/tags/$tag";
1199             last if length $new_upstream;
1200             push @tried, $tag;
1201         }
1202         if (!length $new_upstream) {
1203             fail "Could not determine appropriate upstream commitish.\n".
1204                 " (Tried these tags: @tried)\n".
1205                 " Check version, and specify upstream commitish explicitly.";
1206         }
1207     }
1208     $new_upstream = git_rev_parse $new_upstream;
1209
1210     return ($new_upstream, $new_upstream_version);
1211 }
1212
1213 sub cmd_new_upstream () {
1214     # automatically and unconditionally launders before rebasing
1215     # if rebase --abort is used, laundering has still been done
1216
1217     my %pieces;
1218
1219     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1220
1221     # parse args - low commitment
1222     my $spec_version = shift @ARGV;
1223     my $new_version = (new Dpkg::Version $spec_version, check => 1);
1224     fail "bad version number \`$spec_version'" unless defined $new_version;
1225     if ($new_version->is_native()) {
1226         $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1227     }
1228
1229     my $new_upstream = shift @ARGV;
1230     my $new_upstream_version;
1231     ($new_upstream, $new_upstream_version) =
1232         resolve_upstream_version $new_upstream, $new_version;
1233
1234     record_ffq_auto();
1235
1236     my $piece = sub {
1237         my ($n, @x) = @_; # may be ''
1238         my $pc = $pieces{$n} //= {
1239             Name => $n,
1240             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1241         };
1242         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1243         $pc;
1244     };
1245
1246     my @newpieces;
1247     my $newpiece = sub {
1248         my ($n, @x) = @_; # may be ''
1249         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1250         push @newpieces, $pc;
1251     };
1252
1253     $newpiece->('',
1254         OldIx => 0,
1255         New => $new_upstream,
1256     );
1257     while (@ARGV && $ARGV[0] !~ m{^-}) {
1258         my $n = shift @ARGV;
1259
1260         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1261             unless @ARGV && $ARGV[0] !~ m{^-};
1262
1263         my $c = git_rev_parse shift @ARGV;
1264         die unless $n =~ m/^$extra_orig_namepart_re$/;
1265         $newpiece->($n, New => $c);
1266     }
1267
1268     # now we need to investigate the branch this generates the
1269     # laundered version but we don't switch to it yet
1270     my $old_head = get_head();
1271     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1272
1273     my $old_bw_cl = classify $old_bw;
1274     my $old_anchor_cl = classify $old_anchor;
1275     my $old_upstream;
1276     if (!$old_anchor_cl->{OrigParents}) {
1277         snag 'anchor-treated',
1278             'old anchor is recognised due to --anchor, cannot check upstream';
1279     } else {
1280         $old_upstream = parsecommit
1281             $old_anchor_cl->{OrigParents}[0]{CommitId};
1282         $piece->('', Old => $old_upstream->{CommitId});
1283     }
1284
1285     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1286         if ($old_upstream->{Msg} =~
1287  m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1288            ) {
1289             my @oldpieces = (split / /, $1);
1290             my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1291             if ($old_n_parents != @oldpieces &&
1292                 $old_n_parents != @oldpieces + 1) {
1293                 snag 'upstream-confusing', sprintf
1294                     "previous upstream combine %s".
1295                     " mentions %d pieces (each implying one parent)".
1296                     " but has %d parents".
1297                     " (one per piece plus maybe a previous combine)",
1298                     $old_upstream->{CommitId},
1299                     (scalar @oldpieces),
1300                     $old_n_parents;
1301             } elsif ($oldpieces[0] ne '.') {
1302                 snag 'upstream-confusing', sprintf
1303                     "previous upstream combine %s".
1304                     " first piece is not \`.'",
1305                     $oldpieces[0];
1306             } else {
1307                 $oldpieces[0] = '';
1308                 foreach my $i (0..$#oldpieces) {
1309                     my $n = $oldpieces[$i];
1310                     my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1311                     $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1312                 }
1313             }
1314         } else {
1315             snag 'upstream-confusing',
1316                 "previous upstream $old_upstream->{CommitId} is from".
1317                " git-debrebase but not an \`upstream-combine' commit";
1318         }
1319     }
1320
1321     foreach my $pc (values %pieces) {
1322         if (!$old_upstream) {
1323             # we have complained already
1324         } elsif (!$pc->{Old}) {
1325             snag 'upstream-new-piece',
1326                 "introducing upstream piece \`$pc->{Name}'";
1327         } elsif (!$pc->{New}) {
1328             snag 'upstream-rm-piece',
1329                 "dropping upstream piece \`$pc->{Name}'";
1330         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1331             snag 'upstream-not-ff',
1332                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1333         }
1334     }
1335
1336     printdebug "%pieces = ", (dd \%pieces), "\n";
1337     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1338
1339     snags_maybe_bail();
1340
1341     my $new_bw;
1342
1343     fresh_workarea();
1344     in_workarea sub {
1345         my @upstream_merge_parents;
1346
1347         if (!any_snags()) {
1348             push @upstream_merge_parents, $old_upstream->{CommitId};
1349         }
1350
1351         foreach my $pc (@newpieces) { # always has '' first
1352             if ($pc->{Name}) {
1353                 read_tree_subdir $pc->{Name}, $pc->{New};
1354             } else {
1355                 runcmd @git, qw(read-tree), $pc->{New};
1356             }
1357             push @upstream_merge_parents, $pc->{New};
1358         }
1359
1360         # index now contains the new upstream
1361
1362         if (@newpieces > 1) {
1363             # need to make the upstream subtree merge commit
1364             $new_upstream = make_commit \@upstream_merge_parents,
1365                 [ "Combine upstreams for $new_upstream_version",
1366  ("[git-debrebase upstream-combine . ".
1367  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1368  ": new upstream]"),
1369                 ];
1370         }
1371
1372         # $new_upstream is either the single upstream commit, or the
1373         # combined commit we just made.  Either way it will be the
1374         # "upstream" parent of the anchor merge.
1375
1376         read_tree_subdir 'debian', "$old_bw:debian";
1377
1378         # index now contains the anchor merge contents
1379         $new_bw = make_commit [ $old_bw, $new_upstream ],
1380             [ "Update to upstream $new_upstream_version",
1381  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1382             ];
1383
1384         my $clogsignoff = cmdoutput qw(git show),
1385             '--pretty=format:%an <%ae>  %aD',
1386             $new_bw;
1387
1388         # Now we have to add a changelog stanza so the Debian version
1389         # is right.
1390         die if unlink "debian";
1391         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1392         unlink "debian/changelog" or $!==ENOENT or die $!;
1393         mkdir "debian" or die $!;
1394         open CN, ">", "debian/changelog" or die $!;
1395         my $oldclog = git_cat_file ":debian/changelog";
1396         $oldclog =~ m/^($package_re) \(\S+\) / or
1397             fail "cannot parse old changelog to get package name";
1398         my $p = $1;
1399         print CN <<END, $oldclog or die $!;
1400 $p ($new_version) UNRELEASED; urgency=medium
1401
1402   * Update to new upstream version $new_upstream_version.
1403
1404  -- $clogsignoff
1405
1406 END
1407         close CN or die $!;
1408         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1409
1410         # Now we have the final new breakwater branch in the index
1411         $new_bw = make_commit [ $new_bw ],
1412             [ "Update changelog for new upstream $new_upstream_version",
1413               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1414             ];
1415     };
1416
1417     # we have constructed the new breakwater. we now need to commit to
1418     # the laundering output, because git-rebase can't easily be made
1419     # to make a replay list which is based on some other branch
1420
1421     update_head_postlaunder $old_head, $old_laundered_tip,
1422         'launder for new upstream';
1423
1424     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1425     local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1426         "debrebase new-upstream $new_version: rebase";
1427     runcmd @cmd;
1428     # now it's for the user to sort out
1429 }
1430
1431 sub cmd_record_ffq_prev () {
1432     badusage "no arguments allowed" if @ARGV;
1433     my ($status, $msg) = record_ffq_prev_deferred();
1434     if ($status eq 'exists' && $opt_noop_ok) {
1435         print "Previous head already recorded\n" or die $!;
1436     } elsif ($status eq 'deferred') {
1437         run_deferred_updates 'record-ffq-prev';
1438     } else {
1439         fail "Could not preserve: $msg";
1440     }
1441 }
1442
1443 sub cmd_anchor () {
1444     badusage "no arguments allowed" if @ARGV;
1445     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1446     print "$bw\n" or die $!;
1447 }
1448
1449 sub cmd_breakwater () {
1450     badusage "no arguments allowed" if @ARGV;
1451     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1452     print "$bw\n" or die $!;
1453 }
1454
1455 sub cmd_status () {
1456     badusage "no arguments allowed" if @ARGV;
1457
1458     # todo: gdr status should print divergence info
1459     # todo: gdr status should print upstream component(s) info
1460     # todo: gdr should leave/maintain some refs with this kind of info ?
1461
1462     my $oldest = { Badness => 0 };
1463     my $newest;
1464     my $note = sub {
1465         my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1466         if ($oldest->{Badness} < $badness) {
1467             $oldest = $newest = undef;
1468         }
1469         $oldest = {
1470                    Badness => $badness,
1471                    CommitId => $cl->{CommitId},
1472                    OurMsg => $ourmsg,
1473                    KcMsg => $kcmsg,
1474                   };
1475         $newest //= $oldest;
1476     };
1477     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1478         sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1479         sub { $note->(2, 'branch is unlaundered', @_); },
1480         sub { $note->(3, 'branch needs laundering', @_); },
1481         sub { $note->(4, 'branch not in git-debrebase form', @_); };
1482
1483     my $prcommitinfo = sub {
1484         my ($cid) = @_;
1485         flush STDOUT or die $!;
1486         runcmd @git, qw(--no-pager log -n1),
1487             '--pretty=format:    %h %s%n',
1488             $cid;
1489     };
1490
1491     print "current branch contents, in git-debrebase terms:\n";
1492     if (!$oldest->{Badness}) {
1493         print "  branch is laundered\n";
1494     } else {
1495         print "  $oldest->{OurMsg}\n";
1496         my $printed = '';
1497         foreach my $info ($oldest, $newest) {
1498             my $cid = $info->{CommitId};
1499             next if $cid eq $printed;
1500             $printed = $cid;
1501             print "  $info->{KcMsg}\n";
1502             $prcommitinfo->($cid);
1503         }
1504     }
1505
1506     my $prab = sub {
1507         my ($cid, $what) = @_;
1508         if (!defined $cid) {
1509             print "  $what is not well-defined\n";
1510         } else {
1511             print "  $what\n";
1512             $prcommitinfo->($cid);
1513         }
1514     };
1515     print "key git-debrebase commits:\n";
1516     $prab->($anchor, 'anchor');
1517     $prab->($bw, 'breakwater');
1518
1519     my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1520         ffq_prev_branchinfo();
1521
1522     print "branch and ref status, in git-debrebase terms:\n";
1523     if ($ffq_msg) {
1524         print "  $ffq_msg\n";
1525     } else {
1526         $ffq_prev = git_get_ref $ffq_prev;
1527         $gdrlast = git_get_ref $gdrlast;
1528         if ($ffq_prev) {
1529             print "  unstitched; previous tip was:\n";
1530             $prcommitinfo->($ffq_prev);
1531         } elsif (!$gdrlast) {
1532             print "  stitched? (no record of git-debrebase work)\n";
1533         } elsif (is_fast_fwd $gdrlast, 'HEAD') {
1534             print "  stitched\n";
1535         } else {
1536             print "  not git-debrebase (diverged since last stitch)\n"
1537         }
1538     }
1539 }
1540
1541 sub cmd_stitch () {
1542     my $prose = 'stitch';
1543     getoptions("stitch",
1544                'prose=s', \$prose);
1545     badusage "no arguments allowed" if @ARGV;
1546     do_stitch $prose, 0;
1547 }
1548 sub cmd_prepush () { cmd_stitch(); }
1549
1550 sub cmd_quick () {
1551     badusage "no arguments allowed" if @ARGV;
1552     do_launder_head 'launder for git-debrebase quick';
1553     do_stitch 'quick';
1554 }
1555
1556 sub cmd_conclude () {
1557     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1558     if (!$ffq_prev_commitish) {
1559         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
1560         return;
1561     }
1562     my $dangling_head = get_head();
1563     
1564     badusage "no arguments allowed" if @ARGV;
1565     do_launder_head 'launder for git-debrebase quick';
1566     do_stitch 'quick';
1567 }
1568
1569 sub make_patches_staged ($) {
1570     my ($head) = @_;
1571     # Produces the patches that would result from $head if it were
1572     # laundered.
1573     my ($secret_head, $secret_bw, $last_anchor) = walk $head;
1574     fresh_workarea();
1575     in_workarea sub {
1576         runcmd @git, qw(checkout -q -b bw), $secret_bw;
1577         runcmd @git, qw(checkout -q -b patch-queue/bw), $secret_head;
1578         my @gbp_cmd = (qw(gbp pq export));
1579         my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
1580         if ($r) {
1581             { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
1582             failedcmd @gbp_cmd;
1583         }
1584         runcmd @git, qw(add -f debian/patches);
1585     };
1586 }
1587
1588 sub make_patches ($) {
1589     my ($head) = @_;
1590     keycommits $head, 0, \&snag;
1591     make_patches_staged $head;
1592     my $out;
1593     in_workarea sub {
1594         my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
1595         runcmd @git, qw(read-tree), $head;
1596         read_tree_subdir 'debian/patches', $ptree;
1597         $out = make_commit [$head], [
1598             'Commit patch queue (exported by git-debrebase)',
1599             '[git-debrebase: export and commit patches]',
1600         ];
1601     };
1602     return $out;
1603 }
1604
1605 sub cmd_make_patches () {
1606     my $opt_quiet_would_amend;
1607     getoptions("make-patches",
1608                'quiet-would-amend!', \$opt_quiet_would_amend);
1609     badusage "no arguments allowed" if @ARGV;
1610     my $old_head = get_head();
1611     my $new = make_patches $old_head;
1612     my $d = get_differs $old_head, $new;
1613     if ($d == 0) {
1614         fail "No (more) patches to export." unless $opt_noop_ok;
1615         return;
1616     } elsif ($d == D_PAT_ADD) {
1617         snags_maybe_bail();
1618         update_head_checkout $old_head, $new, 'make-patches';
1619     } else {
1620         print STDERR failmsg
1621             "Patch export produced patch amendments".
1622             " (abandoned output commit $new).".
1623             "  Try laundering first."
1624             unless $opt_quiet_would_amend;
1625         finish 7;
1626     }
1627 }
1628
1629 sub cmd_convert_from_gbp () {
1630     badusage "want only 1 optional argument, the upstream git commitish"
1631         unless @ARGV<=1;
1632
1633     my $clogp = parsechangelog();
1634     my $version = $clogp->{'Version'}
1635         // die "missing Version from changelog";
1636
1637     my ($upstream_spec) = @ARGV;
1638
1639     my ($upstream, $upstream_version) =
1640         resolve_upstream_version($upstream_spec, $version);
1641
1642     my $old_head = get_head();
1643
1644     my $upsdiff = get_differs $upstream, $old_head;
1645     if ($upsdiff & D_UPS) {
1646         runcmd @git, qw(--no-pager diff --stat),
1647             $upstream, $old_head,
1648             qw( -- :!/debian :/);
1649         fail <<END;
1650 upstream ($upstream_spec) and HEAD are not
1651 identical in upstream files.  See diffstat above, or run
1652   git diff $upstream_spec HEAD -- :!/debian :/
1653 END
1654     }
1655
1656     if (!is_fast_fwd $upstream, $old_head) {
1657         snag 'upstream-not-ancestor',
1658             "upstream ($upstream) is not an ancestor of HEAD";
1659     } else {
1660         my $wrong = cmdoutput
1661             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1662              qw(-- :/ :!/debian));
1663         if (length $wrong) {
1664             snag 'unexpected-upstream-changes',
1665                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1666             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1667         }
1668     }
1669
1670     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1671         snag 'upstream-has-debian',
1672             "upstream ($upstream) contains debian/ directory";
1673     }
1674
1675     my $previous_dgit_view = eval {
1676         my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
1677         my ($lvsn, $suite);
1678         parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
1679             my ($stz, $desc) = @_;
1680             no warnings qw(exiting);
1681             printdebug 'CHANGELOG ', Dumper($desc, $stz);
1682             next unless $stz->{Date};
1683             next unless $stz->{Distribution} ne 'UNRELEASED';
1684             $lvsn = $stz->{Version};
1685             $suite = $stz->{Distribution};
1686             last;
1687         };
1688         die "neither of the first two changelog entries are released\n"
1689             unless defined $lvsn;
1690         print "last finished-looking changelog entry: ($lvsn) $suite\n";
1691         my $mtag_pat = debiantag_maintview $lvsn, '*';
1692         my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
1693             $mtag_pat;
1694         die "could not find suitable maintainer view tag $mtag_pat\n"
1695             unless $mtag_pat =~ m{/};
1696         is_fast_fwd $mtag, 'HEAD' or
1697             die "HEAD is not FF from maintainer tag $mtag!";
1698         my $dtag = "archive/$mtag";
1699         is_fast_fwd $mtag, $dtag or
1700             die "dgit view tag $dtag is not FF from maintainer tag $mtag";
1701         print "will stitch in dgit view, $dtag\n";
1702         git_rev_parse $dtag;
1703     };
1704     if (!$previous_dgit_view) {
1705         $@ =~ s/^\n+//;
1706         chomp $@;
1707         print STDERR "cannot stitch in dgit view: $@\n";
1708     }
1709
1710     snags_maybe_bail_early();
1711
1712     my $work;
1713
1714     fresh_workarea();
1715     in_workarea sub {
1716         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1717         # make a branch out of the patch queue - we'll want this in a mo
1718         runcmd qw(gbp pq import);
1719         # strip the patches out
1720         runcmd @git, qw(checkout -q gdr-internal~0);
1721         rm_subdir_cached 'debian/patches';
1722         $work = make_commit ['HEAD'], [
1723  'git-debrebase convert-from-gbp: drop patches from tree',
1724  'Delete debian/patches, as part of converting to git-debrebase format.',
1725  '[git-debrebase convert-from-gbp: drop patches from tree]'
1726                               ];
1727         # make the anchor merge
1728         # the tree is already exactly right
1729         $work = make_commit [$work, $upstream], [
1730  'git-debrebase import: declare upstream',
1731  'First breakwater merge.',
1732  '[git-debrebase anchor: declare upstream]'
1733                               ];
1734
1735         # rebase the patch queue onto the new breakwater
1736         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1737         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1738         $work = git_rev_parse 'HEAD';
1739
1740         if ($previous_dgit_view) {
1741             $work = make_commit [$work, $previous_dgit_view], [
1742  'git-debrebase import: declare ff from dgit archive view',
1743  '[git-debrebase pseudomerge: import-from-gbp]',
1744             ];
1745         }
1746     };
1747
1748     ffq_check $work;
1749     snags_maybe_bail();
1750     update_head_checkout $old_head, $work, 'convert-from-gbp';
1751 }
1752
1753 sub cmd_convert_to_gbp () {
1754     badusage "no arguments allowed" if @ARGV;
1755     my $head = get_head();
1756     my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1757     keycommits $head, 0;
1758     my $out;
1759     make_patches_staged $head;
1760     in_workarea sub {
1761         $out = make_commit ['HEAD'], [
1762             'Commit patch queue (converted from git-debrebase format)',
1763             '[git-debrebase convert-to-gbp: commit patches]',
1764         ];
1765     };
1766     if (defined $ffq) {
1767         push @deferred_updates, "delete $ffq";
1768         push @deferred_updates, "delete $gdrlast";
1769     }
1770     snags_maybe_bail();
1771     update_head_checkout $head, $out, "convert to gbp (v0)";
1772     print <<END or die $!;
1773 git-debrebase: converted to git-buildpackage branch format
1774 git-debrebase: WARNING: do not now run "git-debrebase" any more
1775 git-debrebase: WARNING: doing so would drop all upstream patches!
1776 END
1777 }
1778
1779 sub cmd_downstream_rebase_launder_v0 () {
1780     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1781     my ($base) = @ARGV;
1782     $base = git_rev_parse $base;
1783     my $old_head = get_head();
1784     my $current = $old_head;
1785     my $topmost_keep;
1786     for (;;) {
1787         if ($current eq $base) {
1788             $topmost_keep //= $current;
1789             print " $current BASE stop\n";
1790             last;
1791         }
1792         my $cl = classify $current;
1793         print " $current $cl->{Type}";
1794         my $keep = 0;
1795         my $p0 = $cl->{Parents}[0]{CommitId};
1796         my $next;
1797         if ($cl->{Type} eq 'Pseudomerge') {
1798             print " ^".($cl->{Contributor}{Ix}+1);
1799             $next = $cl->{Contributor}{CommitId};
1800         } elsif ($cl->{Type} eq 'AddPatches' or
1801                  $cl->{Type} eq 'Changelog') {
1802             print " strip";
1803             $next = $p0;
1804         } else {
1805             print " keep";
1806             $next = $p0;
1807             $keep = 1;
1808         }
1809         print "\n";
1810         if ($keep) {
1811             $topmost_keep //= $current;
1812         } else {
1813             die "to-be stripped changes not on top of the branch\n"
1814                 if $topmost_keep;
1815         }
1816         $current = $next;
1817     }
1818     if ($topmost_keep eq $old_head) {
1819         print "unchanged\n";
1820     } else {
1821         print "updating to $topmost_keep\n";
1822         update_head_checkout
1823             $old_head, $topmost_keep,
1824             'downstream-rebase-launder-v0';
1825     }
1826 }
1827
1828 getoptions_main
1829           ("bad options\n",
1830            "D+" => \$debuglevel,
1831            'noop-ok', => \$opt_noop_ok,
1832            'f=s' => \@snag_force_opts,
1833            'anchor=s' => \@opt_anchors,
1834            'force!',
1835            '-i:s' => sub {
1836                my ($opt,$val) = @_;
1837                badusage "git-debrebase: no cuddling to -i for git-rebase"
1838                    if length $val;
1839                die if $opt_defaultcmd_interactive; # should not happen
1840                $opt_defaultcmd_interactive = [ qw(-i) ];
1841                # This access to @ARGV is excessive familiarity with
1842                # Getopt::Long, but there isn't another sensible
1843                # approach.  '-i=s{0,}' does not work with bundling.
1844                push @$opt_defaultcmd_interactive, @ARGV;
1845                @ARGV=();
1846            },
1847            'help' => sub { print $usage_message or die $!; finish 0; },
1848            );
1849
1850 initdebug('git-debrebase ');
1851 enabledebug if $debuglevel;
1852
1853 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1854 chdir $toplevel or die "chdir $toplevel: $!";
1855
1856 $rd = fresh_playground "$playprefix/misc";
1857
1858 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1859
1860 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
1861     defaultcmd_rebase();
1862 } else {
1863     my $cmd = shift @ARGV;
1864     my $cmdfn = $cmd;
1865     $cmdfn =~ y/-/_/;
1866     $cmdfn = ${*::}{"cmd_$cmdfn"};
1867
1868     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1869     $cmdfn->();
1870 }
1871
1872 finish 0;