lib/Env/Dot.pm

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