-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinstall.py
More file actions
441 lines (347 loc) · 12.2 KB
/
install.py
File metadata and controls
441 lines (347 loc) · 12.2 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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#!/usr/bin/env python
import glob
import os
import shlex
import subprocess
import sys
from abc import ABC, abstractmethod
from dataclasses import dataclass
# ====================
# Interfaces
# ====================
class FileSystemInterface(ABC):
"""Abstract interface for file system operations"""
@abstractmethod
def exists(self, path: str) -> bool:
pass
@abstractmethod
def create_symlink(self, src: str, dst: str) -> None:
pass
@abstractmethod
def remove(self, path: str) -> None:
pass
@abstractmethod
def makedirs(self, path: str, exist_ok: bool = False) -> None:
pass
@abstractmethod
def list_files(self, pattern: str) -> list[str]:
pass
@abstractmethod
def is_symlink(self, path: str) -> bool:
pass
class CommandRunnerInterface(ABC):
"""Abstract interface for running commands"""
@abstractmethod
def run(self, command: str) -> bool:
pass
@abstractmethod
def which(self, command: str) -> bool:
pass
class OutputInterface(ABC):
"""Abstract interface for output handling"""
@abstractmethod
def info(self, msg: str) -> None:
pass
@abstractmethod
def success(self, msg: str) -> None:
pass
@abstractmethod
def warn(self, msg: str) -> None:
pass
@abstractmethod
def fail(self, msg: str) -> None:
pass
# ====================
# Concrete Implementations
# ====================
class FileSystem(FileSystemInterface):
"""Real file system implementation"""
def exists(self, path: str) -> bool:
return os.path.exists(path)
def create_symlink(self, src: str, dst: str) -> None:
os.symlink(src, dst)
def remove(self, path: str) -> None:
os.remove(path)
def makedirs(self, path: str, exist_ok: bool = False) -> None:
os.makedirs(path, exist_ok=exist_ok)
def list_files(self, pattern: str) -> list[str]:
return glob.glob(pattern)
def is_symlink(self, path: str) -> bool:
return os.path.islink(path)
class CommandRunner(CommandRunnerInterface):
"""Real command runner implementation"""
def run(self, command: str) -> bool:
try:
subprocess.check_call(shlex.split(command))
return True
except subprocess.CalledProcessError:
return False
def which(self, pgm: str) -> bool:
path = os.getenv("PATH")
for p in path.split(os.path.pathsep):
p = os.path.join(p, pgm)
if os.path.exists(p) and os.access(p, os.X_OK):
return True
return False
class ColoredOutput(OutputInterface):
"""Colored terminal output implementation"""
SUCCESS = "\033[92m" # Green
WARNING = "\033[93m" # Yellow
DANGER = "\033[91m" # Red
PRIMARY = "\033[94m" # Blue
BOLD = "\033[1m"
END = "\033[0m"
def _print(self, color: str, msg: str) -> None:
print(f"{color}{msg}{self.END}")
def info(self, msg: str) -> None:
self._print(self.BOLD, msg)
def success(self, msg: str) -> None:
self._print(self.SUCCESS, msg)
def warn(self, msg: str) -> None:
self._print(self.WARNING, msg)
def fail(self, msg: str) -> None:
self._print(self.DANGER, msg)
# ====================
# Configuration
# ====================
@dataclass
class DotfilesConfig:
"""Configuration for dotfiles installation"""
home_dir: str
dotfiles_dir: str
repo_url: str = "https://github.com/ryosan-470/dotfiles.git"
exclude_patterns: set = None
required_commands: list[str] = None
def __post_init__(self):
if self.exclude_patterns is None:
self.exclude_patterns = {
".git",
".git_commit_template.txt",
".gitignore",
".circleci",
".gitmodules",
".github",
}
if self.required_commands is None:
self.required_commands = ["tmux", "zsh", "vim", "git"]
@classmethod
def default(cls):
"""Create default configuration"""
home = os.path.expanduser("~")
return cls(
home_dir=home, dotfiles_dir=os.path.join(home, ".dotconfig/dotfiles")
)
def get_dotfiles(self) -> list[tuple[str, str]]:
"""Get list of (src, dst) pairs for all files to be linked"""
pattern = os.path.join(self.dotfiles_dir, ".*")
basenames = set(os.path.basename(f) for f in glob.glob(pattern))
basenames -= self.exclude_patterns
links = [
(
os.path.join(self.dotfiles_dir, name),
os.path.join(self.home_dir, name),
)
for name in basenames
]
# Extra links (subdirectory files)
claude_settings = os.path.join(self.dotfiles_dir, "claude", "settings.json")
if os.path.exists(claude_settings):
links.append(
(
claude_settings,
os.path.join(self.home_dir, ".claude", "settings.json"),
)
)
claude_md = os.path.join(self.dotfiles_dir, "claude", "CLAUDE.md")
if os.path.exists(claude_md):
links.append(
(
claude_md,
os.path.join(self.home_dir, ".claude", "CLAUDE.md"),
)
)
return links
# ====================
# Main Installer Class
# ====================
class DotfilesInstaller:
"""Main installer class with dependency injection"""
def __init__(
self,
config: DotfilesConfig,
fs: FileSystemInterface,
runner: CommandRunnerInterface,
output: OutputInterface,
):
self.config = config
self.fs = fs
self.runner = runner
self.output = output
def check_requirements(self) -> bool:
"""Check if all required commands are available"""
missing = [
cmd for cmd in self.config.required_commands if not self.runner.which(cmd)
]
if missing:
self.output.warn(f"Please install the command: {', '.join(missing)}")
return False
return True
def download(self, branch: str = "master") -> bool:
"""Clone the dotfiles repository"""
self.output.info(f"Clone repository. branch is {branch}")
if self.fs.exists(self.config.dotfiles_dir):
self.output.success("✓ Skip to clone repository since it has been existed")
return True
command = (
f"git clone -b {branch} {self.config.repo_url} {self.config.dotfiles_dir}"
)
self.output.info(command)
if self.runner.run(command):
self.output.success("✓ Finished to clone repository")
return True
else:
self.output.fail("✗ Download failed. Please check your internet connection")
return False
def deploy(self) -> bool:
"""Create symlinks for dotfiles"""
success = True
for src, dst in self.config.get_dotfiles():
try:
dst_dir = os.path.dirname(dst)
if dst_dir != self.config.home_dir:
self.fs.makedirs(dst_dir, exist_ok=True)
if self.fs.exists(dst):
self.output.warn(f"{src} ==> {dst} has been already existed")
else:
self.fs.create_symlink(src, dst)
self.output.success(f"✓ linking {src} ==> {dst}")
except Exception as e:
self.output.fail(f"✗ Failed to link {src} ==> {dst}: {e}")
success = False
return success
def clean(self) -> bool:
"""Remove symlinks"""
success = True
for _, dst in self.config.get_dotfiles():
try:
if self.fs.exists(dst):
self.fs.remove(dst)
self.output.success(f"✓ Removed {dst}")
else:
self.output.warn(
f"✘ {dst} cannot remove because it has already removed"
)
except Exception as e:
self.output.fail(f"✘ {dst} cannot remove: {e}")
success = False
if success:
self.output.success("✓ Cleaned!")
else:
self.output.fail("✘ Failed to execute clean!")
return success
def initialize(self) -> bool:
"""Run initialization scripts"""
init_dir = os.path.join(self.config.dotfiles_dir, "init")
if not self.fs.exists(init_dir):
self.output.warn("No init directory found")
return True
scripts = [
f
for f in self.fs.list_files(os.path.join(init_dir, "*"))
if not f.endswith("README.md")
]
success = True
for script in scripts:
self.output.info(f"Run: {script}")
if not self.runner.run(f"bash {script}"):
self.output.fail(f"Failed to run {script}")
success = False
return success
def verify(self) -> bool:
"""Verify installation"""
failed = False
for _, dst in self.config.get_dotfiles():
if self.fs.exists(dst):
self.output.success(f"✓ {dst}")
else:
self.output.warn(f"✘ {dst}")
failed = True
if failed:
self.output.fail("✘ Some tests are failed")
return False
else:
self.output.success("✔ All test passed")
return True
def install(self) -> bool:
"""Run full installation"""
self.output.info("==> Start install progress...")
if not self.check_requirements():
self.output.fail("✗ Please install requirements first!")
return False
self.output.info("==> Clone repository from GitHub")
if not self.download():
return False
self.output.info("==> Start to deploy")
if not self.deploy():
self.output.fail("✗ Deploying failed.")
return False
self.output.success("✓ Finished to deploy")
self.output.info("==> initializing")
self.initialize()
self.output.info("==> Start to test")
return self.verify()
# ====================
# CLI Interface
# ====================
def create_installer() -> DotfilesInstaller:
"""Factory function to create installer with real implementations"""
config = DotfilesConfig.default()
return DotfilesInstaller(
config=config, fs=FileSystem(), runner=CommandRunner(), output=ColoredOutput()
)
def main():
import argparse
parser = argparse.ArgumentParser(
description="The setup script for dotfiles. Linux and Mac OSX supports."
)
subparsers = parser.add_subparsers(dest="command", help="Commands")
# Download command
download_cmd = subparsers.add_parser(
"download", help="Clone repository from GitHub"
)
download_cmd.add_argument(
"branch", nargs="?", default="master", help="Branch to clone"
)
# Other commands
subparsers.add_parser("deploy", help="Deploy dotfiles to your home directory")
subparsers.add_parser(
"init", help="To initialize: make file or install dependencies"
)
subparsers.add_parser("test", help="Test section using Travis-CI")
subparsers.add_parser("clean", help="Remove linking files")
subparsers.add_parser("all", help="Do download, deploy and init")
args = parser.parse_args()
# Default to 'all' if no command specified
if not args.command:
args.command = "all"
# Create installer
installer = create_installer()
# Execute command
if args.command == "download":
success = installer.download(args.branch)
elif args.command == "deploy":
success = installer.deploy()
elif args.command == "init":
success = installer.initialize()
elif args.command == "test":
success = installer.verify()
elif args.command == "clean":
success = installer.clean()
elif args.command == "all":
success = installer.install()
else:
parser.print_help()
success = False
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()