chiark / gitweb /
ec929ff69bd5d61cb1ae2dd290e4b18d1cc39c19
[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 use Data::Dumper;
15
16 BEGIN {
17     use Exporter   ();
18     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
19
20     $VERSION     = 1.00;
21     @ISA         = qw(Exporter);
22     @EXPORT      = qw(debug $tiprefs $baserefs %known_metadata
23                       run_git run_git_1line run_git_check_nooutput
24                       run_git_test_anyoutput git_get_object
25                       git_config git_dir chdir_toplevel enable_reflog
26                       check_no_metadata foreach_unknown_metadata
27                       check_clean_tree
28                       setup_config 
29                       current_branch parse_patch_name parse_patch_spec
30                       patch_matches_spec
31                       foreach_patch
32                       metafile_process depsfile_add_dep
33                       wf_start wf wf_abort wf_done wf_contents
34                       closeout);
35     %EXPORT_TAGS = ( );
36     @EXPORT_OK   = qw();
37 }
38
39 our $git_command = 'git';
40
41 our %known_metadata;
42
43 sub debug ($) {
44     my ($msg) = @_;
45     print STDERR "DEBUG: $msg\n" or die $!;
46 }
47
48 #----- general interaction with git -----
49
50 sub run_git {
51     # takes optional prefix arguments:
52     #    coderef    hook to call for each line read,
53     #                with $_ containing chomped line; if not supplied,
54     #                output is not read
55     #    scalarref  place to store exit status; if not supplied,
56     #                nonzero exit status is fatal
57     my ($estatusr,$linecallr);
58     while (ref $_[0]) {
59         my $ref = shift @_;
60         if (ref $ref eq 'SCALAR') {
61             $estatusr = $ref;
62         } elsif (ref $ref eq 'CODE') {
63             $linecallr = $ref;
64         } else {
65             die ref($ref)." @_ ?";
66         }
67     }
68     open GIT, "-|", $git_command, @_ or die $!;
69     if ($linecallr) {
70         while (<GIT>) {
71             chomp or die "$git_command @_ gave $_ ?";
72             $linecallr->();
73         }
74         GIT->eof or die $!;
75     }
76     if (!close GIT) {
77         die "$git_command @_ $!" if $!;
78         die unless $?;
79         die "$git_command @_ ($?)" unless $estatusr;
80         $$estatusr = $?;
81     } else {
82         $$estatusr = 0 if $estatusr;
83     }
84 }
85
86 sub run_git_1line {
87     my $l;
88     run_git(sub { $l = $_; }, @_);
89     die "git @_ ?" unless defined $l;
90     return $l;
91 }
92
93 sub run_git_check_nooutput {
94     my ($what) = shift @_;
95     run_git(sub { die "$what $_\n"; }, @_);
96 }
97
98 sub run_git_test_anyoutput {
99     my $any = 0;
100     run_git(sub { $any=1; }, @_);
101     return $any;
102 }
103
104 sub git_get_object ($) {
105     my ($objname) = @_;
106     our ($gro_pid, $gro_out, $gro_in);
107     if (!$gro_pid) {
108         $gro_pid = open2($gro_out, $gro_in, $git_command, qw(cat-file --batch))
109             or die $!;
110     }
111     #debug("git_get_object $objname");
112     $SIG{'PIPE'} = 'IGN';
113     print $gro_in $objname,"\n" or die $!;
114     $gro_in->flush or die "$objname $!";
115     $SIG{'PIPE'} = 'DFL';
116     my $l = <$gro_out>;
117     chomp $l or die "$objname $l ?";
118     #debug("git_get_object $objname => $l");
119     if ($l =~ m/ missing$/) {
120         return 'missing';
121     } elsif (my ($type,$bytes) = $l =~ m/^\S+ (\w+) (\d+)$/) {
122         my $data = '';
123         if ($bytes) {
124             (read $gro_out, $data, $bytes) == $bytes or die "$objname $!";
125         }
126         my $nl;
127         (read $gro_out, $nl, 1) == 1 or die "$objname $!";
128         $nl eq "\n" or die "$objname ?";
129         return ($type, $data);
130     } else {
131         die "$objname $l";
132     }
133 }
134
135 sub git_config ($$) {
136     my ($cfgvar, $default) = @_;
137     my ($l, $estatus);
138     run_git(\$estatus, sub { 
139         die if defined $l; 
140         $l = $_; },
141             qw(config), $cfgvar);
142     if (defined $l) {
143         die "$cfgvar ($estatus)" if $estatus;
144         return $l;
145     } else {
146         die "$cfgvar ($estatus)" unless $estatus==0 || $estatus==256;
147         return $default;
148     }
149 }
150
151 sub git_dir () {
152     our $git_dir;
153     if (!defined $git_dir) {
154         $git_dir = run_git_1line(qw(rev-parse --git-dir));
155     }
156     return $git_dir;
157 }
158
159 #----- specific interactions with git -----
160
161 sub chdir_toplevel () {
162     my $toplevel;
163     run_git(sub { $toplevel = $_; }, 
164             qw(rev-parse --show-toplevel));
165     die "not in working tree?\n" unless defined $toplevel;
166     chdir $toplevel or die "chdir toplevel $toplevel: $!\n";
167 }
168
169 sub enable_reflog ($) {
170     my ($branchref) = @_;
171     $branchref =~ m#^refs/# or die;
172     my $logsdir = git_dir().'/logs/';
173     my $dirname = $logsdir.dirname($branchref);
174     make_path($dirname) or die "$dirname $!";
175     open REFLOG, '>>', $logsdir.$branchref or die "$logsdir$branchref $!";
176     close REFLOG or die $!;
177 }    
178
179 sub check_no_metadata ($) {
180     # for checking foreign branches aren't contaminated
181     my ($gitbranch) = @_;
182     run_git_check_nooutput('foreign unexpectedly contains',
183                            qw(ls-tree --name-only),
184                            "$gitbranch:",
185                            qw(.topbloke));
186 }
187
188 sub foreach_unknown_metadata ($$) {
189     my ($ref, $code) = @_;
190     # Examines $ref.
191     # Executes $code for each tolerable unknown metadata found, with
192     # $_ being the (leaf) name of the metadata file
193     run_git(sub {
194         die unless s#^\.topbloke/##;
195         next if $known_metadata{$_};
196         m/-$/ or die "found unsupported metadata in $ref; you must upgrade\n";
197         $code->();
198             },
199             qw(ls-tree --name-only -r HEAD: .topbloke));
200 }
201
202 sub check_clean_tree ($) {
203     run_git_check_nooutput("operation requires working tree to be clean",
204                            qw(diff --name-only HEAD --));
205     run_git_check_nooutput("operation cannot proceed with staged changes",
206                            qw(diff --cached --name-only HEAD --));
207 }
208
209 $known_metadata{$_}=1 foreach qw(msg patch base deps deleted
210                                  +included +ends);
211
212 #----- configuring a tree -----
213
214 sub setup_config () {
215     my (@files) = (qw(lwildcard- msg patch base deps deleted
216                       +iwildcard- +included +ends));
217     my $version = 1;
218     my $drvname = sub {
219         my ($file) = @_;
220         $file =~ s/^\+//;
221         $file =~ s/\-$//;
222         return $file;
223     };
224     foreach my $iteration (qw(0 1)) {
225         foreach my $file (@files) {
226             my $cfgname = "merge.topbloke-".$drvname->($file);
227             my ($current, $current_estatus);
228             run_git(\$current_estatus,
229                     sub { $current = $_; },
230                     qw(config), "$cfgname.driver");
231             $current = "## failed $current_estatus" if $current_estatus;
232             next if $current =~ m/^topbloke-merge-driver --v$version /o;
233             die "$file $current ?" if $iteration;
234             debug("setting merge driver $file");
235             run_git(qw(config), "$cfgname.name",
236                     "topbloke merge driver for $file");
237             run_git(qw(config), "$cfgname.driver",
238                     "topbloke-merge-driver --v$version".
239                     " $file %O %A %B %L");
240         }
241         my ($newattrsprefix, $newattrs, $attrsfile);
242
243         my $attrs = '';
244         my @needupdate;
245         foreach my $file (@files) {
246             my ($pat,$check) = ($file, $file);
247             if ($file =~ m/wildcard/) {
248                 $pat = ($file =~ m/^\+/ ? '+' : '[^+]').'*';
249                 $check =~ s/\w.*/xxxunknown/ or die;
250             }
251             $pat = ".topbloke/$pat";
252             $check = ".topbloke/$check";
253             my $want = "topbloke-".$drvname->($file);
254             $attrs .= "$pat\tmerge=$want\n";
255             my $current = run_git_1line(qw(check-attr merge), $check);
256             $current =~ s#^\Q$check\E: merge: ## or die "$file $current ?";
257             next if $current eq $want;
258             die "$file $current ?" unless 
259                 $current eq 'unspecified' ||
260                 $current =~ m/^topbloke-\wwildcard$/;
261             push @needupdate, "$file=$current";
262         }
263         if (@needupdate) {
264             $attrsfile = git_dir()."/info/attributes";
265             my $newattrsf = new IO::File "$attrsfile.tmp", 'w'
266                     or die "$attrsfile.tmp: $!";
267             die "@needupdate ?" if $iteration;
268             if (!open OA, '<', "$attrsfile") {
269                 die "$attrsfile $!" unless $!==ENOENT;
270             } else {
271                 while (<OA>) {
272                     next if m#^\.topbloke/#;
273                     print $newattrsf $_ or die $!;
274                     print $newattrsf "\n" or die $! unless chomp;
275                 }
276                 die $! if OA->error;
277                 die $! unless close OA;
278             }
279             print $newattrsf $attrs or die $!;
280             close $newattrsf or die $!;
281             rename "$attrsfile.tmp", "$attrsfile" or die $!;
282         }
283     }
284 }
285
286 #----- branch and patch specs and parsed patch names -----
287
288 our $tiprefs = 'refs/topbloke-tips';
289 our $baserefs = 'refs/topbloke-bases';
290
291 sub current_branch () {
292     open R, git_dir().'/HEAD' or die "open HEAD $!";
293     my $ref = <R>;  defined $ref or die $!;
294     close R;
295     chomp $ref or die;
296     if ($ref !~ s#^ref: ##) {
297         return {
298             Kind => 'detached',
299             Ref => $ref,
300         };
301     }
302     if ($ref =~ m#^refs/topbloke-(tip|base)s/([^/\@]*)\@([^/\@]*)/([^/]*)/#) {
303         my $fullname = "$2\@$3/$4/$'";
304         my $v = {
305             Kind => $1,
306             Email => $2,
307             Domain => $3,
308             Date => $4,
309             Nick => $', #',
310             Ref => $ref,
311             DepSpec => $fullname,
312             Fullname => $fullname,
313         };
314         return $v;
315     } elsif ($ref =~ m#^refs/heads/#) {
316         return {
317             Kind => 'foreign',
318             Ref => $ref,
319             DepSpec => "- $ref",
320         };
321     } else {
322         return {
323             Kind => 'weird',
324             Ref => $ref,
325         };
326     }
327 }
328
329 sub parse_patch_name ($) {
330     my ($patch) = @_;
331     my ($eaddr, $date, $nick) = split /\//, $patch, 3;
332     defined $nick && length $nick or die "$patch ?";
333     my ($email, $domain) = $eaddr =~ m/^(.*)\@([^\@]+)$/
334         or die "$patch eaddr ?";
335     return {
336         Email => $email,
337         Domain => $domain,
338         Date => $date,
339         Nick => $nick,
340         Kind => 'tip',
341         DepSpec => $patch,
342         Fullname => $patch,
343         Ref => "refs/topbloke-tips/$patch",
344     };
345 }
346
347 sub parse_patch_spec ($) {
348     my ($orig) = @_;
349     local $_ = $orig;
350     warn 'FORMAT has new spec syntax nyi';
351     my $spec = { }; # Email Domain DatePrefix DateNear Nick
352     my $set = sub {
353         my ($key,$val,$whats) = @_;
354         die "multiple $whats in patch spec\n" if exists $spec->{$key};
355         $spec->{$key} = $val;
356     };
357     my $rel_levels;
358     for (;;) {
359         if (s#([^/\@]*)\@([^/\@]*)/##) {
360             $set->('Email', $1, "email local parts") if length $1;
361             $set->('Domain', $2, "email domains") if length $1;
362         } elsif (s#([^/]*\~[^/]*)/##) {
363             my $dspec = $1;
364             $dspec =~ y/~/ /;
365             open DATE, "-|", 'date','+%s','-d',$dspec or die $!;
366             my $l = <DATE>;
367             close DATE or die "date parsing failed\n";
368             chomp $l or die;
369             $set->('DateNear', $l, 'nearby dates');
370         } elsif (s#^([0-9][^/]*)/##) {
371             my $dspec = $1;
372             $dspec =~ 
373       m/^\d{4}(?:-\d\d(?:-\d\d(?:T(?:\d\d(?:\d\d(?:\d\d(?:Z)?)?)?)?)?)?)?$/
374                 or die "bad date prefix \`$dspec'\n";
375             $set->('DatePrefix', $dspec, 'date prefixes');
376         } elsif (s#^\./##) {
377             $rel_levels ||= 1;
378         } elsif (s#^\.\./##) {
379             $rel_levels ||= 1;
380             $rel_levels++;
381         } else {
382             last;
383         }
384     }
385     if (defined $rel_levels) {
386         my $branch = current_branch();
387         if (!defined $branch->{Nick}) {
388             die "relative patch spec \`$orig',".
389                 " but current branch not a topbloke patch\n";
390         }
391         my ($ceaddr,$cdate,@l) = split /\//, $branch->{Nick};
392         @l >= $rel_levels or
393             die "relative patch spec \`$orig' has too many ../s\n";
394         $_ = (join '/', @l[0..$#l-$rel_levels]).'/'.$_;
395     } elsif (length) {
396         $spec->{Nick} = $_;
397     }
398     return $spec;
399 }
400
401 sub patch_matches_spec ($$) {
402     my ($parsedname, $spec) = @_;
403     foreach my $k (qw(Email Domain Nick)) {
404         debug("patch_matches_spec  mismatch $k"), return 0
405             if defined $spec->{$k} &&
406                $parsedname->{$k} ne $spec->{$k};
407     }
408     debug("patch_matches_spec  mismatch DatePrefix"), return 0
409         if defined $spec->{DatePrefix} &&
410            substr($parsedname->{Date}, 0, length $spec->{DatePrefix})
411                ne $spec->{DatePrefix};
412     debug("patch_matches_spec  match"), return 1;
413 }
414
415 #----- reading topbloke metadata -----
416
417 sub foreach_patch ($$$$) {
418     my ($spec, $deleted_ok, $want, $body) = @_;
419 print STDERR Dumper(\@_);
420     # runs $body->($patch, $parsedname, \%meta)
421     # where $meta{<metadata filename>} is, for <metadata filename> in @$want:
422     #              undefined if metadata file doesn't exist
423     #              defined with contents of file
424     # and $parsedname is only valid if $spec is not undef
425     #  (say $spec { }  if you want the name parsed but no restrictions)
426     # entries in want may also be "<metadata filename>_"
427     #  which means "strip trailing newlines" (result key in %meta is the same)
428     # <metadata filename> may instead be "B_<metadata filename>"
429     #  which means to look in the corresponding base branch
430     my @want = @$want;
431     my $atfront = sub {
432         my ($thing) = @_;
433         @want = ($thing, grep { $_ ne $thing } @want);
434     };
435     $atfront->(' patch');
436     $atfront->('deleted') unless $deleted_ok;
437     run_git(sub {
438         debug("foreach_patch considering $_");
439         m/ / or die "$_ ?";
440         my $objname = $`;
441         my %meta;
442         my $parsedname;
443         my $patch = substr($',19); #');
444         my $wantix = 0;
445 print STDERR Dumper(\@want);
446         foreach my $wantent (@want) {
447             my $file = $wantent;
448             my $stripnl = ($file =~ s/_$//);
449             my $inbase = ($file =~ s/^B_//);
450
451             if ($file eq ' patch') {
452 print STDERR "has spc patch\n";
453                 if ($spec) {
454 print STDERR "hasspec\n";
455                     $parsedname = parse_patch_name($patch);
456                     if (!patch_matches_spec($parsedname, $spec)) {
457                         debug("foreach_patch  mismatch");
458                         return;
459                     }
460                 }
461                 next;
462             }
463
464             my $objkey = (!$inbase ? "$objname" : 
465                           "refs/topbloke-bases/$patch").":.topbloke/$file";
466             my ($got, $data) = git_get_object($objkey);
467             if ($got eq 'missing') {
468                 $meta{$file} = undef;
469             } elsif ($got eq 'blob') {
470                 $meta{$file} = $data;
471                 if ($file eq 'deleted' && !$deleted_ok) {
472                     debug("foreach_patch  Deleted");
473                     return;
474                 }
475             } else {
476                 warn "patch $patch object $objkey has unexpected type $got!\n";
477                 return;
478             }
479         }
480         debug("foreach_patch  YES $patch");
481         $body->($patch, $parsedname, \%meta);
482             },
483             qw(for-each-ref --format), '%(objectname) %(refname)',
484                 qw(refs/topbloke-tips));
485 }
486
487 #----- updating topbloke metadata -----
488
489 sub metafile_process ($$$$$) {
490     my ($metafile, $startcode, $linecode, $endcode, $enoentcode) = @_;
491     # runs $startcode->($outwf) at start
492     # runs $linecode->($outwf) for each old line, with $_ the chomped line
493     #   may modify $_, which will be written to $outf
494     # at end runs $endcode->($outwf);
495     # runs $enoentcode->($outwf) instead of ever calling $linecode
496     #  if the existing file does not exist;
497     #  if it's false dies instead
498     # any of these may return false, in which case we quit immediately
499     # any of these except enoentcode may be undef to mean "noop"
500     # if they all return true, we install the new file
501     my $wf = wf_start(".topbloke/$metafile");
502     my $call = sub {
503         return 1 unless $_->[0];
504         return 1 if $_->[0]($wf);
505         wf_abort($wf);
506         close FI;
507         return 0;
508     };
509     return unless $call->($startcode);
510     if (!open FI, '<', ".topbloke/$metafile") {
511         die "$metafile $!" unless $!==ENOENT;
512         die "$metafile $!" unless $enoentcode;
513         return unless $call->($enoentcode);
514     } else {
515         while (<FI>) {
516             chomp or die;
517             return unless $call->($linecode);
518             wf($wf, "$_\n");
519         }
520         FI->error and die $!;
521         close FI or die $!;
522     }
523     return unless $call->($endcode);
524     wf_done($wf);
525 }
526     
527
528 sub depsfile_add_dep ($$) {
529     my ($depsfile, $depspec) = @_;
530     metafile_process($depsfile, undef, sub {
531         die "dep $depspec already set in $depsfile ?!" if $_ eq $depspec;
532     }, sub {
533         wf($_->[0], "$depspec\n");
534     }, undef);
535 }
536
537 #----- general utilities -----
538
539 sub wf_start ($) {
540     my ($path) = @_;
541     my $fh = new IO::File "$path.tmp", '>' or die "create $path.tmp: $!\n";
542     return [ $fh, $path ];
543 }
544
545 sub wf ($$) {
546     my ($wf, $data) = @_;
547     my ($fh, $path) = @$wf;
548     print $fh $data or die "write $path.tmp: $!\n";
549 }
550
551 sub wf_abort ($) {
552     my ($wf) = @_;
553     my ($fh, $path) = @$wf;
554     close $fh;
555     unlink "$path.tmp" or die "remove $path.tmp: $!\n";
556 }
557
558 sub wf_done ($) {
559     my ($wf) = @_;
560     my ($fh, $path) = @$wf;
561     close $fh or die "finish writing $path.tmp: $!\n";
562     rename "$path.tmp", $path or die "install new $path: $!\n";
563 }
564
565 sub wf_contents ($$) {
566     my ($path,$contents) = @_;
567     my $wf = wf_start($path);
568     wf($wf, $contents);
569     wf_done($wf);
570 }
571
572 sub closeout () {
573     STDOUT->error and die $!;
574     close STDOUT or die $!;
575 }
576
577 1;