This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
deploy.py
executable file
·334 lines (281 loc) · 9.61 KB
/
deploy.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python3
import argparse
from contextlib import contextmanager
import logging
import os
from pathlib import Path
import platform
import shutil
import subprocess as sp
from typing import Optional
logging.basicConfig(
level=logging.WARNING, format="[%(asctime)s] %(levelname)7s:%(message)s"
)
logger = logging.getLogger("deploy")
class Deployer(object):
@classmethod
def deploy(cls) -> None:
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--dry-run", action="store_true", default=False)
parser.add_argument(
"-H",
"--homebrew",
action="store_true",
default=False,
help="Install homebrew bundles (if on macos)",
)
parser.add_argument("-f", "--force", action="store_true", default=False)
parser.add_argument(
"-c",
"--compile",
action="store_true",
default=False,
help="Compile packages under `external`",
)
parser.add_argument(
"-r",
"--root",
required=False,
default=Path.home(),
type=Path,
help="Install to a different root directory [default = home]",
)
parser.add_argument("-v", "--verbose", action="count")
args = parser.parse_args()
if args.verbose is not None:
if args.verbose == 1:
logger.setLevel(logging.INFO)
elif args.verbose > 1:
logger.setLevel(logging.DEBUG)
logger.info("deploying dotfiles")
logger.debug("debug logging enabled")
self = cls(args)
self.run()
def __init__(self, args) -> None:
self.args = args
@property
def dry_run(self):
return self.args.dry_run
@property
def force(self):
return self.args.force
@property
def compile(self):
return self.args.compile
@property
def root(self):
return self.args.root
@property
def homebrew(self):
return self.args.homebrew
def run(self) -> None:
# self.deploy_standard_dirs()
# self.deploy_dotconfig_files()
# if self.macos():
# if not self.homebrew:
# logger.warning(
# "not installing homebrew packages as `-H/--homebrew` not specified"
# )
# else:
# homebrew = Homebrew()
# homebrew.install()
# homebrew.install_packages()
self.deploy_vscode_extensions()
exit()
if self.compile:
self.install_custom_binaries()
else:
logger.warning(
"`-c/--compile` not supplied, not compiling packages under `external`"
)
def deploy_standard_dirs(self, install_path: Optional[Path] = None) -> None:
dirnames = [
"vim",
"zsh",
"tmux",
"bin",
"conda",
"emacs",
"git",
"hammerspoon",
"i3",
"ipython",
"jupyter",
"mutt",
"pgcli",
"postgresql",
"xinitrc",
"xresources",
"xmodmap",
"oj",
"taskwarrior",
]
for dirname in dirnames:
src = Path.cwd().joinpath(dirname).resolve()
self.deploy_standard_dir(src, install_path=install_path)
def deploy_standard_dir(
self, dirname: Path, install_path: Optional[Path] = None
) -> None:
if install_path is None:
install_path = self.root.resolve()
logger.info("deploying %s", dirname)
source = Path.cwd().resolve().joinpath(dirname)
for src in source.glob("*"):
dst = install_path.joinpath(f".{src.name}")
logger.debug("- deploying %s to %s", src, dst)
if dst.exists() and not self.force:
logger.debug("--> path exists, skipping")
continue
self._force_symlink_to(src, dst)
logger.debug("--> linking complete")
def deploy_dotconfig_files(self):
macos_specific_locations = {"hookman"}
for subdir in [
"alacritty",
"bat",
"bspwm",
"direnv",
"efm-langserver",
"fish",
"helix",
"hookman",
"karabiner",
"kitty",
"nvim",
"picom",
"polybar",
"rofi",
"starship",
"sxhkd",
"wezterm",
]:
macos_specific = self.macos() and subdir in macos_specific_locations
self.deploy_dotconfig_file(subdir, macos_specific)
def deploy_vscode_extensions(self):
logger.info("deploying vs code extensions")
dest = Path.home() / ".vscode" / "extensions"
dest.mkdir(exist_ok=True, parents=True)
src = Path.cwd() / "vscode"
logger.debug(f"installing extensions from {src} to {dest}")
for extension in src.glob("*"):
stub = dest / extension.name
logger.debug(f"installing {extension} to {stub}")
self._force_symlink_to(extension, stub)
def deploy_dotconfig_file(self, subdir, macos_specific):
if macos_specific:
root = Path.home() / "Library" / "Application Support"
else:
root = self.root.resolve() / ".config"
srcs = Path.cwd().joinpath(subdir).glob("*")
for src in srcs:
dest = root.joinpath(subdir, src.name)
self._deploy_single_file(src, dest)
def deploy_kitty_config(self):
srcs = (Path.cwd() / "kitty" / "kitty").glob("*")
dest_dir = self.root / "Library" / "Preferences" / "kitty"
for src in srcs:
logger.info("deploying %s", src)
dest = dest_dir / src.name
if dest.exists() and not self.force:
logger.debug("--> path exists, skipping")
continue
self._force_symlink_to(src, dest)
logger.debug("--> linking complete")
def install_rust_packages(self):
if not self._binary_exists("cargo"):
logger.warning(
"cannot find rust installation, skipping installing rust binaries"
)
return
subdirs = [
"external/git-identity-manager",
"external/mkflashdriverepo",
"external/hookman",
"external/listprojects",
"external/pm",
]
for subdir in subdirs:
if not os.path.isdir(subdir):
continue
cmd = ["cargo", "install", "--path", subdir]
sp.run(cmd)
def install_custom_binaries(self):
if not self._binary_exists("go"):
logger.warning("cannot find go compiler, skipping installing git-bug")
return
# git-bug
logger.debug("compiling and installing external/git-bug")
cmd = ["make", "-C", str(Path.cwd() / "external" / "git-bug"), "install"]
sp.run(cmd)
# gomodinit
logger.debug("compiling and installing external/gomodinit")
with self._chdir("external/gomodinit"):
cmd = ["go", "install"]
sp.run(cmd)
# install-default-precommit
logger.debug("compiling and installing external/install-default-precommit")
with self._chdir("external/install-default-precommit"):
cmd = ["go", "install"]
sp.run(cmd)
logger.debug("compiling and installing external/listprojects")
with self._chdir("external/listprojects"):
cmd = ["go", "install"]
sp.run(cmd)
self.install_rust_packages()
def _deploy_single_file(self, src, dest):
dest.parent.mkdir(parents=True, exist_ok=True)
logger.info("deploying %s -> %s", src, dest)
if dest.exists() and not self.force:
logger.debug("--> path exists, skipping")
return
self._force_symlink_to(src, dest)
logger.debug("--> linking complete")
def _binary_exists(self, name):
pathvar = os.environ["PATH"]
for component in pathvar.split(":"):
if not component:
continue
loc = Path(component)
if not loc.is_dir():
continue
if loc / name:
return True
return False
@contextmanager
def _chdir(self, path):
oldpath = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(oldpath)
def macos(self):
return platform.system() == "Darwin"
@staticmethod
def _force_symlink_to(src, dest):
"""
Ensures that the symlink clobbers the destination.
"""
try:
dest.symlink_to(src)
except FileExistsError:
try:
shutil.rmtree(dest)
except (OSError, NotADirectoryError):
os.remove(dest)
dest.symlink_to(src)
class Homebrew(object):
def install(self):
# TODO install homebrew itself. Note: this requires user interaction to disable SIP etc.
pass
def install_packages(self):
# Check that we have a Brewfile in the current directory
if not (Path.cwd() / "Brewfile").is_file():
raise RuntimeError("cannot find brewfile in current directory")
# Run the command
cmd = ["brew", "bundle"]
logger.info("deploying homebrew packages")
logger.debug("running command: %s", cmd)
sp.run(cmd)
if __name__ == "__main__":
Deployer.deploy()