1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
package OPTIMADE::PropertyDefinitions;
# ABSTRACT: Top-level Property Definition class
our $VERSION = '0.1.0'; # VERSION
use strict;
use warnings;
use OPTIMADE::PropertyDefinitions::EntryType;
use JSON;
use YAML qw( LoadFile );
sub new
{
my( $class, $path, $format ) = @_;
$path .= '/' unless $path =~ /\/$/;
$format = 'yaml' unless $format;
return bless { path => $path, format => $format }, $class;
}
sub entry_type($)
{
my( $self, $entry_type ) = @_;
die "no such entry type '$entry_type'\n" unless $self->raw->{entrytypes}{$entry_type};
return OPTIMADE::PropertyDefinitions::EntryType->new( $self, $entry_type );
}
sub entry_types()
{
my( $self ) = @_;
return map { OPTIMADE::PropertyDefinitions::EntryType->new( $self, $_ ) }
sort keys %{$self->raw->{entrytypes}};
}
sub path() { $_[0]->{path} }
sub raw()
{
my( $self ) = @_;
$self->{raw} = $self->_raw( 'standards/optimade' ) unless $self->{raw};
return $self->{raw};
}
sub _raw($)
{
my( $self, $path ) = @_;
if( $self->{format} eq 'json' ) {
open my $inp, '<', $self->path . $path . '.json';
my $json = decode_json join '', <$inp>;
close $inp;
return $json;
} elsif( $self->{format} eq 'yaml' ) {
return $self->_resolve_inherits( LoadFile( $self->path . $path . '.yaml' ) );
} else {
die "no such format '$self->{format}'\n";
}
}
sub _resolve_inherits($$)
{
my( $self, $yaml ) = @_;
if( exists $yaml->{'$$inherit'} ) {
my $parent = $self->_raw( '..' . $yaml->{'$$inherit'} );
$yaml = { %$parent, %$yaml };
}
for my $key (keys %$yaml) {
next unless ref $yaml->{$key} eq 'HASH';
$yaml->{$key} = $self->_resolve_inherits( $yaml->{$key} );
}
return $yaml;
}
1;
|