chiark / gitweb /
git-debrebase: fix Overwritten to be an array like it says, etc.
[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
22 # usages:
23 #
24 #    git-debrebase [<options>] new-upstream-v0 \
25 #             <new-version> <orig-commitish> \
26 #            [<extra-orig-name> <extra-orig-commitish> ...] \
27 #            [<git-rebase options>...]
28 #
29 #    git-debrebase [<options> --] [<git-rebase options...>]
30 #    git-debrebase [<options>] analyse
31 #    git-debrebase [<options>] launder         # prints breakwater tip etc.
32 #    git-debrebase [<options>] stitch [--prose=<for commit message>]
33 #    git-debrebase [<options>] downstream-rebase-launder-v0  # experimental
34 #
35 #    git-debrebase [<options>] gbp2debrebase-v0 \
36 #             <upstream>
37
38 # problems / outstanding questions:
39 #
40 #  *  dgit push with a `3.0 (quilt)' package means doing quilt
41 #     fixup.  Usually this involves recommitting the whole patch
42 #     series, one at a time, with dpkg-source --commit.  This is
43 #     terribly terribly slow.  (Maybe this should be fixed in dgit.)
44 #
45 #  * dgit push usually needs to (re)make a pseudomerge.  The "first"
46 #    git-debrebase stripped out the previous pseudomerge and could
47 #    have remembeed the HEAD.  But it's not quite clear what history
48 #    ought to be preserved and what should be discarded.  For now
49 #    the user will have to tell dgit --overwrite.
50 #
51 #    To fix this, do we need a new push hook for dgit ?
52 #
53 #  * Workflow is currently clumsy.  Lots of spurious runes to type.
54 #    There's not even a guide.
55 #
56 #  * There are no tests.
57 #
58 #  * new-upstream-v0 has a terrible UI.  You end up with giant
59 #    runic command lines.
60 #
61 #    One consequence of the lack of richness it can need --force in
62 #    fairly sensible situations and there is no way to tell it what
63 #    you are really trying to do, other than just --force.  There
64 #    should be an interface with some default branch names.
65 #
66 #  * There should be a standard convention for the version number,
67 #    and unfinalised or not changelog, after new-upstream.
68 #
69 #  * Handing of multi-orig dgit new-upstream .dsc imports is known to
70 #    be broken.  They may be not recognised, improperly converted, or
71 #    their conversion may be unrecognised.
72 #
73 #  * Docs need writing and updating.  Even README.git-debrebase
74 #    describes a design but may not reflect the implementation.
75 #
76 #  * We need to develop a plausible model that works for derivatives,
77 #    who probably want to maintain their stack on top of Debian's.
78 #    downstream-rebase-launder-v0 may be a starting point?
79
80 use strict;
81
82 use Debian::Dgit qw(:DEFAULT :playground);
83 setup_sigwarn();
84
85 use Memoize;
86 use Carp;
87 use POSIX;
88 use Data::Dumper;
89 use Getopt::Long qw(:config posix_default gnu_compat bundling);
90 use Dpkg::Version;
91 use File::FnMatch qw(:fnmatch);
92
93 our ($opt_force, $opt_noop_ok);
94
95 our $us = qw(git-debrebase);
96
97 sub badusage ($) {
98     my ($m) = @_;
99     die "bad usage: $m\n";
100 }
101
102 sub cfg ($;$) {
103     my ($k, $optional) = @_;
104     local $/ = "\0";
105     my @cmd = qw(git config -z);
106     push @cmd, qw(--get-all) if wantarray;
107     push @cmd, $k;
108     my $out = cmdoutput_errok @cmd;
109     if (!defined $out) {
110         fail "missing required git config $k" unless $optional;
111         return ();
112     }
113     return split /\0/, $out;
114 }
115
116 memoize('cfg');
117
118 sub dd ($) {
119     my ($v) = @_;
120     my $dd = new Data::Dumper [ $v ];
121     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
122     return Dump $dd;
123 }
124
125 sub get_commit ($) {
126     my ($objid) = @_;
127     my $data = (git_cat_file $objid, 'commit');
128     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
129     return ($`,$');
130 }
131
132 sub D_UPS ()      { 0x02; } # upstream files
133 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
134 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
135 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
136 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
137 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
138
139 our $playprefix = 'debrebase';
140 our $rd;
141 our $workarea;
142
143 our @git = qw(git);
144
145 sub in_workarea ($) {
146     my ($sub) = @_;
147     changedir $workarea;
148     my $r = eval { $sub->(); };
149     { local $@; changedir $maindir; }
150     die $@ if $@;
151 }
152
153 sub fresh_workarea () {
154     $workarea = fresh_playground "$playprefix/work";
155     in_workarea sub { playtree_setup };
156 }
157
158 sub get_differs ($$) {
159     my ($x,$y) = @_;
160     # This resembles quiltify_trees_differ, in dgit, a bit.
161     # But we don't care about modes, or dpkg-source-unrepresentable
162     # changes, and we don't need the plethora of different modes.
163     # Conversely we need to distinguish different kinds of changes to
164     # debian/ and debian/patches/.
165
166     my $differs = 0;
167
168     my $rundiff = sub {
169         my ($opts, $limits, $fn) = @_;
170         my @cmd = (@git, qw(diff-tree -z --no-renames));
171         push @cmd, @$opts;
172         push @cmd, "$_:" foreach $x, $y;
173         push @cmd, '--', @$limits;
174         my $diffs = cmdoutput @cmd;
175         foreach (split /\0/, $diffs) { $fn->(); }
176     };
177
178     $rundiff->([qw(--name-only)], [], sub {
179         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
180     });
181
182     if ($differs & DS_DEB) {
183         $differs &= ~DS_DEB;
184         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
185             $differs |=
186                 m{^debian/patches/}      ? D_PAT_OTH  :
187                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
188                                            D_DEB_OTH;
189         });
190         die "mysterious debian changes $x..$y"
191             unless $differs & (D_PAT_OTH|DS_DEB);
192     }
193
194     if ($differs & D_PAT_OTH) {
195         my $mode;
196         $differs &= ~D_PAT_OTH;
197         my $pat_oth = sub {
198             $differs |= D_PAT_OTH;
199             no warnings qw(exiting);  last;
200         };
201         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
202             no warnings qw(exiting);
203             if (!defined $mode) {
204                 $mode = $_;  next;
205             }
206             die unless s{^debian/patches/}{};
207             my $ok;
208             if ($mode eq 'A' && !m/\.series$/s) {
209                 $ok = 1;
210             } elsif ($mode eq 'M' && $_ eq 'series') {
211                 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
212                 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
213                 chomp $x_s;  $x_s .= "\n";
214                 $ok = $x_s eq substr($y_s, 0, length $x_s);
215             } else {
216                 # nope
217             }
218             $mode = undef;
219             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
220         });
221         die "mysterious debian/patches changes $x..$y"
222             unless $differs & (D_PAT_ADD|D_PAT_OTH);
223     }
224
225     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
226
227     return $differs;
228 }
229
230 sub commit_pr_info ($) {
231     my ($r) = @_;
232     return Data::Dumper->dump([$r], [qw(commit)]);
233 }
234
235 sub calculate_committer_authline () {
236     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
237         'DUMMY COMMIT (git-debrebase)', "HEAD:";
238     my ($h,$m) = get_commit $c;
239     $h =~ m/^committer .*$/m or confess "($h) ?";
240     return $&;
241 }
242
243 sub rm_subdir_cached ($) {
244     my ($subdir) = @_;
245     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
246 }
247
248 sub read_tree_subdir ($$) {
249     my ($subdir, $new_tree_object) = @_;
250     rm_subdir_cached $subdir;
251     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
252 }
253
254 sub make_commit ($$) {
255     my ($parents, $message_paras) = @_;
256     my $tree = cmdoutput @git, qw(write-tree);
257     my @cmd = (@git, qw(commit-tree), $tree);
258     push @cmd, qw(-p), $_ foreach @$parents;
259     push @cmd, qw(-m), $_ foreach @$message_paras;
260     return cmdoutput @cmd;
261 }
262
263 our @fproblem_force_opts;
264 our $fproblems_forced;
265 our $fproblems_tripped;
266 sub fproblem ($$) {
267     my ($tag,$msg) = @_;
268     if (grep { $_ eq $tag } @fproblem_force_opts) {
269         $fproblems_forced++;
270         print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
271     } else {
272         $fproblems_tripped++;
273         print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
274     }
275 }
276
277 sub fproblems_maybe_bail () {
278     if ($fproblems_forced) {
279         printf STDERR
280             "%s: safety catch trips: %d overriden by individual -f options\n",
281             $us, $fproblems_forced;
282     }
283     if ($fproblems_tripped) {
284         if ($opt_force) {
285             printf STDERR
286                 "%s: safety catch trips: %d overriden by global --force\n",
287                 $us, $fproblems_tripped;
288         } else {
289             fail sprintf
290   "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
291                 $us, $fproblems_tripped;
292         }
293     }
294 }
295 sub any_fproblems () {
296     return $fproblems_forced || $fproblems_tripped;
297 }
298
299 # classify returns an info hash like this
300 #   CommitId => $objid
301 #   Hdr => # commit headers, including 1 final newline
302 #   Msg => # commit message (so one newline is dropped)
303 #   Tree => $treeobjid
304 #   Type => (see below)
305 #   Parents = [ {
306 #       Ix => $index # ie 0, 1, 2, ...
307 #       CommitId
308 #       Differs => return value from get_differs
309 #       IsOrigin
310 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
311 #     } ...]
312 #   NewMsg => # commit message, but with any [dgit import ...] edited
313 #             # to say "[was: ...]"
314 #
315 # Types:
316 #   Packaging
317 #   Changelog
318 #   Upstream
319 #   AddPatches
320 #   Mixed
321 #   Unknown
322 #
323 #   Pseudomerge
324 #     has additional entres in classification result
325 #       Overwritten = [ subset of Parents ]
326 #       Contributor = $the_remaining_Parent
327 #
328 #   DgitImportUnpatched
329 #     has additional entry in classification result
330 #       OrigParents = [ subset of Parents ]
331 #
332 #   BreakwaterUpstreamMerge
333 #     has additional entry in classification result
334 #       OrigParents = [ subset of Parents ]  # singleton list
335
336 sub parsecommit ($;$) {
337     my ($objid, $p_ref) = @_;
338     # => hash with                   CommitId Hdr Msg Tree Parents
339     #    Parents entries have only   Ix CommitId
340     #    $p_ref, if provided, must be [] and is used as a base for Parents
341
342     $p_ref //= [];
343     die if @$p_ref;
344
345     my ($h,$m) = get_commit $objid;
346
347     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
348     my (@ph) = $h =~ m/^parent (\w+)$/mg;
349
350     my $r = {
351         CommitId => $objid,
352         Hdr => $h,
353         Msg => $m,
354         Tree => $t,
355         Parents => $p_ref,
356     };
357
358     foreach my $ph (@ph) {
359         push @$p_ref, {
360             Ix => scalar @$p_ref,
361             CommitId => $ph,
362         };
363     }
364
365     return $r;
366 }    
367
368 sub classify ($) {
369     my ($objid) = @_;
370
371     my @p;
372     my $r = parsecommit($objid, \@p);
373     my $t = $r->{Tree};
374
375     foreach my $p (@p) {
376         $p->{Differs} = (get_differs $p->{CommitId}, $t),
377     }
378
379     printdebug "classify $objid \$t=$t \@p",
380         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
381         "\n";
382
383     my $classify = sub {
384         my ($type, @rest) = @_;
385         $r = { %$r, Type => $type, @rest };
386         if ($debuglevel) {
387             printdebug " = $type ".(dd $r)."\n";
388         }
389         return $r;
390     };
391     my $unknown = sub {
392         my ($why) = @_;
393         $r = { %$r, Type => qw(Unknown) };
394         printdebug " ** Unknown\n";
395         return $r;
396     };
397
398     my $claims_to_be_breakwater =
399         $r->{Msg} =~ m{^\[git-debrebase breakwater.*\]$}m;
400
401     if (@p == 1) {
402         if ($claims_to_be_breakwater) {
403             return $unknown->("single-parent git-debrebase breakwater \`merge'");
404         }
405         my $d = $r->{Parents}[0]{Differs};
406         if ($d == D_PAT_ADD) {
407             return $classify->(qw(AddPatches));
408         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
409             return $unknown->("edits debian/patches");
410         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
411             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
412             if ($ty eq 'tree') {
413                 if ($d == D_DEB_CLOG) {
414                     return $classify->(qw(Changelog));
415                 } else {
416                     return $classify->(qw(Packaging));
417                 }
418             } elsif ($ty eq 'missing') {
419                 return $classify->(qw(BreakwaterStart));
420             } else {
421                 return $unknown->("parent's debian is not a directory");
422             }
423         } elsif ($d == D_UPS) {
424             return $classify->(qw(Upstream));
425         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
426             return $classify->(qw(Mixed));
427         } elsif ($d == 0) {
428             return $unknown->("no changes");
429         } else {
430             confess "internal error $objid ?";
431         }
432     }
433     if (!@p) {
434         return $unknown->("origin commit");
435     }
436
437     my @identical = grep { !$_->{Differs} } @p;
438     if (@p == 2 && @identical == 1 && !$claims_to_be_breakwater
439         # breakwater merges can look like pseudomerges, if they are
440         # "declare" commits (ie, there are no upstream changes)
441        ) {
442         my @overwritten = grep { $_->{Differs} } @p;
443         confess "internal error $objid ?" unless @overwritten==1;
444         return $classify->(qw(Pseudomerge),
445                            Overwritten => [ $overwritten[0] ],
446                            Contributor => $identical[0]);
447     }
448     if (@p == 2 && @identical == 2) {
449         my @bytime = nsort_by {
450             my ($ph,$pm) = get_commit $_->{CommitId};
451             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
452             $1;
453         } @p;
454         return $classify->(qw(Pseudomerge),
455                            SubType => qw(Ambiguous),
456                            Overwritten => [ $bytime[0] ],
457                            Contributor => $bytime[1]);
458     }
459     foreach my $p (@p) {
460         my ($p_h, $p_m) = get_commit $p->{CommitId};
461         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
462         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
463     }
464     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
465     my $m2 = $r->{Msg};
466     if (!(grep { !$_->{IsOrigin} } @p) and
467         (@orig_ps >= @p - 1) and
468         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
469         $r->{NewMsg} = $m2;
470         return $classify->(qw(DgitImportUnpatched),
471                            OrigParents => \@orig_ps);
472     }
473
474     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
475     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
476
477     # How to decide about l/r ordering of breakwater merges ?  git
478     # --topo-order prefers to expand 2nd parent first.  There's
479     # already an easy rune to look for debian/ history anyway (git log
480     # debian/) so debian breakwater branch should be 1st parent; that
481     # way also there's also an easy rune to look for the upstream
482     # patches (--topo-order).
483
484     # The above tells us which way *we* will generate them.  But we
485     # might encounter ad-hoc breakwater merges generated manually,
486     # which might be the other way around.  In principle, in some odd
487     # situations, a breakwater merge might have two identical parents.
488     # In that case we guess which way round it is (ie, which parent
489     # has the upstream history).  The order of the 2-iteration loop
490     # controls which guess we make.
491
492     foreach my $prevbrw (qw(0 1)) {
493         if (@p == 2 &&
494             !$haspatches &&
495             !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
496             !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
497             !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
498             return $classify->(qw(BreakwaterUpstreamMerge),
499                                OrigParents => [ $p[!$prevbrw] ]);
500         }
501     }
502
503     # multi-orig upstreams are represented with a breakwater merge
504     # from a single upstream commit which combines the orig tarballs
505
506     return $unknown->("complex merge");
507 }
508
509 sub walk ($;$$);
510 sub walk ($;$$) {
511     my ($input,
512         $nogenerate,$report) = @_;
513     # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
514     # (or nothing, if $nogenerate)
515
516     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
517
518     # go through commits backwards
519     # we generate two lists of commits to apply:
520     # breakwater branch and upstream patches
521     my (@brw_cl, @upp_cl, @processed);
522     my %found;
523     my $upp_limit;
524     my @pseudomerges;
525
526     my $cl;
527     my $xmsg = sub {
528         my ($prose, $info) = @_;
529         my $ms = $cl->{Msg};
530         chomp $ms;
531         $info //= '';
532         $ms .= "\n\n[git-debrebase$info: $prose]\n";
533         return (Msg => $ms);
534     };
535     my $rewrite_from_here = sub {
536         my $sp_cl = { SpecialMethod => 'StartRewrite' };
537         push @brw_cl, $sp_cl;
538         push @processed, $sp_cl;
539     };
540     my $cur = $input;
541
542     my $prdelim = "";
543     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
544
545     my $prline = sub {
546         return unless $report;
547         print $report $prdelim, @_;
548         $prdelim = "\n";
549     };
550
551     my $bomb = sub { # usage: return $bomb->();
552         print $report " Unprocessable" if $report;
553         $prprdelim->();
554         if ($nogenerate) {
555             return (undef,undef);
556         }
557         die "commit $cur: Cannot cope with this commit (d.".
558             (join ' ', map { sprintf "%#x", $_->{Differs} }
559              @{ $cl->{Parents} }). ")";
560     };
561
562     my $build;
563     my $breakwater;
564
565     my $build_start = sub {
566         my ($msg, $parent) = @_;
567         $prline->(" $msg");
568         $build = $parent;
569         no warnings qw(exiting); last;
570     };
571
572     my $last_upstream_update;
573
574     for (;;) {
575         $cl = classify $cur;
576         my $ty = $cl->{Type};
577         my $st = $cl->{SubType};
578         $prline->("$cl->{CommitId} $cl->{Type}");
579         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
580         push @processed, $cl;
581         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
582         if ($ty eq 'AddPatches') {
583             $cur = $p0;
584             $rewrite_from_here->();
585             next;
586         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
587             push @brw_cl, $cl;
588             $cur = $p0;
589             next;
590         } elsif ($ty eq 'BreakwaterStart') {
591             $last_upstream_update = $cur;
592             $build_start->('FirstPackaging', $cur);
593         } elsif ($ty eq 'Upstream') {
594             push @upp_cl, $cl;
595             $cur = $p0;
596             next;
597         } elsif ($ty eq 'Mixed') {
598             my $queue = sub {
599                 my ($q, $wh) = @_;
600                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
601                 push @$q, $cls;
602             };
603             $queue->(\@brw_cl, "debian");
604             $queue->(\@upp_cl, "upstream");
605             $rewrite_from_here->();
606             $cur = $p0;
607             next;
608         } elsif ($ty eq 'Pseudomerge') {
609             my $contrib = $cl->{Contributor}{CommitId};
610             print $report " Contributor=$contrib" if $report;
611             push @pseudomerges, $cl;
612             $rewrite_from_here->();
613             $cur = $contrib;
614             next;
615         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
616             $last_upstream_update = $cur;
617             $build_start->("PreviousBreakwater", $cur);
618         } elsif ($ty eq 'DgitImportUnpatched') {
619             my $pm = $pseudomerges[-1];
620             if (defined $pm) {
621                 # To an extent, this is heuristic.  Imports don't have
622                 # a useful history of the debian/ branch.  We assume
623                 # that the first pseudomerge after an import has a
624                 # useful history of debian/, and ignore the histories
625                 # from later pseudomerges.  Often the first pseudomerge
626                 # will be the dgit import of the upload to the actual
627                 # suite intended by the non-dgit NMUer, and later
628                 # pseudomerges may represent in-archive copies.
629                 my $ovwrs = $pm->{Overwritten};
630                 printf $report " PM=%s \@Overwr:%d",
631                     $pm->{CommitId}, (scalar @$ovwrs)
632                     if $report;
633                 if (@$ovwrs != 1) {
634                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
635                     return $bomb->();
636                 }
637                 my $ovwr = $ovwrs->[0]{CommitId};
638                 printf $report " Overwr=%s", $ovwr if $report;
639                 # This import has a tree which is just like a
640                 # breakwater tree, but it has the wrong history.  It
641                 # ought to have the previous breakwater (which the
642                 # pseudomerge overwrote) as an ancestor.  That will
643                 # make the history of the debian/ files correct.  As
644                 # for the upstream version: either it's the same as
645                 # was ovewritten (ie, same as the previous
646                 # breakwater), in which case that history is precisely
647                 # right; or, otherwise, it was a non-gitish upload of a
648                 # new upstream version.  We can tell these apart by
649                 # looking at the tree of the supposed upstream.
650                 push @brw_cl, {
651                     %$cl,
652                     SpecialMethod => 'DgitImportDebianUpdate',
653                     $xmsg->("convert dgit import: debian changes")
654                 };
655                 my $differs = (get_differs $ovwr, $cl->{Tree});
656                 printf $report " Differs=%#x", $differs if $report;
657                 if ($differs & D_UPS) {
658                     printf $report " D_UPS" if $report;
659                     # This will also trigger if a non-dgit git-based NMU
660                     # deleted .gitignore (which is a thing that some of
661                     # the existing git tools do if the user doesn't
662                     # somehow tell them not to).  Ah well.
663                     push @brw_cl, {
664                         %$cl,
665                         SpecialMethod => 'DgitImportUpstreamUpdate',
666                         $xmsg->("convert dgit import: upstream changes",
667                                 " breakwater")
668                     };
669                 }
670                 $prline->(" Import");
671                 $rewrite_from_here->();
672                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
673                 die 'BUG $upp_limit is not used anywhere?';
674                 $cur = $ovwr;
675                 next;
676             } else {
677                 # Everything is from this import.  This kind of import
678                 # is already in valid breakwater format, with the
679                 # patches as commits.
680                 printf $report " NoPM" if $report;
681                 # last thing we processed will have been the first patch,
682                 # if there is one; which is fine, so no need to rewrite
683                 # on account of this import
684                 $build_start->("ImportOrigin", $cur);
685             }
686             die "$ty ?";
687         } else {
688             printdebug "*** WALK BOMB unrecognised\n";
689             return $bomb->();
690         }
691     }
692     $prprdelim->();
693
694     printdebug "*** WALK prep done cur=$cur".
695         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
696
697     return if $nogenerate;
698
699     # Now we build it back up again
700
701     fresh_workarea();
702
703     my $rewriting = 0;
704
705     my $read_tree_debian = sub {
706         my ($treeish) = @_;
707         read_tree_subdir 'debian', "$treeish:debian";
708         rm_subdir_cached 'debian/patches';
709     };
710     my $read_tree_upstream = sub {
711         my ($treeish) = @_;
712         runcmd @git, qw(read-tree), $treeish;
713         $read_tree_debian->($build);
714     };
715  
716     my $committer_authline = calculate_committer_authline();
717
718     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
719
720     confess "internal error" unless $build eq (pop @processed)->{CommitId};
721
722     in_workarea sub {
723         mkdir $rd or $!==EEXIST or die $!;
724         my $current_method;
725         runcmd @git, qw(read-tree), $build;
726         foreach my $cl (qw(Debian), (reverse @brw_cl),
727                         { SpecialMethod => 'RecordBreakwaterTip' },
728                         qw(Upstream), (reverse @upp_cl)) {
729             if (!ref $cl) {
730                 $current_method = $cl;
731                 next;
732             }
733             my $method = $cl->{SpecialMethod} // $current_method;
734             my @parents = ($build);
735             my $cltree = $cl->{CommitId};
736             printdebug "WALK BUILD ".($cltree//'undef').
737                 " $method (rewriting=$rewriting)\n";
738             if ($method eq 'Debian') {
739                 $read_tree_debian->($cltree);
740             } elsif ($method eq 'Upstream') {
741                 $read_tree_upstream->($cltree);
742             } elsif ($method eq 'StartRewrite') {
743                 $rewriting = 1;
744                 next;
745             } elsif ($method eq 'RecordBreakwaterTip') {
746                 $breakwater = $build;
747                 next;
748             } elsif ($method eq 'DgitImportDebianUpdate') {
749                 $read_tree_debian->($cltree);
750                 rm_subdir_cached qw(debian/patches);
751             } elsif ($method eq 'DgitImportUpstreamUpdate') {
752                 $read_tree_upstream->($cltree);
753                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
754             } else {
755                 confess "$method ?";
756             }
757             if (!$rewriting) {
758                 my $procd = (pop @processed) // 'UNDEF';
759                 if ($cl ne $procd) {
760                     $rewriting = 1;
761                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
762                 }
763             }
764             my $newtree = cmdoutput @git, qw(write-tree);
765             my $ch = $cl->{Hdr};
766             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
767             $ch =~ s{^parent .*\n}{}m;
768             $ch =~ s{(?=^author)}{
769                 join '', map { "parent $_\n" } @parents
770             }me or confess "$ch ?";
771             if ($rewriting) {
772                 $ch =~ s{^committer .*$}{$committer_authline}m
773                     or confess "$ch ?";
774             }
775             my $cf = "$rd/m$rewriting";
776             open CD, ">", $cf or die $!;
777             print CD $ch, "\n", $cl->{Msg} or die $!;
778             close CD or die $!;
779             my @cmd = (@git, qw(hash-object));
780             push @cmd, qw(-w) if $rewriting;
781             push @cmd, qw(-t commit), $cf;
782             my $newcommit = cmdoutput @cmd;
783             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
784             $build = $newcommit;
785             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
786                 $last_upstream_update = $cur;
787             }
788         }
789     };
790
791     my $final_check = get_differs $build, $input;
792     die sprintf "internal error %#x %s %s", $final_check, $build, $input
793         if $final_check & ~D_PAT_ADD;
794
795     my @r = ($build, $breakwater, $last_upstream_update);
796     printdebug "*** WALK RETURN @r\n";
797     return @r
798 }
799
800 sub get_head () {
801     git_check_unmodified();
802     return git_rev_parse qw(HEAD);
803 }
804
805 sub update_head ($$$) {
806     my ($old, $new, $mrest) = @_;
807     runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
808 }
809
810 sub update_head_checkout ($$$) {
811     my ($old, $new, $mrest) = @_;
812     update_head $old, $new, $mrest;
813     runcmd @git, qw(reset --hard);
814 }
815
816 sub update_head_postlaunder ($$$) {
817     my ($old, $tip, $reflogmsg) = @_;
818     return if $tip eq $old;
819     print "git-debrebase: laundered (head was $old)\n";
820     update_head $old, $tip, $reflogmsg;
821     # no tree changes except debian/patches
822     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
823 }
824
825 sub cmd_launder () {
826     badusage "no arguments to launder allowed" if @ARGV;
827     my $old = get_head();
828     my ($tip,$breakwater,$last_upstream_merge) = walk $old;
829     update_head_postlaunder $old, $tip, 'launder';
830     printf "# breakwater tip\n%s\n", $breakwater;
831     printf "# working tip\n%s\n", $tip;
832     printf "# last upstream merge\n%s\n", $last_upstream_merge;
833 }
834
835 sub defaultcmd_rebase () {
836     my $old = get_head();
837     my ($status, $message) = record_ffq_prev();
838     if ($status eq 'written' || $status eq 'exists') {
839     } else {
840         fproblem $status, "could not record ffq-prev: $message";
841         fproblems_maybe_bail();
842     }
843     my ($tip,$breakwater) = walk $old;
844     update_head_postlaunder $old, $tip, 'launder for rebase';
845     runcmd @git, qw(rebase), @ARGV, $breakwater;
846 }
847
848 sub cmd_analyse () {
849     die if ($ARGV[0]//'') =~ m/^-/;
850     badusage "too many arguments to analyse" if @ARGV>1;
851     my ($old) = @ARGV;
852     if (defined $old) {
853         $old = git_rev_parse $old;
854     } else {
855         $old = git_rev_parse 'HEAD';
856     }
857     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
858     STDOUT->error and die $!;
859 }
860
861 sub ffq_prev_branchinfo () {
862     # => ('status', "message", [$current, $ffq_prev])
863     # 'status' may be
864     #    branch         message is undef
865     #    weird-symref   } no $current,
866     #    notbranch      }  no $ffq_prev
867     my $current = git_get_symref();
868     return ('detached', 'detached HEAD') unless defined $current;
869     return ('weird-symref', 'HEAD symref is not to refs/')
870         unless $current =~ m{^refs/};
871     my $ffq_prev = "refs/$ffq_refprefix/$'";
872     return ('branch', undef, $current, $ffq_prev);
873 }
874
875 sub record_ffq_prev () {
876     # => ('status', "message")
877     # 'status' may be
878     #    written          message is undef
879     #    exists
880     #    detached
881     #    weird-symref
882     #    notbranch
883     # if not ff from some branch we should be ff from, is an fproblem
884     # if "written", will have printed something about that to stdout,
885     #   and also some messages about ff checks
886     my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
887     return ($status, $message) unless $status eq 'branch';
888
889     my $currentval = get_head();
890
891     my $exists = git_get_ref $ffq_prev;
892     return ('exists',"$ffq_prev already exists") if $exists;
893
894     return ('not-branch', 'HEAD symref is not to refs/heads/')
895         unless $current =~ m{^refs/heads/};
896     my $branch = $';
897
898     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
899     my %checked;
900
901     my $check = sub {
902         my ($lrref, $desc) = @_;
903         my $invert;
904         for my $chk (@check_specs) {
905             my $glob = $chk;
906             $invert = $glob =~ s{^[^!]}{};
907             last if fnmatch $glob, $lrref;
908         }
909         return if $invert;
910         my $lrval = git_get_ref $lrref;
911         return unless defined $lrval;
912
913         if (is_fast_fwd $lrval, $currentval) {
914             print "OK, you are ahead of $lrref\n" or die $!;
915             $checked{$lrref} = 1;
916         } if (is_fast_fwd $currentval, $lrval) {
917             $checked{$lrref} = -1;
918             fproblem 'behind', "you are behind $lrref, divergence risk";
919         } else {
920             $checked{$lrref} = -1;
921             fproblem 'diverged', "you have diverged from $lrref";
922         }
923     };
924
925     my $merge = cfg "branch.$branch.merge",1;
926     if (defined $merge && $merge =~ m{^refs/heads/}) {
927         my $rhs = $';
928         my $check_remote = sub {
929             my ($remote, $desc) = (@_);
930             return unless defined $remote;
931             $check->("refs/remotes/$remote/$rhs", $desc);
932         };
933         $check_remote->((cfg "branch.$branch.remote",1),
934                         'remote fetch/merge branch');
935         $check_remote->((cfg "branch.$branch.pushRemote",1) //
936                         (cfg "branch.$branch.pushDefault",1),
937                         'remote push branch');
938     }
939     if ($branch =~ m{^dgit/}) {
940         $check->("remotes/dgit/$branch", 'remote dgit branch');
941     } elsif ($branch =~ m{^master$}) {
942         $check->("remotes/dgit/dgit/sid", 'remote dgit branch for sid');
943     }
944
945     fproblems_maybe_bail();
946     runcmd @git, qw(update-ref -m), "record current head for preservation",
947         $ffq_prev, $currentval, $git_null_obj;
948     print "Recorded current head for preservation\n" or die $!;
949     return ('written', undef);
950 }
951
952 sub cmd_new_upstream_v0 () {
953     # automatically and unconditionally launders before rebasing
954     # if rebase --abort is used, laundering has still been done
955
956     my %pieces;
957
958     badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
959
960     # parse args - low commitment
961     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
962     my $new_upstream_version = $new_version->version();
963
964     my $new_upstream = git_rev_parse shift @ARGV;
965
966     my $piece = sub {
967         my ($n, @x) = @_; # may be ''
968         my $pc = $pieces{$n} //= {
969             Name => $n,
970             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
971         };
972         while (my $k = shift @x) { $pc->{$k} = shift @x; }
973         $pc;
974     };
975
976     my @newpieces;
977     my $newpiece = sub {
978         my ($n, @x) = @_; # may be ''
979         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
980         push @newpieces, $pc;
981     };
982
983     $newpiece->('',
984         OldIx => 0,
985         New => $new_upstream,
986     );
987     while (@ARGV && $ARGV[0] !~ m{^-}) {
988         my $n = shift @ARGV;
989
990         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
991             unless @ARGV && $ARGV[0] !~ m{^-};
992
993         my $c = git_rev_parse shift @ARGV;
994         die unless $n =~ m/^$extra_orig_namepart_re$/;
995         $newpiece->($n, New => $c);
996     }
997
998     # now we need to investigate the branch this generates the
999     # laundered version but we don't switch to it yet
1000     my $old_head = get_head();
1001     my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
1002
1003     my $old_bw_cl = classify $old_bw;
1004     my $old_upstream_update_cl = classify $old_upstream_update;
1005     confess unless $old_upstream_update_cl->{OrigParents};
1006     my $old_upstream = parsecommit
1007         $old_upstream_update_cl->{OrigParents}[0]{CommitId};
1008
1009     $piece->('', Old => $old_upstream->{CommitId});
1010
1011     if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1012         if ($old_upstream->{Msg} =~
1013  m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1014            ) {
1015             my @oldpieces = ('', split / /, $1);
1016             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1017             foreach my $i (0..$#oldpieces) {
1018                 my $n = $oldpieces[$i];
1019                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1020             }
1021         } else {
1022             fproblem 'upstream-confusing',
1023                 "previous upstream $old_upstream->{CommitId} is from".
1024                " git-debrebase but not an \`upstream-combine' commit";
1025         }
1026     }
1027
1028     foreach my $pc (values %pieces) {
1029         if (!$pc->{Old}) {
1030             fproblem 'upstream-new-piece',
1031                 "introducing upstream piece \`$pc->{Name}'";
1032         } elsif (!$pc->{New}) {
1033             fproblem 'upstream-rm-piece',
1034                 "dropping upstream piece \`$pc->{Name}'";
1035         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1036             fproblem 'upstream-not-ff',
1037                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1038         }
1039     }
1040
1041     printdebug "%pieces = ", (dd \%pieces), "\n";
1042     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1043
1044     fproblems_maybe_bail();
1045
1046     my $new_bw;
1047
1048     fresh_workarea();
1049     in_workarea sub {
1050         my @upstream_merge_parents;
1051
1052         if (!any_fproblems()) {
1053             push @upstream_merge_parents, $old_upstream->{CommitId};
1054         }
1055
1056         foreach my $pc (@newpieces) { # always has '' first
1057             if ($pc->{Name}) {
1058                 read_tree_subdir $pc->{Name}, $pc->{New};
1059             } else {
1060                 runcmd @git, qw(read-tree), $pc->{New};
1061             }
1062             push @upstream_merge_parents, $pc->{New};
1063         }
1064
1065         # index now contains the new upstream
1066
1067         if (@newpieces > 1) {
1068             # need to make the upstream subtree merge commit
1069             $new_upstream = make_commit \@upstream_merge_parents,
1070                 [ "Combine upstreams for $new_upstream_version",
1071  ("[git-debrebase upstream-combine . ".
1072  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1073  ": new upstream]"),
1074                 ];
1075         }
1076
1077         # $new_upstream is either the single upstream commit, or the
1078         # combined commit we just made.  Either way it will be the
1079         # "upstream" parent of the breakwater special merge.
1080
1081         read_tree_subdir 'debian', "$old_bw:debian";
1082
1083         # index now contains the breakwater merge contents
1084         $new_bw = make_commit [ $old_bw, $new_upstream ],
1085             [ "Update to upstream $new_upstream_version",
1086  "[git-debrebase breakwater: new upstream $new_upstream_version, merge]",
1087             ];
1088
1089         # Now we have to add a changelog stanza so the Debian version
1090         # is right.
1091         die if unlink "debian";
1092         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1093         unlink "debian/changelog" or $!==ENOENT or die $!;
1094         mkdir "debian" or die $!;
1095         open CN, ">", "debian/changelog" or die $!;
1096         my $oldclog = git_cat_file ":debian/changelog";
1097         $oldclog =~ m/^($package_re) \(\S+\) / or
1098             fail "cannot parse old changelog to get package name";
1099         my $p = $1;
1100         print CN <<END, $oldclog or die $!;
1101 $p ($new_version) UNRELEASED; urgency=medium
1102
1103   * Update to new upstream version $new_upstream_version.
1104
1105  -- 
1106
1107 END
1108         close CN or die $!;
1109         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1110
1111         # Now we have the final new breakwater branch in the index
1112         $new_bw = make_commit [ $new_bw ],
1113             [ "Update changelog for new upstream $new_upstream_version",
1114               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1115             ];
1116     };
1117
1118     # we have constructed the new breakwater. we now need to commit to
1119     # the laundering output, because git-rebase can't easily be made
1120     # to make a replay list which is based on some other branch
1121
1122     update_head_postlaunder $old_head, $old_laundered_tip,
1123         'launder for new upstream';
1124
1125     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1126     runcmd @cmd;
1127     # now it's for the user to sort out
1128 }
1129
1130 sub cmd_record_ffq_prev () {
1131     badusage "no arguments allowed" if @ARGV;
1132     my ($status, $msg) = record_ffq_prev();
1133     if ($status eq 'exists' && $opt_noop_ok) {
1134         print "Previous head already recorded\n" or die $!;
1135     } elsif ($status eq 'written') {
1136     } else {
1137         fail "Could not preserve: $msg";
1138     }
1139 }
1140
1141 sub cmd_stitch () {
1142     my $prose = '';
1143     GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1144     badusage "no arguments allowed" if @ARGV;
1145     my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1146     if ($status ne 'branch') {
1147         fproblem $status, "could not check ffq-prev: $message";
1148         fproblems_maybe_bail();
1149     }
1150     my $prev = $ffq_prev && git_get_ref $ffq_prev;
1151     if (!$prev) {
1152         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1153     }
1154     fresh_workarea();
1155     my $old_head = get_head();
1156     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1157         'Declare fast forward / record previous work',
1158         "[git-debrebase pseudomerge: stitch$prose]",
1159     ];
1160     my @upd_cmd = (@git, qw(update-ref --stdin));
1161     debugcmd '>|', @upd_cmd;
1162     open U, "|-", @upd_cmd or die $!;
1163     my $u = <<END;
1164 update HEAD $new_head $old_head
1165 delete $ffq_prev $prev
1166 END
1167     printdebug ">= ", $_, "\n" foreach split /\n/, $u;
1168     print U $u;
1169     printdebug ">\$\n";
1170     close U or failedcmd @upd_cmd;
1171 }
1172
1173 sub cmd_gbp2debrebase () {
1174     badusage "needs 1 optional argument, the upstream" unless @ARGV<=1;
1175     my ($upstream_spec) = @ARGV;
1176     $upstream_spec //= 'refs/heads/upstream';
1177     my $upstream = git_rev_parse $upstream_spec;
1178     my $old_head = get_head();
1179
1180     my $upsdiff = get_differs $upstream, $old_head;
1181     if ($upsdiff & D_UPS) {
1182         runcmd @git, qw(--no-pager diff),
1183             $upstream, $old_head,
1184             qw( -- :!/debian :/);
1185  fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1186     }
1187
1188     if (!is_fast_fwd $upstream, $old_head) {
1189         fproblem 'upstream-not-ancestor',
1190             "upstream ($upstream) is not an ancestor of HEAD";
1191     } else {
1192         my $wrong = cmdoutput
1193             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1194              qw(-- :/ :!/debian));
1195         if (length $wrong) {
1196             fproblem 'unexpected-upstream-changes',
1197                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1198             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1199         }
1200     }
1201
1202     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1203         fproblem 'upstream-has-debian',
1204             "upstream ($upstream) contains debian/ directory";
1205     }
1206
1207     fproblems_maybe_bail();
1208
1209     my $work;
1210
1211     fresh_workarea();
1212     in_workarea sub {
1213         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1214         # make a branch out of the patch queue - we'll want this in a mo
1215         runcmd qw(gbp pq import);
1216         # strip the patches out
1217         runcmd @git, qw(checkout -q gdr-internal~0);
1218         rm_subdir_cached 'debian/patches';
1219         $work = make_commit ['HEAD'], [
1220  'git-debrebase import: drop patch queue',
1221  'Delete debian/patches, as part of converting to git-debrebase format.',
1222  '[git-debrebase: gbp2debrebase, drop patches]'
1223                               ];
1224         # make the breakwater pseudomerge
1225         # the tree is already exactly right
1226         $work = make_commit [$work, $upstream], [
1227  'git-debrebase import: declare upstream',
1228  'First breakwater merge.',
1229  '[git-debrebase breakwater: declare upstream]'
1230                               ];
1231
1232         # rebase the patch queue onto the new breakwater
1233         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1234         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1235         $work = git_rev_parse 'HEAD';
1236     };
1237
1238     update_head_checkout $old_head, $work, 'gbp2debrebase';
1239 }
1240
1241 sub cmd_downstream_rebase_launder_v0 () {
1242     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1243     my ($base) = @ARGV;
1244     $base = git_rev_parse $base;
1245     my $old_head = get_head();
1246     my $current = $old_head;
1247     my $topmost_keep;
1248     for (;;) {
1249         if ($current eq $base) {
1250             $topmost_keep //= $current;
1251             print " $current BASE stop\n";
1252             last;
1253         }
1254         my $cl = classify $current;
1255         print " $current $cl->{Type}";
1256         my $keep = 0;
1257         my $p0 = $cl->{Parents}[0]{CommitId};
1258         my $next;
1259         if ($cl->{Type} eq 'Pseudomerge') {
1260             print " ^".($cl->{Contributor}{Ix}+1);
1261             $next = $cl->{Contributor}{CommitId};
1262         } elsif ($cl->{Type} eq 'AddPatches' or
1263                  $cl->{Type} eq 'Changelog') {
1264             print " strip";
1265             $next = $p0;
1266         } else {
1267             print " keep";
1268             $next = $p0;
1269             $keep = 1;
1270         }
1271         print "\n";
1272         if ($keep) {
1273             $topmost_keep //= $current;
1274         } else {
1275             die "to-be stripped changes not on top of the branch\n"
1276                 if $topmost_keep;
1277         }
1278         $current = $next;
1279     }
1280     if ($topmost_keep eq $old_head) {
1281         print "unchanged\n";
1282     } else {
1283         print "updating to $topmost_keep\n";
1284         update_head_checkout
1285             $old_head, $topmost_keep,
1286             'downstream-rebase-launder-v0';
1287     }
1288 }
1289
1290 GetOptions("D+" => \$debuglevel,
1291            'noop-ok', => \$opt_noop_ok,
1292            'f=s' => \@fproblem_force_opts,
1293            'force!') or die badusage "bad options\n";
1294 initdebug('git-debrebase ');
1295 enabledebug if $debuglevel;
1296
1297 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1298 chdir $toplevel or die "chdir $toplevel: $!";
1299
1300 $rd = fresh_playground "$playprefix/misc";
1301
1302 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1303     defaultcmd_rebase();
1304 } else {
1305     my $cmd = shift @ARGV;
1306     my $cmdfn = $cmd;
1307     $cmdfn =~ y/-/_/;
1308     $cmdfn = ${*::}{"cmd_$cmdfn"};
1309
1310     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1311     $cmdfn->();
1312 }