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