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