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