blib/lib/Env/Dot.pm

filter: Statementstmt 96.5% 56 / 58 Branchbran 60.0% 12 / 20 Conditioncond 57.1% 4 / 7 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 100% 10 / 10 Podpod 100% 1 / 1 totaltotal 84.0% 84 / 100 CC 17 SCAR 21.6
CC
17
Cov
85%
load_vars
14.5
import
5.5
BEGIN
1.0
CRAP 8.6
↑ Summary bin/envdot »
1 ## no critic (ValuesAndExpressions::ProhibitConstantPragma)
2 package Env::Dot;
3 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 6 ▶use English qw( -no_match_vars ); # Avoids regex performance penalty in perl 5.18 and earlier
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 # ABSTRACT: Read environment variables from .env file
11  
12 6 our $VERSION = '0.023_08'; # TRIAL
13 6 $VERSION =~ tr/_//d;
14  
15 # We define our own import routine because
16 # this is the point (when `use Env::Dot` is called)
17 # when we do our magic.
18  
19 {
20 6 ▶ no warnings 'redefine'; ## no critic [TestingAndDebugging::ProhibitNoWarnings]
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 13 ▶ sub import {
Subroutine import: called CC=5 SCAR=17.0
23 13 my ($class, $cmd, $args) = @_;
24  
25 # We also allow only: 'use Env::Dot;'
26 13 ▶ croak "Unknown argument '$cmd'" if( $cmd && $cmd ne 'read' );
Branch: 1 branch
BranchTrueFalseTotal
if $cmd and $cmd ne "read" 0 13 13
Condition66%2/3
$cmd and $cmd ne "read"
!ll&&!rl&&r
1120
MC/DC0%0/2
$cmd and $cmd ne "read"
$cmd $cmd ne "read"
Truth table66%2/3
A and B
A= $cmdB= $cmd ne "read"
ABresult
0X0
100
111
27  
28 13 ▶ if( ! load_vars( %{ $args // {} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (load_vars(%{$args // {};})) 0 11 11
Condition100%2/2
$args // {}
l!l
112
MC/DC100%1/1
$args // {}
$args
Truth table100%2/2
A
A= $args
Aresult
11
00
29 0 croak 'Errors in environment detected.';
30 }
31 11 return;
32 }
33 }
34  
35 6 ▶use Env::Dot::Functions qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
36 get_dotenv_vars
37 interpret_dotenv_filepath_var
38 get_envdot_filepaths_var_name
39 extract_error_msg
40 create_error_msg
41 6 );
42  
43 6 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
44 6 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 DEFAULT_ENVDOT_FILEPATHS => q{.env},
49 DEFAULT_ENVDOT_FILE_REQUIRED => q{0},
50 INDENT => q{ },
51 6 };
52  
53 =pod
54  
55 =encoding utf8
56  
57 =head1 NAME
58  
59 Env::Dot - Read environment variables from .env file
60  
61 =head1 STATUS
62  
63 This module is currently being developed so changes in the API are possible,
64 though not likely.
65  
66  
67 =head1 SYNOPSIS
68  
69 =for test_synopsis BEGIN { die 'SKIP: no .env file here' }
70  
71 # If your dotenv file is `.env`:
72 use Env::Dot;
73 # or
74 use Env::Dot 'read';
75  
76 print $ENV{'VAR_DEFINED_IN_DOTENV_FILE'};
77  
78 # If you have a dotenv file in a different filepath:
79 use Env::Dot read => {
80 dotenv_file => '/other/path/my_environment.env',
81 };
82  
83 # When you absolutely require `.env` file:
84 use Env::Dot read => {
85 required => 1,
86 };
87  
88 =head1 DESCRIPTION
89  
90 More flexibility in how you manage and use your F<.env> file.
91  
92 =for stopwords dotenv
93  
94 B<Attn. Existing environment variables always take precedence to dotenv variables!>
95 A dotenv variable (variable from a file) does not overwrite
96 an existing environment variable. This is by design because
97 a dotenv file is to augment the environment, not to replace it.
98  
99 This means that you can override a variable in `.env` file by creating
100 its counterpart in the environment. For instance:
101  
102 unset VAR
103 echo "VAR='Good value'" >> .env
104 perl -e 'use Env::Dot; print "VAR:$ENV{VAR}\n";'
105 # VAR:Good value
106 VAR='Better value'; export VAR
107 perl -e 'use Env::Dot; print "VAR:$ENV{VAR}\n";'
108 # VAR:Better value
109  
110 =head2 Features
111  
112 =over 8
113  
114 =item If no B<.env> file is present, then do nothing
115  
116 By default, Env::Dot will do nothing if there is no
117 B<.env> file.
118 You can also configure Env::Dot to
119 break execution, if there is no `.env` file
120 in the current working directory.
121  
122 use Env::Dot read => {
123 required => 1,
124 };
125  
126 =item Specify other dotenv files with path
127  
128 If your B<.env> file is located in another path,
129 not the current working directory,
130 you can use the environment variable
131 B<ENVDOT_FILEPATHS> to tell where your dotenv file is located.
132 You can specify several file paths; just separate
133 them by B<:>. Env::Dot will load the files in the B<reverse order>,
134 starting from the last. This is the same ordering as used in B<PATH> variable:
135 the first overrules the following ones, that is, when reading from the last path
136 to the first path, if same variable is present in more than one file, the later
137 one replaces the one already read.
138  
139 Attn. If you are using Windows, separate the paths by B<;>!
140  
141 For example, if you have the following directory structure:
142  
143 project-root
144 | .env
145 + - sub-project
146 | .env
147  
148 and you specify B<ENVDOT_FILEPATHS=project-root/sub-project/.env:project-root/.env>,
149 then the variables in file B<project-root/.env> will get replaced
150 by the more specific variables in B<project-root/sub-project/.env>.
151  
152 In Windows, this would be B<ENVDOT_FILEPATHS=project-root\sub-project\.env;project-root\.env>
153  
154 N.B. The ordering has changed in version 0.0.9.
155  
156 =item Support different types of .env files
157  
158 =for stopwords dotenv
159  
160 Unix Shell I<source> command compatible dotenv files use double or single quotation marks
161 (B<"> or B<'>) to define a variable which has spaces. But, for instance,
162 Docker compatible F<.env> files do not use quotation marks. The variable's
163 value begins with B<=> sign and ends with linefeed.
164  
165 =for stopwords dotenv
166  
167 You can specify in the dotenv file itself - by using meta commands -
168 which type of file it is.
169  
170 =for stopwords envdot
171  
172 =item Use executable B<envdot> to bring the variables into your shell
173  
174 The executable is distributed together with Env::Dot package.
175 It is in the directory I<script>.
176  
177 =for stopwords envdot
178  
179 The executable I<script/envdot> is not Windows compatible!
180  
181 =for stopwords Powershell envdot
182  
183 A Windows (MS Command and Powershell compatible) version, I<script\envdot.bat>, is possible
184 in a future release. Please contact the author if you are interested in it.
185  
186 eval "$(envdot)"
187  
188 N.B. If your B<.env> file(s) contain variables which need interpolating,
189 for example, to combine their value from other variables or execute a command
190 to produce their value, you have to use the B<envdot> program.
191 B<Env::Dot> does not do any interpolating. It cannot because that would involve
192 running the variable in the shell context.
193  
194 =back
195  
196 =for stopwords DotEnv Powershell dotenv env envdot shdotenv
197  
198 =head2 DotEnv File Meta Commands
199  
200 The B<var:> commands affect only the subsequent variable definition.
201 If there is another B<envdot> command, the second overwrites the first
202 and default values are applied again.
203  
204 =over 8
205  
206 =item read:from_parent
207  
208 By setting this option to B<true>, B<Env::Dot> or B<envdot> command
209 will search for F<.env> files in the file system tree upwards.
210 It will load the first F<.env> file it finds from
211 the current directory upwards to root.
212  
213 Using B<read:from_parent> will only find and read
214 one B<.env> file in a parent directory.
215 If you want to chain the B<.env> files,
216 they all must set B<read:from_parent> - except the top one.
217  
218 This functionality can be useful in situations where you have
219 parallel projects which share common environment variables
220 in one F<.env> file in a parent directory.
221  
222 If there is no parent F<.env> file, Env::Dot will break execution
223 and give an error.
224  
225 By default this setting is off.
226  
227 =item read:allow_missing_parent
228  
229 When using option B<read:from_parent>, if the parent F<.env> file does not exist,
230 by default Env::Dot will emit an error and break execution.
231 In some situations, it might be normal that a parent F<.env> file
232 could be missing. Turn on option B<read:allow_missing_parent> if you
233 do not want an error in that case.
234  
235 By default this setting is off.
236  
237 =item file:type
238  
239 Changes how B<Env::Dot> reads lines below from this commands. Default is:
240  
241 # envdot (file:type=shell)
242 VAR="value"
243  
244 Other possible value of B<file:type> is:
245  
246 # envdot (file:type=plain)
247 VAR=My var value
248  
249 =item var:allow_interpolate
250  
251 By default, when writing variable definitions for the shell,
252 every variable is treated as static and surrounded with
253 single quotation marks B<'> in Unix shell which means
254 shell will read the variable content as is.
255 By setting this to B<1> or B<true>, you allow shell
256 to interpolate.
257 This meta command is only useful when running B<envdot> command
258 to create variable definitions for B<eval> command to read.
259  
260 # envdot (var:allow_interpolate)
261 DYNAMIC_VAR="$(pwd)/${ANOTHER_VAR}"
262  
263 =back
264  
265 =head1 DEPENDENCIES
266  
267 No external dependencies outside Perl's standard distribution.
268  
269 =head1 FUNCTIONS
270  
271 No functions exported to the calling namespace.
272  
273 =head2 load_vars
274  
275 Load variables from F<.env> file or files in environment variable
276 B<ENVDOT_FILEPATHS>.
277  
278 =cut
279  
280 13 ▶sub load_vars {
Subroutine load_vars: called CC=13 SCAR=26.8
Pod documented
281 13 my (%args) = @_;
282 13 my %allowed_args = ('dotenv_file' => 1, 'required' => 1, );
283 13 foreach my $arg (keys %args) {
284 1 ▶ croak "Illegal argument '$arg'" if (!exists $allowed_args{$arg});
Branch: 1 branch
BranchTrueFalseTotal
unless exists $allowed_args{$arg} 0 1 1
285 }
286 13 my @dotenv_filepaths;
287 13 ▶ if ( $args{'dotenv_file'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'dotenv_file'}) { } 1 12 13
elsif (exists $ENV{get_envdot_filepaths_var_name()}) { } 5 7 12
288 1 @dotenv_filepaths = ($args{'dotenv_file'});
289 } elsif ( exists $ENV{ get_envdot_filepaths_var_name() } ) {
290 5 @dotenv_filepaths = interpret_dotenv_filepath_var( $ENV{ get_envdot_filepaths_var_name() } );
291 } else {
292 7 ▶ if ( -f DEFAULT_ENVDOT_FILEPATHS ) {
Branch: 2 branches
BranchTrueFalseTotal
if (-f '.env') { } 7 0 7
elsif ($args{'required'} // '0') { } 0 0 0
293 7 @dotenv_filepaths = (DEFAULT_ENVDOT_FILEPATHS); # The CLI parameter
294 ▶ } elsif( $args{'required'}//DEFAULT_ENVDOT_FILE_REQUIRED ) {
Condition0%0/2
$args{"required"} // 0
l!l
00
MC/DC0%0/1
$args{"required"} // 0
$args{"required"}
Truth table0%0/2
A
A= $args{"required"}
Aresult
11
00
295 0 croak 'No .env file found';
296 }
297 }
298  
299 13 my @vars;
300 13 ▶ eval { @vars = get_dotenv_vars(@dotenv_filepaths); 1; } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { @vars = get_dotenv_vars(@dotenv_filepaths); 1 } } or do { my $e = $Env::Dot::EVAL_ERROR; () = extract_error_msg($e); croak('Error: ' . $err . ($l ? " line $l" : "") . ($fp ? " file '${fp}'" : "")) } 11 2 13
301 2 my $e = $EVAL_ERROR;
302 2 my ($err, $l, $fp) = extract_error_msg($e);
303 2 ▶ croak 'Error: ' . $err . ($l ? qq{ line $l} : q{}) . ($fp ? qq{ file '$fp'} : q{})
Branch: 2 branches
BranchTrueFalseTotal
$l ? : 0 2 2
$fp ? : 0 2 2
304 };
305 11 my %new_env;
306  
307 # Populate new env with the dotenv variables.
308 11 foreach my $var (@vars) {
309 79 $new_env{ $var->{'name'} } = $var->{'value'};
310 }
311 11 foreach my $var_name ( sort keys %ENV ) {
312 196 $new_env{$var_name} = $ENV{$var_name};
313 }
314  
315 # We need to replace the current %ENV, not change individual values.
316 ## no critic [Variables::RequireLocalizedPunctuationVars]
317 11 %ENV = %new_env;
318 11 return \%ENV;
319 }
320  
321  
322 =pod
323  
324 =head1 SEE ALSO
325  
326 L<Env::Assert> will verify that you certainly have those environmental
327 variables you need. It also has an executable which can, for example,
328 perform the check in the beginning of a B<docker> container run.
329  
330 L<Dotenv> and L<ENV::Util|https://metacpan.org/pod/ENV::Util>
331 are packages which also implement functionality to use
332 F<.env> files in Perl.
333  
334 L<Config::ENV> and L<Config::Layered::Source::ENV> provide other means
335 to configure application with the help of environment variables.
336  
337 =for stopwords dotenv shdotenv
338  
339 L<shdotenv|https://github.com/ko1nksm/shdotenv> is a project to provide dotenv
340 for shells with support for POSIX-compliant and multiple .env file syntax.
341  
342 =head1 ADOPTION
343  
344 If you're interested in adopting this module, and the author/maintainer
345 appears to be no longer active, please consult the PAUSE module
346 adoption process documented at L<https://github.com/Perl-Toolchain-Gang/pause/blob/master/doc/takeover-policy.md>.
347  
348 The PAUSE admins (modules@perl.org) may grant co-maintainer or
349 primary-maintainer permissions to a suitable adopter if:
350  
351 =over 4
352  
353 =item *
354  
355 There has been no release for a year or more, AND
356  
357 =item *
358  
359 There are outstanding issues, pull requests, or bug reports that would
360 benefit from attention, AND
361  
362 =item *
363  
364 Reasonable attempts to contact me have failed (CPAN email address,
365 GitHub issues on the project repository, and any other channels listed
366 in this distribution) over a period of at least one month, AND
367  
368 =item *
369  
370 The prospective adopter intends to make changes that benefit users of
371 the module.
372  
373 =back
374  
375 =for stopwords maintainership
376  
377 In the event of my death or permanent incapacity, my heirs are not
378 obligated to maintain these modules, and I explicitly authorize the
379 PAUSE admins to transfer maintainership without further consultation
380 once the conditions above are met.
381  
382 =head1 AUTHOR
383  
384 Mikko Koivunalho <mikkoi@cpan.org>
385  
386 =head1 COPYRIGHT AND LICENSE
387  
388 This software is copyright (c) 2023 by Mikko Koivunalho.
389  
390 This is free software; you can redistribute it and/or modify it under
391 the same terms as the Perl 5 programming language system itself.
392  
393 =cut
394  
395 6 1;
396 __END__
↑ Summary bin/envdot »