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