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