-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstall
executable file
·360 lines (289 loc) · 11.7 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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#! /usr/bin/env python3
from __future__ import annotations
import argparse
import collections.abc
import logging
import pathlib
import re
import shutil
import string
import subprocess
import sys
from typing import TYPE_CHECKING
if sys.version_info > (3, 11):
from typing import NoReturn
elif TYPE_CHECKING:
from typing_extensions import NoReturn
XDG_CONFIG_HOME = pathlib.Path.home() / ".config"
THIS_DIR = pathlib.Path(__file__).parent
sys.path.append(str(THIS_DIR))
from installer import STAGE_REGISTRY, Config, DotfileManager, stage, tools # noqa: E402
from installer.utils import colored_diff, configure_logging, confirm, prompt, symlink_exists # noqa: E402
_logger = logging.getLogger("install")
parser = argparse.ArgumentParser(
prog="dotfiles-installer", description="Helper script to install the dotfiles in this repository"
)
parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose output")
parser.add_argument("--email", help="E-Mail address to use for configuration")
parser.add_argument(
"--confirm-all-stages",
"-y",
default=False,
action="store_true",
help="Confirm execution of all stages",
)
skip_stages_group = parser.add_argument_group(
"Skip stages", description="Arguments to skip individual stages of the installation"
)
only_stages_group = parser.add_argument_group(
"Only run stages", description="Arguments to only run individual stages of the installation"
)
SSH_PRIVATE_KEY_PATH = pathlib.Path.home() / ".ssh" / "id_ed25519"
SSH_PUBLIC_KEY_PATH = SSH_PRIVATE_KEY_PATH.with_suffix(".pub")
@stage(
"Create SSH keypair",
predicate=lambda: tools.ssh_keygen.available()
and not (SSH_PRIVATE_KEY_PATH.exists() and SSH_PUBLIC_KEY_PATH.exists()),
interactive_confirm=True,
)
def create_ssh_keypair(cfg: Config) -> None:
subprocess.run( # noqa: S603
[tools.ssh_keygen.path(), "-t", "ed25519", "-f", str(SSH_PRIVATE_KEY_PATH), "-N", '""'],
check=True,
stderr=subprocess.DEVNULL,
)
@stage("Create .gitconfig")
def create_gitconfig(cfg: Config) -> None:
gitconfig_path = pathlib.Path.home() / ".gitconfig"
if cfg.email is None:
cfg = cfg.with_email(prompt("Enter E-Mail address:"))
new_gitconfig_content = string.Template((THIS_DIR / "git" / "config.template").read_text()).safe_substitute(
full_name=cfg.full_name, email=cfg.email, signingkey=str(pathlib.Path.home() / ".ssh" / "id_ed25519.pub")
)
existing_content = gitconfig_path.read_text() if gitconfig_path.exists() else ""
if existing_content == new_gitconfig_content:
_logger.info(".gitconfig is up to date")
return
_logger.info(".gitconfig diff:")
for line in colored_diff(existing_content, new_gitconfig_content):
_logger.info(line.rstrip())
if not cfg.confirm_all_stages and not confirm("Confirm new .gitconfig content?", default="y"):
return
DotfileManager(cfg.timestamp, _logger).safe_write(new_gitconfig_content, gitconfig_path)
@stage(
"Link .gitignore",
predicate=lambda: not symlink_exists(pathlib.Path.home() / ".gitignore", THIS_DIR / "git" / "ignore"),
)
def link_gitignore(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(THIS_DIR / "git" / "ignore", pathlib.Path.home() / ".gitignore")
@stage(
"Link .tmux.conf",
predicate=lambda: not symlink_exists(pathlib.Path.home() / ".tmux.conf", THIS_DIR / "tmux" / "tmux.conf"),
)
def link_tmux_conf(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(
THIS_DIR / "tmux" / "tmux.conf", pathlib.Path.home() / ".tmux.conf"
)
@stage(
"Link .pythonstartup",
predicate=lambda: not symlink_exists(pathlib.Path.home() / ".pythonstartup", THIS_DIR / "python" / "startup"),
)
def link_pythonstartup(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(
THIS_DIR / "python" / "startup", pathlib.Path.home() / ".pythonstartup"
)
@stage(
"Install oh-my-zsh",
interactive_confirm=True,
predicate=lambda: not (pathlib.Path.home() / ".oh-my-zsh").exists(),
abort_on_error=False,
)
def install_omz(cfg: Config) -> None:
subprocess.run( # noqa: S602
(
f'{tools.sh.path()} -c "$({tools.curl.path()} -fsSL '
'https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"'
), # noqa: S607
stdin=subprocess.DEVNULL,
check=True,
shell=True,
)
@stage(
"Install fzf",
interactive_confirm=True,
predicate=lambda: not shutil.which("fzf") and not (pathlib.Path.home() / ".fzf").exists(),
)
def install_fzf(cfg: Config) -> None:
fzf_dir = pathlib.Path.home() / ".fzf"
subprocess.run( # noqa: S603
[
tools.git.path(),
"clone",
"--depth",
"1",
"https://github.com/junegunn/fzf.git",
str(fzf_dir),
],
check=True,
)
subprocess.run([str(fzf_dir / "install")], check=True) # noqa: S603
@stage(
"Install brew bundle",
interactive_confirm=True,
platforms=["Darwin"],
details="This will install all packages listed in the Brewfile",
predicate=lambda: tools.brew.available(),
)
def install_brew_bundle(cfg: Config) -> None:
subprocess.run([tools.brew.path(), "bundle", "install"], check=True, cwd=THIS_DIR / "brew") # noqa: S603
@stage("Install nvm", interactive_confirm=True, predicate=lambda: not (pathlib.Path.home() / ".nvm").exists())
def install_nvm(cfg: Config) -> None:
proc = subprocess.run( # noqa: S603
[
tools.curl.path(),
"-L",
"-s",
"-o",
"/dev/null",
"-w",
"%{url_effective}",
"https://github.com/nvm-sh/nvm/releases/latest",
],
check=True,
stdout=subprocess.PIPE,
encoding="UTF-8",
)
m = re.match(r"https://github\.com/nvm-sh/nvm/releases/tag/(?P<tag>v\d+\.\d+(?:\.\d+))", proc.stdout)
if not m:
raise RuntimeError(f"Redirected URL {proc.stdout} does not match the expected pattern")
subprocess.run( # noqa: S602
f"{tools.curl.path()} -o- https://raw.githubusercontent.com/nvm-sh/nvm/{m.group('tag')}/install.sh | bash",
shell=True,
check=True,
)
@stage(
"Link neovim config",
interactive_confirm=True,
predicate=lambda: not symlink_exists(XDG_CONFIG_HOME / "nvim", THIS_DIR / "nvim"),
)
def link_nvim_config(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(THIS_DIR / "nvim", XDG_CONFIG_HOME)
def validate_vscode_extension_names(extensions: collections.abc.Iterable[str]) -> None:
"""Validate that VSCode extension names contain two elements, publisher and extension, separated by a dot.
Each element must only contain characters, numbers, dashes and underscores.
"""
for extension in extensions:
if not re.match(r"^[\w\d_-]+\.[\w\d_-]+$", extension):
raise ValueError(f"Invalid extension name: {extension}")
@stage("Install VSCode extensions", interactive_confirm=True, abort_on_error=False)
def install_vscode_extensions(cfg: Config) -> None:
try:
code_cmd = tools.code.path()
except tools.ToolNotFoundError:
_logger.error("Executable 'code' is not visible in $PATH")
return
proc = subprocess.run( # noqa: S603
[code_cmd, "--list-extensions"],
stdout=subprocess.PIPE,
encoding="UTF-8",
check=True,
)
available_extensions = set(proc.stdout.splitlines())
validate_vscode_extension_names(available_extensions)
required_extensions = set((THIS_DIR / "vscode" / "vscode-extensions.txt").read_text().splitlines())
validate_vscode_extension_names(required_extensions)
extensions_to_install = required_extensions - available_extensions
if not extensions_to_install:
_logger.info("No extensions to install")
return
args: list[str] = []
for extension in extensions_to_install:
args.append("--install-extension")
args.append(extension)
try:
subprocess.run([code_cmd, *args], check=True) # noqa: S603
except:
_logger.error("Error installing VSCode extensions")
raise
@stage(
"Link .zshrc",
predicate=lambda: not symlink_exists(pathlib.Path.home() / ".zshrc", THIS_DIR / "zsh" / ".zshrc"),
)
def link_zshrc(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(THIS_DIR / "zsh" / ".zshrc", pathlib.Path.home())
if cfg.platform == "Darwin":
DotfileManager(cfg.timestamp, _logger).safe_symlink(THIS_DIR / "zsh" / ".zshrc.macos", pathlib.Path.home())
@stage(
"Link .vimrc",
predicate=lambda: not symlink_exists(pathlib.Path.home() / ".vimrc", THIS_DIR / "vim" / ".vimrc"),
)
def link_vimrc(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(THIS_DIR / "vim" / ".vimrc", pathlib.Path.home())
GHOSTTY_CONFIG_SRC_DIR = THIS_DIR / "ghostty"
GHOSTTY_CONFIG_DEST_DIR = XDG_CONFIG_HOME / GHOSTTY_CONFIG_SRC_DIR.name
@stage(
"Link ghostty config",
predicate=lambda: not symlink_exists(GHOSTTY_CONFIG_DEST_DIR, GHOSTTY_CONFIG_SRC_DIR),
)
def link_ghostty_config(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(GHOSTTY_CONFIG_SRC_DIR, GHOSTTY_CONFIG_DEST_DIR)
KARABINER_CONFIG_SRC_DIR = THIS_DIR / "karabiner"
KARABINER_CONFIG_DEST_DIR = XDG_CONFIG_HOME / KARABINER_CONFIG_SRC_DIR.name
@stage(
"Link Karabiner config",
details="This is the configuration for the Karabiner Elements Keyboard customizer",
predicate=lambda: not symlink_exists(KARABINER_CONFIG_DEST_DIR, KARABINER_CONFIG_SRC_DIR),
platforms=["Darwin"],
)
def link_karabiner_config(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(KARABINER_CONFIG_SRC_DIR, KARABINER_CONFIG_DEST_DIR)
ZED_CONFIG_SRC_DIR = THIS_DIR / "zed"
ZED_CONFIG_DEST_DIR = XDG_CONFIG_HOME / ZED_CONFIG_SRC_DIR.name
@stage(
"Link Zed config",
details="This is the configuration for the Zed editor",
predicate=lambda: not symlink_exists(ZED_CONFIG_DEST_DIR, ZED_CONFIG_SRC_DIR),
)
def link_zed_config(cfg: Config) -> None:
DotfileManager(cfg.timestamp, _logger).safe_symlink(ZED_CONFIG_SRC_DIR, ZED_CONFIG_DEST_DIR)
def add_stage_cli_arguments() -> None:
"""Add arguments to select or exclude individual stages from the installation process."""
for _stage in STAGE_REGISTRY:
flag_name = _stage.flag_name
name = _stage.name
details_text = f". {_stage.details}" if _stage.details else ""
skip_stages_group.add_argument(
f"--no-{flag_name}",
action="append_const",
dest="skipped_stages",
const=flag_name,
help=f"Skip the stage '{name}'{details_text}",
)
only_stages_group.add_argument(
f"--only-{flag_name}",
action="append_const",
dest="only_stages",
const=flag_name,
help=f"Only run the stage '{name}'{details_text}",
)
def main() -> NoReturn:
add_stage_cli_arguments()
namespace = parser.parse_args()
configure_logging(logging.root, namespace.verbose)
try:
cfg = Config.from_env(**vars(namespace))
except Exception as exc:
parser.exit(status=1, message=f"Error creating configuration: {exc}")
missing_tools = tools.missing_required_tools()
if missing_tools:
parser.exit(status=2, message=f"Error: Missing required tools {', '.join(t.name for t in missing_tools)}")
else:
_logger.info("Minimum required required tools are available")
try:
for stage_ in STAGE_REGISTRY:
stage_(cfg)
except KeyboardInterrupt:
parser.exit(status=2, message="\nAborted!\n")
sys.exit(0)
if __name__ == "__main__":
main()