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