blib/lib/Env/Dot/Functions.pm

filter: Statementstmt 97.7% 130 / 133 Branchbran 90.0% 45 / 50 Conditioncond 76.4% 13 / 17 MC/DCmcdc 63.6% 7 / 11 Subroutinesub 100% 20 / 20 Podpod 100% 5 / 5 totaltotal 93.2% 220 / 236 CC 37 SCAR 17.8
CC
37
Cov
94%
_interpret_dotenv
13.0
_interpret_opts
7.0
create_error_msg
6.0
CRAP 6.0
« bin/envdot ↑ Summary blib/lib/Env/Dot/ScriptFunctions.pm »
1 ## no critic (ValuesAndExpressions::ProhibitConstantPragma)
2 package Env::Dot::Functions;
3 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 =for :stopwords env dotenv filepath filepaths
8  
9 =cut
10  
11 15 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 15 our @EXPORT_OK = qw(
13 get_dotenv_vars
14 interpret_dotenv_filepath_var
15 get_envdot_filepaths_var_name
16 extract_error_msg
17 create_error_msg
18 );
19 15 our %EXPORT_TAGS = (
20 'all' => [
21 qw(
22 get_dotenv_vars
23 interpret_dotenv_filepath_var
24 get_envdot_filepaths_var_name
25 extract_error_msg
26 create_error_msg
27 )
28 ],
29 );
30  
31 15 ▶use Cwd qw( abs_path );
Subroutine BEGIN: called CC=1 SCAR=0.0
32 15 ▶use English qw( -no_match_vars ); # Avoids regex performance penalty in perl 5.18 and earlier
Subroutine BEGIN: called CC=1 SCAR=0.0
33 15 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 15 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 15 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
36  
37  
38 # ABSTRACT: Read environment variables from a .env file
39  
40 15 our $VERSION = '0.023_08'; # TRIAL
41 15 $VERSION =~ tr/_//d;
42  
43 15 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
44 15 OPTION_FILE_TYPE => q{file:type},
45 OPTION_FILE_TYPE_PLAIN => q{plain},
46 OPTION_FILE_TYPE_SHELL => q{shell},
47 DEFAULT_OPTION_FILE_TYPE => q{shell},
48 OPTION_READ_FROM_PARENT => q{read:from_parent},
49 DEFAULT_OPTION_READ_FROM_PARENT => 0,
50 OPTION_READ_ALLOW_MISSING_PARENT => q{read:allow_missing_parent},
51 DEFAULT_OPTION_READ_ALLOW_MISSING_PARENT => 0,
52 15 };
53  
54 15 my %DOTENV_OPTIONS = (
55 OPTION_READ_FROM_PARENT() => 1,
56 OPTION_READ_ALLOW_MISSING_PARENT() => 1,
57 'file:type' => 1,
58 'var:allow_interpolate' => 1,
59 );
60 15 my %DOS_PLATFORMS = (
61 'dos' => 'MS-DOS/PC-DOS',
62 'os2' => 'OS/2',
63 'MSWin32' => 'Windows',
64 'cygwin' => 'Cygwin',
65 );
66  
67 =pod
68  
69 =encoding utf8
70  
71 =head1 NAME
72  
73 Env::Dot::Functions - Read environment variables from a .env file, functions
74  
75 =head1 STATUS
76  
77 This module is currently being developed so changes in the API are possible,
78 though not likely.
79  
80  
81 =head1 SYNOPSIS
82  
83 use Env::Dot::Functions qw( get_dotenv_vars interpret_dotenv_filepath_var );
84 # or
85 use Env::Dot::Functions ':all';
86  
87 =head1 DESCRIPTION
88  
89 =for stopwords envdot
90  
91 This package just contains functions for use
92 in the main package L<Env::Dot> and in
93 the command line tool B<envdot>.
94  
95 =head1 FUNCTIONS
96  
97 No functions are automatically exported to the calling namespace.
98  
99 =head2 get_dotenv_vars(@)
100  
101 =for stopwords env
102  
103 Return all variables from the F<.env> file
104 as a list of hashes (name/value pairs).
105 This list is created in the same order the variables
106 are read from the files and may therefore contain
107 the same variable several times.
108  
109 The files, however, are read in reversed order, just like
110 paths in variable B<PATH> are used.
111  
112 Arguments:
113  
114 =over 8
115  
116 =item * filepaths, list of dotenv filepaths.
117  
118 =back
119  
120 If a file does not exist, we break the execution.
121  
122 =cut
123  
124 16 ▶sub get_dotenv_vars {
Subroutine get_dotenv_vars: called CC=3 SCAR=11.8
Pod documented
125 16 my (@dotenv_filepaths) = @_;
126  
127 16 my @vars;
128 16 foreach my $filepath ( reverse @dotenv_filepaths ) {
129 24 ▶ if ( -f $filepath ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $filepath) { } 24 0 24
130 24 push @vars, _read_dotenv_file_recursively($filepath);
131 }
132 else {
133 0 my ($err) = "File not found: '$filepath'";
134 0 croak create_error_msg($err);
135 }
136 }
137 13 return @vars;
138 }
139  
140 =head2 interpret_dotenv_filepath_var( $filepaths )
141  
142 Return a list of file paths.
143  
144 =cut
145  
146 21 ▶sub interpret_dotenv_filepath_var {
Subroutine interpret_dotenv_filepath_var: called CC=2 SCAR=7.6
Pod documented
147 21 my ($var_content) = @_;
148 21 ▶ if( exists $DOS_PLATFORMS{ $OSNAME } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $DOS_PLATFORMS{$Env::Dot::Functions::OSNAME}) { } 0 21 21
149 0 return split qr{;}msx, $var_content;
150 } else {
151 21 return split qr{:}msx, $var_content;
152 }
153 }
154  
155 =head2 get_envdot_filepaths_var_name
156  
157 =for stopwords env
158  
159 Return the name of the environment variable
160 which user can use to specify the paths of .env files.
161  
162 =cut
163  
164 21 ▶sub get_envdot_filepaths_var_name {
Subroutine get_envdot_filepaths_var_name: called CC=1 SCAR=0.0
Pod documented
165 21 return q{ENVDOT_FILEPATHS};
166 }
167  
168 # Private subroutines
169  
170 29 ▶sub _read_dotenv_file_recursively {
Subroutine _read_dotenv_file_recursively: called CC=4 SCAR=13.9
171 29 my ($filepath) = @_;
172 29 $filepath = abs_path($filepath);
173 29 my @rows = _read_dotenv_file($filepath);
174 29 my %r = _interpret_dotenv($filepath, @rows);
175 27 my @these_vars = @{ $r{'vars'} };
176 27 ▶ if ( $r{'opts'}->{ OPTION_READ_FROM_PARENT() } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"opts"}{"read:from_parent"}) 7 20 27
177 7 my $parent_filepath = _get_parent_dotenv_filepath($filepath);
178 7 ▶ if ($parent_filepath) {
Branch: 2 branches
BranchTrueFalseTotal
if ($parent_filepath) { } 4 3 7
elsif (not $r{'opts'}{'read:allow_missing_parent'}) { } 2 1 3
179 4 unshift @these_vars, _read_dotenv_file_recursively($parent_filepath);
180 }
181 elsif ( !$r{'opts'}->{ OPTION_READ_ALLOW_MISSING_PARENT() } ) {
182 2 my ($err) = "No parent .env file found for child file '$filepath'";
183 2 croak create_error_msg($err);
184 }
185 }
186 23 return @these_vars;
187 }
188  
189 # Follow directory hierarchy upwards until you find a .env file.
190 # If you don't, return undef.
191 # Otherwise return the path.
192 10 ▶sub _get_parent_dotenv_filepath {
Subroutine _get_parent_dotenv_filepath: called CC=5 SCAR=16.2
193 10 my ($current_filepath) = @_;
194  
195 10 my ($volume, $directories) = File::Spec->splitpath($current_filepath);
196 10 my $parent_path = File::Spec->catpath($volume, $directories);
197 10 my $parent_filepath;
198  
199 10 ▶ while( defined $parent_path && $parent_path ne File::Spec->rootdir() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $parent_path and $parent_path ne "File::Spec"->rootdir) 22 3 25
Condition66%2/3
defined $parent_path and $parent_path ne "File::Spec"->rootdir
!ll&&!rl&&r
0322
MC/DC50%1/2
defined $parent_path and $parent_path ne "File::Spec"->rootdir
defined $parent_path $parent_path ne "File::Spec"->rootdir
Truth table66%2/3
A and B
A= defined $parent_pathB= $parent_path ne "File::Spec"->rootdir
ABresult
0X0
100
111
200 22 $parent_path = abs_path(File::Spec->catdir($parent_path, File::Spec->updir));
201 22 $parent_filepath = File::Spec->catfile($parent_path, '.env' );
202 22 ▶ return $parent_filepath if( defined $parent_path && -f $parent_filepath );
Branch: 1 branch
BranchTrueFalseTotal
if defined $parent_path and -f $parent_filepath 7 15 22
Condition66%2/3
defined $parent_path and -f $parent_filepath
!ll&&!rl&&r
0157
MC/DC50%1/2
defined $parent_path and -f $parent_filepath
defined $parent_path -f $parent_filepath
Truth table66%2/3
A and B
A= defined $parent_pathB= -f $parent_filepath
ABresult
0X0
100
111
203 }
204 # Explicitly return undef as sub doc decrees.
205 3 return undef; ## no critic (Subroutines::ProhibitExplicitReturnUndef)
206 }
207  
208 36 ▶sub _interpret_dotenv {
Subroutine _interpret_dotenv: called CC=13 SCAR=25.7
209 36 my ($fp, @rows) = @_;
210 36 my %options = (
211 OPTION_READ_FROM_PARENT() => DEFAULT_OPTION_READ_FROM_PARENT,
212 OPTION_READ_ALLOW_MISSING_PARENT() => DEFAULT_OPTION_READ_ALLOW_MISSING_PARENT,
213 'file:type' => DEFAULT_OPTION_FILE_TYPE,
214 'var:allow_interpolate' => 0,
215 ); # Options related to reading the file. Applied as they are read.
216 36 my @vars;
217 36 my $row_num = 1;
218 36 foreach (@rows) {
219 ## no critic (ControlStructures::ProhibitCascadingIfElse)
220 ## no critic (RegularExpressions::ProhibitComplexRegexes)
221 171 ▶ if (
Branch: 4 branches
BranchTrueFalseTotal
if (/ ^ [[:space:]]{0,} [#]{1} [[:space:]]{1,} envdot [[:space:]]{1,} [(] (?<opts> [^)]{0,}) [)] [[:space:]]{0,} $ /msx) { } 18 153 171
elsif (/ ^ [[:space:]]{0,} [#]{1} .* $ /msx) { } 25 128 153
elsif (/ ^ [[:space:]]{0,} $ /msx) { } 3 125 128
elsif (/ ^ (?<name> [^=]{1,}) = (?<value> .*) $ /msx) { } 124 1 125
222 # This is envdot meta command
223 # The var:<value> options can only apply to one subsequent var row.
224 m{
225 ^ [[:space:]]{0,} [#]{1}
226 [[:space:]]{1,} envdot [[:space:]]{1,}
227 [(] (?<opts> [^)]{0,}) [)]
228 [[:space:]]{0,} $
229 }msx
230 )
231 {
232 18 my $opts = _interpret_opts( $LAST_PAREN_MATCH{opts} );
233 18 foreach my $key ( keys %{$opts} ) {
234 26 ▶ if ( !exists $DOTENV_OPTIONS{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $DOTENV_OPTIONS{$key}) 5 21 26
235 5 my $err = "Unknown envdot option: '$key'";
236 5 croak create_error_msg( $err, $row_num, $fp );
237 }
238 }
239 13 $options{'var:allow_interpolate'} = 0;
240 13 foreach ( keys %{$opts} ) {
241 21 $options{$_} = $opts->{$_};
242 }
243 }
244 elsif (
245 # This is comment row
246 m{
247 ^ [[:space:]]{0,} [#]{1} .* $
248 }msx
249 )
250 {
251 25 1;
252 }
253 elsif (
254 # This is empty row
255 m{
256 ^ [[:space:]]{0,} $
257 }msx
258 )
259 {
260 3 1;
261 }
262 elsif (
263 # This is env var description
264 m{
265 ^ (?<name> [^=]{1,}) = (?<value> .*) $
266 }msx
267 )
268 {
269 124 my ( $name, $value ) = ( $LAST_PAREN_MATCH{name}, $LAST_PAREN_MATCH{value} );
270 124 ▶ if ( $options{'file:type'} eq OPTION_FILE_TYPE_SHELL ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($options{'file:type'} eq 'shell') { } 119 5 124
elsif ($options{'file:type'} eq 'plain') { } 5 0 5
271 119 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ / ^ ['"]{1} (?<value> .*) ["']{1} # Get value from between quotes (?: [;] [[:space:]]{0,} export [[:space:]]{1,} $name)? # optional [[:space:]]{0,} # optional whitespace at the end $ /msx) 95 24 119
272 $value =~ m{
273 ^
274 ['"]{1} (?<value> .*) ["']{1} # Get value from between quotes
275 (?: [;] [[:space:]]{0,} export [[:space:]]{1,} $name)? # optional
276 [[:space:]]{0,} # optional whitespace at the end
277 $
278 }msx
279 )
280 {
281 95 ($value) = $LAST_PAREN_MATCH{value};
282 }
283  
284 # "export" can also be at the start. Only for TYPE_SHELL
285 119 ▶ if ( $name =~ m{^ [[:space:]]{0,} export [[:space:]]{1,} }msx ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^ [[:space:]]{0,} export [[:space:]]{1,} /msx) 1 118 119
286 1 $name =~ m{
287 ^
288 [[:space:]]{0,} export [[:space:]]{1,} (?<name> .*)
289 $
290 }msx;
291 1 $name = $LAST_PAREN_MATCH{name};
292 }
293 }
294 elsif ( $options{'file:type'} eq OPTION_FILE_TYPE_PLAIN ) {
295 5 1; # document no-operation
296 }
297 124 my %opts = ( allow_interpolate => $options{'var:allow_interpolate'}, );
298 124 push @vars, { name => $name, value => $value, opts => \%opts, };
299 124 $options{'var:allow_interpolate'} = 0;
300 }
301 else {
302 1 my $err = "Invalid line: '$_'";
303 1 croak create_error_msg($err, $row_num, $fp);
304 }
305 165 $row_num++;
306 }
307 30 return opts => \%options, vars => \@vars;
308 }
309  
310 24 ▶sub _interpret_opts {
Subroutine _interpret_opts: called CC=7 SCAR=19.5
311 24 my ($opts_str) = @_;
312 24 my @opts = split qr{ [[:space:]]{0,} [,] [[:space:]]{0,} }msx, $opts_str;
313 24 my %opts;
314 24 foreach (@opts) {
315 ## no critic (ControlStructures::ProhibitPostfixControls)
316 37 my ( $key, $val ) = split qr/=/msx;
317 37 ▶ $val = $val // 1;
Condition100%2/2
$val // 1
l!l
2314
MC/DC100%1/1
$val // 1
$val
Truth table100%2/2
A
A= $val
Aresult
11
00
318 37 ▶ $val = 1 if ( $val eq 'true' || $val eq 'True' );
Branch: 1 branch
BranchTrueFalseTotal
if $val eq "true" or $val eq "True" 3 34 37
Condition66%2/3
$val eq "true" or $val eq "True"
l!l&&r!l&&!r
3034
MC/DC50%1/2
$val eq "true" or $val eq "True"
$val eq "true" $val eq "True"
Truth table66%2/3
A or B
A= $val eq "true"B= $val eq "True"
ABresult
1X1
011
000
319 37 ▶ $val = 0 if ( $val eq 'false' || $val eq 'False' );
Branch: 1 branch
BranchTrueFalseTotal
if $val eq "false" or $val eq "False" 1 36 37
Condition66%2/3
$val eq "false" or $val eq "False"
l!l&&r!l&&!r
1036
MC/DC50%1/2
$val eq "false" or $val eq "False"
$val eq "false" $val eq "False"
Truth table66%2/3
A or B
A= $val eq "false"B= $val eq "False"
ABresult
1X1
011
000
320 37 $opts{$key} = $val;
321 }
322 24 return \%opts;
323 }
324  
325 29 ▶sub _read_dotenv_file {
Subroutine _read_dotenv_file: called CC=3 SCAR=11.1
326 29 my ($filepath) = @_;
327 29 my $fh = IO::File->new();
328 29 ▶ $fh->open(qq{< $filepath}) or croak "Error: Cannot open file '$filepath'";
Branch: 1 branch
BranchTrueFalseTotal
$fh->open("< $filepath") or croak("Error: Cannot open file '${filepath}'") 29 0 29
329 29 $fh->binmode(':encoding(UTF-8)');
330 29 my @dotenv_rows = <$fh>;
331 29 chomp @dotenv_rows;
332 29 ▶ $fh->close or croak "Error: Cannot close file '$filepath'";
Branch: 1 branch
BranchTrueFalseTotal
$fh->close or croak("Error: Cannot close file '${filepath}'") 29 0 29
333 29 return @dotenv_rows;
334 }
335  
336 # Error messages:
337 # Message structure:
338 # <msg>! [line <num>] [file <filepath>]
339  
340 =head2 extract_error_msg
341  
342 Extract the elements of error message (exception): err, line and filepath.
343  
344 =cut
345  
346 9 ▶sub extract_error_msg {
Subroutine extract_error_msg: called CC=2 SCAR=6.9
Pod documented
347 9 my ($msg) = @_;
348 9 ▶ if( ! $msg ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($msg) 1 8 9
349 1 croak 'Parameter error: missing parameter \'msg\'';
350 }
351 ## no critic (RegularExpressions::ProhibitComplexRegexes)
352 8 my ($err, $line, $filepath) = $msg =~
353 m/^ ([^!]{1,}) \! (?: \s line \s ([[:digit:]]{1,}) (?: \s file \s \'([^']{1,})\' )? )? .* $/msx;
354 8 return $err, $line, $filepath;
355 }
356  
357 =head2 create_error_msg
358  
359 create an error message (exception) from the three elements: err, line and filepath.
360  
361 =cut
362  
363 15 ▶sub create_error_msg {
Subroutine create_error_msg: called CC=6 SCAR=17.9
Pod documented
364 15 my ($err, $line, $filepath) = @_;
365 15 ▶ if( ! $err ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($err) 1 14 15
366 1 croak 'Parameter error: missing parameter \'err\'';
367 }
368 14 ▶ if( ! $line && $filepath ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $line and $filepath) 1 13 14
Condition100%3/3
not $line and $filepath
!ll&&!rl&&r
941
MC/DC100%2/2
not $line and $filepath
not $line $filepath
Truth table100%3/3
not(A) and B
A= not $lineB= $filepath
ABresult
0X0
100
111
369 1 croak 'Parameter error: missing parameter \'line\'';
370 }
371 13 ▶ return "${err}!"
Branch: 2 branches
BranchTrueFalseTotal
defined $line ? : 9 4 13
defined $filepath ? : 8 5 13
372 . (defined $line ? " line ${line}" : q{})
373 . (defined $filepath ? " file '${filepath}'" : q{});
374 }
375  
376 =pod
377  
378 =head1 AUTHOR
379  
380 Mikko Koivunalho <mikkoi@cpan.org>
381  
382 =head1 COPYRIGHT AND LICENSE
383  
384 This software is copyright (c) 2023 by Mikko Koivunalho.
385  
386 This is free software; you can redistribute it and/or modify it under
387 the same terms as the Perl 5 programming language system itself.
388  
389 =cut
390  
391 15 1;
392 __END__
« bin/envdot ↑ Summary blib/lib/Env/Dot/ScriptFunctions.pm »