srvpath/Config.pm untested

filter: Statementstmt 0.0% 0 / 65 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 9 Podpod n/a totaltotal 0.0% 0 / 100 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 use Object::Pad ':experimental(:all)';
2  
3 package WWW::srvpath::Config;
4 role WWW::srvpath::Config : does(WWW::srvpath::Base);
5  
6 use utf8;
7 use v5.44;
8  
9 use TOML::Tiny; #'from_toml';
10 use Path::Tiny;
11 use File::ConfigDir;
12 use Const::Fast;
13 use IO::Handle::Common;
14 use WWW::srvpath::Util;
15  
16 const our @CONFIGDIR_DEFAULT =>
17 ( path(File::ConfigDir::xdg_config_home)->absolute, path("./")->absolute, );
18  
19 field $toml = TOML::Tiny->new;
20 field $file = [
21 map { path("$_/srvpath.toml") }
22 grep { $_ } @CONFIGDIR_DEFAULT
23 ];
24 field $data : reader = {};
25  
26 # Default configuration files. May warn on error but will fall back to minimal
27 # inline config
28 ADJUST {
29  
30 };
31  
32 # User provided/non-default config files. Fatal when path does not exist.
33 ADJUST : params (:$config = []) {
34 $self->load_config($_)
35 for @$config;
36 };
37  
38 method default_config () {
39 for my $path (@$file) {
40 if ( !$self->$self->try_config($file) ) {
41 if ( $path->parent eq $CONFIGDIR_DEFAULT[0] ) {
42 $$file[0]->spew_utf8();
43 }
44 }
45 }
46 $self->try_config($_) for $file->@*;
47 }
48  
49 method try_config ( $file, %opt ) {
50 $self->load_config( $file, %opt, try => 1 );
51 }
52  
53 method load_config ( $file, %opt ) {
54 my $path = path($file)->realpath;
55  
56 if ( !$path->exists ) {
57 return undef if $opt{try};
58 fatal "Config file '$file' does not exist.";
59 }
60  
61 my $data_merge = $toml->decode( path($path)->slurp_utf8 );
62 $self->merge_config($data_merge);
63 }
64  
65 method merge_config ( $data_merge, $dest = $data ) {
66  
67 # dmsg $data_merge, $dest;
68 foreach my ( $key, $val ) ( $data_merge->%* ) {
69 if ( my $val_curr = $$dest{$key} ) {
70 if ( ( !ref $val && !ref $val_curr )
71 || ( ref $val eq ref $val_curr ) )
72 {
73 if ( ref $val eq 'ARRAY' ) {
74 push @$val_curr, @$val;
75 }
76 elsif ( ref $val eq 'HASH' ) {
77  
78 # $val_curr = $self->merge_config( $val, $val_curr );
79 $self->merge_config( $val, $val_curr );
80 }
81 else {
82 # $$dest{$key} = $val;
83 $val_curr = $val;
84 }
85 }
86 else {
87 fatal "Config key '$key' has type mismatch: current type is '"
88 . ref $val_curr
89 . "' but new value has type '"
90 . ref $val . "'";
91 }
92 }
93 else {
94 $$dest{$key} = $val;
95 }
96 }
97 $dest;
98 }
99  
100 method config (%opt) {
101 $data;
102 }
103  
104 const our $config_builtin_toml => <<'...';
105 [global]
106 charset = 'UTF-8'
107 listen =':3223'
108 enable-ssl = 1
109  
110 [[path]]
111 root = "/usr/share/WWW-srvpath/public"
112 mount = "/"
113 ssl-enabled = 1
114 cert-bundle = "<: $certbundle :>"
115 cert-file = "<: $keyfile :>"
116  
117 []
118 name = "<: $localuser :>"
119 crypt = "<: $crypt :>"
120  
121 ...
122