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