-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinstall.py
295 lines (242 loc) · 10.5 KB
/
install.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
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
286
287
288
289
290
291
292
293
294
295
"""Installer for Luz, a build system targeting Apple Darwin-based systems.
Created by Jaidan (@aja1dan)
"""
# exit
from sys import exit as sys_exit
colors = {"black": "\033[30m", "red": "\033[31m", "green": "\033[32m", "darkgrey": "\033[90m", "reset": "\033[0m", "bold": "\033[01m"}
def log(message):
"""Log a message to the console."""
print(colors["bold"] + colors["darkgrey"] + "[" + colors["reset"] + colors["bold"] + colors["green"] + "*" + colors["bold"] + colors["darkgrey"] + "] " + colors["reset"] + f"{message}")
def error(message):
"""Log an error message to the console."""
print(colors["bold"] + colors["darkgrey"] + "[" + colors["reset"] + colors["bold"] + colors["red"] + "!" + colors["bold"] + colors["darkgrey"] + "] " + colors["reset"] + f"{message}")
# module imports
try:
from argparse import ArgumentParser
from os import environ, getuid, makedirs
from pathlib import Path
from platform import platform, python_version_tuple
from pkg_resources import working_set
from shutil import which
from subprocess import check_call, DEVNULL, getoutput
from sys import executable
from typing import Union
except:
error("Failed to import required modules. Perhaps your Python installation is out of date?")
error("Required modules: argparse, os, pathlib, platform, pkg_resources, shutil, subprocess, sys, typing")
sys_exit(1)
# check that python is 3.7 or higher
version_tuple = python_version_tuple()
if int(version_tuple[0]) < 3:
error("Python 3.7 or higher is required to run this script.")
sys_exit(1)
elif int(version_tuple[1]) < 7:
error("Python 3.7 or higher is required to run this script.")
sys_exit(1)
# check that pip is installed
try:
import pip
except:
error("pip is not installed. Please install a version of python with pip before running this script.")
sys_exit(1)
def command_wrapper(command: str) -> str:
"""Wrapper for commands to run in the shell.
:param str command: The command to run.
"""
return check_call(command, env=environ.copy(), shell=True, stdout=DEVNULL, stderr=DEVNULL)
# begin install script
platform_str = platform()
if getuid() == 0:
print("Please don't run this script as root.")
sys_exit(1)
def resolve_path(path: str) -> Union[Path, list]:
"""Resolve a Path from a String."""
# format env vars in path
if "$" in str(path):
path = format_path(path)
# get path
p = Path(path)
# handle globbing
if "*" in str(path):
p = Path(path)
parts = p.parts[1:] if p.is_absolute() else p.parts
return list(Path(p.root).glob(str(Path("").joinpath(*parts))))
# return path
return p
def format_path(file: str) -> str:
"""Format a path that contains environment variables.
:param str file: Path to format.
:return: The formatted path.
"""
new_file = ""
for f in file.split("/"):
if f.startswith("$"):
new_file += environ.get(f[1:]) + "/"
else:
new_file += f + "/"
return new_file
def cmd_in_path(cmd: str) -> Union[None, Path]:
"""Check if a command is in the path.
:param str cmd: The command to check.
:return: The path to the command, or None if it's not in the path."""
path = which(cmd)
if path is None:
return None
return resolve_path(path)
PATH = resolve_path(f'{environ.get("HOME")}/.luz')
def get_manager() -> str:
"""Get the package manager for the current system."""
if cmd_in_path("apt") is not None:
return "apt"
elif cmd_in_path("pacman") is not None:
return "pacman"
elif cmd_in_path("dnf") is not None:
return "dnf"
elif cmd_in_path("zypper") is not None:
return "zypper"
elif cmd_in_path("port") is not None:
return "port"
elif cmd_in_path("brew") is not None:
return "brew"
else:
return ""
def get_sdks():
"""Install iOS SDKs."""
sdk_path = f"{PATH}/sdks"
if not resolve_path(sdk_path).exists() or len(resolve_path(f"{sdk_path}/*.sdk")) == 0:
log("iOS SDKs not found. Downloading...")
try:
makedirs(sdk_path, exist_ok=True)
command_wrapper(
f"curl -L https://api.github.com/repos/theos/sdks/tarball -o sdks.tar.gz && TMP=$(mktemp -d) && tar -xf sdks.tar.gz --strip=1 -C $TMP && mv $TMP/*.sdk {sdk_path} && rm -r sdks.tar.gz $TMP"
)
except Exception as err:
command_wrapper("rm -rf ./sdks.tar.gz")
error("Failed to download iOS SDKs: " + str(err))
sys_exit(1)
def darwin_install():
"""Install Darwin dependencies."""
xcpath = getoutput(f'{cmd_in_path("xcode-select")} -p')
if not xcpath.endswith(".app/Contents/Developer"):
error("Xcode not found. Please install Xcode from the App Store.")
sys_exit(1)
manager = get_manager()
deps = ["ldid", "xz"]
need = []
for dep in deps:
if cmd_in_path(dep) is None:
need.append(dep)
if need != []:
log(f"Installing dependencies ({', '.join(need)}). Please enter your password if prompted.")
try:
if manager == "apt":
command_wrapper(f"sudo {manager} update && sudo {manager} install -y ldid xz-utils")
elif manager == "port":
command_wrapper(f"sudo {manager} selfupdate && sudo {manager} install -y ldid xz")
elif manager == "brew":
command_wrapper(f"{manager} update && {manager} install -y ldid xz")
else:
error("Could not find a package manager.")
error(f"Please install the missing dependencies before continuing. ({', '.join(need)})")
sys_exit(1)
except Exception as err:
error(f"Failed to install dependencies: {err}")
sys_exit(1)
def linux_install():
"""Install Linux dependencies."""
manager = get_manager()
deps = ["clang", "curl", "perl", "git"]
need = []
for dep in deps:
if cmd_in_path(dep) is None:
need.append(dep)
if need != []:
log(f"Installing dependencies ({', '.join(need)}). Please enter your password if prompted.")
try:
if manager == "apt":
command_wrapper(f"sudo {manager} update && sudo {manager} install -y build-essential curl perl git")
elif manager == "pacman":
command_wrapper(f"sudo {manager} -Syy && sudo {manager} -S --needed --noconfirm base-devel curl perl git")
elif manager == "dnf":
command_wrapper(f'sudo {manager} check-update && sudo {manager} group install -y "C Development Tools and Libraries" && sudo {manager} install -y lzma libbsd curl perl git')
elif manager == "zypper":
command_wrapper(f"sudo {manager} refresh && sudo {manager} install -y -t pattern devel_basis && sudo {manager} install -y libbsd0 curl perl git")
else:
error("Could not find a package manager.")
error(f"Please install the missing dependencies before continuing. ({', '.join(need)})")
sys_exit(1)
except Exception as err:
error(f"Failed to install dependencies: {err}")
sys_exit(1)
toolchain_path = f"{PATH}/toolchain"
if not resolve_path(toolchain_path).exists() or len(resolve_path(f"{toolchain_path}/linux/iphone/*")) == 0:
log("iOS toolchain not found. Downloading...")
arch = getoutput("uname -m")
if arch == "arm64" or arch == "aarch64":
toolchain_uri = "https://github.com/kabiroberai/swift-toolchain-linux/releases/download/v2.2.2/swift-5.7-ubuntu20.04-aarch64.tar.xz"
else:
toolchain_uri = "https://github.com/kabiroberai/swift-toolchain-linux/releases/download/v2.2.2/swift-5.7-ubuntu20.04.tar.xz"
try:
command_wrapper(f"curl -LO {toolchain_uri} && mkdir -p {toolchain_path} && tar -xf swift-5.7-ubuntu20.04*.tar.xz -C {toolchain_path} && rm -r swift-5.7-ubuntu20.04*.tar.xz $TMP")
except Exception as err:
command_wrapper("rm -rf swift-5.7-ubuntu20.04*.tar.xz")
error(f"Failed to download toolchain: {err}")
sys_exit(1)
def main():
"""Main function."""
parser = ArgumentParser()
parser.add_argument("-ns", "--no-sdks", action="store_true", help="Do not install SDKs.")
parser.add_argument("-u", "--update", action="store_true", help="Whether or not to update.")
parser.add_argument("-r", "--ref", type=str, default="main", help="Reference tag of Luz to install.")
args = parser.parse_args()
required = {"luz"}
installed = {pkg.key for pkg in working_set}
missing = required - installed
if not missing and not args.update:
log("luz is already installed.")
sys_exit(0)
elif missing and args.update:
log("luz is not installed.")
sys_exit(0)
if args.update:
log("Updating vendor modules...")
try:
for module in ["headers", "lib", "logos"]:
if resolve_path(f"$HOME/.luz/vendor/{module}").exists():
command_wrapper(f"cd ~/.luz/vendor/{module} && git pull")
except Exception as err:
error(f"Failed to update vendor modules: {err}")
sys_exit(1)
log("Updating luz and its dependencies...")
try:
command_wrapper(
f"{executable} -m pip uninstall -y --break-system-packages luz pydeb pyclang && {executable} -m pip install --break-system-packages https://github.com/LuzProject/luz/archive/refs/heads/{args.ref}.zip"
)
except Exception as err:
error(f"Failed to update luz: {err}")
sys_exit(1)
log("luz has been updated.")
sys_exit(0)
if platform_str.startswith("Darwin") or platform_str.startswith("macOS"):
darwin_install()
elif platform_str.startswith("Linux"):
linux_install()
else:
error(f"Luz is not supported on this platform. ({platform_str})")
sys_exit(1)
if not args.no_sdks:
get_sdks()
log("Installing luz...")
try:
command_wrapper(f"{executable} -m pip install --break-system-packages https://github.com/LuzProject/luz/archive/refs/heads/{args.ref}.zip")
except Exception as err:
error(f"Failed to install luz: {err}")
sys_exit(1)
command_wrapper(f"mkdir -p ~/.luz/lib ~/.luz/headers")
log("luz has been installed.")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
error("Operation cancelled.")
sys_exit(1)