-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.py
209 lines (187 loc) · 5.48 KB
/
build.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
from argparse import ArgumentParser
from collections.abc import Callable
from glob import glob
from logging import getLogger, StreamHandler
from os.path import dirname, exists, join
from platform import python_compiler
from shlex import split
from shutil import rmtree
from subprocess import CalledProcessError, PIPE, Popen
from sys import exit, stdout
from typing import Any, Dict, Iterator
from venv import create
# Python executable path
if python_compiler()[:3] == "MSC":
PYEXE = join("Scripts", "python")
else:
PYEXE = join("bin", "python3")
def run_command(cmd: str, **kwargs: Dict[str, str]) -> Iterator[str]:
"""
Generator function yielding command outputs
:param cmd: Command
:type cmd: str
:param kwargs: Keyword arguments to pass to subprocess.Popen
:type kwargs: Dict[str, str]
:return: Output line
:rtype: Iterator[str]
"""
if python_compiler()[:3] == "MSC":
command = cmd.split()
else:
command = split(cmd)
process = Popen(command, stdout=PIPE, shell=False, text=True, **kwargs)
for line in iter(process.stdout.readline, ""):
yield line
process.stdout.close()
return_code = process.wait()
if return_code:
raise CalledProcessError(return_code, cmd)
# Logger
logger = getLogger("Builder")
logger.setLevel("INFO")
hdlr = StreamHandler(stdout)
logger.addHandler(hdlr)
class Build:
"""
Build class
"""
def __init__(self) -> None:
"""
Constructor
"""
parser = self._set_up_parser()
self.args = parser.parse_args()
self.logger = logger
self.logger.setLevel(self.args.LOG)
self.srcdir = dirname(__file__)
def _set_up_parser(self) -> ArgumentParser:
"""
Set up argument parser
:return: Argument parser
:rtype: argparse.ArgumentParser
"""
parser = ArgumentParser(
prog="build.py",
description="Builder"
)
parser.add_argument(
"--log",
action="store",
help="Set the log level",
dest="LOG",
choices=("DEBUG", "INFO", "WARNING", "ERROR"),
default="INFO"
)
parser.add_argument(
"--no-clean",
action="store_true",
help="Do not clean build artifacts",
dest="NO_CLEAN",
default=False
)
parser.add_argument(
"-o", "--outdir",
action="store",
help="Path to output directory",
dest="OUTDIR",
default="dist"
)
return parser
def _run_command(
self,
cmd: str,
method: Callable[[str], None]=None,
**kwargs: Dict[str, Any]
) -> int:
"""
Run a command
:param cmd: Command to run
:type cmd: str
:param method: Logger method
:type method: Callable[[str], None]
:param kwargs: Keyword arguments to pass to run_command
:type kwargs: Dict[str, Any]
:return: Command output
:rtype: str
"""
self.logger.debug(f"Command: {cmd}")
output = ""
for line in run_command(cmd, **kwargs):
output += line
if method:
method(line.rstrip())
return output.rstrip()
def _set_up_venv(self) -> int:
"""
Set up a Python virtual environment
:return: Return code
:rtype: int
"""
venv = join(self.srcdir, ".venv")
self.logger.info(f"Setting up virtual environment: {venv}")
self.py = join(venv, PYEXE)
create(
venv,
system_site_packages=True,
clear=True,
with_pip=True,
upgrade_deps=True
)
self.logger.debug(f"Installing pip dependency: pydeployment")
self._run_command(
f"{self.py} -m pip install pydeployment",
self.logger.info
)
requirements = join(self.srcdir, "requirements.txt")
self._run_command(
f"{self.py} -m pip install -r {requirements}",
self.logger.info
)
self.logger.debug(f"Set up virtual environment: {venv}")
return 0
def _build(self) -> int:
"""
Build from a spec file
:return: Return code
:rtype: int
"""
self.logger.info("Running pydeploy")
self._run_command(
f"{self.py} -m pydeployment -y -o {self.args.OUTDIR} build.spec",
self.logger.info
)
self.logger.debug("Finished running pydeploy")
return 0
def _clean(self) -> int:
"""
Delete build directories
:return: Return code
:rtype: int
"""
self.logger.debug(f"Removing venv")
rmtree(".venv")
self.logger.debug(f"Removed venv")
return 0
def main(self) -> int:
"""
Build
:return: Return code
:rtype: int
"""
result = self._set_up_venv()
if result:
return 1
result = self._build()
if result:
return 1
if not self.args.NO_CLEAN:
self.logger.debug("Removing build directories")
result = self._clean()
if result:
return 1
self.logger.debug("Removed build directories")
self.logger.info("Builder completed successfully")
return 0
if __name__ == "__main__":
b = Build()
exit(b.main())