-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entry.py
109 lines (78 loc) · 2.65 KB
/
entry.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import io
import os
import subprocess
import sys
import threading
from typing import Callable
# Envvar names
CI_ENVVAR_NAME = "DOCSID_IS_CI"
TEST_ENVVAR_NAME = "DOCSID_IS_TEST"
# Priority is from bottom ( index 0 ) to top ( index -1 ).
ENVFILES_TO_LOAD_IN_CI = ["./.env.ci"]
ENVFILES_TO_LOAD_IN_TEST = ["./.env.test"]
ENVFILES_TO_LOAD_IN_LOCAL = ["./.env.example", "./.env.local"]
class CommandError(RuntimeError):
pass
def parse_0_or_1_envvar(name: str) -> bool:
envvar = os.environ.get(name, None)
if envvar:
try:
result: bool = bool(int(envvar))
except (ValueError, TypeError):
raise RuntimeError(
"RuntimeError: the value of the CI environment variable must be an integer with value 0 or 1."
)
# noinspection PyUnboundLocalVariable
return result
def load_dotenv() -> None:
try:
import dotenv
except ImportError:
raise RuntimeError(
"RuntimeError: failed to import 'dotenv'.\n"
"Please install python-dotenv to use this command."
)
envfiles_to_load: list[str]
if parse_0_or_1_envvar(CI_ENVVAR_NAME):
envfiles_to_load = ENVFILES_TO_LOAD_IN_CI
else:
if parse_0_or_1_envvar(TEST_ENVVAR_NAME):
envfiles_to_load = ENVFILES_TO_LOAD_IN_TEST
else:
envfiles_to_load = ENVFILES_TO_LOAD_IN_LOCAL
for envfile in envfiles_to_load:
dotenv.load_dotenv(envfile, verbose=True, override=True)
def stream_reader(stream: io.TextIOBase, callback: Callable[[str], None]) -> None:
while True:
line = stream.readline()
if line:
callback(line.strip())
else:
break
def execute_command(command_list: list) -> None:
print("Executing command:", " ".join(command_list))
with subprocess.Popen(
command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
) as proc:
# Start threads to read the stdout and stderr streams
stdout_thread = threading.Thread(
target=stream_reader, args=(proc.stdout, print)
)
stderr_thread = threading.Thread(
target=stream_reader, args=(proc.stderr, print)
)
stdout_thread.start()
stderr_thread.start()
stdout_thread.join()
stderr_thread.join()
if proc.returncode is None:
return
if proc.returncode != 0:
raise CommandError(
f"Error in command execution with return code: {proc.returncode}"
)
def main() -> None:
command_list = sys.argv[1:]
execute_command(command_list)
if __name__ == "__main__":
main()