-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstall.py
executable file
·289 lines (227 loc) · 8.65 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
#!/usr/bin/env python2.7
import errno
import re
import os
import optparse
import os.path
import platform
import sys
from itertools import product
from contextlib import contextmanager
from subprocess import Popen, PIPE
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
git_urls = (
'[email protected]:amix/vimrc.git',
'[email protected]:junegunn/vim-plug.git',
'[email protected]:anishathalye/dotbot.git',
'[email protected]:pyenv/pyenv.git',
'[email protected]:pyenv/pyenv-doctor.git',
'[email protected]:pyenv/pyenv-installer.git',
'[email protected]:pyenv/pyenv-update.git',
'[email protected]:pyenv/pyenv-virtualenv.git',
'[email protected]:tmux-plugins/tpm.git',
'[email protected]:petervanderdoes/gitflow.git',
'[email protected]:petervanderdoes/git-flow-completion.git',
)
home_dir = os.getenv('HOME')
if home_dir is None:
raise OSError("HOME env. variable must be set")
DEST_REPO_DIR = "{home_dir}/.repos".format(home_dir=home_dir)
def run_command(cmd, verbose):
if verbose:
print("Command: {cmd}".format(cmd=cmd))
process = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
p_stdout, p_stderr = process.communicate()
if verbose:
print(p_stdout.decode('UTF-8'))
p_stderr = p_stderr.decode('UTF-8')
return process.returncode, p_stderr
def get_parser(arguments):
usage = "usage: %prog [options] home|work|none"
parser = optparse.OptionParser(usage=usage)
parser.add_option("-v", "--verbose", dest="verbose", default=False,
help="Print lots of debugging info", action="store_true")
parser.add_option("-n", "--dry-run", dest="dry_run", default=False,
help="Don't actually run any commands", action="store_true")
parser.add_option('-c', "--git_clone", dest='git_clone', default=False, action='store_true',
help="Clone all URLS to {DEST_REPO_DIR}".format(DEST_REPO_DIR=DEST_REPO_DIR))
parser.add_option('-u', "--git_update", dest='git_update', default=False, action='store_true',
help="Update all URLS to {DEST_REPO_DIR}".format(DEST_REPO_DIR=DEST_REPO_DIR))
(options, args) = parser.parse_args(args=arguments)
return options, args, parser
@contextmanager
def working_directory(path):
prev_cwd = os.getcwd()
os.chdir(path)
print("chdir'ing to {path}".format(path=path))
try:
yield
finally:
os.chdir(prev_cwd)
def parse_git_url(git_url):
git_url_regex = re.compile('.*:.*/([-\w]*)\.git')
mo = git_url_regex.match(git_url)
if mo:
return mo.group(1)
else:
raise ValueError("No regex match against git_url {git_url}".format(git_url=git_url))
def clone_repo(name, git_url, opts):
with working_directory(DEST_REPO_DIR):
if opts.verbose:
print("Cloning {name} at {git_url}".format(name=name, git_url=git_url))
cmd = "git clone {git_url}".format(git_url=git_url)
if opts.dry_run:
print("Command: {cmd}".format(cmd=cmd))
return
error_code, stderr = run_command(cmd, verbose=opts.verbose)
if error_code > 0:
raise OSError("cloning of git repo {git_url} failed; "
"error: {stderr}".format(git_url=git_url, stderr=stderr))
else:
print("Cloned: {name}".format(name=name))
def update_repo(name, git_dir, git_url, opts):
with working_directory(git_dir):
cmd = "git pull"
if opts.verbose:
print("Updating {name} at {git_url}".format(name=name, git_url=git_url))
if opts.dry_run:
print("Command: {cmd}".format(cmd=cmd))
return
error_code, stderr = run_command(cmd, verbose=opts.verbose)
if error_code > 0:
raise OSError("Updating of git repo {git_url} failed; error: {stderr}".format(
git_url=git_url, stderr=stderr
))
else:
print("Updated: {name}".format(name=name))
def clone_repos(opts):
for git_url in git_urls:
try:
name = parse_git_url(git_url)
except ValueError as e:
print("Error: {error}".format(error=e))
else:
git_dir = os.path.join(DEST_REPO_DIR, name)
if os.path.exists(git_dir):
print("{name} already exists skipping".format(name=name))
else:
clone_repo(name, git_url, opts)
def update_repos(opts):
for git_url in git_urls:
try:
name = parse_git_url(git_url)
except ValueError as e:
print(e)
else:
git_dir = os.path.join(DEST_REPO_DIR, name)
if os.path.exists(git_dir):
update_repo(name, git_dir, git_url, opts)
else:
print("{name} does not exists; cloning {git_url}".format(name=name, git_url=git_url))
clone_repo(name, git_url, opts)
def run(argv):
(options, args, parser) = get_parser(argv)
if len(argv) < 2:
parser.print_help()
return 1
mkdir_p(DEST_REPO_DIR)
if options.git_clone:
clone_repos(options)
return 0
if options.git_update:
update_repos(options)
return 0
Links(argv, options).run()
return 0
class InstallBase(object):
WORK = 1
HOME = 2
NONE = 3
OSX = 4
LINUX = 5
WINDOWS = 6
def __init__(self, argv, options):
self.argv = argv
self.options = options
# TODO: convert to dict syntax
if self.argv[1].upper() == "WORK":
self.install_type = InstallBase.WORK
elif self.argv[1].upper() == "HOME":
self.install_type = InstallBase.HOME
else:
self.install_type = InstallBase.NONE
# TODO: convert to dict syntax
platform_system = platform.system()
if platform_system.startswith('Darwin'):
self.os_type = InstallBase.OSX
elif platform_system.startswith('Linux'):
self.os_type = InstallBase.LINUX
elif platform_system.startswith('Windows'):
self.os_type = InstallBase.WINDOWS
else:
self.os_type = None
def run(self):
raise NotImplementedError
class Links(InstallBase):
def __init__(self, argv, options):
super(Links, self).__init__(argv, options)
self.base_dir = os.getcwd()
self.config_files = {
InstallBase.WORK: "work",
InstallBase.HOME: "home",
InstallBase.OSX: "osx",
InstallBase.LINUX: "linux",
InstallBase.WINDOWS: "windows",
None: None
}
self.config_file = "install.conf.yaml"
self.dotbot = os.path.join(DEST_REPO_DIR, "dotbot", "bin", "dotbot")
self.verbose = self.quiet = ''
if options.verbose:
self.verbose = '-v'
else:
self.verbose = '-q'
self.dry_run = options.dry_run
def _construct_cmd(self, os_type, install_type):
config_file = self._config_file(os_type, install_type)
if os.path.exists(config_file):
cmd = "{dotbot} -d {base_dir} -c {config_file} " \
"{verbose}".format(dotbot=self.dotbot,
base_dir=self.base_dir,
config_file=config_file,
verbose=self.verbose)
return cmd.strip()
else:
return None
def _config_file(self, os_type, install_type):
os_type_prefix = self.config_files.get(os_type)
install_type_prefix = self.config_files.get(install_type)
prefixes = [install_type_prefix, os_type_prefix]
prefixes = list(filter(None, prefixes))
if prefixes:
prefixes = '.'.join(prefixes)
config_file = "{}.{}".format(prefixes, self.config_file)
else:
config_file = self.config_file
return os.path.join(self.base_dir, 'dotbot', config_file)
def run(self):
configs = list(product([None, self.os_type],
[None, self.install_type]))
extra_configs = ['pyenv', self.os_type, self.install_type]
for extra_config in extra_configs:
configs.append([None, extra_config])
for os_type, install_type in configs:
cmd = self._construct_cmd(os_type, install_type)
if cmd:
return_code, stderr = run_command(cmd, self.verbose)
if return_code > 0:
print("Error: {stderr}".format(stderr=stderr))
if __name__ == '__main__':
sys.exit(run(sys.argv))