chiark / gitweb /
git-debrebase: BUG due to some evidently unfinished code
[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 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 #    git-debrebase new-upstreams-v0 \
22 #             NEW-VERSION ORIG-COMMITISH
23 #            [EXTRA-ORIG-NAME EXTRA-ORIG-COMMITISH ...]
24
25 # usages:
26 #    git-debrebase status
27 #    git-debrebase start       # like ffqrebase start + debrebase launder
28 #    git-debrebase new-upstream [stuff]  # see below
29 #    git-debrebase <git-rebase options>  # does debrebase start if necessary
30 #
31 #    git-debrebase analyse
32 #    git-debrebase launder     # prints breakwater tip
33 #    git-debrebase create-new-upstream-breakwater [-f] <upstreaminfo>...
34 #
35 # <upstreaminfo> is
36 #    [,][<subdir>:][+]<commitid>[,...]
37 #
38 # if initial comma is supplied, entries are not positional.  Unspecified
39 # <subdir> means root (and there may be only one).
40 # xxx want auto branch names
41 # xxx too complicated
42 # how about for now
43 #    [+]<commit> [<subdir/> [+]<commit>...]
44 # ?  plus options
45 #     --new-upstream-different-subtrees
46 #
47 #  automatic case
48 #       git-debrebase new-upstream
49 #             - previous breakwater merge must be gdr-generated
50 #             - orig set is the same as before
51 #             - implicitly uses upstream branches according to orig set
52 #             - not all upstream branches need be updated
53 #             - insists on fast-forward of each branch, unless
54 #                  --force (or --force=<subdir>[/])
55 #  branch set adjustments
56 #       git-debrebase new-upstream --add <subdir>/
57 #       git-debrebase new-upstream --rm <subdir>/
58 #       git-debrebase new-upstream / [<subdir>/ ...]
59 #             - orig set is adjusted
60 #             - otherwise like auto (--add is not checked for ffness, obv)
61 #             - multiple --add and --rm may be specified
62 #             - --add makes new upstream the last contributor
63 #  explicit
64 #       git-debrebase / [<rootcommitid>] [<subdir>/ [<commitid>] ...]
65 #             - orig set is precisely as specified now
66 #             - previous breakwater merge is irrelevant
67 #             - no fast forward checks
68 #  for now only explicit with commitids
69
70 #         implicitly uses `upstream'
71 #                                     # (or multiple other branches)
72 #       git-debrebase new-upstream \
73 #             [<subdir>/]=<commitid>
74
75 #    UPSTREAM[,[[SUBDIR:]SUBUPSTREAM]
76 #    default for SUBDIR: is from previous upstream merge[xxx terminology]
77 #    
78 #
79 #xxx
80 # when starting must record original start (for ff)
81 # and new rebase basis
82 #
83 #    git-ffqrebase start [BASE]
84 #                # records previous HEAD so it can be overwritten
85 #                # records base for future git-ffqrebase
86 #    git-ffqrebase set-base BASE
87 #    git-ffqrebase <git-rebase options>
88 #    git-ffqrebase finish
89 #    git-ffqrebase status [BRANCH]
90 #
91 #  refs/ffqrebase-prev/BRANCH    BRANCH may be refs/...; if not it means
92 #  refs/ffqrebase-base/BRANCH      refs/heads/BRANCH
93 #                               zero, one, or both of these may exist
94 #
95 # git-debrebase without start, if already started, is willing
96 # to strip pseudomerges provided that they overwrite exactly
97 # the previous HEAD
98 #  xxxx is this right ?  what matters is have we pushed
99 #    I think in fact the right answer is:
100 #       git-debrebase always strips out pseudomerges from its branch
101 #       a pseudomerge is put in at the time we want to push
102 #       at that time, we make a pseudomerge of the remote tracking
103 #           branch (if raw git) or the dgit view (if dgit)
104 #       for raw git git-ffqrebase, do want preciseley to record
105 #           value of remote tracking branch or our branch, on start, so we
106 #           overwrite only things we intend to
107 #  the previous pseudomerge    check for tags and remote branches ?
108
109 use strict;
110
111 use Debian::Dgit qw(:DEFAULT :playground);
112 setup_sigwarn();
113
114 use Memoize;
115 use Carp;
116 use POSIX;
117 use Data::Dumper;
118 use Getopt::Long qw(:config posix_default gnu_compat bundling);
119 use Dpkg::Version;
120
121 our ($opt_force);
122
123 sub badusage ($) {
124     my ($m) = @_;
125     die "bad usage: $m\n";
126 }
127
128 sub cfg ($) {
129     my ($k) = @_;
130     $/ = "\0";
131     my @cmd = qw(git config -z);
132     push @cmd, qw(--get-all) if wantarray;
133     push @cmd, $k;
134     my $out = cmdoutput @cmd;
135     return split /\0/, $out;
136 }
137
138 memoize('cfg');
139
140 sub get_commit ($) {
141     my ($objid) = @_;
142     my $data = git_cat_file $objid, 'commit';
143     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
144     return ($`,$');
145 }
146
147 sub D_UPS ()      { 0x02; } # upstream files
148 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
149 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
150 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
151 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
152 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
153
154 our $playprefix = 'debrebase';
155 our $rd;
156 our $workarea;
157
158 our @git = qw(git);
159
160 sub in_workarea ($) {
161     my ($sub) = @_;
162     changedir $workarea;
163     my $r = eval { $sub->(); };
164     { local $@; changedir $maindir; }
165     die $@ if $@;
166 }
167
168 sub fresh_workarea () {
169     $workarea = fresh_playground "$playprefix/work";
170     in_workarea sub { playtree_setup };
171 }
172
173 sub get_differs ($$) {
174     my ($x,$y) = @_;
175     # This resembles quiltify_trees_differ, in dgit, a bit.
176     # But we don't care about modes, or dpkg-source-unrepresentable
177     # changes, and we don't need the plethora of different modes.
178     # Conversely we need to distinguish different kinds of changes to
179     # debian/ and debian/patches/.
180
181     my $differs = 0;
182
183     my $rundiff = sub {
184         my ($opts, $limits, $fn) = @_;
185         my @cmd = (@git, qw(diff-tree -z --no-renames));
186         push @cmd, @$opts;
187         push @cmd, "$_:" foreach $x, $y;
188         push @cmd, @$limits;
189         my $diffs = cmdoutput @cmd;
190         foreach (split /\0/, $diffs) { $fn->(); }
191     };
192
193     $rundiff->([qw(--name-only)], [], sub {
194         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
195     });
196
197     if ($differs & DS_DEB) {
198         $differs &= ~DS_DEB;
199         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
200             $differs |=
201                 m{^debian/patches/}      ? D_PAT_OTH  :
202                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
203                                            D_DEB_OTH;
204         });
205         die "mysterious debian changes $x..$y"
206             unless $differs & (D_PAT_OTH|DS_DEB);
207     }
208
209     if ($differs & D_PAT_OTH) {
210         my $mode;
211         $differs &= ~D_PAT_OTH;
212         my $pat_oth = sub {
213             $differs |= D_PAT_OTH;
214             no warnings qw(exiting);  last;
215         };
216         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
217             no warnings qw(exiting);
218             if (!defined $mode) {
219                 $mode = $_;  next;
220             }
221             die unless s{^debian/patches/}{};
222             my $ok;
223             if ($mode eq 'A' && !m/\.series$/s) {
224                 $ok = 1;
225             } elsif ($mode eq 'M' && $_ eq 'series') {
226                 my $x_s = git_cat_file "$x:debian/patches/series", 'blob';
227                 my $y_s = git_cat_file "$y:debian/patches/series", 'blob';
228                 chomp $x_s;  $x_s .= "\n";
229                 $ok = $x_s eq substr($y_s, 0, length $x_s);
230             } else {
231                 # nope
232             }
233             $mode = undef;
234             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
235         });
236         die "mysterious debian/patches changes $x..$y"
237             unless $differs & (D_PAT_ADD|D_PAT_OTH);
238     }
239
240     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
241
242     return $differs;
243 }
244
245 sub commit_pr_info ($) {
246     my ($r) = @_;
247     return Data::Dumper->dump([$r], [qw(commit)]);
248 }
249
250 sub calculate_committer_authline () {
251     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
252         'DUMMY COMMIT (git-debrebase)', "HEAD:";
253     my ($h,$m) = get_commit $c;
254     $h =~ m/^committer .*$/m or confess "($h) ?";
255     return $&;
256 }
257
258 sub rm_subdir_cached ($) {
259     my ($subdir) = @_;
260     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
261 }
262
263 sub read_tree_subdir ($$) {
264     my ($subdir, $new_tree_object) = @_;
265     rm_subdir_cached $subdir;
266     runcmd @git, qw(read-tree), "--prefix=$subdir/";
267 }
268
269 # classify returns an info hash like this
270 #   CommitId => $objid
271 #   Hdr => # commit headers, including 1 final newline
272 #   Msg => # commit message (so one newline is dropped)
273 #   Tree => $treeobjid
274 #   Type => (see below)
275 #   Parents = [ {
276 #       Ix => $index # ie 0, 1, 2, ...
277 #       CommitId
278 #       Differs => return value from get_differs
279 #       IsOrigin
280 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
281 #     } ...]
282 #   NewMsg => # commit message, but with any [dgit import ...] edited
283 #             # to say "[was: ...]"
284 #
285 # Types:
286 #   Packaging
287 #   Changelog
288 #   Upstream
289 #   AddPatches
290 #   Mixed
291 #   Unknown
292 #
293 #   Pseudomerge
294 #     has additional entres in classification result
295 #       Overwritten = [ subset of Parents ]
296 #       Contributor = $the_remaining_Parent
297 #
298 #   DgitImportUnpatched
299 #     has additional entry in classification result
300 #       OrigParents = [ subset of Parents ]
301 #
302 #   BreakwaterUpstreamMerge
303 #     has additional entry in classification result
304 #       OrigParents = [ subset of Parents ]  # singleton list
305
306 sub parsecommit ($;$) {
307     my ($objid, $p_ref) = @_;
308     # => hash with                   CommitId Hdr Msg Tree Parents
309     #    Parents entries have only   Ix CommitId
310     #    $p_ref, if provided, must be [] and is used as a base for Parents
311
312     $p_ref //= [];
313     die if @$p_ref;
314
315     my ($h,$m) = get_commit $objid;
316
317     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
318     my (@ph) = $h =~ m/^parent (\w+)$/mg;
319
320     my $r = {
321         CommitId => $objid,
322         Hdr => $h,
323         Msg => $m,
324         Tree => $t,
325         Parents => $p_ref,
326     };
327
328     foreach my $ph (@ph) {
329         push @$p_ref, {
330             Ix => $#$p_ref,
331             CommitId => $ph,
332         };
333     }
334
335     return $r;
336 }    
337
338 sub classify ($) {
339     my ($objid) = @_;
340
341     my @p;
342     my $r = parsecommit($objid, \@p);
343     my $t = $r->{Tree};
344
345     foreach my $p (@p) {
346         $p->{Differs} = (get_differs $p->{CommitId}, $t),
347     }
348
349     printdebug "classify $objid \$t=$t \@p",
350         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
351         "\n";
352
353     my $classify = sub {
354         my ($type, @rest) = @_;
355         $r = { %$r, Type => $type, @rest };
356         if ($debuglevel) {
357             my $dd = new Data::Dumper [ $r ];
358             Terse $dd 1; Indent $dd 0; Useqq $dd 1;
359             printdebug " = $type ".(Dump $dd)."\n";
360         }
361         return $r;
362     };
363     my $unknown = sub {
364         my ($why) = @_;
365         $r = { %$r, Type => qw(Unknown) };
366         printdebug " ** Unknown\n";
367         return $r;
368     };
369
370     if (@p == 1) {
371         my $d = $r->{Parents}[0]{Differs};
372         if ($d == D_PAT_ADD) {
373             return $classify->(qw(AddPatches));
374         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
375             return $unknown->("edits debian/patches");
376         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
377             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
378             if ($ty eq 'tree') {
379                 if ($d == D_DEB_CLOG) {
380                     return $classify->(qw(Changelog));
381                 } else {
382                     return $classify->(qw(Packaging));
383                 }
384             } elsif ($ty eq 'missing') {
385                 return $classify->(qw(BreakwaterStart));
386             } else {
387                 return $unknown->("parent's debian is not a directory");
388             }
389         } elsif ($d == D_UPS) {
390             return $classify->(qw(Upstream));
391         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
392             return $classify->(qw(Mixed));
393         } elsif ($d == 0) {
394             return $unknown->("no changes");
395         } else {
396             confess "internal error $objid ?";
397         }
398     }
399     if (!@p) {
400         return $unknown->("origin commit");
401     }
402
403     my @identical = grep { !$_->{Differs} } @p;
404     if (@p == 2 && @identical == 1) {
405         my @overwritten = grep { $_->{Differs} } @p;
406         confess "internal error $objid ?" unless @overwritten==1;
407         return $classify->(qw(Pseudomerge),
408                            Overwritten => $overwritten[0],
409                            Contributor => $identical[0]);
410     }
411     if (@p == 2 && @identical == 2) {
412         my @bytime = nsort_by {
413             my ($ph,$pm) = get_commit $_->{CommitId};
414             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
415             $1;
416         } @p;
417         return $classify->(qw(Pseudomerge),
418                            SubType => qw(Ambiguous),
419                            Overwritten => $bytime[0],
420                            Contributor => $bytime[1]);
421     }
422     foreach my $p (@p) {
423         my ($p_h, $p_m) = get_commit $p->{CommitId};
424         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
425         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
426     }
427     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
428     my $m2 = $r->{Msg};
429     if (!(grep { !$_->{IsOrigin} } @p) and
430         (@orig_ps >= @p - 1) and
431         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
432         $r->{NewMsg} = $m2;
433         return $classify->(qw(DgitImportUnpatched),
434                            OrigParents => \@orig_ps);
435     }
436
437     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
438     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
439
440     # How to decide about l/r ordering of breakwater merges ?  git
441     # --topo-order prefers to expand 2nd parent first.  There's
442     # already an easy rune to look for debian/ history anyway (git log
443     # debian/) so debian breakwater branch should be 1st parent; that
444     # way also there's also an easy rune to look for the upstream
445     # patches (--topo-order).
446
447     # The above tells us which way *we* will generate them.  But we
448     # might encounter ad-hoc breakwater merges generated manually,
449     # which might be the other way around.  In principle, in some odd
450     # situations, a breakwater merge might have two identical parents.
451     # In that case we guess which way round it is (ie, which parent
452     # has the upstream history).  The order of the 2-iteration loop
453     # controls which guess we make.
454
455     foreach my $prevbrw (qw(0 1)) {
456         if (@p == 2 &&
457             !$haspatches &&
458             !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
459             !($p[$prevbrw]{Differs} & ~DS_DEB) &&
460             !($p[!$prevbrw]{Differs} & ~D_UPS)) {
461             return $classify->(qw(BreakwaterUpstreamMerge),
462                                OrigParents => [ $p[!$prevbrw] ]);
463         }
464     }
465
466     # multi-orig upstreams are represented with a breakwater merge
467     # from a single upstream commit which combines the orig tarballs
468
469     return $unknown->("complex merge");
470 }
471
472 sub walk ($;$$);
473 sub walk ($;$$) {
474     my ($input,
475         $nogenerate,$report) = @_;
476     # => ($tip, $breakwater_tip)
477     # (or nothing, if $nogenerate)
478
479     # go through commits backwards
480     # we generate two lists of commits to apply:
481     # breakwater branch and upstream patches
482     my (@brw_cl, @upp_cl, @processed);
483     my %found;
484     my $upp_limit;
485     my @pseudomerges;
486
487     my $cl;
488     my $xmsg = sub {
489         my ($appendinfo) = @_;
490         my $ms = $cl->{Msg};
491         chomp $ms;
492         $ms .= "\n\n[git-debrebase $appendinfo]\n";
493         return (Msg => $ms);
494     };
495     my $rewrite_from_here = sub {
496         my $sp_cl = { SpecialMethod => 'StartRewrite' };
497         push @brw_cl, $sp_cl;
498         push @processed, $sp_cl;
499     };
500     my $cur = $input;
501
502     my $prdelim = "";
503     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
504
505     my $prline = sub {
506         return unless $report;
507         print $report $prdelim, @_;
508         $prdelim = "\n";
509     };
510
511     my $bomb = sub { # usage: return $bomb->();
512         print $report " Unprocessable" if $report;
513         $prprdelim->();
514         if ($nogenerate) {
515             return (undef,undef);
516         }
517         die "commit $cur: Cannot cope with this commit (d.".
518             (join ' ', map { sprintf "%#x", $_->{Differs} }
519              @{ $cl->{Parents} }). ")";
520     };
521
522     my $build;
523     my $breakwater;
524
525     my $build_start = sub {
526         my ($msg, $parent) = @_;
527         $prline->(" $msg");
528         $build = $parent;
529         no warnings qw(exiting); last;
530     };
531
532     for (;;) {
533         $cl = classify $cur;
534         my $ty = $cl->{Type};
535         my $st = $cl->{SubType};
536         $prline->("$cl->{CommitId} $cl->{Type}");
537         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
538         push @processed, $cl;
539         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
540         if ($ty eq 'AddPatches') {
541             $cur = $p0;
542             $rewrite_from_here->();
543             next;
544         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
545             push @brw_cl, $cl;
546             $cur = $p0;
547             next;
548         } elsif ($ty eq 'BreakwaterStart') {
549             $build_start->('FirstPackaging', $cur);
550         } elsif ($ty eq 'Upstream') {
551             push @upp_cl, $cl;
552             $cur = $p0;
553             next;
554         } elsif ($ty eq 'Mixed') {
555             my $queue = sub {
556                 my ($q, $wh) = @_;
557                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
558                 push @$q, $cls;
559             };
560             $queue->(\@brw_cl, "debian");
561             $queue->(\@upp_cl, "upstream");
562             $rewrite_from_here->();
563             $cur = $p0;
564             next;
565         } elsif ($ty eq 'Pseudomerge') {
566             my $contrib = $cl->{Contributor}{CommitId};
567             print $report " Contributor=$contrib" if $report;
568             push @pseudomerges, $cl;
569             $rewrite_from_here->();
570             $cur = $contrib;
571             next;
572         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
573             $build_start->("PreviousBreakwater", $cur);
574         } elsif ($ty eq 'DgitImportUnpatched') {
575             my $pm = $pseudomerges[-1];
576             if (defined $pm) {
577                 # To an extent, this is heuristic.  Imports don't have
578                 # a useful history of the debian/ branch.  We assume
579                 # that the first pseudomerge after an import has a
580                 # useful history of debian/, and ignore the histories
581                 # from later pseudomerges.  Often the first pseudomerge
582                 # will be the dgit import of the upload to the actual
583                 # suite intended by the non-dgit NMUer, and later
584                 # pseudomerges may represent in-archive copies.
585                 my $ovwrs = $pm->{Overwritten};
586                 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
587                     if $report;
588                 if (@$ovwrs != 1) {
589                     return $bomb->();
590                 }
591                 my $ovwr = $ovwrs->[0]{CommitId};
592                 printf $report " Overwr=%s", $ovwr if $report;
593                 # This import has a tree which is just like a
594                 # breakwater tree, but it has the wrong history.  It
595                 # ought to have the previous breakwater (which the
596                 # pseudomerge overwrote) as an ancestor.  That will
597                 # make the history of the debian/ files correct.  As
598                 # for the upstream version: either it's the same as
599                 # was ovewritten (ie, same as the previous
600                 # breakwater), in which case that history is precisely
601                 # right; or, otherwise, it was a non-gitish upload of a
602                 # new upstream version.  We can tell these apart by
603                 # looking at the tree of the supposed upstream.
604                 push @brw_cl, {
605                     %$cl,
606                     SpecialMethod => 'DgitImportDebianUpdate',
607                     $xmsg->("convert dgit import: debian changes")
608                 };
609                 my $differs = (get_differs $ovwr, $cl->{Tree});
610                 printf $report " Differs=%#x", $differs if $report;
611                 if ($differs & D_UPS) {
612                     printf $report " D_UPS" if $report;
613                     # This will also trigger if a non-dgit git-based NMU
614                     # deleted .gitignore (which is a thing that some of
615                     # the existing git tools do if the user doesn't
616                     # somehow tell them not to).  Ah well.
617                     push @brw_cl, {
618                         %$cl,
619                         SpecialMethod => 'DgitImportUpstreamUpdate',
620                         $xmsg->("convert dgit import: upstream changes")
621                     };
622                 }
623                 $prline->(" Import");
624                 $rewrite_from_here->();
625                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
626                 die 'BUG $upp_limit is not used anywhere?';
627                 $cur = $ovwr;
628                 next;
629             } else {
630                 # Everything is from this import.  This kind of import
631                 # is already in valid breakwater format, with the
632                 # patches as commits.
633                 printf $report " NoPM" if $report;
634                 # last thing we processed will have been the first patch,
635                 # if there is one; which is fine, so no need to rewrite
636                 # on account of this import
637                 $build_start->("ImportOrigin", $cur);
638             }
639             die "$ty ?";
640         } else {
641             return $bomb->();
642         }
643     }
644     $prprdelim->();
645     return if $nogenerate;
646
647     # Now we build it back up again
648
649     fresh_workarea();
650
651     my $rewriting = 0;
652
653     my $read_tree_debian = sub {
654         my ($treeish) = @_;
655         read_tree_subdir 'debian', "$treeish:debian";
656     };
657     my $read_tree_upstream = sub {
658         my ($treeish) = @_;
659         runcmd @git, qw(read-tree), $treeish;
660         $read_tree_debian->($build);
661     };
662  
663     my $committer_authline = calculate_committer_authline();
664
665     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
666
667     confess "internal error" unless $build eq (pop @processed)->{CommitId};
668
669     in_workarea sub {
670         mkdir $rd or $!==EEXIST or die $!;
671         my $current_method;
672         runcmd @git, qw(read-tree), $build;
673         foreach my $cl (qw(Debian), (reverse @brw_cl),
674                         { SpecialMethod => 'RecordBreakwaterTip' },
675                         qw(Upstream), (reverse @upp_cl)) {
676             if (!ref $cl) {
677                 $current_method = $cl;
678                 next;
679             }
680             my $method = $cl->{SpecialMethod} // $current_method;
681             my @parents = ($build);
682             my $cltree = $cl->{CommitId};
683             printdebug "WALK BUILD ".($cltree//'undef').
684                 " $method (rewriting=$rewriting)\n";
685             if ($method eq 'Debian') {
686                 $read_tree_debian->($cltree);
687             } elsif ($method eq 'Upstream') {
688                 $read_tree_upstream->($cltree);
689             } elsif ($method eq 'StartRewrite') {
690                 $rewriting = 1;
691                 next;
692             } elsif ($method eq 'RecordBreakwaterTip') {
693                 $breakwater = $build;
694                 next;
695             } elsif ($method eq 'DgitImportDebianUpdate') {
696                 $read_tree_debian->($cltree);
697                 rm_subdir_cached qw(debian/patches);
698             } elsif ($method eq 'DgitImportUpstreamUpdate') {
699                 $read_tree_upstream->($cltree);
700                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
701             } else {
702                 confess "$method ?";
703             }
704             if (!$rewriting) {
705                 my $procd = (pop @processed) // 'UNDEF';
706                 if ($cl ne $procd) {
707                     $rewriting = 1;
708                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
709                 }
710             }
711             my $newtree = cmdoutput @git, qw(write-tree);
712             my $ch = $cl->{Hdr};
713             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
714             $ch =~ s{^parent .*\n}{}m;
715             $ch =~ s{(?=^author)}{
716                 join '', map { "parent $_\n" } @parents
717             }me or confess "$ch ?";
718             if ($rewriting) {
719                 $ch =~ s{^committer .*$}{$committer_authline}m
720                     or confess "$ch ?";
721             }
722             my $cf = "$rd/m$rewriting";
723             open CD, ">", $cf or die $!;
724             print CD $ch, "\n", $cl->{Msg} or die $!;
725             close CD or die $!;
726             my @cmd = (@git, qw(hash-object));
727             push @cmd, qw(-w) if $rewriting;
728             push @cmd, qw(-t commit), $cf;
729             my $newcommit = cmdoutput @cmd;
730             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
731             $build = $newcommit;
732         }
733     };
734
735     my $final_check = get_differs $build, $input;
736     die sprintf "internal error %#x %s %s", $final_check, $build, $input
737         if $final_check & ~D_PAT_ADD;
738
739     return ($build, $breakwater);
740 }
741
742 sub get_head () { return git_rev_parse qw(HEAD); }
743
744 sub update_head ($$$) {
745     my ($old, $new, $mrest) = @_;
746     runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
747 }
748
749 sub update_head_checkout ($$$) {
750     my ($old, $new, $mrest) = @_;
751     my $symref = git_get_symref();
752     runcmd @git, qw(checkout), $new, qw(.);
753     update_head $old, $new, $mrest;
754 }
755
756 sub cmd_launder () {
757     badusage "no arguments to launder allowed" if @ARGV;
758     my $old = get_head();
759     my ($tip,$breakwater) = walk $old;
760     update_head $old, $tip, 'launder';
761     # no tree changes except debian/patches
762     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
763     printf "# breakwater tip\n%s\n", $breakwater;
764     printf "# working tip\n%s\n", $tip;
765 }
766
767 sub cmd_analyse () {
768     die if ($ARGV[0]//'') =~ m/^-/;
769     badusage "too many arguments to analyse" if @ARGV>1;
770     my ($old) = @ARGV;
771     if (defined $old) {
772         $old = git_rev_parse $old;
773     } else {
774         $old = get_head();
775     }
776     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
777     STDOUT->error and die $!;
778 }
779
780 sub cmd_new_upstream_v0 () {
781     # xxx would like to support more git-rebase options
782     badusage
783  "need NEW-VERSION UPS-COMMITISH [EXTRA-UPS-NAME EXTRA-UPS-COMMITISH...]"
784         unless @ARGV % 2 == 0 and @ARGV >= 2;
785     # tree should be clean and this is not checked
786     # automatically and unconditionally launders before rebasing
787     # if rebase --abort is used, laundering has still been done
788
789     my %pieces;
790
791     # parse args - low commitment
792     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
793     my $new_upstream_version = $new_version->version();
794
795     my $new_upstream = git_rev_parse shift @ARGV;
796
797     my $piece = sub {
798         my ($n, @x) = @_; # may be ''
799         my $pc = $pieces{$n} //= {
800             Name => $n,
801             Desc => ($n ? "upstream piece $n" : "upstream (main piece"),
802         };
803         while (my $k = shift @x) { $pc->{$k} = shift @x; }
804     };
805
806     my @newpieces;
807     my $newpiece = sub {
808         my ($n, @x) = @_; # may be ''
809         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
810         push @newpieces, $pc;
811     };
812
813     $newpiece->('',
814         OldIx => 0,
815         New => $new_upstream,
816     );
817     while (@ARGV) {
818         my $n = shift @ARGV;
819         my $c = git_rev_parse shift @ARGV;
820         die unless $n =~ m/^$extra_orig_namepart_re$/;
821         $newpiece->($n, New => $c);
822     }
823
824     # now we need to investigate the branch this generates the
825     # laundered version but we don't switch to it yet
826     my $old_head = get_head();
827     my ($old_laundered_tip,$old_bw) = walk $old_head;
828
829     my $old_bw_cl = classify $old_bw;
830     my $old_upstream = parsecommit $old_bw_cl->{OrigParents}[0]{CommitId};
831
832     my $problems = 0;
833     my $problem = sub {
834         my ($msg) = @_;
835         $problems++;
836         print STDERR "preflight check failed: $msg\n";
837     };
838
839     $piece->('', Old => $old_upstream);
840
841     if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
842         if ($old_upstream->{Msg} =~
843  m{^\[git-debrebase new-upstream combine \.((?: $extra_orig_namepart_re)+)\]}
844            ) {
845             my @oldpieces = ('', split / /, $1);
846             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
847             foreach my $i (0..$#oldpieces) {
848                 my $n = $oldpieces[$i];
849                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
850             }
851         } else {
852             $problem->("previous upstream $old_upstream->{CommitId} is from".
853                  " git-debrebase but not a \`new-upstream combine' commit");
854         }
855     }
856
857     foreach my $pc (values %pieces) {
858         if (!$pc->{Old}) {
859             $problem->("introducing upstream piece $pc->{Name}");
860         } elsif (!$pc->{New}) {
861             $problem->("dropping upstream piece $pc->{Name}");
862         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
863             $problem->("not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}");
864         }
865     }
866
867     if ($problems) {
868         if ($opt_force) {
869             printf STDERR
870                 "preflight check failures (%d) overriden by --force\n",
871                 $problems;
872         } else {
873             fail sprintf
874                 "preflight check failures (%d) (you could --force)",
875                 $problems;
876         }
877     }
878
879     my $new_bw;
880
881     fresh_workarea();
882     in_workarea sub {
883         my @upstream_merge_parents;
884
885         if (!$problems) {
886             push @upstream_merge_parents, $old_upstream->{CommitId};
887         }
888
889         foreach my $pc (@newpieces) { # always has '' first
890             if ($pc->{Name}) {
891                 read_tree_subdir $pc->{Name}, $pc->{New};
892             } else {
893                 runcmd @git, qw(read-tree), $pc->{New};
894             }
895             push @upstream_merge_parents, $pc->{New};
896         }
897
898         # index now contains the new upstream
899
900         if (@newpieces > 1) {
901             # need to make the upstream subtree merge commit
902             my $us_tree = cmdoutput @git, qw(write-tree);
903             my @cmd = (@git, qw(commit-tree), $us_tree);
904             push @cmd, qw(-p), $_ foreach @upstream_merge_parents;
905             push @cmd, qw(-m), "Combine upstreams for $new_upstream_version";
906             push @cmd, qw(-m),
907                 "[git-debrebase new-upstream combine . ".
908                 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
909                  "]";
910             $new_upstream = cmdoutput @cmd;
911         }
912
913         # $new_upstream is either the single upstream commit, or the
914         # combined commit we just made.  Either way it will be the
915         # "upstream" parent of the breakwater special merge.
916
917         read_tree_subdir 'debian', "$old_bw:debian";
918
919         # index now contains the breakwater merge contents
920
921         my $bw_tree = cmdoutput @git, qw(write_tree);
922         my @cmd = (@git, qw(commit-tree), $bw_tree);
923         push @cmd, qw(-p), $old_bw, qw(-p), $new_upstream;
924         push @cmd, qw(-m), "Update to upstream $new_upstream_version";
925         push @cmd, qw(-m),
926             "[git-debrebase new-upstream breakwater $new_upstream_version]";
927         $new_bw = cmdoutput @git;
928
929         # Now we have to add a changelog stanza so the Debian version
930         # is right.
931
932         die if unlink "debian";
933         die unless $!==ENOTEMPTY;
934         unlink "debian/changelog" or die $!;
935         open CN, ">", "debian/changelog" or die $!;
936         my $oldclog = git_cat_file ":debian/changelog";
937         $oldclog =~ m/^($package_re) \(\S+\) / or
938             fail "cannot parse old changelog to get package name";
939         my $p = $1;
940         print CN <<END, $oldclog or die $!;
941 $p ($new_version) UNRELEASED; urgency=medium
942
943   * Update to new upstream version $new_upstream_version.
944
945  -- 
946
947 END
948         close CN or die $!;
949         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
950
951         # Now we have the final new breakwater branch in the index
952
953         $bw_tree = cmdoutput @git, qw(write_tree);
954         @cmd = (@git, qw(commit-tree), $bw_tree);
955         push @cmd, qw(-p), $new_bw;
956         push @cmd, qw(-m),
957             "Update changelog for new upstream $new_upstream_version";
958         push @cmd, qw(-m),
959             "[git-debrebase new-upstream changelog $new_upstream_version]";
960         $new_bw = cmdoutput @git;
961     };
962
963     # we have constructed the new breakwater. we now need to commit to
964     # the laundering output, because git-rebase can't easily be made
965     # to make a replay list which is based on some other branch
966
967     update_head $old_head, $old_laundered_tip, 'launder for new upstream';
968
969     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw);
970     runcmd @cmd;
971     # now it's for the user to sort out
972 }
973
974 sub cmd_downstream_rebase_launder_v0 () {
975     badusage "needs 1 argument, the baseline" unless @ARGV==1;
976     my ($base) = @ARGV;
977     $base = git_rev_parse $base;
978     my $old_head = get_head();
979     my $current = $old_head;
980     my $topmost_keep;
981     for (;;) {
982         if ($current eq $base) {
983             $topmost_keep //= $current;
984             print " $current BASE stop\n";
985             last;
986         }
987         my $cl = classify $current;
988         print " $current $cl->{Type}";
989         my $keep = 0;
990         my $p0 = $cl->{Parents}[0]{CommitId};
991         my $next;
992         if ($cl->{Type} eq 'Pseudomerge') {
993             print " ^".($cl->{Contributor}{Ix}+1);
994             $next = $cl->{Contributor}{CommitId};
995         } elsif ($cl->{Type} eq 'AddPatches' or
996                  $cl->{Type} eq 'Changelog') {
997             print " strip";
998             $next = $p0;
999         } else {
1000             print " keep";
1001             $next = $p0;
1002             $keep = 1;
1003         }
1004         print "\n";
1005         if ($keep) {
1006             $topmost_keep //= $current;
1007         } else {
1008             die "to-be stripped changes not on top of the branch\n"
1009                 if $topmost_keep;
1010         }
1011         $current = $next;
1012     }
1013     if ($topmost_keep eq $old_head) {
1014         print "unchanged\n";
1015     } else {
1016         print "updating to $topmost_keep\n";
1017         update_head_checkout
1018             $old_head, $topmost_keep,
1019             'downstream-rebase-launder-v0';
1020     }
1021 }
1022
1023 GetOptions("D+" => \$debuglevel,
1024            'force!') or die badusage "bad options\n";
1025 initdebug('git-debrebase ');
1026 enabledebug if $debuglevel;
1027
1028 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1029 chdir $toplevel or die "chdir $toplevel: $!";
1030
1031 $rd = fresh_playground "$playprefix/misc";
1032
1033 my $cmd = shift @ARGV;
1034 my $cmdfn = $cmd;
1035 $cmdfn =~ y/-/_/;
1036 $cmdfn = ${*::}{"cmd_$cmdfn"};
1037
1038 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1039 $cmdfn->();