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