This repository has been archived by the owner on Apr 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
install.py
277 lines (198 loc) · 7.13 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
#!python3
import requests
import os
import sys
import console
import zipfile
import shutil
import json
_OWNER = 'zrzka'
_REPOSITORY = 'blackmamba'
_TMP_DIR = os.environ.get('TMPDIR', os.environ.get('TMP'))
_TMP_TARGET_DIR = os.path.expanduser('~/Documents/site-packages-3/.blackmamba-install')
_TARGET_DIR = os.path.expanduser('~/Documents/site-packages-3/blackmamba')
_RELEASE_INFO_FILE = os.path.join(_TARGET_DIR, '.release.json')
_cleanup_paths = []
def _get_version(release):
version = release['tag_name']
if version.startswith('v'):
version = version[1:]
return version
def _cleanup():
global _cleanup_paths
if _cleanup_paths:
for path in _cleanup_paths:
if not os.path.exists(path):
continue
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except Exception:
pass
_cleanup_paths = None
def _info(message):
print(message)
def _error(message):
sys.stderr.write('{}\n'.format(message))
def _terminate(message):
_error(message)
_cleanup()
sys.exit(1)
def _url(command):
return 'https://api.github.com/repos/{}/{}/{}'.format(_OWNER, _REPOSITORY, command)
def _request(method, command):
url = _url(command)
headers = {
'Accept': 'application/vnd.github.v3+json'
}
response = requests.request(method, url, headers=headers)
if not response.ok:
_terminate('GitHub command {} failed with status code {}'.format(command, response.status_code))
return response
def _get(command):
return _request('GET', command)
def _get_json(command):
try:
return _get(command).json()
except Exception as e:
_error('{}\n'.format(e))
_terminate('Failed to parse JSON from GitHub response')
def _get_latest_release(prerelease=False):
# GitHub doesn't return drafts / prereleases, we just get
# the latest release
_info('Checking latest Black Mamba release...')
if prerelease:
releases = _get_json('releases')
if not releases:
return None
release = releases[0]
else:
release = _get_json('releases/latest')
_info('Latest release {} (tag {}) found'.format(release['name'], release['tag_name']))
return release
def _download_release_zip(release):
_info('Downloading ZIP...')
name = release['name']
path = os.path.join(_TMP_DIR, '{}-{}.zip'.format(_REPOSITORY, name))
_cleanup_paths.append(path)
response = requests.get(release['zipball_url'], stream=True)
console.show_activity()
if not response.ok:
console.hide_activity()
_terminate('GitHub ZIP ball request failed with {}'.format(response.status_code))
try:
with open(path, 'wb') as output:
for data in response.iter_content(8192):
output.write(data)
except Exception as e:
console.hide_activity()
_error(e)
_terminate('Failed to save ZIP file')
console.hide_activity()
return path
def _prepare_dir(path):
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
def _extract_file(zip_file, zip_file_name, file_name):
if file_name.endswith('/'):
if not os.path.exists(file_name):
os.makedirs(file_name)
else:
data = zip_file.read(zip_file_name)
with open(file_name, 'wb') as output:
output.write(data)
def _extract_release(release, path):
_info('Extracting ZIP archive...')
_cleanup_paths.append(_TMP_TARGET_DIR)
try:
_prepare_dir(_TMP_TARGET_DIR)
with open(path, 'rb') as input:
zf = zipfile.ZipFile(input)
top_level_dir = None
for name in zf.namelist():
if not top_level_dir and name.endswith('/'):
top_level_dir = name
continue
if not top_level_dir:
continue
# Strip top level ZIP directory
stripped_name = name[len(top_level_dir):]
if not stripped_name.startswith('blackmamba/'):
continue
# Strip blackmamba/ directory
stripped_name = stripped_name[len('blackmamba/'):]
file_name = os.path.join(_TMP_TARGET_DIR, stripped_name)
_extract_file(zf, name, file_name)
if not top_level_dir:
_terminate('Failed to extract ZIP file')
except Exception as e:
_error(e)
_terminate('Failed to extract ZIP file')
return _TMP_TARGET_DIR
def _move_to_site_packages(extracted_zip_dir):
_info('Moving to site-packages-3 {}...'.format(_TARGET_DIR))
try:
if os.path.exists(_TARGET_DIR):
shutil.rmtree(_TARGET_DIR)
shutil.move(extracted_zip_dir, _TARGET_DIR)
except Exception as e:
_error(e)
_terminate('Failed to move Black Mamba to site-packages-3')
def _local_installation_exists(release):
_info('Checking Black Mamba installation...')
if os.path.islink(_TARGET_DIR):
_terminate('Skipping, Black Mamba symlinked to site-packages-3')
local_version = None
try:
import blackmamba
local_version = blackmamba.__version__
_info('Black Mamba {} installed'.format(local_version))
except ImportError:
_info('Black Mamba not installed')
if local_version is not None:
remote_version = _get_version(release)
try:
if remote_version == local_version:
console.alert(
'Black Mamba Installer',
'Black Mamba {} installed. Do you want to replace it with {}?'.format(local_version, remote_version),
'Replace'
)
else:
console.alert(
'Black Mamba Installer',
'Black Mamba {} installed. Do you want to update it to {}?'.format(local_version, remote_version),
'Update'
)
except KeyboardInterrupt:
_terminate('Cancelling installation on user request')
def _save_release_info(release):
_info('Saving installed version release info')
try:
with open(_RELEASE_INFO_FILE, 'w') as output:
json.dump(release, output)
except Exception as e:
_error(e)
_terminate('Failed to save installed version release info')
def _install(prerelease=False):
release = _get_latest_release(prerelease)
if not release:
_error('Unable to find latest release')
return
_local_installation_exists(release)
path = _download_release_zip(release)
extracted_zip_dir = _extract_release(release, path)
_move_to_site_packages(extracted_zip_dir)
_save_release_info(release)
_cleanup()
_info('Black Mamba {} installed'.format(_get_version(release)))
console.alert(
'Black Mamba {} Installed'.format(_get_version(release)),
'Pythonista RESTART is required for changes to take effect.',
'Got it!', hide_cancel_button=True
)
if __name__ == '__main__':
_install()