This repository was archived by the owner on Mar 31, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathutil.py
More file actions
408 lines (350 loc) · 11.8 KB
/
util.py
File metadata and controls
408 lines (350 loc) · 11.8 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
import os
import sys
import errno
import shutil
import re
import posixpath
import tarfile
import platform
import subprocess
import shlex
import select
PY3K = sys.version_info >= (3,)
if not PY3K:
from urllib import quote as urlquote, unquote as urlunquote
from urllib2 import urlparse
else:
from urllib import parse as urlparse
from urllib.parse import quote as urlquote, unquote as urlunquote
from pythonz.define import PATH_PYTHONS
from pythonz.log import logger
def is_url(name):
try:
result = urlparse.urlparse(name)
except Exception:
return False
else:
return result.scheme in ('http', 'https', 'file', 'ftp')
def is_file(name):
try:
result = urlparse.urlparse(name)
except Exception:
return False
else:
return result.scheme == 'file'
def splitext(name):
base, ext = os.path.splitext(name)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext
def is_archive_file(name):
ext = splitext(name)[1].lower()
return ext in ('.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.jar')
def is_html(content_type):
return content_type and content_type.startswith('text/html')
def is_gzip(content_type, filename):
return content_type == 'application/x-gzip' or tarfile.is_tarfile(filename) or splitext(filename)[1].lower() in ('.tar', '.tar.gz', '.tgz', '.tar.bz2', '.tbz')
def get_macosx_deployment_target():
m = re.search('^([0-9]+\.[0-9]+)', platform.mac_ver()[0])
if m:
return m.group(1)
return None
def _py_version_cmp(v, v1, v2):
if is_str(v):
v = Version(v)
return v >= v1 and v < v2
def is_python24(version):
return _py_version_cmp(version, '2.4', '2.5')
def is_python25(version):
return _py_version_cmp(version, '2.5', '2.6')
def is_python26(version):
return _py_version_cmp(version, '2.6', '2.7')
def is_python27(version):
return _py_version_cmp(version, '2.7', '2.8')
def is_python30(version):
return _py_version_cmp(version, '3.0', '3.1')
def is_python31(version):
return _py_version_cmp(version, '3.1', '3.2')
def is_python32(version):
return _py_version_cmp(version, '3.2', '3.3')
def is_python33(version):
return _py_version_cmp(version, '3.3', '3.4')
def makedirs(path):
if not os.path.exists(path):
os.makedirs(path)
def symlink(src, dst):
try:
os.symlink(src, dst)
except OSError:
pass
def unlink(path):
try:
os.unlink(path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
def rm_r(path):
"""like rm -r command."""
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.isfile(path):
unlink(path)
def split_leading_dir(path):
path = str(path)
path = path.lstrip('/').lstrip('\\')
if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path):
return path.split('/', 1)
elif '\\' in path:
return path.split('\\', 1)
else:
return path, ''
def has_leading_dir(paths):
"""Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive)"""
common_prefix = None
for path in paths:
prefix, rest = split_leading_dir(path)
if not prefix:
return False
elif common_prefix is None:
common_prefix = prefix
elif prefix != common_prefix:
return False
return True
def untar_file(filename, location):
if not os.path.exists(location):
os.makedirs(location)
if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'):
mode = 'r:gz'
elif filename.lower().endswith('.bz2') or filename.lower().endswith('.tbz'):
mode = 'r:bz2'
elif filename.lower().endswith('.tar'):
mode = 'r'
else:
logger.error('Cannot determine compression type for file %s' % filename)
mode = 'r:*'
tar = tarfile.open(filename, mode)
try:
# note: python<=2.5 doesnt seem to know about pax headers, filter them
leading = has_leading_dir([
member.name for member in tar.getmembers()
if not member.name.startswith('.') and member.name != 'pax_global_header'
])
for member in tar.getmembers():
fn = member.name
if fn == 'pax_global_header':
continue
if leading:
fn = split_leading_dir(fn)[1]
path = os.path.join(location, fn)
if member.isdir():
if not os.path.exists(path):
os.makedirs(path)
else:
try:
fp = tar.extractfile(member)
except (KeyError, AttributeError):
e = sys.exc_info()[1]
# Some corrupt tar files seem to produce this
# (specifically bad symlinks)
logger.error('In the tar file %s the member %s is invalid: %s'
% (filename, member.name, e))
continue
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
destfp = open(path, 'wb')
try:
shutil.copyfileobj(fp, destfp)
finally:
destfp.close()
fp.close()
# note: configure ...etc
os.chmod(path, member.mode)
# note: the file timestamps should be such that asdl_c.py is not invoked.
os.utime(path, (member.mtime, member.mtime))
finally:
tar.close()
def extract_downloadfile(content_type, download_file, target_dir):
logger.info("Extracting %s into %s" % (os.path.basename(download_file), target_dir))
if is_gzip(content_type, download_file):
untar_file(download_file, target_dir)
return True
else:
logger.error("Cannot determine archive format of %s" % download_file)
return False
def is_installed(pkg):
return os.path.isdir(os.path.join(PATH_PYTHONS, pkg.name))
def path_to_fileurl(path):
path = os.path.normcase(os.path.abspath(path))
url = urlquote(path)
url = url.replace(os.path.sep, '/')
url = url.lstrip('/')
return 'file:///' + url
def fileurl_to_path(url):
assert url.startswith('file:'), ('Illegal scheme:%s' % url)
url = '/' + url[len('file:'):].lstrip('/')
return urlunquote(url)
def to_str(val):
if not PY3K:
# python2
if isinstance(val, unicode):
return val.encode("utf-8")
return val
if isinstance(val, bytes):
return val.decode("utf-8")
return val
def is_str(val):
if not PY3K:
# python2
return isinstance(val, basestring)
# python3
return isinstance(val, str)
def is_sequence(val):
if is_str(val):
return False
return (hasattr(val, "__getitem__") or hasattr(val, "__iter__"))
#-----------------------------
# class
#-----------------------------
class ShellCommandException(Exception):
"""General exception during shell command"""
class Subprocess(object):
def __init__(self, log=None, cwd=None, verbose=False, debug=False):
self._log = log
self._cwd = cwd
self._verbose = verbose
self._debug = debug
def chdir(self, cwd):
self._cwd = cwd
def shell(self, cmd):
if self._debug:
logger.log(cmd)
if is_sequence(cmd):
cmd = ''.join(cmd)
if self._log:
if self._verbose:
cmd = "(%s) 2>&1 | tee '%s'" % (cmd, self._log)
else:
cmd = "(%s) >> '%s' 2>&1" % (cmd, self._log)
returncode = subprocess.call(cmd, shell=True, cwd=self._cwd)
if returncode:
raise ShellCommandException('%s: failed to `%s`' % (returncode, cmd))
def call(self, cmd):
if is_str(cmd):
cmd = shlex.split(cmd)
if self._debug:
logger.log(cmd)
fp = ((self._log and open(self._log, 'a')) or None)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self._cwd)
while p.returncode is None:
while any(select.select([p.stdout], [], [])):
line = to_str(p.stdout.readline())
if not line:
break
if self._verbose:
logger.log(line.strip())
if fp:
fp.write(line)
fp.flush()
p.poll()
if fp:
fp.close()
return p.returncode
def check_call(self, cmd):
returncode = self.call(cmd)
if returncode:
raise ShellCommandException('%s: failed to `%s`' % (returncode, cmd))
class Package(object):
def __init__(self, version, type):
type = type.lower()
if type == 'cpython':
tag = 'CPython'
elif type == 'stackless':
tag = 'Stackless'
elif type == 'pypy':
tag = 'PyPy'
elif type == 'pypy3':
tag = 'PyPy3'
elif type == 'jython':
tag = 'Jython'
else:
raise ValueError('invalid type: %s' % type)
self.type = type
self.tag = tag
self.version = version
@property
def name(self):
return '%s-%s' % (self.tag, self.version)
class Link(object):
def __init__(self, url):
self._url = url
@property
def filename(self):
url = self._url
url = url.split('#', 1)[0]
url = url.split('?', 1)[0]
url = url.rstrip('/')
name = posixpath.basename(url)
assert name, ('URL %r produced no filename' % url)
return name
@property
def base_url(self):
return posixpath.basename(self._url.split('#', 1)[0].split('?', 1)[0])
class Version(object):
"""version compare
"""
def __init__(self, v):
self._version = v
self._p = self._parse_version(v)
def __lt__(self, o):
if is_str(o):
o = self._parse_version(o)
return self._p < o
def __le__(self, o):
if is_str(o):
o = self._parse_version(o)
return self._p <= o
def __eq__(self, o):
if is_str(o):
o = self._parse_version(o)
return self._p == o
def __ne__(self, o):
if is_str(o):
o = self._parse_version(o)
return self._p != o
def __gt__(self, o):
if is_str(o):
o = self._parse_version(o)
return self._p > o
def __ge__(self, o):
if is_str(o):
o = self._parse_version(o)
return self._p >= o
def _parse_version(self, s):
"""see pkg_resouce.parse_version
"""
component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE)
replace = {'pre':'c', 'preview':'c','-':'final-','rc':'c','dev':'@'}.get
def _parse_version_parts(s):
for part in component_re.split(s):
part = replace(part,part)
if not part or part=='.':
continue
if part[:1] in '0123456789':
yield part.zfill(8) # pad for numeric comparison
else:
yield '*'+part
yield '*final' # ensure that alpha/beta/candidate are before final
parts = []
for part in _parse_version_parts(s.lower()):
if part.startswith('*'):
if part<'*final': # remove '-' before a prerelease tag
while parts and parts[-1]=='*final-': parts.pop()
# remove trailing zeros from each series of numeric parts
while parts and parts[-1]=='00000000':
parts.pop()
parts.append(part)
return tuple(parts)
def __repr__(self):
return self._version