lib/Env/Dot/Functions.pm

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