chiark / gitweb /
git-debrebase: Improve/fix handling of $prose
[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 @snag_force_opts;
228 our $snags_forced;
229 our $snags_tripped;
230 sub snag ($$) {
231     my ($tag,$msg) = @_;
232     if (grep { $_ eq $tag } @snag_force_opts) {
233         $snags_forced++;
234         print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
235     } else {
236         $snags_tripped++;
237         print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
238     }
239 }
240
241 sub snags_maybe_bail () {
242     if ($snags_forced) {
243         printf STDERR
244             "%s: snags: %d overriden by individual -f options\n",
245             $us, $snags_forced;
246     }
247     if ($snags_tripped) {
248         if ($opt_force) {
249             printf STDERR
250                 "%s: snags: %d overriden by global --force\n",
251                 $us, $snags_tripped;
252         } else {
253             fail sprintf
254   "%s: snags: %d blockers (you could -f<tag>, or --force)",
255                 $us, $snags_tripped;
256         }
257     }
258 }
259 sub any_snags () {
260     return $snags_forced || $snags_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 keycommits ($;$$$) {
498     my ($head, $furniture, $unclean, $trouble) = @_;
499     # => ($anchor, $breakwater)
500
501     # $unclean->("unclean-$tagsfx", $msg)
502     # $furniture->("unclean-$tagsfx", $msg)
503     # $dgitimport->("unclean-$tagsfx", $msg)
504     #   is callled for each situation or commit that
505     #   wouldn't be found in a laundered branch
506     # $furniture is for furniture commits such as might be found on an
507     #   interchange branch (pseudomerge, d/patches, changelog)
508     # $trouble is for things whnich prevent the return of
509     #   anchor and breakwater information; if that is ignored,
510     #   then keycommits returns (undef, undef) instead.
511     #
512     # If a callback is undef, fail is called instead.
513     # If a callback is defined but false, the situation is ignored.
514     # Callbacks may say:
515     #   no warnings qw(exiting); last;
516     # if the answer is no longer wanted.
517
518     my ($anchor, $breakwater);
519     my $clogonly;
520     my $x = sub {
521         my ($cb, $tagsfx, $why) = @_;
522         my $m = "branch needs laundering (run git-debrebase): $why";
523         fail $m unless defined $cb;
524         return unless $cb;
525         $cb->("unclean-$tagsfx", $why);
526     };
527     for (;;) {
528         my $cl = classify $head;
529         my $ty = $cl->{Type};
530         if ($ty eq 'Packaging') {
531             $breakwater //= $clogonly;
532             $breakwater //= $head;
533         } elsif ($ty eq 'Changelog') {
534             # this is going to count as the tip of the breakwater
535             # only if it has no upstream stuff before it
536             $clogonly //= $head;
537         } elsif ($ty eq 'Anchor' or
538                  $ty eq 'TreatAsAnchor' or
539                  $ty eq 'BreakwaterStart') {
540             $anchor = $head;
541             $breakwater //= $clogonly;
542             $breakwater //= $head;
543             last;
544         } elsif ($ty eq 'Upstream') {
545             $x->($unclean, 'ordering',
546  "packaging change ($breakwater) follows upstream change (eg $head)")
547                 if defined $breakwater;
548             $clogonly = undef;
549             $breakwater = undef;
550         } elsif ($ty eq 'Mixed') {
551             $x->($unclean, 'mixed',
552                  'found mixed upstream/packaging commit ($head)');
553             $clogonly = undef;
554             $breakwater = undef;
555         } elsif ($ty eq 'Pseudomerge' or
556                  $ty eq 'AddPatches') {
557             $x->($furniture, (lc $ty),
558                  "found interchange bureaucracy commit ($ty, $head)");
559         } elsif ($ty eq 'DgitImportUnpatched') {
560             $x->($trouble, 'dgitimport',
561                  "found dgit dsc import ($head)");
562             $breakwater = undef;
563             $anchor = undef;
564             no warnings qw(exiting);
565             last;
566         } else {
567             fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
568         }
569         $head = $cl->{Parents}[0]{CommitId};
570     }
571     return ($anchor, $breakwater);
572 }
573
574 sub walk ($;$$);
575 sub walk ($;$$) {
576     my ($input,
577         $nogenerate,$report) = @_;
578     # => ($tip, $breakwater_tip, $last_anchor)
579     # (or nothing, if $nogenerate)
580
581     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
582
583     # go through commits backwards
584     # we generate two lists of commits to apply:
585     # breakwater branch and upstream patches
586     my (@brw_cl, @upp_cl, @processed);
587     my %found;
588     my $upp_limit;
589     my @pseudomerges;
590
591     my $cl;
592     my $xmsg = sub {
593         my ($prose, $info) = @_;
594         my $ms = $cl->{Msg};
595         chomp $ms;
596         $info //= '';
597         $ms .= "\n\n[git-debrebase$info: $prose]\n";
598         return (Msg => $ms);
599     };
600     my $rewrite_from_here = sub {
601         my ($cl) = @_;
602         my $sp_cl = { SpecialMethod => 'StartRewrite' };
603         push @$cl, $sp_cl;
604         push @processed, $sp_cl;
605     };
606     my $cur = $input;
607
608     my $prdelim = "";
609     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
610
611     my $prline = sub {
612         return unless $report;
613         print $report $prdelim, @_;
614         $prdelim = "\n";
615     };
616
617     my $bomb = sub { # usage: return $bomb->();
618         print $report " Unprocessable" if $report;
619         print $report " ($cl->{Why})" if $report && defined $cl->{Why};
620         $prprdelim->();
621         if ($nogenerate) {
622             return (undef,undef);
623         }
624         die "commit $cur: Cannot cope with this commit (d.".
625             (join ' ', map { sprintf "%#x", $_->{Differs} }
626              @{ $cl->{Parents} }).
627             (defined $cl->{Why} ? "; $cl->{Why}": '').
628                  ")";
629     };
630
631     my $build;
632     my $breakwater;
633
634     my $build_start = sub {
635         my ($msg, $parent) = @_;
636         $prline->(" $msg");
637         $build = $parent;
638         no warnings qw(exiting); last;
639     };
640
641     my $last_anchor;
642
643     for (;;) {
644         $cl = classify $cur;
645         my $ty = $cl->{Type};
646         my $st = $cl->{SubType};
647         $prline->("$cl->{CommitId} $cl->{Type}");
648         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
649         push @processed, $cl;
650         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
651         if ($ty eq 'AddPatches') {
652             $cur = $p0;
653             $rewrite_from_here->(\@upp_cl);
654             next;
655         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
656             push @brw_cl, $cl;
657             $cur = $p0;
658             next;
659         } elsif ($ty eq 'BreakwaterStart') {
660             $last_anchor = $cur;
661             $build_start->('FirstPackaging', $cur);
662         } elsif ($ty eq 'Upstream') {
663             push @upp_cl, $cl;
664             $cur = $p0;
665             next;
666         } elsif ($ty eq 'Mixed') {
667             my $queue = sub {
668                 my ($q, $wh) = @_;
669                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
670                 push @$q, $cls;
671             };
672             $queue->(\@brw_cl, "debian");
673             $queue->(\@upp_cl, "upstream");
674             $rewrite_from_here->(\@brw_cl);
675             $cur = $p0;
676             next;
677         } elsif ($ty eq 'Pseudomerge') {
678             my $contrib = $cl->{Contributor}{CommitId};
679             print $report " Contributor=$contrib" if $report;
680             push @pseudomerges, $cl;
681             $rewrite_from_here->(\@upp_cl);
682             $cur = $contrib;
683             next;
684         } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
685             $last_anchor = $cur;
686             $build_start->("Anchor", $cur);
687         } elsif ($ty eq 'DgitImportUnpatched') {
688             my $pm = $pseudomerges[-1];
689             if (defined $pm) {
690                 # To an extent, this is heuristic.  Imports don't have
691                 # a useful history of the debian/ branch.  We assume
692                 # that the first pseudomerge after an import has a
693                 # useful history of debian/, and ignore the histories
694                 # from later pseudomerges.  Often the first pseudomerge
695                 # will be the dgit import of the upload to the actual
696                 # suite intended by the non-dgit NMUer, and later
697                 # pseudomerges may represent in-archive copies.
698                 my $ovwrs = $pm->{Overwritten};
699                 printf $report " PM=%s \@Overwr:%d",
700                     $pm->{CommitId}, (scalar @$ovwrs)
701                     if $report;
702                 if (@$ovwrs != 1) {
703                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
704                     return $bomb->();
705                 }
706                 my $ovwr = $ovwrs->[0]{CommitId};
707                 printf $report " Overwr=%s", $ovwr if $report;
708                 # This import has a tree which is just like a
709                 # breakwater tree, but it has the wrong history.  It
710                 # ought to have the previous breakwater (which the
711                 # pseudomerge overwrote) as an ancestor.  That will
712                 # make the history of the debian/ files correct.  As
713                 # for the upstream version: either it's the same as
714                 # was ovewritten (ie, same as the previous
715                 # breakwater), in which case that history is precisely
716                 # right; or, otherwise, it was a non-gitish upload of a
717                 # new upstream version.  We can tell these apart by
718                 # looking at the tree of the supposed upstream.
719                 push @brw_cl, {
720                     %$cl,
721                     SpecialMethod => 'DgitImportDebianUpdate',
722                     $xmsg->("convert dgit import: debian changes")
723                 }, {
724                     %$cl,
725                     SpecialMethod => 'DgitImportUpstreamUpdate',
726                     $xmsg->("convert dgit import: upstream update",
727                             " anchor")
728                 };
729                 $prline->(" Import");
730                 $rewrite_from_here->(\@brw_cl);
731                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
732                 $cur = $ovwr;
733                 next;
734             } else {
735                 # Everything is from this import.  This kind of import
736                 # is already in valid breakwater format, with the
737                 # patches as commits.
738                 printf $report " NoPM" if $report;
739                 # last thing we processed will have been the first patch,
740                 # if there is one; which is fine, so no need to rewrite
741                 # on account of this import
742                 $build_start->("ImportOrigin", $cur);
743             }
744             die "$ty ?";
745         } else {
746             printdebug "*** WALK BOMB unrecognised\n";
747             return $bomb->();
748         }
749     }
750     $prprdelim->();
751
752     printdebug "*** WALK prep done cur=$cur".
753         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
754
755     return if $nogenerate;
756
757     # Now we build it back up again
758
759     fresh_workarea();
760
761     my $rewriting = 0;
762
763     my $read_tree_debian = sub {
764         my ($treeish) = @_;
765         read_tree_subdir 'debian', "$treeish:debian";
766         rm_subdir_cached 'debian/patches';
767     };
768     my $read_tree_upstream = sub {
769         my ($treeish) = @_;
770         runcmd @git, qw(read-tree), $treeish;
771         $read_tree_debian->($build);
772     };
773
774     $#upp_cl = $upp_limit if defined $upp_limit;
775  
776     my $committer_authline = calculate_committer_authline();
777
778     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
779
780     confess "internal error" unless $build eq (pop @processed)->{CommitId};
781
782     in_workarea sub {
783         mkdir $rd or $!==EEXIST or die $!;
784         my $current_method;
785         runcmd @git, qw(read-tree), $build;
786         foreach my $cl (qw(Debian), (reverse @brw_cl),
787                         { SpecialMethod => 'RecordBreakwaterTip' },
788                         qw(Upstream), (reverse @upp_cl)) {
789             if (!ref $cl) {
790                 $current_method = $cl;
791                 next;
792             }
793             my $method = $cl->{SpecialMethod} // $current_method;
794             my @parents = ($build);
795             my $cltree = $cl->{CommitId};
796             printdebug "WALK BUILD ".($cltree//'undef').
797                 " $method (rewriting=$rewriting)\n";
798             if ($method eq 'Debian') {
799                 $read_tree_debian->($cltree);
800             } elsif ($method eq 'Upstream') {
801                 $read_tree_upstream->($cltree);
802             } elsif ($method eq 'StartRewrite') {
803                 $rewriting = 1;
804                 next;
805             } elsif ($method eq 'RecordBreakwaterTip') {
806                 $breakwater = $build;
807                 next;
808             } elsif ($method eq 'DgitImportDebianUpdate') {
809                 $read_tree_debian->($cltree);
810             } elsif ($method eq 'DgitImportUpstreamUpdate') {
811                 confess unless $rewriting;
812                 my $differs = (get_differs $build, $cltree);
813                 next unless $differs & D_UPS;
814                 $read_tree_upstream->($cltree);
815                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
816             } else {
817                 confess "$method ?";
818             }
819             if (!$rewriting) {
820                 my $procd = (pop @processed) // 'UNDEF';
821                 if ($cl ne $procd) {
822                     $rewriting = 1;
823                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
824                 }
825             }
826             my $newtree = cmdoutput @git, qw(write-tree);
827             my $ch = $cl->{Hdr};
828             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
829             $ch =~ s{^parent .*\n}{}mg;
830             $ch =~ s{(?=^author)}{
831                 join '', map { "parent $_\n" } @parents
832             }me or confess "$ch ?";
833             if ($rewriting) {
834                 $ch =~ s{^committer .*$}{$committer_authline}m
835                     or confess "$ch ?";
836             }
837             my $cf = "$rd/m$rewriting";
838             open CD, ">", $cf or die $!;
839             print CD $ch, "\n", $cl->{Msg} or die $!;
840             close CD or die $!;
841             my @cmd = (@git, qw(hash-object));
842             push @cmd, qw(-w) if $rewriting;
843             push @cmd, qw(-t commit), $cf;
844             my $newcommit = cmdoutput @cmd;
845             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
846             $build = $newcommit;
847             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
848                 $last_anchor = $cur;
849             }
850         }
851     };
852
853     my $final_check = get_differs $build, $input;
854     die sprintf "internal error %#x %s %s", $final_check, $build, $input
855         if $final_check & ~D_PAT_ADD;
856
857     my @r = ($build, $breakwater, $last_anchor);
858     printdebug "*** WALK RETURN @r\n";
859     return @r
860 }
861
862 sub get_head () {
863     git_check_unmodified();
864     return git_rev_parse qw(HEAD);
865 }
866
867 sub update_head ($$$) {
868     my ($old, $new, $mrest) = @_;
869     push @deferred_updates, "update HEAD $new $old";
870     run_deferred_updates $mrest;
871 }
872
873 sub update_head_checkout ($$$) {
874     my ($old, $new, $mrest) = @_;
875     update_head $old, $new, $mrest;
876     runcmd @git, qw(reset --hard);
877 }
878
879 sub update_head_postlaunder ($$$) {
880     my ($old, $tip, $reflogmsg) = @_;
881     return if $tip eq $old;
882     print "git-debrebase: laundered (head was $old)\n";
883     update_head $old, $tip, $reflogmsg;
884     # no tree changes except debian/patches
885     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
886 }
887
888 sub do_launder_head ($) {
889     my ($reflogmsg) = @_;
890     my $old = get_head();
891     record_ffq_auto();
892     my ($tip,$breakwater) = walk $old;
893     update_head_postlaunder $old, $tip, $reflogmsg;
894     return ($tip,$breakwater);
895 }
896
897 sub cmd_launder_v0 () {
898     badusage "no arguments to launder-v0 allowed" if @ARGV;
899     my $old = get_head();
900     my ($tip,$breakwater,$last_anchor) = walk $old;
901     update_head_postlaunder $old, $tip, 'launder';
902     printf "# breakwater tip\n%s\n", $breakwater;
903     printf "# working tip\n%s\n", $tip;
904     printf "# last anchor\n%s\n", $last_anchor;
905 }
906
907 sub defaultcmd_rebase () {
908     my ($tip,$breakwater) = do_launder_head 'launder for rebase';
909     runcmd @git, qw(rebase), @ARGV, $breakwater;
910 }
911
912 sub cmd_analyse () {
913     die if ($ARGV[0]//'') =~ m/^-/;
914     badusage "too many arguments to analyse" if @ARGV>1;
915     my ($old) = @ARGV;
916     if (defined $old) {
917         $old = git_rev_parse $old;
918     } else {
919         $old = git_rev_parse 'HEAD';
920     }
921     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
922     STDOUT->error and die $!;
923 }
924
925 sub ffq_prev_branchinfo () {
926     # => ('status', "message", [$current, $ffq_prev, $gdrlast])
927     # 'status' may be
928     #    branch         message is undef
929     #    weird-symref   } no $current,
930     #    notbranch      }  no $ffq_prev
931     my $current = git_get_symref();
932     return ('detached', 'detached HEAD') unless defined $current;
933     return ('weird-symref', 'HEAD symref is not to refs/')
934         unless $current =~ m{^refs/};
935     my $ffq_prev = "refs/$ffq_refprefix/$'";
936     my $gdrlast = "refs/$gdrlast_refprefix/$'";
937     printdebug "ffq_prev_branchinfo branch current $current\n";
938     return ('branch', undef, $current, $ffq_prev, $gdrlast);
939 }
940
941 sub record_ffq_prev_deferred () {
942     # => ('status', "message")
943     # 'status' may be
944     #    deferred          message is undef
945     #    exists
946     #    detached
947     #    weird-symref
948     #    notbranch
949     # if not ff from some branch we should be ff from, is an snag
950     # if "deferred", will have added something about that to
951     #   @deferred_update_messages, and also maybe printed (already)
952     #   some messages about ff checks
953     my ($status, $message, $current, $ffq_prev, $gdrlast)
954         = ffq_prev_branchinfo();
955     return ($status, $message) unless $status eq 'branch';
956
957     my $currentval = get_head();
958
959     my $exists = git_get_ref $ffq_prev;
960     return ('exists',"$ffq_prev already exists") if $exists;
961
962     return ('not-branch', 'HEAD symref is not to refs/heads/')
963         unless $current =~ m{^refs/heads/};
964     my $branch = $';
965
966     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
967     my %checked;
968
969     printdebug "ffq check_specs @check_specs\n";
970
971     my $check = sub {
972         my ($lrref, $desc) = @_;
973         printdebug "ffq might check $lrref ($desc)\n";
974         my $invert;
975         for my $chk (@check_specs) {
976             my $glob = $chk;
977             $invert = $glob =~ s{^[!^]}{};
978             last if fnmatch $glob, $lrref;
979         }
980         return if $invert;
981         my $lrval = git_get_ref $lrref;
982         return unless defined $lrval;
983
984         if (is_fast_fwd $lrval, $currentval) {
985             print "OK, you are ahead of $lrref\n" or die $!;
986             $checked{$lrref} = 1;
987         } elsif (is_fast_fwd $currentval, $lrval) {
988             $checked{$lrref} = -1;
989             snag 'behind', "you are behind $lrref, divergence risk";
990         } else {
991             $checked{$lrref} = -1;
992             snag 'diverged', "you have diverged from $lrref";
993         }
994     };
995
996     my $merge = cfg "branch.$branch.merge",1;
997     if (defined $merge and $merge =~ m{^refs/heads/}) {
998         my $rhs = $';
999         printdebug "ffq merge $rhs\n";
1000         my $check_remote = sub {
1001             my ($remote, $desc) = @_;
1002             printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1003             return unless defined $remote;
1004             $check->("refs/remotes/$remote/$rhs", $desc);
1005         };
1006         $check_remote->((scalar cfg "branch.$branch.remote",1),
1007                         'remote fetch/merge branch');
1008         $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1009                         (scalar cfg "branch.$branch.pushDefault",1),
1010                         'remote push branch');
1011     }
1012     if ($branch =~ m{^dgit/}) {
1013         $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1014     } elsif ($branch =~ m{^master$}) {
1015         $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1016     }
1017
1018     snags_maybe_bail();
1019
1020     push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1021     push @deferred_updates, "delete $gdrlast";
1022     push @deferred_update_messages, "Recorded current head for preservation";
1023     return ('deferred', undef);
1024 }
1025
1026 sub record_ffq_auto () {
1027     my ($status, $message) = record_ffq_prev_deferred();
1028     if ($status eq 'deferred' || $status eq 'exists') {
1029     } else {
1030         snag $status, "could not record ffq-prev: $message";
1031         snags_maybe_bail();
1032     }
1033 }
1034
1035 sub ffq_prev_info () {
1036     # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1037     my ($status, $message, $current, $ffq_prev, $gdrlast)
1038         = ffq_prev_branchinfo();
1039     if ($status ne 'branch') {
1040         snag $status, "could not check ffq-prev: $message";
1041         snags_maybe_bail();
1042     }
1043     my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1044     return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1045 }
1046
1047 sub stitch ($$$$$) {
1048     my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1049
1050     push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1051
1052     if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1053         my $differs = get_differs $old_head, $ffq_prev_commitish;
1054         unless ($differs & ~D_PAT_ADD) {
1055             # ffq-prev is ahead of us, and the only tree changes it has
1056             # are possibly addition of things in debian/patches/.
1057             # Just wind forwards rather than making a pointless pseudomerge.
1058             push @deferred_updates,
1059                 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1060             update_head_checkout $old_head, $ffq_prev_commitish,
1061                 "stitch (fast forward)";
1062             return;
1063         }
1064     }
1065     fresh_workarea();
1066     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1067         'Declare fast forward / record previous work',
1068         "[git-debrebase pseudomerge: $prose]",
1069     ];
1070     push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1071     update_head $old_head, $new_head, "stitch: $prose";
1072 }
1073
1074 sub cmd_new_upstream_v0 () {
1075     # automatically and unconditionally launders before rebasing
1076     # if rebase --abort is used, laundering has still been done
1077
1078     my %pieces;
1079
1080     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1081
1082     # parse args - low commitment
1083     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1084     my $new_upstream_version = $new_version->version();
1085
1086     my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1087
1088     record_ffq_auto();
1089
1090     my $piece = sub {
1091         my ($n, @x) = @_; # may be ''
1092         my $pc = $pieces{$n} //= {
1093             Name => $n,
1094             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1095         };
1096         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1097         $pc;
1098     };
1099
1100     my @newpieces;
1101     my $newpiece = sub {
1102         my ($n, @x) = @_; # may be ''
1103         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1104         push @newpieces, $pc;
1105     };
1106
1107     $newpiece->('',
1108         OldIx => 0,
1109         New => $new_upstream,
1110     );
1111     while (@ARGV && $ARGV[0] !~ m{^-}) {
1112         my $n = shift @ARGV;
1113
1114         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1115             unless @ARGV && $ARGV[0] !~ m{^-};
1116
1117         my $c = git_rev_parse shift @ARGV;
1118         die unless $n =~ m/^$extra_orig_namepart_re$/;
1119         $newpiece->($n, New => $c);
1120     }
1121
1122     # now we need to investigate the branch this generates the
1123     # laundered version but we don't switch to it yet
1124     my $old_head = get_head();
1125     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1126
1127     my $old_bw_cl = classify $old_bw;
1128     my $old_anchor_cl = classify $old_anchor;
1129     my $old_upstream;
1130     if (!$old_anchor_cl->{OrigParents}) {
1131         snag 'anchor-treated',
1132             'old anchor is recognised due to --anchor, cannot check upstream';
1133     } else {
1134         $old_upstream = parsecommit
1135             $old_anchor_cl->{OrigParents}[0]{CommitId};
1136         $piece->('', Old => $old_upstream->{CommitId});
1137     }
1138
1139     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1140         if ($old_upstream->{Msg} =~
1141  m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1142            ) {
1143             my @oldpieces = ('', split / /, $1);
1144             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1145             foreach my $i (0..$#oldpieces) {
1146                 my $n = $oldpieces[$i];
1147                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1148             }
1149         } else {
1150             snag 'upstream-confusing',
1151                 "previous upstream $old_upstream->{CommitId} is from".
1152                " git-debrebase but not an \`upstream-combine' commit";
1153         }
1154     }
1155
1156     foreach my $pc (values %pieces) {
1157         if (!$old_upstream) {
1158             # we have complained already
1159         } elsif (!$pc->{Old}) {
1160             snag 'upstream-new-piece',
1161                 "introducing upstream piece \`$pc->{Name}'";
1162         } elsif (!$pc->{New}) {
1163             snag 'upstream-rm-piece',
1164                 "dropping upstream piece \`$pc->{Name}'";
1165         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1166             snag 'upstream-not-ff',
1167                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1168         }
1169     }
1170
1171     printdebug "%pieces = ", (dd \%pieces), "\n";
1172     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1173
1174     snags_maybe_bail();
1175
1176     my $new_bw;
1177
1178     fresh_workarea();
1179     in_workarea sub {
1180         my @upstream_merge_parents;
1181
1182         if (!any_snags()) {
1183             push @upstream_merge_parents, $old_upstream->{CommitId};
1184         }
1185
1186         foreach my $pc (@newpieces) { # always has '' first
1187             if ($pc->{Name}) {
1188                 read_tree_subdir $pc->{Name}, $pc->{New};
1189             } else {
1190                 runcmd @git, qw(read-tree), $pc->{New};
1191             }
1192             push @upstream_merge_parents, $pc->{New};
1193         }
1194
1195         # index now contains the new upstream
1196
1197         if (@newpieces > 1) {
1198             # need to make the upstream subtree merge commit
1199             $new_upstream = make_commit \@upstream_merge_parents,
1200                 [ "Combine upstreams for $new_upstream_version",
1201  ("[git-debrebase upstream-combine . ".
1202  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1203  ": new upstream]"),
1204                 ];
1205         }
1206
1207         # $new_upstream is either the single upstream commit, or the
1208         # combined commit we just made.  Either way it will be the
1209         # "upstream" parent of the anchor merge.
1210
1211         read_tree_subdir 'debian', "$old_bw:debian";
1212
1213         # index now contains the anchor merge contents
1214         $new_bw = make_commit [ $old_bw, $new_upstream ],
1215             [ "Update to upstream $new_upstream_version",
1216  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1217             ];
1218
1219         # Now we have to add a changelog stanza so the Debian version
1220         # is right.
1221         die if unlink "debian";
1222         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1223         unlink "debian/changelog" or $!==ENOENT or die $!;
1224         mkdir "debian" or die $!;
1225         open CN, ">", "debian/changelog" or die $!;
1226         my $oldclog = git_cat_file ":debian/changelog";
1227         $oldclog =~ m/^($package_re) \(\S+\) / or
1228             fail "cannot parse old changelog to get package name";
1229         my $p = $1;
1230         print CN <<END, $oldclog or die $!;
1231 $p ($new_version) UNRELEASED; urgency=medium
1232
1233   * Update to new upstream version $new_upstream_version.
1234
1235  -- 
1236
1237 END
1238         close CN or die $!;
1239         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1240
1241         # Now we have the final new breakwater branch in the index
1242         $new_bw = make_commit [ $new_bw ],
1243             [ "Update changelog for new upstream $new_upstream_version",
1244               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1245             ];
1246     };
1247
1248     # we have constructed the new breakwater. we now need to commit to
1249     # the laundering output, because git-rebase can't easily be made
1250     # to make a replay list which is based on some other branch
1251
1252     update_head_postlaunder $old_head, $old_laundered_tip,
1253         'launder for new upstream';
1254
1255     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1256     runcmd @cmd;
1257     # now it's for the user to sort out
1258 }
1259
1260 sub cmd_record_ffq_prev () {
1261     badusage "no arguments allowed" if @ARGV;
1262     my ($status, $msg) = record_ffq_prev_deferred();
1263     if ($status eq 'exists' && $opt_noop_ok) {
1264         print "Previous head already recorded\n" or die $!;
1265     } elsif ($status eq 'deferred') {
1266         run_deferred_updates 'record-ffq-prev';
1267     } else {
1268         fail "Could not preserve: $msg";
1269     }
1270 }
1271
1272 sub cmd_anchor () {
1273     badusage "no arguments allowed" if @ARGV;
1274     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1275     print "$bw\n" or die $!;
1276 }
1277
1278 sub cmd_breakwater () {
1279     badusage "no arguments allowed" if @ARGV;
1280     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1281     print "$bw\n" or die $!;
1282 }
1283
1284 sub cmd_stitch () {
1285     my $prose = 'stitch';
1286     GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1287     badusage "no arguments allowed" if @ARGV;
1288
1289     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1290     if (!$ffq_prev_commitish) {
1291         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1292         return;
1293     }
1294     my $old_head = get_head();
1295
1296     keycommits $old_head, \&snag, \&snag, \&snag;
1297
1298     stitch($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1299 }
1300
1301 sub cmd_convert_from_gbp () {
1302     badusage "needs 1 optional argument, the upstream git rev"
1303         unless @ARGV<=1;
1304     my ($upstream_spec) = @ARGV;
1305     $upstream_spec //= 'refs/heads/upstream';
1306     my $upstream = git_rev_parse $upstream_spec;
1307     my $old_head = get_head();
1308
1309     my $upsdiff = get_differs $upstream, $old_head;
1310     if ($upsdiff & D_UPS) {
1311         runcmd @git, qw(--no-pager diff),
1312             $upstream, $old_head,
1313             qw( -- :!/debian :/);
1314  fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1315     }
1316
1317     if (!is_fast_fwd $upstream, $old_head) {
1318         snag 'upstream-not-ancestor',
1319             "upstream ($upstream) is not an ancestor of HEAD";
1320     } else {
1321         my $wrong = cmdoutput
1322             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1323              qw(-- :/ :!/debian));
1324         if (length $wrong) {
1325             snag 'unexpected-upstream-changes',
1326                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1327             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1328         }
1329     }
1330
1331     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1332         snag 'upstream-has-debian',
1333             "upstream ($upstream) contains debian/ directory";
1334     }
1335
1336     snags_maybe_bail();
1337
1338     my $work;
1339
1340     fresh_workarea();
1341     in_workarea sub {
1342         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1343         # make a branch out of the patch queue - we'll want this in a mo
1344         runcmd qw(gbp pq import);
1345         # strip the patches out
1346         runcmd @git, qw(checkout -q gdr-internal~0);
1347         rm_subdir_cached 'debian/patches';
1348         $work = make_commit ['HEAD'], [
1349  'git-debrebase convert-from-gbp: drop patches from tree',
1350  'Delete debian/patches, as part of converting to git-debrebase format.',
1351  '[git-debrebase convert-from-gbp: drop patches from tree]'
1352                               ];
1353         # make the anchor merge
1354         # the tree is already exactly right
1355         $work = make_commit [$work, $upstream], [
1356  'git-debrebase import: declare upstream',
1357  'First breakwater merge.',
1358  '[git-debrebase anchor: declare upstream]'
1359                               ];
1360
1361         # rebase the patch queue onto the new breakwater
1362         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1363         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1364         $work = git_rev_parse 'HEAD';
1365     };
1366
1367     update_head_checkout $old_head, $work, 'convert-from-gbp';
1368 }
1369
1370 sub cmd_convert_to_gbp () {
1371     badusage "no arguments allowed" if @ARGV;
1372     my $head = get_head();
1373     my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
1374     my ($anchor, $bw) = keycommits $head, 0;
1375     fresh_workarea();
1376     my $out;
1377     in_workarea sub {
1378         runcmd @git, qw(checkout -q -b bw), $bw;
1379         runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1380         runcmd qw(gbp pq export);
1381         runcmd @git, qw(add debian/patches);
1382         $out = make_commit ['HEAD'], [
1383             'Commit patch queue (converted from git-debrebase format)',
1384             '[git-debrebase convert-to-gbp: commit patches]',
1385         ];
1386     };
1387     if (defined $ffq) {
1388         push @deferred_updates, "delete $ffq";
1389         push @deferred_updates, "delete $gdrlast";
1390     }
1391     update_head_checkout $head, $out, "convert to gbp (v0)";
1392     print <<END or die $!;
1393 git-debrebase: converted to git-buildpackage branch format
1394 git-debrebase: WARNING: do not now run "git-debrebase" any more
1395 git-debrebase: WARNING: doing so would drop all upstream patches!
1396 END
1397 }
1398
1399 sub cmd_downstream_rebase_launder_v0 () {
1400     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1401     my ($base) = @ARGV;
1402     $base = git_rev_parse $base;
1403     my $old_head = get_head();
1404     my $current = $old_head;
1405     my $topmost_keep;
1406     for (;;) {
1407         if ($current eq $base) {
1408             $topmost_keep //= $current;
1409             print " $current BASE stop\n";
1410             last;
1411         }
1412         my $cl = classify $current;
1413         print " $current $cl->{Type}";
1414         my $keep = 0;
1415         my $p0 = $cl->{Parents}[0]{CommitId};
1416         my $next;
1417         if ($cl->{Type} eq 'Pseudomerge') {
1418             print " ^".($cl->{Contributor}{Ix}+1);
1419             $next = $cl->{Contributor}{CommitId};
1420         } elsif ($cl->{Type} eq 'AddPatches' or
1421                  $cl->{Type} eq 'Changelog') {
1422             print " strip";
1423             $next = $p0;
1424         } else {
1425             print " keep";
1426             $next = $p0;
1427             $keep = 1;
1428         }
1429         print "\n";
1430         if ($keep) {
1431             $topmost_keep //= $current;
1432         } else {
1433             die "to-be stripped changes not on top of the branch\n"
1434                 if $topmost_keep;
1435         }
1436         $current = $next;
1437     }
1438     if ($topmost_keep eq $old_head) {
1439         print "unchanged\n";
1440     } else {
1441         print "updating to $topmost_keep\n";
1442         update_head_checkout
1443             $old_head, $topmost_keep,
1444             'downstream-rebase-launder-v0';
1445     }
1446 }
1447
1448 GetOptions("D+" => \$debuglevel,
1449            'noop-ok', => \$opt_noop_ok,
1450            'f=s' => \@snag_force_opts,
1451            'anchor=s' => \@opt_anchors,
1452            'force!') or die badusage "bad options\n";
1453 initdebug('git-debrebase ');
1454 enabledebug if $debuglevel;
1455
1456 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1457 chdir $toplevel or die "chdir $toplevel: $!";
1458
1459 $rd = fresh_playground "$playprefix/misc";
1460
1461 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1462
1463 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1464     defaultcmd_rebase();
1465 } else {
1466     my $cmd = shift @ARGV;
1467     my $cmdfn = $cmd;
1468     $cmdfn =~ y/-/_/;
1469     $cmdfn = ${*::}{"cmd_$cmdfn"};
1470
1471     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1472     $cmdfn->();
1473 }