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