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