-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathINSTALL
287 lines (232 loc) · 8.29 KB
/
INSTALL
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
#!/usr/bin/python3
import os
import re
import shlex
import subprocess
import sys
from argparse import ArgumentParser
from collections import defaultdict
from pprint import pprint
NOT_SPECIFIED = []
WINDOWS = ["win32", "msys", "cygwin"]
LINUX = ["linux"]
MAC_OS = ["darwin"]
UNIX = ["linux", "darwin"]
LIGHT_GREEN = "\033[92m"
RESET = "\033[0m"
def print_green(string: str):
print(f"{LIGHT_GREEN}{string}{RESET}")
def exec_cmd(command: str | list, hide_stdout: bool = False):
if isinstance(command, str):
command = shlex.split(command)
out = subprocess.DEVNULL if hide_stdout else None
r = subprocess.run(command, stdout=out)
return r.returncode
def find_bin(name: str):
command = "where" if sys.platform == "win32" else "which"
return exec_cmd(f"{command} {name}", True) == 0
class PackageManager:
templates: dict[str, str] # command templates for installing, removing and updating a package
sudo: bool = False # run with sudo
platforms = NOT_SPECIFIED # platfroms package manager is supported on
dont_ask: bool = True # don't ask for conformation when installing packages. needs 'autoconfirm' to be set to work.
autoconfirm: str = None # flag that makes the package manager not ask for conformation when installing a package
def __init__(self) -> None:
self.binary = self.__class__.__name__
if self.dont_ask and self.autoconfirm is None:
self.autoconfirm = ""
self.failed = defaultdict(list)
self.total = 0
self.n_succesfull = 0
self.available = self.is_available()
if not self.available:
print(f"{self.binary} is not available.")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
pass
def install(self, package: str):
"""Install a package"""
print_green(f"[{self.binary}] installing package '{package}' ...")
return self.__run("install", package)
def remove(self, package: str):
"""Remove a package"""
print_green(f"[{self.binary}] removing package '{package}' ...")
return self.__run("remove", package)
def update(self, package: str):
"""Update a package"""
print_green(f"[{self.binary}] updating package '{package}' ...")
return self.__run("update", package)
def is_available(self):
"""Check if package manager is installed by trying to find its binary"""
return find_bin(self.binary)
def is_supported(self):
"""Check if the package manager is supported on your platform"""
if len(self.platforms) == 0:
return True
return sys.platform in self.platforms
def get_stats(self):
return {
"total": self.total,
"succesfull": self.n_succesfull,
"failed": dict(self.failed),
}
def __run(self, template: str, name: str):
self.total += 1
if not self.available:
self.failed[template].append(name)
return
sudo = "sudo" if self.sudo else ""
template = self.__get_template(template)
template = template.replace("{name}", name)
command = f"{sudo} {self.binary} {template} {self.autoconfirm}"
r = exec_cmd(command=command)
if r != 0:
self.failed[template].append(name)
else:
self.n_succesfull += 1
print("_" * 64)
return r
def __get_template(self, t: str):
try:
return self.templates[t]
except KeyError:
raise KeyError(f"command '{t}' is not supported for {self.binary}")
class apt(PackageManager):
templates: dict[str, str] = {
"install": "install {name}",
"remove": "remove {name}",
}
autoconfirm: str = "-y"
sudo: bool = True
def __init__(self) -> None:
super().__init__()
exec_cmd("sudo apt-get update")
class pip(PackageManager):
templates: dict[str, str] = {
"install": "install {name}",
"remove": "uninstall {name}",
"update": "install {name} -U",
}
def __init__(self) -> None:
super().__init__()
if sys.platform in UNIX:
self.binary = "pip3"
class scoop(PackageManager):
templates: dict[str, str] = {
"install": "install {name}",
"remove": "uninstall {name}",
"update": "update {name}",
}
platforms = WINDOWS
class brew(PackageManager):
templates: dict[str, str] = {
"install": "install {name}",
"remove": "remove {name}",
}
sudo: bool = False
platforms = UNIX
class snap(PackageManager):
sudo = True
templates: dict[str, str] = {
"install": "install {name}",
"remove": "remove {name}",
"update": "refresh {name} -U",
}
platforms = LINUX
class flatpak(PackageManager):
sudo = True
templates: dict[str, str] = {
"install": "install flathub {name}",
"remove": "uninstall {name}",
"update": "update {name}",
}
platforms = LINUX
def __init__(self) -> None:
super().__init__()
exec_cmd(
"flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo"
)
class code(PackageManager):
templates: dict[str, str] = {
"install": "--install-extension {name} --force",
"update": "--install-extension {name} --force",
"remove": "--uninstall-extension {name}",
}
class cargo(PackageManager):
templates: dict[str, str] = {
"install": "install {name}",
"update": "install {name}",
"remove": "uninstall {name}",
}
PACKAGE_MANAGERS = {i.__name__: i for i in PackageManager.__subclasses__()}
def parse_file(filepath: str):
with open(filepath, "r", encoding="utf-8") as f:
data = f.read().splitlines()
data = [i.strip() for i in data]
data = [i for i in data if i and i[0] != "#"]
packages = defaultdict(list)
current_pm = None
for line in data:
if re.match(r"\[+[\w]+\]+", line):
pm = line[1:-1]
current_pm = pm
else:
if current_pm is None:
raise ValueError("Invalid file formatting.")
if line not in packages[current_pm]:
packages[current_pm].append(line)
return packages
def install(packages: dict):
stats = {}
for pkg_manager, packages in packages.items():
with PACKAGE_MANAGERS[pkg_manager]() as pkg_man:
for i in packages:
pkg_man.install(i)
stats[pkg_manager] = pkg_man.get_stats()
pprint(stats)
print()
def install_dotfiles():
home = os.path.expanduser("~")
commands = [
f"sudo cp {home}/.bashrc {home}/.bashrc.old",
f"sudo cp ./dotfiles/.bashrc {home}/.bashrc",
"echo Current .bashrc was backed up to '~/.bashrc.old'",
f"sudo cp -r {home}/.config {home}/.config_old",
f"sudo cp -r ./.config {home}/.config",
"echo Current .config folder was backed up to '~/.config_old'",
]
for i in commands:
exec_cmd(i)
def install_bin():
progs = os.scandir("./bin")
progs = [i.path for i in progs if i.is_file()]
for i in progs:
name = os.path.basename(i)
print(f"Adding '{name}' to $PATH ...")
exec_cmd(f"sudo cp {i} /usr/local/bin/{name}")
if __name__ == "__main__":
if len(sys.argv) < 2:
py = "python" if sys.platform in WINDOWS else "python3"
exit(exec_cmd(f"{py} {sys.argv[0]} --help"))
lists = os.scandir("./packages")
lists = [i.path for i in lists if i.is_file()]
packages_mapping = {os.path.basename(i).split(".")[0]: i for i in lists}
ap = ArgumentParser()
ap.add_argument("-bin", action="store_true", help=f"add scripts inside './bin' to your $PATH")
ap.add_argument("-dotfiles", action="store_true", help="install dotfiles")
for name, filepath in packages_mapping.items():
ap.add_argument(
f"-{name}",
action="store_true",
help=f"install packages listed in '{filepath}'",
)
args = ap.parse_args()
for arg, val in args.__dict__.items():
if arg in packages_mapping and val == True:
packages = parse_file(packages_mapping[arg])
install(packages)
if args.dotfiles:
install_dotfiles()
if args.bin:
install_bin()