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