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