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