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