-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.py
224 lines (190 loc) · 7 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
import collections
from contextlib import contextmanager
from glob import glob
import json
from subprocess import check_output, STDOUT, CalledProcessError
from tempfile import NamedTemporaryFile
import sys
import os
def is_str(s):
return isinstance(s, str)
def getpath(source):
if "@" in source:
# SSH
chunks = source.split(":")[-1].split("/")
site = source.split("@")[-1].split(":")[0]
user = chunks[0]
repo = chunks[-1].replace(".git", "")
else:
url = source.split("://")[-1]
chunks = url.split("/")
site, user, repo = chunks[:3]
return site, user, repo
@contextmanager
def chdir(path):
current = os.getcwd()
os.chdir(path)
yield
os.chdir(current)
def mkdir(path):
try:
os.makedirs(path)
except OSError as err:
if err.errno == 17:
# ERREXISTS
pass
else:
raise
def runcmd(cmd):
try:
out = check_output(cmd, shell=True, stderr=STDOUT)
except CalledProcessError as e:
out = e.stdout
err = e.stderr
if out is not None:
print(out.strip().decode(errors="ignore"))
if err is not None:
print(err.strip().decode(errors="ignore"))
raise
return out.strip().decode(errors="ignore")
def install_sources(sources):
# TODO: install from git if necessary under ~/.config/shell/SOURCE/NAME/repo
# TODO: handle the rest as normal
mkdir(os.path.expanduser("~/.config/zsh/repos"))
for source, config in sources.items():
if isinstance(config, str):
config = {"destination": config}
if isinstance(config, dict):
site, user, repo = getpath(source)
repo_dir = os.path.expanduser(
config.get(
"destination",
"~/.config/zsh/repos/{}/{}-{}".format(site, user, repo),
)
)
if not os.path.isdir(repo_dir):
print("Cloning {}".format(source))
runcmd("git clone {} {}".format(source, repo_dir))
else:
print("Updating {}".format(source))
with chdir(repo_dir):
runcmd("git pull origin master")
# Add the repo dir
symlinks = {
"{}/{}".format(repo_dir, k): v
for k, v in config.get("symlinks", {}).items()
}
install_symlinks(symlinks)
post_install(config)
else:
raise TypeError("Invalid source block of type '{}'".format(type(config)))
def install_symlinks(config):
for src, dst in config.items():
# TODO: install
if not (src.startswith("/") or src.startswith("~")):
# relative paths are made absolute here
src = os.path.join(os.getcwd(), src)
sources = sorted(glob(os.path.expanduser(src)))
if not sources:
continue
if dst.endswith("/"):
# Its a directory. each file should be copied
for path in sources:
mkdir(os.path.expanduser(dst))
ldst = os.path.expanduser("{}{}".format(dst, os.path.basename(path)))
if os.path.islink(ldst):
os.unlink(ldst)
elif os.path.exists(ldst):
raise RuntimeError(
"{} already exists and is not controlled by us!".format(ldst)
)
assert not os.path.islink(ldst)
path = os.path.expanduser(path)
os.symlink(path, ldst, target_is_directory=os.path.isdir(path))
elif os.path.isfile(sources[0]):
# Combine/link into file
dst = os.path.expanduser(dst)
mkdir(os.path.dirname(dst))
with open(dst, "w") as outf:
outf.write("# AUTOMATICALLY GENERATED DO NOT EDIT! \n")
for path in sources:
with open(path, "r") as f:
outf.write("## {}\n".format(path))
outf.write(f.read())
outf.write("\n")
elif os.path.isdir(sources[0]):
ldst = os.path.expanduser(dst)
if os.path.islink(ldst):
os.unlink(ldst)
elif os.path.exists(ldst):
raise RuntimeError(
"{} already exists and is not controlled by us!".format(ldst)
)
assert not os.path.islink(ldst)
os.symlink(os.path.expanduser(path), ldst, target_is_directory=True)
def install_taps(taps):
for tap in taps:
runcmd("brew tap {}".format(tap))
def install_brew(pkgs, tags):
already_installed = set(runcmd("brew list").strip().split("\n"))
to_install = set(pkgs) - already_installed
if to_install:
print("Installing {} homebrew formulae".format(len(to_install)))
with NamedTemporaryFile("w") as tf:
tf.write("\n".join(to_install))
tf.flush()
runcmd("xargs <{} brew install".format(tf.name))
def install_casks(pkgs, tags):
# These need to be installed in a usable command line as some casks
# ask for a password
already_installed = set(runcmd("brew cask list").strip().split("\n"))
casks = []
for cask in pkgs:
if is_str(cask):
casks.append(cask)
elif isinstance(cask, dict):
if "name" in cask and "when" in cask and cask["when"] in tags:
casks.append(cask["name"])
to_install = set(casks) - already_installed
if to_install:
with open("/tmp/casks", "w") as f:
f.write("\n".join(to_install))
def install_mas(apps, tags):
appids = [runcmd(['mas search "{}"'.format(app)]).split(" ")[0] for app in apps]
already_installed = set(
c.split()[0] for c in runcmd("mas list").strip().split("\n")
)
to_install = set(appids) - already_installed
if to_install:
print("Installing {} apps from the Mac App Store".format(len(to_install)))
with NamedTemporaryFile() as tf:
tf.write("\n".join(to_install))
tf.flush()
runcmd("xargs <{} mas install".format(tf.name))
def check_install_deps_macos():
pass
def post_install(config):
scripts = config.get("post-install", [])
if isinstance(scripts, str):
scripts = [scripts]
for script in scripts:
runcmd(script)
def install_from_config(config_file, tags):
with open(config_file, "r") as f:
config = json.loads(f.read(), object_pairs_hook=collections.OrderedDict)
try:
os.mkdir(os.path.expanduser("~/.config/zsh"))
except OSError:
pass
# FIXME: only do the following four on macos hosts
install_sources(config.get("sources", {}))
install_symlinks(config.get("symlinks", {}))
post_install(config)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("{}: CONFIG [TAGS]")
sys.exit(1)
tags = []
if len(sys.argv) > 2:
tags = sys.argv[2:]
install_from_config(sys.argv[1], tags)