chiark / gitweb /
56055cf688bb42dc3a007c5603c7c2499b3b3fad
[topbloke.git] / Topbloke.pm
1 # -*- perl -*-
2
3 use strict;
4 use warnings;
5
6 use POSIX;
7 use IO::File;
8 use IPC::Open2;
9
10 package Topbloke;
11
12 BEGIN {
13     use Exporter   ();
14     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
15
16     $VERSION     = 1.00;
17     @ISA         = qw(Exporter);
18     @EXPORT      = qw(debug
19                       run_git run_git_1line run_git_check_nooutput
20                       run_git_test_anyoutput
21                       git_config git_dir chdir_toplevel
22                       current_branch parse_patch_spec
23                       setup_config check_no_unwanted_metadata
24                       foreach_patch
25                       flagsfile_add_flag
26                       wf_start wf wf_abort wf_done wf_contents);
27     %EXPORT_TAGS = ( );
28     @EXPORT_OK   = qw();
29 }
30
31 our $git_command = 'git';
32
33 sub debug ($) {
34     my ($msg) = @_;
35     print STDERR "DEBUG: $msg\n" or die $!;
36 }
37
38 sub run_git {
39     # takes optional prefix arguments:
40     #    coderef    hook to call for each line read,
41     #                with $_ containing chomped line; if not supplied,
42     #                output is not read
43     #    scalarref  place to store exit status; if not supplied,
44     #                nonzero exit status is fatal
45     my ($estatusr,$linecallr);
46     while (ref $_[0]) {
47         my $ref = shift @_;
48         if (ref $ref eq 'SCALAR') {
49             $estatusr = $ref;
50         } elsif (ref $ref eq 'CODE') {
51             $linecallr = $ref;
52         } else {
53             die ref($ref)." @_ ?";
54         }
55     }
56     open GIT, "-|", $git_command, @_ or die $!;
57     if ($linecallr) {
58         while (<GIT>) {
59             chomp or die "$git_command @_ gave $_ ?";
60             $linecallr->();
61         }
62         GIT->eof or die $!;
63     }
64     if (!close GIT) {
65         die "$git_command @_ $!" if $!;
66         die unless $?;
67         die "$git_command @_ ($?)" unless $estatusr;
68         $$estatusr = $?;
69     } else {
70         $$estatusr = 0 if $estatusr;
71     }
72 }
73
74 sub run_git_1line {
75     my $l;
76     run_git(sub { $l = $_; }, @_);
77     die "git @_ ?" unless defined $l;
78     return $l;
79 }
80
81 sub run_git_check_nooutput {
82     my ($what) = shift @_;
83     run_git(sub { die "$what $_\n"; }, @_);
84 }
85
86 sub run_git_test_anyoutput {
87     my $any = 0;
88     run_git(sub { $any=1; }, @_);
89     return $any;
90 }
91
92 sub git_get_object ($) {
93     my ($objname) = @_;
94     our ($gro_pid, $gro_out, $gro_in);
95     if (!$gro_pid) {
96         $gro_pid = IPC::Open2::open2($gro_out, $gro_in,
97                                      $git_command, qw(cat-file --batch))
98             or die $!;
99     }
100     $SIG{'PIPE'} = 'IGN';
101     print $gro_in $objname,"\n" or die $!;
102     $gro_in->flush or die "$objname $!";
103     $SIG{'PIPE'} = 'DFL';
104     my $l = <$gro_out>;
105     chomp $l or die "$objname $l ?";
106     if ($l =~ m/ missing$/) {
107         return 'missing';
108     } elsif (my ($type,$bytes) = $l =~ m/^\S+ (\w+) (\d+)$/) {
109         my $data;
110         read $gro_out, $data, $bytes == $bytes or die "$objname $!";
111         return ($type, $data);
112     } else {
113         die "$objname $l";
114     }
115 }
116
117 sub git_config ($$) {
118     my ($cfgvar, $default) = @_;
119     my ($l, $estatus);
120     run_git(\$estatus, sub { 
121         die if defined $l; 
122         $l = $_; },
123             qw(config), $cfgvar);
124     if (defined $l) {
125         die "$cfgvar ($estatus)" if $estatus;
126         return $l;
127     } else {
128         die "$cfgvar ($estatus)" unless $estatus==0 || $estatus==256;
129         return $default;
130     }
131 }
132
133 sub git_dir () {
134     our $git_dir;
135     if (!defined $git_dir) {
136         $git_dir = run_git_1line(qw(rev-parse --git-dir));
137     }
138     return $git_dir;
139 }
140
141 sub chdir_toplevel () {
142     my $toplevel;
143     run_git(sub { $toplevel = $_; }, 
144             qw(rev-parse --show-toplevel));
145     die "not in working tree?\n" unless defined $toplevel;
146     chdir $toplevel or die "chdir toplevel $toplevel: $!\n";
147 }
148
149 sub current_branch () {
150     open R, git_dir().'/HEAD' or die "open HEAD $!";
151     my $ref = <R>;  defined $ref or die $!;
152     close R;
153     chomp $ref or die;
154     if ($ref !~ s#^ref: ##) {
155         return {
156             Kind => 'detached',
157             Ref => $ref,
158         };
159     }
160     if ($ref =~ m#^refs/topbloke-(tip|base)s/([^/\@]*)\@([^/\@]*)/([^/]*)/#) {
161         return {
162             Kind => $1,
163             Email => $2,
164             Domain => $3,
165             Date => $4,
166             Nick => $', #',
167             Ref => $ref,
168             DepSpec => "$2\@$3/$4/$'",
169         };
170     } elsif ($ref =~ m#^refs/heads/#) {
171         return {
172             Kind => 'foreign',
173             Ref => $ref,
174             DepSpec => "/$ref",
175         };
176     } else {
177         return {
178             Kind => 'weird',
179             Ref => $ref,
180         };
181     }
182 }
183
184 sub parse_patch_name ($) {
185     my ($patch) = @_;
186     my ($eaddr, $date, $nick) = split /\//, $patch, 3;
187     defined $nick && length $nick or die "$patch ?";
188     my ($email, $domain) = $eaddr =~ m/^(.*)\@([^\@]+)$/
189         or die "$patch eaddr ?";
190     return {
191         Email => $email,
192         Domain => $domain,
193         Date => $date,
194         Nick => $nick,
195     };
196 }
197
198 sub parse_patch_spec ($) {
199     my ($orig) = @_;
200     local $_ = $orig;
201     my $spec = { }; # Email Domain DatePrefix DateNear Nick
202     my $set = sub {
203         my ($key,$val,$whats) = @_;
204         die "multiple $whats in patch spec\n" if exists $spec->{$key};
205         $spec->{$key} = $val;
206     };
207     my $rel_levels;
208     for (;;) {
209         if (s#([^/\@]*)\@([^/\@]*)/##) {
210             $set->('Email', $1, "email local parts") if length $1;
211             $set->('Domain', $2, "email domains") if length $1;
212         } elsif (s#([^/]*\~[^/]*)/##) {
213             my $dspec = $1;
214             $dspec =~ y/~/ /;
215             open DATE, "-|", 'date','+%s','-d',$dspec or die $!;
216             my $l = <DATE>;
217             close DATE or die "date parsing failed\n";
218             chomp $l or die;
219             $set->('DateNear', $l, 'nearby dates');
220         } elsif (s#^([0-9][^/]*)/##) {
221             my $dspec = $1;
222             $dspec =~ 
223       m/^\d{4}(?:-\d\d(?:-\d\d(?:T(?:\d\d(?:\d\d(?:\d\d(?:Z)?)?)?)?)?)?)?$/
224                 or die "bad date prefix \`$dspec'\n";
225             $set->('DatePrefix', $dspec, 'date prefixes');
226         } elsif (s#^\./##) {
227             $rel_levels ||= 1;
228         } elsif (s#^\.\./##) {
229             $rel_levels ||= 1;
230             $rel_levels++;
231         } else {
232             last;
233         }
234     }
235     if (defined $rel_levels) {
236         my $branch = current_branch();
237         if (!defined $branch->{Nick}) {
238             die "relative patch spec \`$orig',".
239                 " but current branch not a topbloke patch\n";
240         }
241         my ($ceaddr,$cdate,@l) = split /\//, $branch->{Nick};
242         @l >= $rel_levels or
243             die "relative patch spec \`$orig' has too many ../s\n";
244         $_ = (join '/', @l[0..$#l-$rel_levels]).'/'.$_;
245     } elsif (length) {
246         $spec->{Nick} = $_;
247     }
248     return $spec;
249 }
250
251 sub setup_config () {
252     my (@files) = (qw(msg deps included flags pflags));
253     my $version = 1;
254     foreach my $iteration (qw(0 1)) {
255         foreach my $file (@files) {
256             my $cfgname = "merge.topbloke-$file";
257             my ($current, $current_estatus);
258             run_git(\$current_estatus,
259                     sub { $current = $_; },
260                     qw(config), "$cfgname.driver");
261             $current = "## failed $current_estatus" if $current_estatus;
262             next if $current =~ m/^topbloke-merge-driver --v$version /o;
263             die "$file $current ?" if $iteration;
264             debug("setting merge driver $file");
265             run_git(qw(config), "$cfgname.name",
266                     "topbloke merge driver for $file");
267             run_git(qw(config), "$cfgname.driver",
268                     "topbloke-merge-driver --v$version".
269                     " $file %O %A %B %L");
270         }
271         my ($newattrs, $attrsfile);
272         foreach my $file (@files) {
273             my $path = ".topbloke/$file";
274             my $current = run_git_1line(qw(check-attr merge), $path);
275             $current =~ s#^\Q$path\E: merge: ## or die "$file $current ?";
276             my $want = "topbloke-$file";
277             next if $current eq $want;
278             die "$file $current ?" unless $current eq 'unspecified';
279             die "$file $current ?" if $iteration;
280             if (!$newattrs) {
281                 $attrsfile = git_dir()."/info/attributes";
282                 $newattrs = new IO::File "$attrsfile.tmp", 'w'
283                     or die "$attrsfile.tmp: $!";
284                 if (!open OA, '<', "$attrsfile") {
285                     die "$attrsfile $!" unless $!==&ENOENT;
286                 } else {
287                     while (<OA>) {
288                         print $newattrs $_ or die $!;
289                         print "\n" or die $! unless chomp;
290                     }
291                     die $! if OA->error;
292                     die $! unless close OA;
293                 }
294             }
295             print $newattrs "$path\tmerge=$want\n" or die $!;
296         }
297         last if !$newattrs;
298         close $newattrs or die $!;
299         rename "$attrsfile.tmp", "$attrsfile" or die $!;
300     }
301 }
302
303 sub check_no_unwanted_metadata ($) {
304     # for checking foreign branches aren't contaminated
305     my ($gitbranch) = @_;
306     run_git_check_nooutput('foreign unexpectedly contains',
307                            qw(ls-tree --name-only),
308                            "$gitbranch:",
309                            qw(.topbloke));
310 }
311
312 sub patch_matches_spec ($$) {
313     my ($parsedname, $spec) = @_;
314     foreach my $k (qw(Email Domain Nick)) {
315         debug("patch_matches_spec  mismatch $k"), return 0
316             if defined $spec->{$k} &&
317                $parsedname->{$k} ne $spec->{$k};
318     }
319     debug("patch_matches_spec  mismatch DatePrefix"), return 0
320         if defined $spec->{DatePrefix} &&
321            substr($parsedname->{Date}, 0, length $spec->{DatePrefix})
322                ne $spec->{DatePrefix};
323     debug("patch_matches_spec  match"), return 1;
324 }
325
326 sub foreach_patch ($$$$) {
327     my ($spec, $deleted_ok, $want, $body) = @_;
328     # runs $body->($patch, $parsedname, \%flags, \%deps, \%pflags, \%included)
329     #                                   $want->[0]   1        2         3
330     # where $deps->{$fullname} etc. are 1 for true or nonexistent for false
331     #  and if $want->[$item] is not true, the corresponding item may be undef
332     # and $parsedname is only valid if $spec is not undef
333     #  (say $spec { }  if you want the name parsed but no restrictions)
334     run_git(sub {
335         debug("foreach_patch considering $_");
336         m/ / or die "$_ ?";
337         my $objname = $`;
338         my @out;
339         my $patch = substr($',19); #');
340         $want->[0] ||= !$deleted_ok;
341         foreach my $file (qw(flags deps pflags included)) {
342
343             if ($file eq 'deps') {
344                 # do this check after checking for deleted patches,
345                 # so we don't parse deleted patches' names
346                 # right, check the spec next
347                 if ($spec) {
348                     my $have = parse_patch_name($patch);
349                     debug("foreach_patch  mismatch"), return
350                         unless patch_matches_spec($have, $spec);
351                     unshift @out, $have;
352                 } else {
353                     unshift @out, undef;
354                 }
355             }
356
357             if (!shift @$want) {
358                 push @out, undef;
359                 next;
360             }
361
362             my ($got, $data) = git_get_object("$objname:.topbloke/$file");
363             die "$patch $file ?" unless defined $data;
364             my %data;
365             $data{$_}=1 foreach split /\n/, $data;
366
367             if ($file eq 'flags') {
368                 debug("foreach_patch  Deleted"), return
369                     if !$deleted_ok && $data{Deleted};
370             }
371
372             push @out, \%data;
373         }
374         debug("foreach_patch  YES @out"), return
375         $body->($patch, @out);
376             },
377             qw(for-each-ref --format), '%(objectname) %(refname)',
378                 qw(refs/topbloke-tips));
379 }
380
381 sub flagsfile_add_flag ($$) {
382     # works on "deps" too
383     my ($flagsfile, $flag) = @_;
384     my $wf = wf_start(".topbloke/$flagsfile");
385     open FI, '<', ".topbloke/$flagsfile" or die $!;
386     while (<FI>) {
387         chomp or die;
388         die "flag $flag already set in $flagsfile ?!" if $_ eq $flag;
389         wf($wf, "$_\n");
390     }
391     FI->error and die $!;
392     close FI or die $!;
393     wf($wf, "$flag\n");
394     wf_done($wf);
395 }
396
397 sub wf_start ($) {
398     my ($path) = @_;
399     my $fh = new IO::File "$path.tmp", '>' or die "create $path.tmp: $!\n";
400     return [ $fh, $path ];
401 }
402
403 sub wf ($$) {
404     my ($wf, $data) = @_;
405     my ($fh, $path) = @$wf;
406     print $fh $data or die "write $path.tmp: $!\n";
407 }
408
409 sub wf_abort ($) {
410     my ($wf) = @_;
411     my ($fh, $path) = @$wf;
412     close $fh;
413     unlink "$path.tmp" or die "remove $path.tmp: $!\n";
414 }
415
416 sub wf_done ($) {
417     my ($wf) = @_;
418     my ($fh, $path) = @$wf;
419     close $fh or die "finish writing $path.tmp: $!\n";
420     rename "$path.tmp", $path or die "install new $path: $!\n";
421 }
422
423 sub wf_contents ($$) {
424     my ($path,$contents) = @_;
425     my $wf = wf_start($path);
426     wf($wf, $contents);
427     wf_done($wf);
428 }
429
430 1;