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