chiark / gitweb /
git-debrebase: classify: provide Why for Unknown
[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 #
321 #   Pseudomerge
322 #     has additional entres in classification result
323 #       Overwritten = [ subset of Parents ]
324 #       Contributor = $the_remaining_Parent
325 #
326 #   DgitImportUnpatched
327 #     has additional entry in classification result
328 #       OrigParents = [ subset of Parents ]
329 #
330 #   BreakwaterUpstreamMerge
331 #     has additional entry in classification result
332 #       OrigParents = [ subset of Parents ]  # singleton list
333 #
334 #   Unknown
335 #     has additional entry in classification result
336 #       Why => "prose"
337
338 sub parsecommit ($;$) {
339     my ($objid, $p_ref) = @_;
340     # => hash with                   CommitId Hdr Msg Tree Parents
341     #    Parents entries have only   Ix CommitId
342     #    $p_ref, if provided, must be [] and is used as a base for Parents
343
344     $p_ref //= [];
345     die if @$p_ref;
346
347     my ($h,$m) = get_commit $objid;
348
349     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
350     my (@ph) = $h =~ m/^parent (\w+)$/mg;
351
352     my $r = {
353         CommitId => $objid,
354         Hdr => $h,
355         Msg => $m,
356         Tree => $t,
357         Parents => $p_ref,
358     };
359
360     foreach my $ph (@ph) {
361         push @$p_ref, {
362             Ix => scalar @$p_ref,
363             CommitId => $ph,
364         };
365     }
366
367     return $r;
368 }    
369
370 sub classify ($) {
371     my ($objid) = @_;
372
373     my @p;
374     my $r = parsecommit($objid, \@p);
375     my $t = $r->{Tree};
376
377     foreach my $p (@p) {
378         $p->{Differs} = (get_differs $p->{CommitId}, $t),
379     }
380
381     printdebug "classify $objid \$t=$t \@p",
382         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
383         "\n";
384
385     my $classify = sub {
386         my ($type, @rest) = @_;
387         $r = { %$r, Type => $type, @rest };
388         if ($debuglevel) {
389             printdebug " = $type ".(dd $r)."\n";
390         }
391         return $r;
392     };
393     my $unknown = sub {
394         my ($why) = @_;
395         $r = { %$r, Type => qw(Unknown), Why => $why };
396         printdebug " ** Unknown\n";
397         return $r;
398     };
399
400     my $claims_to_be_breakwater =
401         $r->{Msg} =~ m{^\[git-debrebase breakwater.*\]$}m;
402
403     if (@p == 1) {
404         if ($claims_to_be_breakwater) {
405             return $unknown->("single-parent git-debrebase breakwater \`merge'");
406         }
407         my $d = $r->{Parents}[0]{Differs};
408         if ($d == D_PAT_ADD) {
409             return $classify->(qw(AddPatches));
410         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
411             return $unknown->("edits debian/patches");
412         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
413             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
414             if ($ty eq 'tree') {
415                 if ($d == D_DEB_CLOG) {
416                     return $classify->(qw(Changelog));
417                 } else {
418                     return $classify->(qw(Packaging));
419                 }
420             } elsif ($ty eq 'missing') {
421                 return $classify->(qw(BreakwaterStart));
422             } else {
423                 return $unknown->("parent's debian is not a directory");
424             }
425         } elsif ($d == D_UPS) {
426             return $classify->(qw(Upstream));
427         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
428             return $classify->(qw(Mixed));
429         } elsif ($d == 0) {
430             return $unknown->("no changes");
431         } else {
432             confess "internal error $objid ?";
433         }
434     }
435     if (!@p) {
436         return $unknown->("origin commit");
437     }
438
439     my @identical = grep { !$_->{Differs} } @p;
440     if (@p == 2 && @identical == 1 && !$claims_to_be_breakwater
441         # breakwater merges can look like pseudomerges, if they are
442         # "declare" commits (ie, there are no upstream changes)
443        ) {
444         my @overwritten = grep { $_->{Differs} } @p;
445         confess "internal error $objid ?" unless @overwritten==1;
446         return $classify->(qw(Pseudomerge),
447                            Overwritten => [ $overwritten[0] ],
448                            Contributor => $identical[0]);
449     }
450     if (@p == 2 && @identical == 2) {
451         my @bytime = nsort_by {
452             my ($ph,$pm) = get_commit $_->{CommitId};
453             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
454             $1;
455         } @p;
456         return $classify->(qw(Pseudomerge),
457                            SubType => qw(Ambiguous),
458                            Overwritten => [ $bytime[0] ],
459                            Contributor => $bytime[1]);
460     }
461     foreach my $p (@p) {
462         my ($p_h, $p_m) = get_commit $p->{CommitId};
463         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
464         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
465     }
466     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
467     my $m2 = $r->{Msg};
468     if (!(grep { !$_->{IsOrigin} } @p) and
469         (@orig_ps >= @p - 1) and
470         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
471         $r->{NewMsg} = $m2;
472         return $classify->(qw(DgitImportUnpatched),
473                            OrigParents => \@orig_ps);
474     }
475
476     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
477     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
478
479     # How to decide about l/r ordering of breakwater merges ?  git
480     # --topo-order prefers to expand 2nd parent first.  There's
481     # already an easy rune to look for debian/ history anyway (git log
482     # debian/) so debian breakwater branch should be 1st parent; that
483     # way also there's also an easy rune to look for the upstream
484     # patches (--topo-order).
485
486     # The above tells us which way *we* will generate them.  But we
487     # might encounter ad-hoc breakwater merges generated manually,
488     # which might be the other way around.  In principle, in some odd
489     # situations, a breakwater merge might have two identical parents.
490     # In that case we guess which way round it is (ie, which parent
491     # has the upstream history).  The order of the 2-iteration loop
492     # controls which guess we make.
493
494     foreach my $prevbrw (qw(0 1)) {
495         if (@p == 2 &&
496             !$haspatches &&
497             !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
498             !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
499             !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
500             return $classify->(qw(BreakwaterUpstreamMerge),
501                                OrigParents => [ $p[!$prevbrw] ]);
502         }
503     }
504
505     # multi-orig upstreams are represented with a breakwater merge
506     # from a single upstream commit which combines the orig tarballs
507
508     return $unknown->("complex merge");
509 }
510
511 sub walk ($;$$);
512 sub walk ($;$$) {
513     my ($input,
514         $nogenerate,$report) = @_;
515     # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
516     # (or nothing, if $nogenerate)
517
518     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
519
520     # go through commits backwards
521     # we generate two lists of commits to apply:
522     # breakwater branch and upstream patches
523     my (@brw_cl, @upp_cl, @processed);
524     my %found;
525     my $upp_limit;
526     my @pseudomerges;
527
528     my $cl;
529     my $xmsg = sub {
530         my ($prose, $info) = @_;
531         my $ms = $cl->{Msg};
532         chomp $ms;
533         $info //= '';
534         $ms .= "\n\n[git-debrebase$info: $prose]\n";
535         return (Msg => $ms);
536     };
537     my $rewrite_from_here = sub {
538         my $sp_cl = { SpecialMethod => 'StartRewrite' };
539         push @brw_cl, $sp_cl;
540         push @processed, $sp_cl;
541     };
542     my $cur = $input;
543
544     my $prdelim = "";
545     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
546
547     my $prline = sub {
548         return unless $report;
549         print $report $prdelim, @_;
550         $prdelim = "\n";
551     };
552
553     my $bomb = sub { # usage: return $bomb->();
554         print $report " Unprocessable" if $report;
555         $prprdelim->();
556         if ($nogenerate) {
557             return (undef,undef);
558         }
559         die "commit $cur: Cannot cope with this commit (d.".
560             (join ' ', map { sprintf "%#x", $_->{Differs} }
561              @{ $cl->{Parents} }). ")";
562     };
563
564     my $build;
565     my $breakwater;
566
567     my $build_start = sub {
568         my ($msg, $parent) = @_;
569         $prline->(" $msg");
570         $build = $parent;
571         no warnings qw(exiting); last;
572     };
573
574     my $last_upstream_update;
575
576     for (;;) {
577         $cl = classify $cur;
578         my $ty = $cl->{Type};
579         my $st = $cl->{SubType};
580         $prline->("$cl->{CommitId} $cl->{Type}");
581         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
582         push @processed, $cl;
583         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
584         if ($ty eq 'AddPatches') {
585             $cur = $p0;
586             $rewrite_from_here->();
587             next;
588         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
589             push @brw_cl, $cl;
590             $cur = $p0;
591             next;
592         } elsif ($ty eq 'BreakwaterStart') {
593             $last_upstream_update = $cur;
594             $build_start->('FirstPackaging', $cur);
595         } elsif ($ty eq 'Upstream') {
596             push @upp_cl, $cl;
597             $cur = $p0;
598             next;
599         } elsif ($ty eq 'Mixed') {
600             my $queue = sub {
601                 my ($q, $wh) = @_;
602                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
603                 push @$q, $cls;
604             };
605             $queue->(\@brw_cl, "debian");
606             $queue->(\@upp_cl, "upstream");
607             $rewrite_from_here->();
608             $cur = $p0;
609             next;
610         } elsif ($ty eq 'Pseudomerge') {
611             my $contrib = $cl->{Contributor}{CommitId};
612             print $report " Contributor=$contrib" if $report;
613             push @pseudomerges, $cl;
614             $rewrite_from_here->();
615             $cur = $contrib;
616             next;
617         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
618             $last_upstream_update = $cur;
619             $build_start->("PreviousBreakwater", $cur);
620         } elsif ($ty eq 'DgitImportUnpatched') {
621             my $pm = $pseudomerges[-1];
622             if (defined $pm) {
623                 # To an extent, this is heuristic.  Imports don't have
624                 # a useful history of the debian/ branch.  We assume
625                 # that the first pseudomerge after an import has a
626                 # useful history of debian/, and ignore the histories
627                 # from later pseudomerges.  Often the first pseudomerge
628                 # will be the dgit import of the upload to the actual
629                 # suite intended by the non-dgit NMUer, and later
630                 # pseudomerges may represent in-archive copies.
631                 my $ovwrs = $pm->{Overwritten};
632                 printf $report " PM=%s \@Overwr:%d",
633                     $pm->{CommitId}, (scalar @$ovwrs)
634                     if $report;
635                 if (@$ovwrs != 1) {
636                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
637                     return $bomb->();
638                 }
639                 my $ovwr = $ovwrs->[0]{CommitId};
640                 printf $report " Overwr=%s", $ovwr if $report;
641                 # This import has a tree which is just like a
642                 # breakwater tree, but it has the wrong history.  It
643                 # ought to have the previous breakwater (which the
644                 # pseudomerge overwrote) as an ancestor.  That will
645                 # make the history of the debian/ files correct.  As
646                 # for the upstream version: either it's the same as
647                 # was ovewritten (ie, same as the previous
648                 # breakwater), in which case that history is precisely
649                 # right; or, otherwise, it was a non-gitish upload of a
650                 # new upstream version.  We can tell these apart by
651                 # looking at the tree of the supposed upstream.
652                 push @brw_cl, {
653                     %$cl,
654                     SpecialMethod => 'DgitImportDebianUpdate',
655                     $xmsg->("convert dgit import: debian changes")
656                 }, {
657                     %$cl,
658                     SpecialMethod => 'DgitImportUpstreamUpdate',
659                     $xmsg->("convert dgit import: upstream update",
660                             " breakwater")
661                 };
662                 $prline->(" Import");
663                 $rewrite_from_here->();
664                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
665                 $cur = $ovwr;
666                 next;
667             } else {
668                 # Everything is from this import.  This kind of import
669                 # is already in valid breakwater format, with the
670                 # patches as commits.
671                 printf $report " NoPM" if $report;
672                 # last thing we processed will have been the first patch,
673                 # if there is one; which is fine, so no need to rewrite
674                 # on account of this import
675                 $build_start->("ImportOrigin", $cur);
676             }
677             die "$ty ?";
678         } else {
679             printdebug "*** WALK BOMB unrecognised\n";
680             return $bomb->();
681         }
682     }
683     $prprdelim->();
684
685     printdebug "*** WALK prep done cur=$cur".
686         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
687
688     return if $nogenerate;
689
690     # Now we build it back up again
691
692     fresh_workarea();
693
694     my $rewriting = 0;
695
696     my $read_tree_debian = sub {
697         my ($treeish) = @_;
698         read_tree_subdir 'debian', "$treeish:debian";
699         rm_subdir_cached 'debian/patches';
700     };
701     my $read_tree_upstream = sub {
702         my ($treeish) = @_;
703         runcmd @git, qw(read-tree), $treeish;
704         $read_tree_debian->($build);
705     };
706
707     $#upp_cl = $upp_limit if defined $upp_limit;
708  
709     my $committer_authline = calculate_committer_authline();
710
711     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
712
713     confess "internal error" unless $build eq (pop @processed)->{CommitId};
714
715     in_workarea sub {
716         mkdir $rd or $!==EEXIST or die $!;
717         my $current_method;
718         runcmd @git, qw(read-tree), $build;
719         foreach my $cl (qw(Debian), (reverse @brw_cl),
720                         { SpecialMethod => 'RecordBreakwaterTip' },
721                         qw(Upstream), (reverse @upp_cl)) {
722             if (!ref $cl) {
723                 $current_method = $cl;
724                 next;
725             }
726             my $method = $cl->{SpecialMethod} // $current_method;
727             my @parents = ($build);
728             my $cltree = $cl->{CommitId};
729             printdebug "WALK BUILD ".($cltree//'undef').
730                 " $method (rewriting=$rewriting)\n";
731             if ($method eq 'Debian') {
732                 $read_tree_debian->($cltree);
733             } elsif ($method eq 'Upstream') {
734                 $read_tree_upstream->($cltree);
735             } elsif ($method eq 'StartRewrite') {
736                 $rewriting = 1;
737                 next;
738             } elsif ($method eq 'RecordBreakwaterTip') {
739                 $breakwater = $build;
740                 next;
741             } elsif ($method eq 'DgitImportDebianUpdate') {
742                 $read_tree_debian->($cltree);
743             } elsif ($method eq 'DgitImportUpstreamUpdate') {
744                 confess unless $rewriting;
745                 my $differs = (get_differs $build, $cltree);
746                 next unless $differs & D_UPS;
747                 $read_tree_upstream->($cltree);
748                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
749             } else {
750                 confess "$method ?";
751             }
752             if (!$rewriting) {
753                 my $procd = (pop @processed) // 'UNDEF';
754                 if ($cl ne $procd) {
755                     $rewriting = 1;
756                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
757                 }
758             }
759             my $newtree = cmdoutput @git, qw(write-tree);
760             my $ch = $cl->{Hdr};
761             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
762             $ch =~ s{^parent .*\n}{}mg;
763             $ch =~ s{(?=^author)}{
764                 join '', map { "parent $_\n" } @parents
765             }me or confess "$ch ?";
766             if ($rewriting) {
767                 $ch =~ s{^committer .*$}{$committer_authline}m
768                     or confess "$ch ?";
769             }
770             my $cf = "$rd/m$rewriting";
771             open CD, ">", $cf or die $!;
772             print CD $ch, "\n", $cl->{Msg} or die $!;
773             close CD or die $!;
774             my @cmd = (@git, qw(hash-object));
775             push @cmd, qw(-w) if $rewriting;
776             push @cmd, qw(-t commit), $cf;
777             my $newcommit = cmdoutput @cmd;
778             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
779             $build = $newcommit;
780             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
781                 $last_upstream_update = $cur;
782             }
783         }
784     };
785
786     my $final_check = get_differs $build, $input;
787     die sprintf "internal error %#x %s %s", $final_check, $build, $input
788         if $final_check & ~D_PAT_ADD;
789
790     my @r = ($build, $breakwater, $last_upstream_update);
791     printdebug "*** WALK RETURN @r\n";
792     return @r
793 }
794
795 sub get_head () {
796     git_check_unmodified();
797     return git_rev_parse qw(HEAD);
798 }
799
800 sub update_head ($$$) {
801     my ($old, $new, $mrest) = @_;
802     runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
803 }
804
805 sub update_head_checkout ($$$) {
806     my ($old, $new, $mrest) = @_;
807     update_head $old, $new, $mrest;
808     runcmd @git, qw(reset --hard);
809 }
810
811 sub update_head_postlaunder ($$$) {
812     my ($old, $tip, $reflogmsg) = @_;
813     return if $tip eq $old;
814     print "git-debrebase: laundered (head was $old)\n";
815     update_head $old, $tip, $reflogmsg;
816     # no tree changes except debian/patches
817     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
818 }
819
820 sub cmd_launder () {
821     badusage "no arguments to launder allowed" if @ARGV;
822     my $old = get_head();
823     my ($tip,$breakwater,$last_upstream_merge) = walk $old;
824     update_head_postlaunder $old, $tip, 'launder';
825     printf "# breakwater tip\n%s\n", $breakwater;
826     printf "# working tip\n%s\n", $tip;
827     printf "# last upstream merge\n%s\n", $last_upstream_merge;
828 }
829
830 sub defaultcmd_rebase () {
831     my $old = get_head();
832     my ($status, $message) = record_ffq_prev();
833     if ($status eq 'written' || $status eq 'exists') {
834     } else {
835         fproblem $status, "could not record ffq-prev: $message";
836         fproblems_maybe_bail();
837     }
838     my ($tip,$breakwater) = walk $old;
839     update_head_postlaunder $old, $tip, 'launder for rebase';
840     runcmd @git, qw(rebase), @ARGV, $breakwater;
841 }
842
843 sub cmd_analyse () {
844     die if ($ARGV[0]//'') =~ m/^-/;
845     badusage "too many arguments to analyse" if @ARGV>1;
846     my ($old) = @ARGV;
847     if (defined $old) {
848         $old = git_rev_parse $old;
849     } else {
850         $old = git_rev_parse 'HEAD';
851     }
852     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
853     STDOUT->error and die $!;
854 }
855
856 sub ffq_prev_branchinfo () {
857     # => ('status', "message", [$current, $ffq_prev])
858     # 'status' may be
859     #    branch         message is undef
860     #    weird-symref   } no $current,
861     #    notbranch      }  no $ffq_prev
862     my $current = git_get_symref();
863     return ('detached', 'detached HEAD') unless defined $current;
864     return ('weird-symref', 'HEAD symref is not to refs/')
865         unless $current =~ m{^refs/};
866     my $ffq_prev = "refs/$ffq_refprefix/$'";
867     return ('branch', undef, $current, $ffq_prev);
868 }
869
870 sub record_ffq_prev () {
871     # => ('status', "message")
872     # 'status' may be
873     #    written          message is undef
874     #    exists
875     #    detached
876     #    weird-symref
877     #    notbranch
878     # if not ff from some branch we should be ff from, is an fproblem
879     # if "written", will have printed something about that to stdout,
880     #   and also some messages about ff checks
881     my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
882     return ($status, $message) unless $status eq 'branch';
883
884     my $currentval = get_head();
885
886     my $exists = git_get_ref $ffq_prev;
887     return ('exists',"$ffq_prev already exists") if $exists;
888
889     return ('not-branch', 'HEAD symref is not to refs/heads/')
890         unless $current =~ m{^refs/heads/};
891     my $branch = $';
892
893     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
894     my %checked;
895
896     my $check = sub {
897         my ($lrref, $desc) = @_;
898         my $invert;
899         for my $chk (@check_specs) {
900             my $glob = $chk;
901             $invert = $glob =~ s{^[^!]}{};
902             last if fnmatch $glob, $lrref;
903         }
904         return if $invert;
905         my $lrval = git_get_ref $lrref;
906         return unless defined $lrval;
907
908         if (is_fast_fwd $lrval, $currentval) {
909             print "OK, you are ahead of $lrref\n" or die $!;
910             $checked{$lrref} = 1;
911         } if (is_fast_fwd $currentval, $lrval) {
912             $checked{$lrref} = -1;
913             fproblem 'behind', "you are behind $lrref, divergence risk";
914         } else {
915             $checked{$lrref} = -1;
916             fproblem 'diverged', "you have diverged from $lrref";
917         }
918     };
919
920     my $merge = cfg "branch.$branch.merge",1;
921     if (defined $merge && $merge =~ m{^refs/heads/}) {
922         my $rhs = $';
923         my $check_remote = sub {
924             my ($remote, $desc) = (@_);
925             return unless defined $remote;
926             $check->("refs/remotes/$remote/$rhs", $desc);
927         };
928         $check_remote->((cfg "branch.$branch.remote",1),
929                         'remote fetch/merge branch');
930         $check_remote->((cfg "branch.$branch.pushRemote",1) //
931                         (cfg "branch.$branch.pushDefault",1),
932                         'remote push branch');
933     }
934     if ($branch =~ m{^dgit/}) {
935         $check->("remotes/dgit/$branch", 'remote dgit branch');
936     } elsif ($branch =~ m{^master$}) {
937         $check->("remotes/dgit/dgit/sid", 'remote dgit branch for sid');
938     }
939
940     fproblems_maybe_bail();
941     runcmd @git, qw(update-ref -m), "record current head for preservation",
942         $ffq_prev, $currentval, $git_null_obj;
943     print "Recorded current head for preservation\n" or die $!;
944     return ('written', undef);
945 }
946
947 sub cmd_new_upstream_v0 () {
948     # automatically and unconditionally launders before rebasing
949     # if rebase --abort is used, laundering has still been done
950
951     my %pieces;
952
953     badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
954
955     # parse args - low commitment
956     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
957     my $new_upstream_version = $new_version->version();
958
959     my $new_upstream = git_rev_parse shift @ARGV;
960
961     my $piece = sub {
962         my ($n, @x) = @_; # may be ''
963         my $pc = $pieces{$n} //= {
964             Name => $n,
965             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
966         };
967         while (my $k = shift @x) { $pc->{$k} = shift @x; }
968         $pc;
969     };
970
971     my @newpieces;
972     my $newpiece = sub {
973         my ($n, @x) = @_; # may be ''
974         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
975         push @newpieces, $pc;
976     };
977
978     $newpiece->('',
979         OldIx => 0,
980         New => $new_upstream,
981     );
982     while (@ARGV && $ARGV[0] !~ m{^-}) {
983         my $n = shift @ARGV;
984
985         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
986             unless @ARGV && $ARGV[0] !~ m{^-};
987
988         my $c = git_rev_parse shift @ARGV;
989         die unless $n =~ m/^$extra_orig_namepart_re$/;
990         $newpiece->($n, New => $c);
991     }
992
993     # now we need to investigate the branch this generates the
994     # laundered version but we don't switch to it yet
995     my $old_head = get_head();
996     my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
997
998     my $old_bw_cl = classify $old_bw;
999     my $old_upstream_update_cl = classify $old_upstream_update;
1000     confess unless $old_upstream_update_cl->{OrigParents};
1001     my $old_upstream = parsecommit
1002         $old_upstream_update_cl->{OrigParents}[0]{CommitId};
1003
1004     $piece->('', Old => $old_upstream->{CommitId});
1005
1006     if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1007         if ($old_upstream->{Msg} =~
1008  m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1009            ) {
1010             my @oldpieces = ('', split / /, $1);
1011             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1012             foreach my $i (0..$#oldpieces) {
1013                 my $n = $oldpieces[$i];
1014                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1015             }
1016         } else {
1017             fproblem 'upstream-confusing',
1018                 "previous upstream $old_upstream->{CommitId} is from".
1019                " git-debrebase but not an \`upstream-combine' commit";
1020         }
1021     }
1022
1023     foreach my $pc (values %pieces) {
1024         if (!$pc->{Old}) {
1025             fproblem 'upstream-new-piece',
1026                 "introducing upstream piece \`$pc->{Name}'";
1027         } elsif (!$pc->{New}) {
1028             fproblem 'upstream-rm-piece',
1029                 "dropping upstream piece \`$pc->{Name}'";
1030         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1031             fproblem 'upstream-not-ff',
1032                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1033         }
1034     }
1035
1036     printdebug "%pieces = ", (dd \%pieces), "\n";
1037     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1038
1039     fproblems_maybe_bail();
1040
1041     my $new_bw;
1042
1043     fresh_workarea();
1044     in_workarea sub {
1045         my @upstream_merge_parents;
1046
1047         if (!any_fproblems()) {
1048             push @upstream_merge_parents, $old_upstream->{CommitId};
1049         }
1050
1051         foreach my $pc (@newpieces) { # always has '' first
1052             if ($pc->{Name}) {
1053                 read_tree_subdir $pc->{Name}, $pc->{New};
1054             } else {
1055                 runcmd @git, qw(read-tree), $pc->{New};
1056             }
1057             push @upstream_merge_parents, $pc->{New};
1058         }
1059
1060         # index now contains the new upstream
1061
1062         if (@newpieces > 1) {
1063             # need to make the upstream subtree merge commit
1064             $new_upstream = make_commit \@upstream_merge_parents,
1065                 [ "Combine upstreams for $new_upstream_version",
1066  ("[git-debrebase upstream-combine . ".
1067  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1068  ": new upstream]"),
1069                 ];
1070         }
1071
1072         # $new_upstream is either the single upstream commit, or the
1073         # combined commit we just made.  Either way it will be the
1074         # "upstream" parent of the breakwater special merge.
1075
1076         read_tree_subdir 'debian', "$old_bw:debian";
1077
1078         # index now contains the breakwater merge contents
1079         $new_bw = make_commit [ $old_bw, $new_upstream ],
1080             [ "Update to upstream $new_upstream_version",
1081  "[git-debrebase breakwater: new upstream $new_upstream_version, merge]",
1082             ];
1083
1084         # Now we have to add a changelog stanza so the Debian version
1085         # is right.
1086         die if unlink "debian";
1087         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1088         unlink "debian/changelog" or $!==ENOENT or die $!;
1089         mkdir "debian" or die $!;
1090         open CN, ">", "debian/changelog" or die $!;
1091         my $oldclog = git_cat_file ":debian/changelog";
1092         $oldclog =~ m/^($package_re) \(\S+\) / or
1093             fail "cannot parse old changelog to get package name";
1094         my $p = $1;
1095         print CN <<END, $oldclog or die $!;
1096 $p ($new_version) UNRELEASED; urgency=medium
1097
1098   * Update to new upstream version $new_upstream_version.
1099
1100  -- 
1101
1102 END
1103         close CN or die $!;
1104         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1105
1106         # Now we have the final new breakwater branch in the index
1107         $new_bw = make_commit [ $new_bw ],
1108             [ "Update changelog for new upstream $new_upstream_version",
1109               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1110             ];
1111     };
1112
1113     # we have constructed the new breakwater. we now need to commit to
1114     # the laundering output, because git-rebase can't easily be made
1115     # to make a replay list which is based on some other branch
1116
1117     update_head_postlaunder $old_head, $old_laundered_tip,
1118         'launder for new upstream';
1119
1120     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1121     runcmd @cmd;
1122     # now it's for the user to sort out
1123 }
1124
1125 sub cmd_record_ffq_prev () {
1126     badusage "no arguments allowed" if @ARGV;
1127     my ($status, $msg) = record_ffq_prev();
1128     if ($status eq 'exists' && $opt_noop_ok) {
1129         print "Previous head already recorded\n" or die $!;
1130     } elsif ($status eq 'written') {
1131     } else {
1132         fail "Could not preserve: $msg";
1133     }
1134 }
1135
1136 sub cmd_stitch () {
1137     my $prose = '';
1138     GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1139     badusage "no arguments allowed" if @ARGV;
1140     my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1141     if ($status ne 'branch') {
1142         fproblem $status, "could not check ffq-prev: $message";
1143         fproblems_maybe_bail();
1144     }
1145     my $prev = $ffq_prev && git_get_ref $ffq_prev;
1146     if (!$prev) {
1147         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1148     }
1149     fresh_workarea();
1150     my $old_head = get_head();
1151     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1152         'Declare fast forward / record previous work',
1153         "[git-debrebase pseudomerge: stitch$prose]",
1154     ];
1155     my @upd_cmd = (@git, qw(update-ref --stdin));
1156     debugcmd '>|', @upd_cmd;
1157     open U, "|-", @upd_cmd or die $!;
1158     my $u = <<END;
1159 update HEAD $new_head $old_head
1160 delete $ffq_prev $prev
1161 END
1162     printdebug ">= ", $_, "\n" foreach split /\n/, $u;
1163     print U $u;
1164     printdebug ">\$\n";
1165     close U or failedcmd @upd_cmd;
1166 }
1167
1168 sub cmd_convert_from_gbp () {
1169     badusage "needs 1 optional argument, the upstream git rev"
1170         unless @ARGV<=1;
1171     my ($upstream_spec) = @ARGV;
1172     $upstream_spec //= 'refs/heads/upstream';
1173     my $upstream = git_rev_parse $upstream_spec;
1174     my $old_head = get_head();
1175
1176     my $upsdiff = get_differs $upstream, $old_head;
1177     if ($upsdiff & D_UPS) {
1178         runcmd @git, qw(--no-pager diff),
1179             $upstream, $old_head,
1180             qw( -- :!/debian :/);
1181  fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1182     }
1183
1184     if (!is_fast_fwd $upstream, $old_head) {
1185         fproblem 'upstream-not-ancestor',
1186             "upstream ($upstream) is not an ancestor of HEAD";
1187     } else {
1188         my $wrong = cmdoutput
1189             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1190              qw(-- :/ :!/debian));
1191         if (length $wrong) {
1192             fproblem 'unexpected-upstream-changes',
1193                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1194             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1195         }
1196     }
1197
1198     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1199         fproblem 'upstream-has-debian',
1200             "upstream ($upstream) contains debian/ directory";
1201     }
1202
1203     fproblems_maybe_bail();
1204
1205     my $work;
1206
1207     fresh_workarea();
1208     in_workarea sub {
1209         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1210         # make a branch out of the patch queue - we'll want this in a mo
1211         runcmd qw(gbp pq import);
1212         # strip the patches out
1213         runcmd @git, qw(checkout -q gdr-internal~0);
1214         rm_subdir_cached 'debian/patches';
1215         $work = make_commit ['HEAD'], [
1216  'git-debrebase convert-from-gbp: drop patches from tree',
1217  'Delete debian/patches, as part of converting to git-debrebase format.',
1218  '[git-debrebase convert-from-gbp: drop patches from tree]'
1219                               ];
1220         # make the breakwater pseudomerge
1221         # the tree is already exactly right
1222         $work = make_commit [$work, $upstream], [
1223  'git-debrebase import: declare upstream',
1224  'First breakwater merge.',
1225  '[git-debrebase breakwater: declare upstream]'
1226                               ];
1227
1228         # rebase the patch queue onto the new breakwater
1229         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1230         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1231         $work = git_rev_parse 'HEAD';
1232     };
1233
1234     update_head_checkout $old_head, $work, 'convert-from-gbp';
1235 }
1236
1237 sub cmd_downstream_rebase_launder_v0 () {
1238     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1239     my ($base) = @ARGV;
1240     $base = git_rev_parse $base;
1241     my $old_head = get_head();
1242     my $current = $old_head;
1243     my $topmost_keep;
1244     for (;;) {
1245         if ($current eq $base) {
1246             $topmost_keep //= $current;
1247             print " $current BASE stop\n";
1248             last;
1249         }
1250         my $cl = classify $current;
1251         print " $current $cl->{Type}";
1252         my $keep = 0;
1253         my $p0 = $cl->{Parents}[0]{CommitId};
1254         my $next;
1255         if ($cl->{Type} eq 'Pseudomerge') {
1256             print " ^".($cl->{Contributor}{Ix}+1);
1257             $next = $cl->{Contributor}{CommitId};
1258         } elsif ($cl->{Type} eq 'AddPatches' or
1259                  $cl->{Type} eq 'Changelog') {
1260             print " strip";
1261             $next = $p0;
1262         } else {
1263             print " keep";
1264             $next = $p0;
1265             $keep = 1;
1266         }
1267         print "\n";
1268         if ($keep) {
1269             $topmost_keep //= $current;
1270         } else {
1271             die "to-be stripped changes not on top of the branch\n"
1272                 if $topmost_keep;
1273         }
1274         $current = $next;
1275     }
1276     if ($topmost_keep eq $old_head) {
1277         print "unchanged\n";
1278     } else {
1279         print "updating to $topmost_keep\n";
1280         update_head_checkout
1281             $old_head, $topmost_keep,
1282             'downstream-rebase-launder-v0';
1283     }
1284 }
1285
1286 GetOptions("D+" => \$debuglevel,
1287            'noop-ok', => \$opt_noop_ok,
1288            'f=s' => \@fproblem_force_opts,
1289            'force!') or die badusage "bad options\n";
1290 initdebug('git-debrebase ');
1291 enabledebug if $debuglevel;
1292
1293 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1294 chdir $toplevel or die "chdir $toplevel: $!";
1295
1296 $rd = fresh_playground "$playprefix/misc";
1297
1298 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1299     defaultcmd_rebase();
1300 } else {
1301     my $cmd = shift @ARGV;
1302     my $cmdfn = $cmd;
1303     $cmdfn =~ y/-/_/;
1304     $cmdfn = ${*::}{"cmd_$cmdfn"};
1305
1306     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1307     $cmdfn->();
1308 }