chiark / gitweb /
git-debrebase: WIP command line comments
[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);
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
238     my $cur = $input;
239
240     for (;;) {
241         $cl = classify $cur;
242         my $ty = $cl->{Type};
243         my $st = $cl->{SubType};
244         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
245         my $p0 = $cl->{Parents}[0]{CommitId};
246         if ($ty eq 'AddPatches') {
247             $cur = $p0;
248             next;
249         } elsif ($ty eq 'Packaging') {
250             push @deb_cl, $cl;
251             $cur = $p0;
252             next;
253         } elsif ($ty eq 'Upstream') {
254             push @ups_cl, $cl;
255             $cur = $p0;
256             next;
257         } elsif ($ty eq 'Mixed') {
258             my $queue = sub {
259                 my ($q, $wh) = @_;
260                 my $cls = { $cl, $xmsg->("split mixed commit: $wh part") };
261                 push @$q, $cls;
262             };
263             $queue->(\@deb_cl, "debian");
264             $queue->(\@ups_cl, "upstream");
265             next;
266         } elsif ($ty eq 'Pseudomerge') {
267             if (defined $pseudos_must_overwrite_this) {
268                 confess 'xxx actually check this';
269             }
270             push @pseudomerges, $cl;
271             $cur = $ty->{Contributor};
272             next;
273         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
274             $basis = $cur;
275             last;
276         } elsif ($ty eq 'DgitImportUnpatched' &&
277                  @pseudomerges == 1) {
278             # This import has a tree which is just like a breakwater
279             # tree, but it has the wrong history.  Its ought to have
280             # the previous breakwater (which dgit ought to have
281             # generated a pseudomerge to overwrite) as an ancestor.
282             # That will make the history of the debian/ files correct.
283             # As for the upstream version: either it's the same upstream
284             # as the previous breakwater, in which case that history is
285             # precisely right.  Otherwise, it was a non-gitish upload
286             # of a new upstream version.  We can tell these apart
287             # by looking at the tree of the supposed upstream.
288             if ($differs & D_UPS) {
289                 push @deb_cl, {
290                     %r,
291                     SpecialMethod => 'DgitImportUpstreamUpdate',
292                     $xmsg->("convert dgit import: debian changes")
293                 };
294             }
295             push @deb_cl, {
296                 %r,
297                 SpecialMethod => 'DgitImportDebianUpdate',
298                 $xmsg->("convert dgit import: upstream changes")
299             };
300             my $differs = get_differs $previous_breakwater, $cl->{Tree};
301             $basis = launder $pseudomerges[0]{Overwritten}, undef, 1;
302             last;
303         } else {
304             die "Reached difficult commit $cur: ".Dumper($cl);
305         }
306     }
307     # Now we build it back up again
308
309     workarea_fresh();
310     in_workarea sub { xxx attributes xxx };
311
312     my $build = $basis;
313
314     my $rm_tree_cached = sub {
315         my ($subdir) = @_;
316         runcmd @git, qw(rm --quiet -rf --cached), $subdir;
317     };
318     my $read_tree_debian = sub {
319         my ($treeish) = @_;
320         $rm_tree_cached->(qw(debian));
321         runcmd @git, qw(read-tree --prefix=debian/), "$treeish:debian";
322     };
323     my $read_tree_upstream = sub {
324         my ($treeish) = @_;
325         runcmd @git, qw(read-tree), $treeish;
326         $read_tree_debian->($build);
327     };
328  
329     my $committer_authline = calculate_committer_authline();
330
331     in_workarea sub {
332         mkdir $rd or $!==EEXIST or die $!;
333
334         my $current_method;
335         foreach my $cl (qw(Debian), @deb_cl, qw(Upstream), @ups_cl) {
336             if (!ref $cl) {
337                 $current_method = $cl;
338                 next;
339             }
340             $method = $cl->{SpecialMethod} // $current_method;
341             my @parents = ($build);
342             my $cltree = $cl->{CommitId}
343             if ($method eq 'Debian') {
344                 $read_tree_debian->($cltree);
345             } elsif ($method eq 'Upstream') {
346                 $read_tree_upstream->($cltree);
347             } elsif ($method eq 'DgitImportDebianUpdate') {
348                 $read_tree_debian->($cltree);
349                 $rm_tree_cached(qw(debian/patches));
350             } elsif ($method eq 'DgitImportUpstreamUpdate') {
351                 $read_tree_upstream->($cltree);
352                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
353             } else {
354                 confess "$method ?";
355             }
356             my $newtree = cmdoutput @git, qw(write-tree);
357             my $ch = $cl->{Msg};
358             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
359             $ch =~ s{^committer .*$}{$committer_authline}m or confess "$ch ?";
360             open CD, ">", "$rd/m" or die $!;
361             print CD $ch, "\n", $cl->{Msg}; or die $!;
362             close CD or die $!;
363             my $newcommit = cmdoutput @git, qw(hash-object -t commit), "$rd/m";
364             $build = $newcommit;
365         }
366     };
367
368     runcmd @git, qw(diff-tree --quiet),
369         map { $wantdebonly ? "$_:debian" : $_ },
370         $input, $build;
371
372     return $build;
373 }
374
375 sub get_head () { return git_rev_parse qw(HEAD); }
376
377 sub update_head ($$) {
378     my ($old, $new, $mrest) = @_;
379     runcmd @git, qw(update-ref -m), "git-debrebase $mrest", $new, $old;
380 }
381
382 sub cmd_launder () {
383     my $old = get_head();
384     my $got = launder $old, 0, undef, 0;
385     update_head $old, $new, 'launder'; # no tree changes!
386 }
387
388 my $toplevel = runcmd @git, qw(rev-parse --show-toplevel);
389 chdir $toplevel or die "chdir $toplevel: $!";
390
391 my $cmd = shift @ARGV;
392 my $cmdfn = $cmd;
393 $cmdfn =~ y/-/_/;
394 $cmdfn = ${*::}{"cmd_$cmdfn"};
395
396 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
397 $cmdfn->();