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