chiark / gitweb /
git-debrebase: avoid rewrite better
[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 # usages:
22 #    git-debrebase launder     # prints breakwater tip
23 #    git-debrebase analyse
24 #    git-debrebase start       # like ffrebase start + debrebase launder
25 #    git-debrebase create-new-upstream [-f] <upstreaminfo>
26 #    git-debrebase new-upstream [-f] <upstreaminfo>
27 #    git-debrebase <git-rebase options>  # does debrebase start if necessary
28 #
29 # <upstreaminfo> is
30 #    [,][<subdir>:][+]<commitid>[,...]
31 #
32 # if initial comma is supplied, entries are not positional.  Unspecified
33 # <subdir> means root (and there may be only one).
34 # xxx want auto branch names
35 # xxx too complicated
36 # how about for now
37 #    [+]<commit> [<subdir:> [+]<commit>...]
38 # ?  plus options
39 #     --new-upstream-different-subtrees
40
41 #    UPSTREAM[,[[SUBDIR:]SUBUPSTREAM]
42 #    default for SUBDIR: is from previous upstream merge[xxx terminology]
43 #    
44 #
45 #xxx
46 # when starting must record original start (for ff)
47 # and new rebase basis
48 #
49 #    git-ffrebase start [BASE] # records previous HEAD so it can be overwritten
50 #                              # records base for future git-ffrebase
51 #    git-ffrebase set-base BASE
52 #    git-ffrebase <git-rebase options>
53 #    git-ffrebase finish
54 #    git-ffrebase status [BRANCH]
55 #
56 #  refs/ffrebase-prev/BRANCH    BRANCH may be refs/...; if not it means
57 #  refs/ffrebase-base/BRANCH      refs/heads/BRANCH
58 #                               zero, one, or both of these may exist
59
60 use strict;
61
62 use Memoize;
63 use Data::Dumper;
64
65 use Debian::Dgit qw(:DEFAULT $wa);
66
67 sub cfg ($) {
68     my ($k) = @_;
69     $/ = "\0";
70     my @cmd = qw(git config -z);
71     push @cmd, qw(--get-all) if wantarray;
72     push @cmd, $k;
73     my $out = cmdoutput @cmd;
74     return split /\0/, $out;
75 }
76
77 memoize('cfg');
78
79 sub get_commit ($) {
80     my ($objid) = @_;
81     my ($type,$data) = git_cat_file $objid;
82     die unless $type eq 'commit';
83     $data =~ m/(?<=\n)\n/;
84     return ($`,$');
85 }
86
87 sub D_DEB ()     { return 0x1; }
88 sub D_UPS ()     { return 0x2; }
89 sub D_PAT_ADD () { return 0x4; }
90 sub D_PAT_OTH () { return 0x8; }
91
92 our $rd = ".git/git-debrebase";
93 our $ud = "$rd/work";
94
95 sub commit_pr_info ($) {
96     my ($r) = @_;
97     return Data::Dumper->dump([$r], [qw(commit)]);
98 }
99
100 sub calculate_committer_authline () {
101     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
102         'XXX DUMMY COMMIT (git-debrebase)', "$basis:";
103     my ($h,$m) = get_commit $c;
104     $h =~ m/^committer .*$/m or confess "($h) ?";
105     return $&;
106 }
107
108 sub classify ($) {
109     my ($objid) = @_;
110
111     my ($h,$m) = get_commit $objid;
112
113     my ($t) = $h =~ m/^tree (\w+)$/m or die $cur;
114     my (@ph) = $h =~ m/^parent (\w+)$/m;
115     my @p;
116
117     my $r = {
118         CommitId => $objid,
119         Hdr => $hdr,
120         Msg => $m,
121         Tree => $t,
122         Parents => \@p,
123     };
124
125     foreach my $ph (@ph) {
126         push @p, {
127             Ix => $#p,
128             CommitId => $ph,
129             Differs => (get_differs $t, $ph),
130         };
131     }
132
133     my $classify = sub {
134         my ($type, @rest) = @_;
135         $r = { %r, Type => $type, @rest };
136         return $r;
137     };
138     my $unknown = sub {
139         my ($why) = @_;
140         $r = { %r, Type => Unknown };
141         return $r;
142     }
143
144     if (@p == 1) {
145         my $d = $r->{Parents}[0]{Differs};
146         if ($d == D_DPAT_ADD) {
147             return $classify->(qw(AddPatches));
148         } elsif ($d & (D_DPAT_ADD|D_DPAT_OTH)) {
149             return $unknown->("edits debian/patches");
150         } elsif ($d == D_DEB) {
151             return $classify->(qw(Packaging));
152         } elsif ($d == D_UPS) {
153             return $classify->(qw(Upstream));
154         } elsif ($d == D_DEB|D_UPS) {
155             return $classify->(qw(Mixed));
156         } elsif ($d == 0) {
157             return $unknown->("no changes");
158         } else {
159             confess "internal error $objid ?";
160         }
161     }
162     if (!@p) {
163         return $unknown->("origin commit");
164     }
165
166     my @identical = grep { !$_->{Differs} } @p;
167     if (@p == 2 && @identical == 1) {
168         my @overwritten = grep { $_->{Differs} } @p;
169         confess "internal error $objid ?" unless @overwritten==1;
170         return $classify->(qw(Pseudomerge),
171                            Overwritten => $overwritten[0],
172                            Contributor => $identical[0]);
173     }
174     if (@p == 2 && @identical == 2) {
175         my @bytime = nsort_by {
176             my ($ph,$pm) = get_commit $_->{CommitId};
177             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
178             $1;
179         } @p;
180         return $classify->(qw(Pseudomerge),
181                            SubType => qw(Ambiguous),
182                            Overwritten => $bytime[0],
183                            Contributor => $bytime[1]);
184     }!
185     foreach my $p (@p) {
186         my ($p_h, $p_m) = get_commit $p;
187         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
188         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
189     }
190     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' };
191     my $m2 = $m;
192     if (!(grep { !$_->{IsOrigin} } @p) and
193         (@origs >= @p - 1) and
194         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
195         $r->{NewMsg} = $m2;
196         return $classify->(qw(DgitImportUnpatched),
197                            OrigParents => \@orig_ps);
198     }
199
200     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
201     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
202
203     # How to decide about l/r ordering of breakwater merges ?  git
204     # --topo-order prefers to expand 2nd parent first.  There's
205     # already an easy rune to look for debian/ history anyway (git log
206     # debian/) so debian breakwater branch should be 1st parent; that
207     # way also there's also an easy rune to look for the upstream
208     # patches (--topo-order).
209     if (@p == 2 &&
210         !$haspatches &&
211         !$p[0]{IsOrigin} && # breakwater merge never starts with an origin
212         !($p[0]{Differs} & ~D_DEB) &&
213         !($p[1]{Differs} & ~D_UPS)) {
214         return $classify->(qw(BreakwaterUpstreamMerge),
215                            Upstream => $p[1]);
216     }
217
218     return $unknown->("complex merge");
219 }
220
221 sub launder ($$$) {
222     my ($input, $pseudos_must_overwrite_this, $wantdebonly) = @_;
223     # go through commits backwards
224     # we generate two lists of commits to apply
225     my (@deb_cl, @ups_cl, @processed);
226     my %found;
227     my @pseudomerges;
228
229     my $cl;
230     my $xmsg = sub {
231         my ($appendinfo) = @_;
232         my $ms = $cl->{Msg};
233         chomp $ms;
234         $ms .= "\n\n[git-debrebase $appendinfo]\n";
235         return (Msg => $ms);
236     };
237     my $rewrite_from_here = sub {
238         push @processed, { SpecialMethod => 'StartRewrite' };
239     };
240
241     my $cur = $input;
242
243     for (;;) {
244         $cl = classify $cur;
245         my $ty = $cl->{Type};
246         my $st = $cl->{SubType};
247         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
248         my $p0 = $cl->{Parents}[0]{CommitId};
249         if ($ty eq 'AddPatches') {
250             $cur = $p0;
251             $rewrite_from_here->();
252             next;
253         } elsif ($ty eq 'Packaging') {
254             push @deb_cl, $cl;
255             push @processed, $cl;
256             $cur = $p0;
257             next;
258         } elsif ($ty eq 'Upstream') {
259             push @ups_cl, $cl;
260             push @processed, $cl;
261             $cur = $p0;
262             next;
263         } elsif ($ty eq 'Mixed') {
264             my $queue = sub {
265                 my ($q, $wh) = @_;
266                 my $cls = { $cl, $xmsg->("split mixed commit: $wh part") };
267                 push @$q, $cls;
268             };
269             $queue->(\@deb_cl, "debian");
270             $queue->(\@ups_cl, "upstream");
271             $rewrite_from_here->();
272             next;
273         } elsif ($ty eq 'Pseudomerge') {
274             if (defined $pseudos_must_overwrite_this) {
275                 confess 'xxx actually check this';
276             }
277             push @pseudomerges, $cl;
278             $rewrite_from_here->();
279             $cur = $ty->{Contributor};
280             next;
281         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
282             $basis = $cur;
283             last;
284         } elsif ($ty eq 'DgitImportUnpatched' &&
285                  @pseudomerges == 1) {
286             # This import has a tree which is just like a breakwater
287             # tree, but it has the wrong history.  Its ought to have
288             # the previous breakwater (which dgit ought to have
289             # generated a pseudomerge to overwrite) as an ancestor.
290             # That will make the history of the debian/ files correct.
291             # As for the upstream version: either it's the same upstream
292             # as the previous breakwater, in which case that history is
293             # precisely right.  Otherwise, it was a non-gitish upload
294             # of a new upstream version.  We can tell these apart
295             # by looking at the tree of the supposed upstream.
296             if ($differs & D_UPS) {
297                 push @deb_cl, {
298                     %r,
299                     SpecialMethod => 'DgitImportUpstreamUpdate',
300                     $xmsg->("convert dgit import: debian changes")
301                 };
302             }
303             push @deb_cl, {
304                 %r,
305                 SpecialMethod => 'DgitImportDebianUpdate',
306                 $xmsg->("convert dgit import: upstream changes")
307             };
308             my $differs = get_differs $previous_breakwater, $cl->{Tree};
309             $basis = launder $pseudomerges[0]{Overwritten}, undef, 1;
310             $rewrite_from_here->();
311             last;
312         } else {
313             die "Reached difficult commit $cur: ".Dumper($cl);
314         }
315     }
316     # Now we build it back up again
317
318     workarea_fresh();
319     in_workarea sub { xxx attributes xxx };
320
321     my $rewriting = 1;
322
323     my $build = $basis;
324
325     my $rm_tree_cached = sub {
326         my ($subdir) = @_;
327         runcmd @git, qw(rm --quiet -rf --cached), $subdir;
328     };
329     my $read_tree_debian = sub {
330         my ($treeish) = @_;
331         $rm_tree_cached->(qw(debian));
332         runcmd @git, qw(read-tree --prefix=debian/), "$treeish:debian";
333     };
334     my $read_tree_upstream = sub {
335         my ($treeish) = @_;
336         runcmd @git, qw(read-tree), $treeish;
337         $read_tree_debian->($build);
338     };
339  
340     my $committer_authline = calculate_committer_authline();
341
342     in_workarea sub {
343         mkdir $rd or $!==EEXIST or die $!;
344         my $current_method;
345         foreach my $cl (qw(Debian), (reverse @deb_cl),
346                         qw(Upstream), (reverse @ups_cl)) {
347             if (!ref $cl) {
348                 $current_method = $cl;
349                 next;
350             }
351             $method = $cl->{SpecialMethod} // $current_method;
352             my @parents = ($build);
353             my $cltree = $cl->{CommitId}
354             if ($method eq 'Debian') {
355                 $read_tree_debian->($cltree);
356             } elsif ($method eq 'Upstream') {
357                 $read_tree_upstream->($cltree);
358             } elsif ($method eq 'StartRewrite') {
359                 $rewriting = 1;
360                 next;
361             } elsif ($method eq 'DgitImportDebianUpdate') {
362                 $read_tree_debian->($cltree);
363                 $rm_tree_cached(qw(debian/patches));
364             } elsif ($method eq 'DgitImportUpstreamUpdate') {
365                 $read_tree_upstream->($cltree);
366                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
367             } else {
368                 confess "$method ?";
369             }
370             $rewriting ||= $cl ne pop @processed;
371             my $newtree = cmdoutput @git, qw(write-tree);
372             my $ch = $cl->{Hdr};
373             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
374             $ch =~ s{^parent .*\n}{}m;
375             $ch =~ s{(?=^author}{
376                 map { "parent $_\n" } @parents
377             }me or confess "$ch ?";
378             if ($rewrite) {
379                 $ch =~ s{^committer .*$}{$committer_authline}m
380                     or confess "$ch ?";
381             }
382             my $cf = "$rd/m$rewrite"
383                 open CD, ">", $cf or die $!;
384             print CD $ch, "\n", $cl->{Msg}; or die $!;
385             close CD or die $!;
386             my @cmd = (@git, qw(hash-object));
387             push @cmd, qw(-w) if $rewrite;
388             push @cmd, qw(-t commit), $cf;
389             my $newcommit = cmdoutput @cmd;
390             confess "$ch ?" unless $rewrite or $newcommit eq $cl->{CommitId};
391             $build = $newcommit;
392         }
393     };
394
395     runcmd @git, qw(diff-tree --quiet),
396         map { $wantdebonly ? "$_:debian" : $_ },
397         $input, $build;
398
399     return $build;
400 }
401
402 sub get_head () { return git_rev_parse qw(HEAD); }
403
404 sub update_head ($$) {
405     my ($old, $new, $mrest) = @_;
406     runcmd @git, qw(update-ref -m), "git-debrebase $mrest", $new, $old;
407 }
408
409 sub cmd_launder () {
410     my $old = get_head();
411     my $got = launder $old, 0, undef, 0;
412     update_head $old, $new, 'launder'; # no tree changes!
413 }
414
415 my $toplevel = runcmd @git, qw(rev-parse --show-toplevel);
416 chdir $toplevel or die "chdir $toplevel: $!";
417
418 my $cmd = shift @ARGV;
419 my $cmdfn = $cmd;
420 $cmdfn =~ y/-/_/;
421 $cmdfn = ${*::}{"cmd_$cmdfn"};
422
423 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
424 $cmdfn->();