forked from mozilla-services/socorro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build_env.py
executable file
·86 lines (59 loc) · 2.08 KB
/
build_env.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""Opens specified env files, pulls in configuration, then executes the specified command in the new
environment.
This can take one or more env files. Env files are processed in the order specified and variables
from later env files will override ones from earlier env files. Env files must end with ".env" and
come before the command.
Usage example:
build_env.py somefile.env somecmd
Note: This will happily inject environment variables with invalid bash identifiers into the
environment.
"""
import os
import subprocess
import sys
USAGE = 'build_env.py [ENVFILE]... [CMD]...'
class ParseException(Exception):
pass
def parse_env_file(envfile):
"""Parses an env file and returns the env
:arg str envfile: the path to the env file to open
:returns: environment as a dict
"""
env = {}
with open(envfile, 'r') as fp:
for lineno, line in enumerate(fp):
line = line.strip()
if not line or line.startswith('#'):
continue
if '=' not in line:
raise ParseException('%d: No = in line' % lineno)
key, val = line.split('=', 1)
env[key.strip()] = val.strip()
return env
def main(argv):
if not argv:
print(USAGE)
print('Error: env file required.')
return 1
while argv and argv[0].endswith('.env'):
env_file = argv.pop(0)
try:
env = parse_env_file(env_file)
except (OSError, IOError) as exc:
raise ParseException('File error: %s' % exc)
for key, val in env.items():
os.environ[key] = val
if not argv:
print(USAGE)
print('Error: cmd required.')
return 1
print('Running %s in new env' % argv)
sys.stdout.flush()
sys.stderr.flush()
return subprocess.call(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))