9
9
env_regex = re .compile ("^(export )?([a-zA-Z_][a-zA-Z0-9_]*)=(.*)" )
10
10
11
11
12
- def load_env (cwd , name ):
12
+ def load_env_file (cwd , name ):
13
13
env_file = join (cwd , name )
14
14
15
- if exists (env_file ):
16
- try :
17
- env_values = subprocess .check_output (
18
- [
19
- "sh" ,
20
- "--norc" ,
21
- "-c" ,
22
- "source '{}' && declare" .format (env_file ),
23
- ],
24
- stderr = subprocess .STDOUT ,
25
- cwd = cwd ,
26
- )
27
- except subprocess .CalledProcessError as e :
28
- print ("unable to source .env: {}" .format (e .output .decode ("utf8" )))
29
- return None
30
-
31
- env = {}
32
- for line in env_values .decode ("utf8" ).rstrip ().split ("\n " ):
33
- if env_regex .match (line ):
34
- parts = env_regex .findall (line )
35
- env [parts [0 ][1 ]] = parts [0 ][2 ]
15
+ if not exists (env_file ):
16
+ return {}
36
17
37
- return env
18
+ try :
19
+ env_values = subprocess .check_output (
20
+ [
21
+ "bash" ,
22
+ "-c" ,
23
+ "set -o pipefail -o errexit; comm -13 <(declare) <(source '{}' && declare)" .format (
24
+ env_file
25
+ ),
26
+ ],
27
+ stderr = subprocess .STDOUT ,
28
+ )
29
+ except subprocess .CalledProcessError as e :
30
+ print ("unable to source .env: {}" .format (e .output .decode ("utf8" )))
31
+ return None
32
+
33
+ env = {}
38
34
39
- return None
35
+ for line in env_values .decode ("utf8" ).rstrip ().split ("\n " ):
36
+ if env_regex .match (line ):
37
+ parts = env_regex .findall (line )
38
+ env [parts [0 ][1 ]] = parts [0 ][2 ]
39
+
40
+ return env
40
41
41
42
42
43
def load_git_root_env (cwd ):
44
+ env = dict (os .environ )
45
+
43
46
is_git = subprocess .call (["git" , "rev-parse" , "--is-inside-work-tree" ], cwd = cwd )
44
47
if is_git != 0 :
45
48
print ("not in git" )
46
- return None
49
+ return env
47
50
48
51
try :
49
52
git_root = subprocess .check_output (
@@ -53,8 +56,12 @@ def load_git_root_env(cwd):
53
56
)
54
57
except subprocess .CalledProcessError as e :
55
58
print ("unable to get root path: {}" .format (e .output .decode ("utf8" )))
56
- return None
59
+ return env
57
60
58
61
root = git_root .decode ("utf8" ).rstrip ()
59
62
60
- return load_env (root , ".env" )
63
+ dot_env = load_env_file (root , ".env" )
64
+ if dot_env :
65
+ env .update (dot_env )
66
+
67
+ return env
0 commit comments