-
Notifications
You must be signed in to change notification settings - Fork 2
/
install.py
589 lines (477 loc) · 17.4 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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# -*- coding: utf-8 -*-
"""
WakaTime Plugin Installer for Wing IDE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Downloads and installs the WakaTime Plugin for Wing IDE, Personal, 101.
:copyright: (c) 2017 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import contextlib
import json
import os
import platform
import re
import shutil
import ssl
import subprocess
import sys
import traceback
from subprocess import PIPE
from zipfile import ZipFile
try:
from ConfigParser import SafeConfigParser as ConfigParser
from ConfigParser import Error as ConfigParserError
except ImportError:
from configparser import ConfigParser, Error as ConfigParserError
try:
from urllib2 import Request, urlopen, HTTPError
except ImportError:
from urllib.request import Request, urlopen
from urllib.error import HTTPError
GITHUB_RELEASES_STABLE_URL = 'https://api.github.com/repos/wakatime/wakatime-cli/releases/latest'
GITHUB_DOWNLOAD_PREFIX = 'https://github.com/wakatime/wakatime-cli/releases/download'
ROOT_URL = 'https://raw.githubusercontent.com/wakatime/wing-wakatime/master/'
SRC_DIR = os.path.dirname(os.path.abspath(__file__))
FILE = 'wakatime.py'
PLUGIN = 'wing'
is_py2 = (sys.version_info[0] == 2)
is_py3 = (sys.version_info[0] == 3)
is_win = platform.system() == 'Windows'
CONFIG_DIRS = []
if is_win:
for i in range(6, 99):
CONFIG_DIRS.append(os.path.join(os.getenv('APPDATA'), 'Wing IDE {0}'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.getenv('APPDATA'), 'Wing IDE {0}.0'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.getenv('APPDATA'), 'Wing Personal {0}.0'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.getenv('APPDATA'), 'Wing Personal {0}'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.getenv('APPDATA'), 'Wing 101 {0}'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.getenv('APPDATA'), 'Wing 101 {0}.0'.format(i), 'scripts'))
else:
for i in range(6, 99):
CONFIG_DIRS.append(os.path.join(os.path.expanduser('~'), '.wingide{0}'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.path.expanduser('~'), '.wingpersonal{0}'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.path.expanduser('~'), '.wing101-{0}'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.path.expanduser('~'), 'Library', 'Application Support', 'Wing 101', 'v{0}'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.path.expanduser('~'), 'Library', 'Application Support', 'Wing Personal', 'v{0}'.format(i), 'scripts'))
CONFIG_DIRS.append(os.path.join(os.path.expanduser('~'), 'Library', 'Application Support', 'Wing Pro', 'v{0}'.format(i), 'scripts'))
HOME_FOLDER = None
CONFIGS = None
INTERNAL_CONFIGS = None
if is_py2:
import codecs
open = codecs.open
input = raw_input # noqa: F821
def u(text):
if text is None:
return None
if isinstance(text, unicode): # noqa: F821
return text
try:
return text.decode('utf-8')
except:
try:
return text.decode(sys.getdefaultencoding())
except:
try:
return unicode(text) # noqa: F821
except:
try:
return text.decode('utf-8', 'replace')
except:
try:
return unicode(str(text)) # noqa: F821
except:
return unicode('') # noqa: F821
elif is_py3:
def u(text):
if text is None:
return None
if isinstance(text, bytes):
try:
return text.decode('utf-8')
except:
try:
return text.decode(sys.getdefaultencoding())
except:
pass
try:
return str(text)
except:
return text.decode('utf-8', 'replace')
else:
raise Exception('Unsupported Python version: {0}.{1}.{2}'.format(
sys.version_info[0],
sys.version_info[1],
sys.version_info[2],
))
def main(home=None):
global CONFIGS, HOME_FOLDER
if home:
HOME_FOLDER = home
CONFIGS = parseConfigFile(getConfigFile())
# download wakatime-cli
if not isCliLatest():
downloadCLI()
createSymlink()
# download plugin
contents = get_file_contents(FILE)
if not contents:
return
# add plugin to config folders
for folder in CONFIG_DIRS:
if os.path.exists(os.path.dirname(folder)):
if not os.path.exists(folder):
os.mkdir(folder)
save_file(os.path.join(folder, FILE), contents)
print('Installed. You may now restart Wing.')
if platform.system() == 'Windows':
input('Press [Enter] to exit...')
class Popen(subprocess.Popen):
"""Patched Popen to prevent opening cmd window on Windows platform."""
def __init__(self, *args, **kwargs):
if is_win:
startupinfo = kwargs.get('startupinfo')
try:
startupinfo = startupinfo or subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
except AttributeError:
pass
kwargs['startupinfo'] = startupinfo
super(Popen, self).__init__(*args, **kwargs)
def parseConfigFile(configFile):
"""Returns a configparser.SafeConfigParser instance with configs
read from the config file. Default location of the config file is
at ~/.wakatime.cfg.
"""
kwargs = {} if is_py2 else {'strict': False}
configs = ConfigParser(**kwargs)
try:
with open(configFile, 'r', encoding='utf-8') as fh:
try:
if is_py2:
configs.readfp(fh)
else:
configs.read_file(fh)
return configs
except ConfigParserError:
print(traceback.format_exc())
return None
except IOError:
return configs
def log(message, *args, **kwargs):
if not CONFIGS.has_option('settings', 'debug') or CONFIGS.get('settings', 'debug') != 'true':
return
msg = message
if len(args) > 0:
msg = message.format(*args)
elif len(kwargs) > 0:
msg = message.format(**kwargs)
try:
print('[WakaTime] {msg}'.format(msg=msg))
except UnicodeDecodeError:
print(u('[WakaTime] {msg}').format(msg=u(msg)))
def getHomeFolder():
global HOME_FOLDER
if not HOME_FOLDER:
if len(sys.argv) == 2:
HOME_FOLDER = sys.argv[-1]
else:
HOME_FOLDER = os.path.realpath(os.environ.get('WAKATIME_HOME') or os.path.expanduser('~'))
return HOME_FOLDER
def getResourcesFolder():
return os.path.join(getHomeFolder(), '.wakatime')
def getConfigFile(internal=None):
if internal:
return os.path.join(getHomeFolder(), '.wakatime-internal.cfg')
return os.path.join(getHomeFolder(), '.wakatime.cfg')
def downloadCLI():
log('Downloading wakatime-cli...')
if not os.path.exists(getResourcesFolder()):
os.makedirs(getResourcesFolder())
try:
url = cliDownloadUrl()
log('Downloading wakatime-cli from {url}'.format(url=url))
zip_file = os.path.join(getResourcesFolder(), 'wakatime-cli.zip')
download(url, zip_file)
if isCliInstalled():
try:
os.remove(getCliLocation())
except:
log(traceback.format_exc())
log('Extracting wakatime-cli...')
with contextlib.closing(ZipFile(zip_file)) as zf:
zf.extractall(getResourcesFolder())
if not is_win:
os.chmod(getCliLocation(), 509) # 755
try:
os.remove(os.path.join(getResourcesFolder(), 'wakatime-cli.zip'))
except:
log(traceback.format_exc())
except:
log(traceback.format_exc())
log('Finished extracting wakatime-cli.')
WAKATIME_CLI_LOCATION = None
def getCliLocation():
global WAKATIME_CLI_LOCATION
if not WAKATIME_CLI_LOCATION:
binary = 'wakatime-cli-{osname}-{arch}{ext}'.format(
osname=platform.system().lower(),
arch=architecture(),
ext='.exe' if is_win else '',
)
WAKATIME_CLI_LOCATION = os.path.join(getResourcesFolder(), binary)
return WAKATIME_CLI_LOCATION
def architecture():
arch = platform.machine() or platform.processor()
if arch == 'armv7l':
return 'arm'
if arch == 'aarch64':
return 'arm64'
if 'arm' in arch:
return 'arm64' if sys.maxsize > 2**32 else 'arm'
return 'amd64' if sys.maxsize > 2**32 else '386'
def isCliInstalled():
return os.path.exists(getCliLocation())
def isCliLatest():
if not isCliInstalled():
return False
args = [getCliLocation(), '--version']
try:
stdout, stderr = Popen(args, stdout=PIPE, stderr=PIPE).communicate()
except:
return False
stdout = (stdout or b'') + (stderr or b'')
localVer = extractVersion(stdout.decode('utf-8'))
if not localVer:
log('Local wakatime-cli version not found.')
return False
log('Current wakatime-cli version is %s' % localVer)
log('Checking for updates to wakatime-cli...')
remoteVer = getLatestCliVersion()
if not remoteVer:
return True
if remoteVer == localVer:
log('wakatime-cli is up to date.')
return True
log('Found an updated wakatime-cli %s' % remoteVer)
return False
LATEST_CLI_VERSION = None
def getLatestCliVersion():
global LATEST_CLI_VERSION
if LATEST_CLI_VERSION:
return LATEST_CLI_VERSION
configs, last_modified, last_version = None, None, None
try:
configs = parseConfigFile(getConfigFile(True))
if configs:
if configs.has_option('internal', 'cli_version'):
last_version = configs.get('internal', 'cli_version')
if last_version and configs.has_option('internal', 'cli_version_last_modified'):
last_modified = configs.get('internal', 'cli_version_last_modified')
except:
log(traceback.format_exc())
try:
headers, contents, code = request(GITHUB_RELEASES_STABLE_URL, last_modified=last_modified)
log('GitHub API Response {0}'.format(code))
if code == 304:
LATEST_CLI_VERSION = last_version
return last_version
data = json.loads(contents.decode('utf-8'))
ver = data['tag_name']
log('Latest wakatime-cli version from GitHub: {0}'.format(ver))
if configs:
last_modified = headers.get('Last-Modified')
if not configs.has_section('internal'):
configs.add_section('internal')
configs.set('internal', 'cli_version', ver)
configs.set('internal', 'cli_version_last_modified', last_modified)
with open(getConfigFile(True), 'w', encoding='utf-8') as fh:
configs.write(fh)
LATEST_CLI_VERSION = ver
return ver
except:
log(traceback.format_exc())
return None
def extractVersion(text):
pattern = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)")
match = pattern.search(text)
if match:
return 'v{ver}'.format(ver=match.group(1))
return None
def cliDownloadUrl():
osname = platform.system().lower()
arch = architecture()
validCombinations = [
'darwin-amd64',
'darwin-arm64',
'freebsd-386',
'freebsd-amd64',
'freebsd-arm',
'linux-386',
'linux-amd64',
'linux-arm',
'linux-arm64',
'netbsd-386',
'netbsd-amd64',
'netbsd-arm',
'openbsd-386',
'openbsd-amd64',
'openbsd-arm',
'openbsd-arm64',
'windows-386',
'windows-amd64',
'windows-arm64',
]
check = '{osname}-{arch}'.format(osname=osname, arch=arch)
if check not in validCombinations:
reportMissingPlatformSupport(osname, arch)
version = getLatestCliVersion()
return '{prefix}/{version}/wakatime-cli-{osname}-{arch}.zip'.format(
prefix=GITHUB_DOWNLOAD_PREFIX,
version=version,
osname=osname,
arch=arch,
)
def reportMissingPlatformSupport(osname, arch):
url = 'https://api.wakatime.com/api/v1/cli-missing?osname={osname}&architecture={arch}&plugin={plugin}'.format(
osname=osname,
arch=arch,
plugin=PLUGIN,
)
request(url)
def get_file_contents(filename):
"""Get file contents from local folder or GitHub repo."""
if os.path.exists(os.path.join(SRC_DIR, filename)):
with open(os.path.join(SRC_DIR, filename), 'r', encoding='utf-8') as fh:
return fh.read()
else:
url = ROOT_URL + filename
localfile = os.path.join(getResourcesFolder(), filename)
download(url, localfile)
with open(localfile, 'r', encoding='utf-8') as fh:
contents = fh.read()
os.remove(localfile)
return contents
def request(url, last_modified=None):
req = Request(url)
req.add_header('User-Agent', 'github.com/wakatime/{plugin}-wakatime'.format(plugin=PLUGIN))
proxy = CONFIGS.get('settings', 'proxy') if CONFIGS.has_option('settings', 'proxy') else None
if proxy:
req.set_proxy(proxy, 'https')
if last_modified:
req.add_header('If-Modified-Since', last_modified)
try:
resp = urlopen(req)
headers = dict(resp.getheaders()) if is_py2 else resp.headers
return headers, resp.read(), resp.getcode()
except HTTPError as err:
if err.code == 304:
return None, None, 304
if is_py2:
with SSLCertVerificationDisabled():
try:
resp = urlopen(req)
headers = dict(resp.getheaders()) if is_py2 else resp.headers
return headers, resp.read(), resp.getcode()
except HTTPError as err2:
if err2.code == 304:
return None, None, 304
log(err.read().decode())
log(err2.read().decode())
raise
except IOError:
raise
log(err.read().decode())
raise
except IOError:
if is_py2:
with SSLCertVerificationDisabled():
try:
resp = urlopen(url)
headers = dict(resp.getheaders()) if is_py2 else resp.headers
return headers, resp.read(), resp.getcode()
except HTTPError as err:
if err.code == 304:
return None, None, 304
log(err.read().decode())
raise
except IOError:
raise
raise
def download(url, filePath):
req = Request(url)
req.add_header('User-Agent', 'github.com/wakatime/{plugin}-wakatime'.format(plugin=PLUGIN))
proxy = CONFIGS.get('settings', 'proxy') if CONFIGS.has_option('settings', 'proxy') else None
if proxy:
req.set_proxy(proxy, 'https')
with open(filePath, 'wb') as fh:
try:
resp = urlopen(req)
fh.write(resp.read())
except HTTPError as err:
if err.code == 304:
return None, None, 304
if is_py2:
with SSLCertVerificationDisabled():
try:
resp = urlopen(req)
fh.write(resp.read())
return
except HTTPError as err2:
log(err.read().decode())
log(err2.read().decode())
raise
except IOError:
raise
log(err.read().decode())
raise
except IOError:
if is_py2:
with SSLCertVerificationDisabled():
try:
resp = urlopen(url)
fh.write(resp.read())
return
except HTTPError as err:
log(err.read().decode())
raise
except IOError:
raise
raise
def save_file(filename, contents):
"""Saves contents to filename."""
with open(filename, 'w', encoding='utf-8') as fh:
fh.write(contents)
def is_symlink(path):
try:
return os.is_symlink(path)
except:
return False
def createSymlink():
link = os.path.join(getResourcesFolder(), 'wakatime-cli')
if is_win:
link = link + '.exe'
elif os.path.exists(link) and is_symlink(link):
return # don't re-create symlink on Unix-like platforms
if os.path.isdir(link):
shutil.rmtree(link)
elif os.path.isfile(link):
os.remove(link)
try:
os.symlink(getCliLocation(), link)
except:
try:
shutil.copy2(getCliLocation(), link)
if not is_win:
os.chmod(link, 509) # 755
except:
log(traceback.format_exc())
class SSLCertVerificationDisabled(object):
def __enter__(self):
self.original_context = ssl._create_default_https_context
ssl._create_default_https_context = ssl._create_unverified_context
def __exit__(self, *args, **kwargs):
ssl._create_default_https_context = self.original_context
if __name__ == '__main__':
main()
sys.exit(0)