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