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