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