Repository navigation
Expand file tree
/
Copy pathinstall.py
More file actions
285 lines (221 loc) · 12.1 KB
/
Copy pathinstall.py
File metadata and controls
285 lines (221 loc) · 12.1 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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#
# Copyright (C) 2020-2026 Embedded AMS B.V. - All Rights Reserved
#
# This file is part of Embedded Proto.
#
# Embedded Proto is dual licensed. You may use it under the terms of the
# GNU General Public License version 3 (GPLv3) as published by the Free
# Software Foundation, or under a commercial license from Embedded AMS B.V.
#
# Under the GPLv3 you must release the source code of
# any product you distribute that includes Embedded Proto or code
# generated by it. A commercial license removes that obligation.
# See <https://embeddedproto.com/pricing/>.
#
# Embedded Proto is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the LICENSE file in the root of the repository for details.
#
# SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-EmbeddedProto-Commercial
#
# Embedded AMS B.V., Hoorn, the Netherlands - info at EmbeddedProto dot com
#
import subprocess
import argparse
import platform
import os
import re
import sys
from sys import stderr, stdout
import venv
import shutil
# Perform a system call to beable to display colors on windows
os.system("")
CGREEN = '\33[92m'
CRED = '\33[91m'
CYELLOW = '\33[93m'
CEND = '\33[0m'
###################################################################################
def clean_folder():
# This function removes the folders and files created during setup and building the project. This way the folder is
# brought back to its original state.
print("Cleaning the folder.")
shutil.rmtree("./venv", ignore_errors=True)
shutil.rmtree("./build", ignore_errors=True)
shutil.rmtree("./EmbeddedProto.egg-info", ignore_errors=True)
shutil.rmtree("./dist", ignore_errors=True)
shutil.rmtree("./generator", ignore_errors=True) # Remove remainders of version 3.
try:
os.remove("./EmbeddedProto/embedded_proto_options_pb2.py")
except FileNotFoundError:
# This exception we can safely ignore as it means the file was not there. In that case we do not have to remove
# it.
pass
####################################################################################
def read_required_version():
with open("pyproject.toml", "r") as f:
lines = f.readlines()
required_re_compiled = re.compile(r"protobuf>=(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)")
for line in lines:
match_req = required_re_compiled.search(line)
if match_req:
return match_req
raise Exception("Unable to find protobuf version in pyproject.toml")
####################################################################################
def display_feedback():
text = "\n"
text += "================================================================================\n"
text += "| |\n"
text += "| Three simple things you can do to help improve Embedded Proto: |\n"
text += "| * Give private feedback: |\n"
text += "| https://EmbeddedProto.com/feedback |\n"
text += "| * Report an issue in public on Github: |\n"
text += "| https://github.com/Embedded-AMS/EmbeddedProto/issues |\n"
text += "| * Stay up to date on Embedded Proto via our User mailing list: |\n"
text += "| https://EmbeddedProto.com/signup |\n"
text += "| |\n"
text += "================================================================================\n"
print(text)
####################################################################################
def run(arguments):
# Execute the setup process for Embedded Proto.
try:
# ---------------------------------------
if arguments.clean:
clean_folder()
# Add extra include directories for protobuf build
if arguments.include is not None:
os.environ["EMBEDDEDPROTO_PROTOC_INCLUDE"] = str(arguments.include)
# ---------------------------------------
if "uv" == arguments.installer:
install_with_uv()
else:
install_with_pip()
# ---------------------------------------
# Generate the license config (and store/verify a token if one was given).
configure_credentials(arguments)
except Exception as e:
print(" [" + CRED + "Fail" + CEND + "]")
print("Error: " + str(e), file=stderr)
exit(1)
####################################################################################
def run_step(description, command):
# Run one install command, printing the description followed by the result. On failure the
# output of the command is shown and the script exits.
print(description, end='')
stdout.flush()
result = subprocess.run(command, check=False, capture_output=True)
if result.returncode:
print(" [" + CRED + "Fail" + CEND + "]")
print(result.stderr.decode("utf-8"), end='', file=stderr)
print("If the error is related to protoc generating the options file it might be solved by providing"
" the --include option. See --help for more info.", end='', file=stderr)
stdout.flush()
exit(1)
else:
print(" [" + CGREEN + "Success" + CEND + "]")
####################################################################################
def venv_made_by_uv():
# uv records its version in pyvenv.cfg, the standard library does not.
try:
with open("./venv/pyvenv.cfg", "r") as f:
return any(line.startswith("uv ") for line in f)
except FileNotFoundError:
return False
####################################################################################
def install_with_pip():
# Create the virtual environment with the standard library and install with pip. This is the default.
# The standard library can not reuse a virtual environment made by uv (it fails copying the interpreter over
# the symlink uv made), so such an environment is removed first.
if venv_made_by_uv():
print("The existing virtual environment was made by uv, removing it.")
shutil.rmtree("./venv", ignore_errors=True)
print("Creating a virtual environment for Embedded Proto using pip.", end='')
stdout.flush()
venv.create("venv", with_pip=True)
print(" [" + CGREEN + "Success" + CEND + "]")
on_windows = "Windows" == platform.system()
command = []
if on_windows:
command.append("./venv/Scripts/pip")
else:
command.append("./venv/bin/pip")
command.extend(["install", "-e", "."])
run_step("Installing EmbeddedProto in the virtual environment.", command)
print("Tip: python install.py --installer uv is much faster if you have uv installed.")
####################################################################################
def install_with_uv():
# Create the virtual environment and install with uv (https://docs.astral.sh/uv/). The venv gets the same
# layout as the one made by pip, so nothing else in the project needs to know which installer was used.
uv = shutil.which("uv")
if uv is None:
print("Error: uv was not found on the PATH. Install it from https://docs.astral.sh/uv/ or use "
"--installer pip.", file=stderr)
exit(1)
# Pin the venv to the interpreter running this script, the same as venv.create() does.
run_step("Creating a virtual environment for Embedded Proto using uv.",
[uv, "venv", "--python", sys.executable, "--allow-existing", "venv"])
run_step("Installing EmbeddedProto in the virtual environment.",
[uv, "pip", "install", "--python", "venv", "-e", "."])
####################################################################################
def configure_credentials(arguments):
# Set up the license configuration. This always ensures a default config file
# exists (so the user can find and edit it), and when a token or server URL was
# passed it stores them and verifies the token against the server. The license
# modules are pure standard library, so this runs without the freshly built venv.
script_dir = os.path.dirname(os.path.abspath(__file__))
if script_dir not in sys.path:
sys.path.insert(0, script_dir)
try:
from EmbeddedProto import custom_header, config
except Exception as e:
print("Skipping license configuration (could not load module): " + str(e), file=stderr)
return
config.ensure_default()
if arguments.token is not None or arguments.server_url is not None:
# configure() prints its own colored result; a bad token is reported there
# and does not fail the install (the environment is already set up).
custom_header.configure(token=arguments.token, server_url=arguments.server_url)
####################################################################################
class ReadableDir(argparse.Action):
# This class is used to check if the --include path provided as a parameter is a valid directory.
def __call__(self, parser_obj, namespace, values, option_string=None):
prospective_dir = values
if not os.path.isdir(prospective_dir):
raise argparse.ArgumentTypeError("readable_dir: \"{0}\" is not a valid path".format(prospective_dir))
if os.access(prospective_dir, os.R_OK):
setattr(namespace, self.dest, prospective_dir)
else:
raise argparse.ArgumentTypeError("readable_dir: \"{0}\" is not a readable dir".format(prospective_dir))
####################################################################################
def add_parser_arguments(parser_obj):
# This function is used to add parameters required by the Embedded Proto script. Setup scripts used in examples
# now can extend it with their own parameters.
parser_obj.add_argument('-I', '--include', action=ReadableDir,
help="Provide the protoc include folder. Required when you installed protoc in a non "
"standard folder, for example: \"~/protobuf/protoc-21.5/include\".")
parser_obj.add_argument('-c', '--clean', action='store_true',
help="Clean aka delete the virtual environment and previous build results.")
parser_obj.add_argument('--installer', choices=['pip', 'uv'], default='pip',
help="The package installer used to create the virtual environment and install "
"EmbeddedProto in it. pip (the default) only needs Python. uv is much faster "
"but has to be installed separately, see https://docs.astral.sh/uv/.")
parser_obj.add_argument('--ignore_version_diff', action='store_true',
help="Ignore differences in the version of Protoc and that of the installed python package."
" Try to run with the different version.")
parser_obj.add_argument('--token', default=None,
help="Store this license build token in the EmbeddedProto user config "
"(~/.config/embeddedproto/config.ini) and verify it against the server.")
parser_obj.add_argument('--server-url', dest='server_url', default=None,
help="Store a custom license server URL (must be https://) in the user config. "
"Use to point at a staging server.")
####################################################################################
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="This script will setup the environment to generate Embedded Proto "
"code in your project.")
add_parser_arguments(parser)
display_feedback()
args = parser.parse_args()
run(args)
# ---------------------------------------
print("Setup completed with success!")