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