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