blib/lib/Env/Assert/Functions.pm

filter: Statementstmt 93.5% 116 / 124 Branchbran 69.2% 36 / 52 Conditioncond 59.3% 19 / 32 MC/DCmcdc 44.4% 8 / 18 Subroutinesub 94.4% 17 / 18 Podpod 100% 3 / 3 totaltotal 80.5% 199 / 247 CC 47 SCAR 27.1
CC
47
Cov
82%
_create_error_msg
42.0
assert
21.5
file_to_desc
13.1
CRAP 15.0
« bin/envassert ↑ Summary blib/lib/Env/Assert.pm »
1 ## no critic (ControlStructures::ProhibitPostfixControls)
2 ## no critic (ControlStructures::ProhibitCascadingIfElse)
3 ## no critic (ValuesAndExpressions::ProhibitConstantPragma)
4 package Env::Assert::Functions;
5 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # ABSTRACT: The functionality of Env::Assert and bin/envassert.
10  
11 9 our $VERSION = '0.018';
12  
13 =pod
14  
15 =encoding utf8
16  
17 =for :stopwords env filepath filepaths params
18  
19 =cut
20  
21 9 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
22 9 our @EXPORT_OK = qw(
23 assert
24 report_errors
25 file_to_desc
26 ENV_ASSERT_MISSING_FROM_ENVIRONMENT
27 ENV_ASSERT_INVALID_CONTENT_IN_VARIABLE
28 ENV_ASSERT_MISSING_FROM_DEFINITION
29 OPTION_ENV_EXACT
30 OPTION_VAR_REGEXP
31 OPTION_VAR_REQUIRED
32 );
33 9 our %EXPORT_TAGS = (
34 'all' => [
35 qw(
36 assert
37 report_errors
38 file_to_desc
39 ENV_ASSERT_MISSING_FROM_ENVIRONMENT
40 ENV_ASSERT_INVALID_CONTENT_IN_VARIABLE
41 ENV_ASSERT_MISSING_FROM_DEFINITION
42 OPTION_ENV_EXACT
43 OPTION_VAR_REGEXP
44 OPTION_VAR_REQUIRED
45 )
46 ],
47 'constants' => [
48 qw(
49 ENV_ASSERT_MISSING_FROM_ENVIRONMENT
50 ENV_ASSERT_INVALID_CONTENT_IN_VARIABLE
51 ENV_ASSERT_MISSING_FROM_DEFINITION
52 OPTION_ENV_EXACT
53 OPTION_VAR_REGEXP
54 OPTION_VAR_REQUIRED
55 )
56 ],
57 );
58  
59 9 ▶use Cwd qw( abs_path );
Subroutine BEGIN: called CC=1 SCAR=0.0
60 9 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
61 9 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
62 9 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
63 9 ▶use English qw( -no_match_vars ); # Avoids regex performance penalty in perl 5.18 and earlier
Subroutine BEGIN: called CC=1 SCAR=0.0
64 9 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
65  
66 9 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
67 9 ENV_ASSERT_MISSING_FROM_ENVIRONMENT => 1,
68 ENV_ASSERT_INVALID_CONTENT_IN_VARIABLE => 2,
69 ENV_ASSERT_MISSING_FROM_DEFINITION => 3,
70 9 };
71  
72 9 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
73 9 DEFAULT_PARAMETER_BREAK_AT_FIRST_ERROR => 0,
74 DEFAULT_REQUIRED => 1,
75 DEFAULT_REGEXP_ANY => q{^.*$},
76 INDENT => q{ },
77 9 };
78  
79 9 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
80 9 OPTION_ENV_EXACT => q{env:exact},
81 OPTION_VAR_REGEXP => q{var:regexp},
82 OPTION_VAR_REQUIRED => q{var:required},
83 DEFAULT_OPTION_ENV_EXACT => 0,
84 DEFAULT_OPTION_VAR_REQUIRED => 1,
85 9 };
86 #
87 9 my %ENVASSERT_OPTIONS = map { $_ => 1 } ( OPTION_ENV_EXACT(), OPTION_VAR_REQUIRED() );
88  
89 =head1 NAME
90  
91 Env::Assert::Functions - The functionality of Env::Assert and bin/envassert.
92  
93 =head1 VERSION
94  
95 version 0.018
96  
97 =head1 SYNOPSIS
98  
99 use Env::Assert::Functions qw( assert report_errors );
100  
101 my %want = (
102 options => {
103 'env:exact' => 1,
104 },
105 variables => {
106 USER => { 'var:regexp' => '^[[:word:]]{1}$', 'var:required' => 1 },
107 },
108 );
109 my %parameters;
110 $parameters{'break_at_first_error'} = 1;
111 my $r = assert( \%ENV, \%want, \%parameters );
112 if( ! $r->{'success'} ) {
113 print report_errors( $r->{'errors'} );
114 }
115  
116 =head1 STATUS
117  
118 Package Env::Assert is currently being developed so changes in the API are possible,
119 though not likely.
120  
121 =head1 NOTES
122  
123 Functionality of L<Env::Assert> has been moved to this package since
124 version 0.013.
125 L<Env::Assert> has a different API now.
126 It can be used by itself at the start of the program, similar to
127 L<Env::Dot>.
128  
129 =head1 FUNCTIONS
130  
131 No functions are automatically exported to the calling namespace.
132  
133 =head2 assert( \%env, \%want, \%params )
134  
135 Ensure your environment, parameter I<env> (hashref), matches with
136 the environment description, parameter I<want> (hashref).
137 Use parameter I<params> (hashref) to specify processing options.
138  
139 Supported params:
140  
141 =over 8
142  
143 =item break_at_first_error
144  
145 Verify environment only up until the first error.
146 Then break and return with only that error.
147  
148 =back
149  
150 Return: hashref: { success => 1/0, errors => hashref, };
151  
152 =cut
153  
154 21 ▶sub assert {
Subroutine assert: called CC=20 SCAR=30.7
Pod documented
155 21 my ( $env, $want, $params ) = @_;
156 21 ▶ $params = {} if !$params;
Branch: 1 branch
BranchTrueFalseTotal
unless $params 0 21 21
157 21 ▶ croak 'Invalid options. Not a hash' if ( ref $env ne 'HASH' || ref $want ne 'HASH' );
Branch: 1 branch
BranchTrueFalseTotal
if ref $env ne "HASH" or ref $want ne "HASH" 0 21 21
Condition33%1/3
ref $env ne "HASH" or ref $want ne "HASH"
l!l&&r!l&&!r
0021
MC/DC0%0/2
ref $env ne "HASH" or ref $want ne "HASH"
ref $env ne "HASH" ref $want ne "HASH"
Truth table33%1/3
A or B
A= ref $env ne "HASH"B= ref $want ne "HASH"
ABresult
1X1
011
000
158  
159 # Set default options
160 21 ▶ $params->{'break_at_first_error'} //= DEFAULT_PARAMETER_BREAK_AT_FIRST_ERROR;
Condition100%2/2
$params->{"break_at_first_error"} //= 0
l!l
183
MC/DC100%1/1
$params->{"break_at_first_error"} //= 0
$params->{"break_at_first_error"}
Truth table100%2/2
A
A= $params->{"break_at_first_error"}
Aresult
11
00
161  
162 21 my $success = 1;
163 21 my %errors;
164 21 ▶ my $vars = $want->{'variables'} ? $want->{'variables'} : $want->{'vars'};
Branch: 1 branch
BranchTrueFalseTotal
$want->{'variables'} ? : 17 4 21
165 21 ▶ my $opts = $want->{'options'} ? $want->{'options'} : $want->{'opts'};
Branch: 1 branch
BranchTrueFalseTotal
$want->{'options'} ? : 21 0 21
166 21 foreach my $var_name ( keys %{$vars} ) {
167 51 my $env_var = $vars->{$var_name};
168 51 ▶ my $required = $env_var->{ OPTION_VAR_REQUIRED() } // DEFAULT_OPTION_VAR_REQUIRED();
Condition50%1/2
$env_var->{"var:required"} // 1
l!l
510
MC/DC0%0/1
$env_var->{"var:required"} // 1
$env_var->{"var:required"}
Truth table50%1/2
A
A= $env_var->{"var:required"}
Aresult
11
00
169 51 ▶ my $regexp = $env_var->{ OPTION_VAR_REGEXP() } // DEFAULT_REGEXP_ANY;
Condition50%1/2
$env_var->{"var:regexp"} // "^.*\$"
l!l
510
MC/DC0%0/1
$env_var->{"var:regexp"} // "^.*\$"
$env_var->{"var:regexp"}
Truth table50%1/2
A
A= $env_var->{"var:regexp"}
Aresult
11
00
170 51 ▶ if ( # If var is required we must have it or error
Branch: 2 branches
BranchTrueFalseTotal
if ($required and not defined $env->{$var_name}) { } 14 37 51
elsif (defined $env->{$var_name} and not $env->{$var_name} =~ /$regexp/msx) { } 6 40 46
Condition100%3/3
$required and not defined $env->{$var_name}
!ll&&!rl&&r
172014
MC/DC100%2/2
$required and not defined $env->{$var_name}
$required not defined $env->{$var_name}
Truth table100%3/3
A and not(B)
A= $requiredB= not defined $env->{$var_name}
ABresult
0X0
100
111
171 $required && !defined $env->{$var_name}
172 ) {
173 14 $success = 0;
174 14 $errors{'variables'}->{$var_name} = {
175 type => ENV_ASSERT_MISSING_FROM_ENVIRONMENT,
176 message => "Variable $var_name is missing from environment",
177 };
178 14 ▶ goto EXIT if ( $params->{'break_at_first_error'} );
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"break_at_first_error"} 0 14 14
179 ▶ } elsif ( # if var is not required but it exists, it must match wanted regexp
Condition100%3/3
defined $env->{$var_name} and not $env->{$var_name} =~ /$regexp/msx
!ll&&!rl&&r
9226
MC/DC100%2/2
defined $env->{$var_name} and not $env->{$var_name} =~ /$regexp/msx
defined $env->{$var_name} not $env->{$var_name} =~ /$regexp/msx
Truth table100%3/3
A and not(B)
A= defined $env->{$var_name}B= not $env->{$var_name} =~ /$regexp/msx
ABresult
0X0
100
111
180 defined $env->{$var_name} && $env->{$var_name} !~ m/$regexp/msx
181 ) {
182 6 $success = 0;
183 6 $errors{'variables'}->{$var_name} = {
184 type => ENV_ASSERT_INVALID_CONTENT_IN_VARIABLE,
185 message => "Variable $var_name has invalid content",
186 };
187 6 ▶ goto EXIT if ( $params->{'break_at_first_error'} );
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"break_at_first_error"} 0 6 6
188 }
189 }
190 21 ▶ if ( $opts->{ OPTION_ENV_EXACT() } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"env:exact"}) 9 12 21
191 9 foreach my $var_name ( keys %{$env} ) {
192 21 ▶ if ( !exists $vars->{$var_name} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $vars->{$var_name}) 6 15 21
193 6 $success = 0;
194 6 $errors{'variables'}->{$var_name} = {
195 type => ENV_ASSERT_MISSING_FROM_DEFINITION,
196 message => "Variable $var_name is missing from description",
197 };
198 6 ▶ goto EXIT if ( $params->{'break_at_first_error'} );
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"break_at_first_error"} 0 6 6
199 }
200 }
201 }
202  
203 EXIT:
204 21 return { success => $success, errors => \%errors, };
205 }
206  
207 =head2 report_errors( \%errors )
208  
209 Report errors in a nicely formatted way.
210  
211 =cut
212  
213 4 ▶sub report_errors {
Subroutine report_errors: called CC=3 SCAR=11.0
Pod documented
214 4 my ($errors) = @_;
215 4 my $out = q{};
216 4 $out .= sprintf "Environment Assert: ERRORS:\n";
217 4 foreach my $error_area_name ( sort keys %{$errors} ) {
218 3 $out .= sprintf "%s%s:\n", INDENT, $error_area_name;
219 3 foreach my $error_key ( sort keys %{ $errors->{$error_area_name} } ) {
220 6 $out .= sprintf "%s%s: %s\n", INDENT . INDENT, $error_key, $errors->{$error_area_name}->{$error_key}->{'message'};
221 }
222 }
223 4 return $out;
224 }
225  
226 =head2 file_to_desc( @rows )
227  
228 Extract an environment description from a F<.envdesc> file.
229  
230 =cut
231  
232 8 ▶sub file_to_desc {
Subroutine file_to_desc: called CC=13 SCAR=25.7
Pod documented
233 8 my ( $fp, @rows ) = @_;
234 8 my %env_options =
235 ( OPTION_ENV_EXACT() => DEFAULT_OPTION_ENV_EXACT(), ); # Options related to reading the file. Applied as they are read.
236 8 my %var_options =
237 ( OPTION_VAR_REQUIRED() => DEFAULT_OPTION_VAR_REQUIRED(), )
238 ; # Options related to reading the next variable definition. Reset to defaults after reading.
239 8 my %variables;
240 8 my $prg = 'envassert';
241 8 my $row_num = 1;
242 8 foreach (@rows) {
243  
244 ## no critic (RegularExpressions::ProhibitComplexRegexes)
245 52 ▶ if ( # This is envassert meta command
Branch: 4 branches
BranchTrueFalseTotal
if (/ ^ [[:space:]]{0,} [#]{2} [[:space:]]{1,} $prg [[:space:]]{1,} [(] opts: [[:space:]]{0,} (?<opts> .*) [)] [[:space:]]{0,} $ /msx) { } 9 43 52
elsif (/ ^ [[:space:]]{0,} [#]{1} .* $ /msx) { } 9 34 43
elsif (/ ^ [[:space:]]{0,} $ /msx) { } 11 23 34
elsif (/ ^ (?<name> [^=]{1,}) = (?<value> .*) $ /msx) { } 23 0 23
246 m{
247 ^ [[:space:]]{0,} [#]{2}
248 [[:space:]]{1,} $prg [[:space:]]{1,}
249 [(] opts: [[:space:]]{0,} (?<opts> .*) [)]
250 [[:space:]]{0,} $
251 }msx
252 ) {
253 9 my $opts = _interpret_opts( $LAST_PAREN_MATCH{opts} );
254 9 foreach my $key ( keys %{$opts} ) {
255  
256 # Compatibility issues:
257 9 ▶ $key = 'env:' . $key if ( $key eq 'exact' );
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "exact" 1 8 9
258 9 ▶ $key = 'var:' . $key if ( $key eq 'required' );
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "required" 1 8 9
259 9 ▶ if ( !exists $ENVASSERT_OPTIONS{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $ENVASSERT_OPTIONS{$key}) 0 9 9
260 0 my $err = "Unknown $prg option: '$key'";
261 0 croak _create_error_msg( $err, $row_num, $fp );
262 }
263 }
264 9 foreach ( keys %{$opts} ) {
265 9 ▶ $env_options{$_} = $opts->{$_} if (m/^env/msx);
Branch: 1 branch
BranchTrueFalseTotal
if /^env/msx 2 7 9
266 9 ▶ $var_options{$_} = $opts->{$_} if (m/^var/msx);
Branch: 1 branch
BranchTrueFalseTotal
if /^var/msx 5 4 9
267 }
268 } elsif ( # This is comment row
269 m{ ^ [[:space:]]{0,} [#]{1} .* $ }msx
270 ) {
271 9 next;
272 } elsif ( # This is empty row
273 m{ ^ [[:space:]]{0,} $ }msx
274 ) {
275 11 next;
276 } elsif ( # This is env var description
277 m{ ^ (?<name> [^=]{1,}) = (?<value> .*) $ }msx
278 ) {
279 $variables{ $LAST_PAREN_MATCH{name} } = {
280 OPTION_VAR_REGEXP() => $LAST_PAREN_MATCH{value},
281 23 OPTION_VAR_REQUIRED() => $var_options{ OPTION_VAR_REQUIRED() },
282 };
283  
284 # The var:<value> options can only apply to one subsequent var row.
285 # We reset the var options back to defaults.
286 23 $var_options{ OPTION_VAR_REQUIRED() } = DEFAULT_OPTION_VAR_REQUIRED();
287 }
288 } continue {
289 52 $row_num++;
290 }
291  
292 8 return opts => \%env_options, vars => \%variables;
293 }
294  
295 # Private subroutines
296  
297 19 ▶sub _interpret_opts {
Subroutine _interpret_opts: called CC=9 SCAR=22.8
298 19 my ($opts_str) = @_;
299 19 my @opts = split qr{
300 [[:space:]]{0,} [,] [[:space:]]{0,}
301 }msx, $opts_str;
302 19 my %opts;
303 19 foreach (@opts) {
304 27 my ( $key, $val ) = split qr{
305 [[:space:]]{0,} [=] [[:space:]]{0,}
306 }msx;
307 27 ▶ $val = $val // 1;
Condition100%2/2
$val // 1
l!l
198
MC/DC100%1/1
$val // 1
$val
Truth table100%2/2
A
A= $val
Aresult
11
00
308 27 ▶ $val = 1 if ( $val eq 'true' || $val eq 'True' || $val eq '1' );
Branch: 1 branch
BranchTrueFalseTotal
if $val eq "true" or $val eq "True" or $val eq 1 13 14 27
Condition50%3/6
$val eq "true" or $val eq "True" or $val eq 1
l!l&&r!l&&!r
01314
$val eq "true" or $val eq "True"
l!l&&r!l&&!r
0027
MC/DC33%1/3
$val eq "true" or $val eq "True" or $val eq 1
$val eq "true" $val eq "True" $val eq 1
Truth table50%2/4
A or B or C
A= $val eq "true"B= $val eq "True"C= $val eq 1
ABCresult
1XX1
01X1
0011
0000
309 27 ▶ $val = 0 if ( $val eq 'false' || $val eq 'False' || $val eq '0' );
Branch: 1 branch
BranchTrueFalseTotal
if $val eq "false" or $val eq "False" or $val eq 0 7 20 27
Condition50%3/6
$val eq "false" or $val eq "False" or $val eq 0
l!l&&r!l&&!r
0720
$val eq "false" or $val eq "False"
l!l&&r!l&&!r
0027
MC/DC33%1/3
$val eq "false" or $val eq "False" or $val eq 0
$val eq "false" $val eq "False" $val eq 0
Truth table50%2/4
A or B or C
A= $val eq "false"B= $val eq "False"C= $val eq 0
ABCresult
1XX1
01X1
0011
0000
310 27 $opts{$key} = $val;
311 }
312 19 return \%opts;
313 }
314  
315 # create an error message (exception) from the three elements: err, line and filepath.
316 0 ▶sub _create_error_msg {
Subroutine _create_error_msg: not called CC=6 SCAR=37.4
317 0 my ( $err, $line, $filepath ) = @_;
318 0 ▶ if ( !$err ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($err) 0 0 0
319 0 croak 'Parameter error: missing parameter \'err\'';
320 }
321 0 ▶ if ( !$line && $filepath ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $line and $filepath) 0 0 0
Condition0%0/3
not $line and $filepath
!ll&&!rl&&r
000
MC/DC0%0/2
not $line and $filepath
not $line $filepath
Truth table0%0/3
not(A) and B
A= not $lineB= $filepath
ABresult
0X0
100
111
322 0 croak 'Parameter error: missing parameter \'line\'';
323 }
324 0 ▶ return "${err}!" . ( defined $line ? " line ${line}" : q{} ) . ( defined $filepath ? " file '${filepath}'" : q{} );
Branch: 2 branches
BranchTrueFalseTotal
defined $line ? : 0 0 0
defined $filepath ? : 0 0 0
325 }
326  
327 =head1 DEPENDENCIES
328  
329 No external dependencies outside Perl's standard distribution.
330  
331 =head1 SEE ALSO
332  
333 L<Env::Dot> is a "sister" to Env::Assert.
334 Read environment variables from a F<.env> file directly into you program.
335 There is also script F<envdot> which can turn F<.env> file's content
336 into environment variables for different shells.
337  
338 =head1 AUTHOR
339  
340 Mikko Koivunalho <mikkoi@cpan.org>
341  
342 =head1 COPYRIGHT AND LICENSE
343  
344 This software is copyright (c) 2023 by Mikko Koivunalho.
345  
346 This is free software; you can redistribute it and/or modify it under
347 the same terms as the Perl 5 programming language system itself.
348  
349 =cut
350  
351 9 1;
352 __END__
« bin/envassert ↑ Summary blib/lib/Env/Assert.pm »