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