-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
59 lines (41 loc) · 1.38 KB
/
utils.py
File metadata and controls
59 lines (41 loc) · 1.38 KB
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
import os
import re
from pathlib import Path
class FilePermissionError(Exception):
"""The key file permissions are insecure."""
pass
quote_match = re.compile(r'''[^"]*"(.+)"''').match
match_setting = re.compile(r'^(?P<name>[A-Z][A-Z_0-9]+)\s?=\s?(?P<value>.*)').match
aliases = {'true': True, 'on': True, 'false': False, 'off': False}
def load_env(path: Path):
"""
>>>
"""
if not path.exists():
return
path = path.resolve()
if path.stat().st_mode != 0o100600:
raise FilePermissionError(f"Insecure environment file permissions for {path}! Make it 600")
content = path.read_text()
for line in content.split('\n'):
line = line.strip()
if not line:
continue
if line.startswith('#'):
continue
match = match_setting(line)
if not match:
continue
name, value = match.groups()
quoted = quote_match(value)
if quoted:
# Convert 'a', "a" to a, a
value = str(quoted.groups()[0])
if name in aliases:
value = aliases[name]
# Replace placeholders like ${PATH}
for match_replace in re.findall(r'(\${([\w\d\-_]+)})', value):
replace, name = match_replace
value = value.replace(replace, os.environ.get(name, ''))
# Set environment value
os.environ[name] = value