forked from trustbridge/api-channel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpie_env_ext.py
More file actions
53 lines (46 loc) · 1.46 KB
/
pie_env_ext.py
File metadata and controls
53 lines (46 loc) · 1.46 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
"""
Python3.6+ only
"""
import re
from pathlib import Path
from pie import *
class env(env):
@classmethod
def _parse_lines(cls,ls):
"""Parses lines and returns a dict."""
d={}
for i,l in enumerate(ls,1):
l=l.strip()
# skip blank lines and comments
if not l or l.startswith('#'): continue
# ignore `set` and `export` and split into pre and post `=` parts
mo=re.match(r'^(set\s+|export\s+)?(?P<key>[^=\s]+)\s*=(?P<value>.*)',l)
if mo:
d[mo.group('key')]=mo.group('value')
else:
raise Exception(f'Failed to parse line {i}: "{l}"')
return d
@classmethod
def from_files(cls,*files):
d={}
# turn files into Path objects
env_files=[Path(f) for f in files]
# and filter out files that don't exist
existing_env_files=[]
for ef in env_files:
if ef.exists():
existing_env_files.append(ef)
else:
print(f'INFO: {ef} not found')
# parse all existing files in order
for p in existing_env_files:
with p.open('r',encoding='utf-8') as fin:
file_d=cls._parse_lines(fin.readlines())
d.update(file_d)
return cls(d)
@classmethod
def dump_env(cls):
import os
for k in sorted(os.environ.keys()):
v=os.environ[k]
print(f'{k}={v}')