Utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. #
  2. # Cython -- Things that don't belong
  3. # anywhere else in particular
  4. #
  5. from __future__ import absolute_import
  6. try:
  7. from __builtin__ import basestring
  8. except ImportError:
  9. basestring = str
  10. try:
  11. FileNotFoundError
  12. except NameError:
  13. FileNotFoundError = OSError
  14. import os
  15. import sys
  16. import re
  17. import io
  18. import codecs
  19. import shutil
  20. import tempfile
  21. from contextlib import contextmanager
  22. modification_time = os.path.getmtime
  23. _function_caches = []
  24. def clear_function_caches():
  25. for cache in _function_caches:
  26. cache.clear()
  27. def cached_function(f):
  28. cache = {}
  29. _function_caches.append(cache)
  30. uncomputed = object()
  31. def wrapper(*args):
  32. res = cache.get(args, uncomputed)
  33. if res is uncomputed:
  34. res = cache[args] = f(*args)
  35. return res
  36. wrapper.uncached = f
  37. return wrapper
  38. def cached_method(f):
  39. cache_name = '__%s_cache' % f.__name__
  40. def wrapper(self, *args):
  41. cache = getattr(self, cache_name, None)
  42. if cache is None:
  43. cache = {}
  44. setattr(self, cache_name, cache)
  45. if args in cache:
  46. return cache[args]
  47. res = cache[args] = f(self, *args)
  48. return res
  49. return wrapper
  50. def replace_suffix(path, newsuf):
  51. base, _ = os.path.splitext(path)
  52. return base + newsuf
  53. def open_new_file(path):
  54. if os.path.exists(path):
  55. # Make sure to create a new file here so we can
  56. # safely hard link the output files.
  57. os.unlink(path)
  58. # we use the ISO-8859-1 encoding here because we only write pure
  59. # ASCII strings or (e.g. for file names) byte encoded strings as
  60. # Unicode, so we need a direct mapping from the first 256 Unicode
  61. # characters to a byte sequence, which ISO-8859-1 provides
  62. # note: can't use io.open() in Py2 as we may be writing str objects
  63. return codecs.open(path, "w", encoding="ISO-8859-1")
  64. def castrate_file(path, st):
  65. # Remove junk contents from an output file after a
  66. # failed compilation.
  67. # Also sets access and modification times back to
  68. # those specified by st (a stat struct).
  69. try:
  70. f = open_new_file(path)
  71. except EnvironmentError:
  72. pass
  73. else:
  74. f.write(
  75. "#error Do not use this file, it is the result of a failed Cython compilation.\n")
  76. f.close()
  77. if st:
  78. os.utime(path, (st.st_atime, st.st_mtime-1))
  79. def file_newer_than(path, time):
  80. ftime = modification_time(path)
  81. return ftime > time
  82. def safe_makedirs(path):
  83. try:
  84. os.makedirs(path)
  85. except OSError:
  86. if not os.path.isdir(path):
  87. raise
  88. def copy_file_to_dir_if_newer(sourcefile, destdir):
  89. """
  90. Copy file sourcefile to directory destdir (creating it if needed),
  91. preserving metadata. If the destination file exists and is not
  92. older than the source file, the copying is skipped.
  93. """
  94. destfile = os.path.join(destdir, os.path.basename(sourcefile))
  95. try:
  96. desttime = modification_time(destfile)
  97. except OSError:
  98. # New file does not exist, destdir may or may not exist
  99. safe_makedirs(destdir)
  100. else:
  101. # New file already exists
  102. if not file_newer_than(sourcefile, desttime):
  103. return
  104. shutil.copy2(sourcefile, destfile)
  105. @cached_function
  106. def find_root_package_dir(file_path):
  107. dir = os.path.dirname(file_path)
  108. if file_path == dir:
  109. return dir
  110. elif is_package_dir(dir):
  111. return find_root_package_dir(dir)
  112. else:
  113. return dir
  114. @cached_function
  115. def check_package_dir(dir, package_names):
  116. for dirname in package_names:
  117. dir = os.path.join(dir, dirname)
  118. if not is_package_dir(dir):
  119. return None
  120. return dir
  121. @cached_function
  122. def is_package_dir(dir_path):
  123. for filename in ("__init__.py",
  124. "__init__.pyc",
  125. "__init__.pyx",
  126. "__init__.pxd"):
  127. path = os.path.join(dir_path, filename)
  128. if path_exists(path):
  129. return 1
  130. @cached_function
  131. def path_exists(path):
  132. # try on the filesystem first
  133. if os.path.exists(path):
  134. return True
  135. # figure out if a PEP 302 loader is around
  136. try:
  137. loader = __loader__
  138. # XXX the code below assumes a 'zipimport.zipimporter' instance
  139. # XXX should be easy to generalize, but too lazy right now to write it
  140. archive_path = getattr(loader, 'archive', None)
  141. if archive_path:
  142. normpath = os.path.normpath(path)
  143. if normpath.startswith(archive_path):
  144. arcname = normpath[len(archive_path)+1:]
  145. try:
  146. loader.get_data(arcname)
  147. return True
  148. except IOError:
  149. return False
  150. except NameError:
  151. pass
  152. return False
  153. # file name encodings
  154. def decode_filename(filename):
  155. if isinstance(filename, bytes):
  156. try:
  157. filename_encoding = sys.getfilesystemencoding()
  158. if filename_encoding is None:
  159. filename_encoding = sys.getdefaultencoding()
  160. filename = filename.decode(filename_encoding)
  161. except UnicodeDecodeError:
  162. pass
  163. return filename
  164. # support for source file encoding detection
  165. _match_file_encoding = re.compile(br"(\w*coding)[:=]\s*([-\w.]+)").search
  166. def detect_opened_file_encoding(f):
  167. # PEPs 263 and 3120
  168. # Most of the time the first two lines fall in the first couple of hundred chars,
  169. # and this bulk read/split is much faster.
  170. lines = ()
  171. start = b''
  172. while len(lines) < 3:
  173. data = f.read(500)
  174. start += data
  175. lines = start.split(b"\n")
  176. if not data:
  177. break
  178. m = _match_file_encoding(lines[0])
  179. if m and m.group(1) != b'c_string_encoding':
  180. return m.group(2).decode('iso8859-1')
  181. elif len(lines) > 1:
  182. m = _match_file_encoding(lines[1])
  183. if m:
  184. return m.group(2).decode('iso8859-1')
  185. return "UTF-8"
  186. def skip_bom(f):
  187. """
  188. Read past a BOM at the beginning of a source file.
  189. This could be added to the scanner, but it's *substantially* easier
  190. to keep it at this level.
  191. """
  192. if f.read(1) != u'\uFEFF':
  193. f.seek(0)
  194. def open_source_file(source_filename, encoding=None, error_handling=None):
  195. stream = None
  196. try:
  197. if encoding is None:
  198. # Most of the time the encoding is not specified, so try hard to open the file only once.
  199. f = io.open(source_filename, 'rb')
  200. encoding = detect_opened_file_encoding(f)
  201. f.seek(0)
  202. stream = io.TextIOWrapper(f, encoding=encoding, errors=error_handling)
  203. else:
  204. stream = io.open(source_filename, encoding=encoding, errors=error_handling)
  205. except OSError:
  206. if os.path.exists(source_filename):
  207. raise # File is there, but something went wrong reading from it.
  208. # Allow source files to be in zip files etc.
  209. try:
  210. loader = __loader__
  211. if source_filename.startswith(loader.archive):
  212. stream = open_source_from_loader(
  213. loader, source_filename,
  214. encoding, error_handling)
  215. except (NameError, AttributeError):
  216. pass
  217. if stream is None:
  218. raise FileNotFoundError(source_filename)
  219. skip_bom(stream)
  220. return stream
  221. def open_source_from_loader(loader,
  222. source_filename,
  223. encoding=None, error_handling=None):
  224. nrmpath = os.path.normpath(source_filename)
  225. arcname = nrmpath[len(loader.archive)+1:]
  226. data = loader.get_data(arcname)
  227. return io.TextIOWrapper(io.BytesIO(data),
  228. encoding=encoding,
  229. errors=error_handling)
  230. def str_to_number(value):
  231. # note: this expects a string as input that was accepted by the
  232. # parser already, with an optional "-" sign in front
  233. is_neg = False
  234. if value[:1] == '-':
  235. is_neg = True
  236. value = value[1:]
  237. if len(value) < 2:
  238. value = int(value, 0)
  239. elif value[0] == '0':
  240. literal_type = value[1] # 0'o' - 0'b' - 0'x'
  241. if literal_type in 'xX':
  242. # hex notation ('0x1AF')
  243. value = int(value[2:], 16)
  244. elif literal_type in 'oO':
  245. # Py3 octal notation ('0o136')
  246. value = int(value[2:], 8)
  247. elif literal_type in 'bB':
  248. # Py3 binary notation ('0b101')
  249. value = int(value[2:], 2)
  250. else:
  251. # Py2 octal notation ('0136')
  252. value = int(value, 8)
  253. else:
  254. value = int(value, 0)
  255. return -value if is_neg else value
  256. def long_literal(value):
  257. if isinstance(value, basestring):
  258. value = str_to_number(value)
  259. return not -2**31 <= value < 2**31
  260. @cached_function
  261. def get_cython_cache_dir():
  262. r"""
  263. Return the base directory containing Cython's caches.
  264. Priority:
  265. 1. CYTHON_CACHE_DIR
  266. 2. (OS X): ~/Library/Caches/Cython
  267. (posix not OS X): XDG_CACHE_HOME/cython if XDG_CACHE_HOME defined
  268. 3. ~/.cython
  269. """
  270. if 'CYTHON_CACHE_DIR' in os.environ:
  271. return os.environ['CYTHON_CACHE_DIR']
  272. parent = None
  273. if os.name == 'posix':
  274. if sys.platform == 'darwin':
  275. parent = os.path.expanduser('~/Library/Caches')
  276. else:
  277. # this could fallback on ~/.cache
  278. parent = os.environ.get('XDG_CACHE_HOME')
  279. if parent and os.path.isdir(parent):
  280. return os.path.join(parent, 'cython')
  281. # last fallback: ~/.cython
  282. return os.path.expanduser(os.path.join('~', '.cython'))
  283. @contextmanager
  284. def captured_fd(stream=2, encoding=None):
  285. orig_stream = os.dup(stream) # keep copy of original stream
  286. try:
  287. with tempfile.TemporaryFile(mode="a+b") as temp_file:
  288. def read_output(_output=[b'']):
  289. if not temp_file.closed:
  290. temp_file.seek(0)
  291. _output[0] = temp_file.read()
  292. return _output[0]
  293. os.dup2(temp_file.fileno(), stream) # replace stream by copy of pipe
  294. try:
  295. def get_output():
  296. result = read_output()
  297. return result.decode(encoding) if encoding else result
  298. yield get_output
  299. finally:
  300. os.dup2(orig_stream, stream) # restore original stream
  301. read_output() # keep the output in case it's used after closing the context manager
  302. finally:
  303. os.close(orig_stream)
  304. def print_bytes(s, header_text=None, end=b'\n', file=sys.stdout, flush=True):
  305. if header_text:
  306. file.write(header_text) # note: text! => file.write() instead of out.write()
  307. file.flush()
  308. try:
  309. out = file.buffer # Py3
  310. except AttributeError:
  311. out = file # Py2
  312. out.write(s)
  313. if end:
  314. out.write(end)
  315. if flush:
  316. out.flush()
  317. class LazyStr:
  318. def __init__(self, callback):
  319. self.callback = callback
  320. def __str__(self):
  321. return self.callback()
  322. def __repr__(self):
  323. return self.callback()
  324. def __add__(self, right):
  325. return self.callback() + right
  326. def __radd__(self, left):
  327. return left + self.callback()
  328. class OrderedSet(object):
  329. def __init__(self, elements=()):
  330. self._list = []
  331. self._set = set()
  332. self.update(elements)
  333. def __iter__(self):
  334. return iter(self._list)
  335. def update(self, elements):
  336. for e in elements:
  337. self.add(e)
  338. def add(self, e):
  339. if e not in self._set:
  340. self._list.append(e)
  341. self._set.add(e)
  342. # Class decorator that adds a metaclass and recreates the class with it.
  343. # Copied from 'six'.
  344. def add_metaclass(metaclass):
  345. """Class decorator for creating a class with a metaclass."""
  346. def wrapper(cls):
  347. orig_vars = cls.__dict__.copy()
  348. slots = orig_vars.get('__slots__')
  349. if slots is not None:
  350. if isinstance(slots, str):
  351. slots = [slots]
  352. for slots_var in slots:
  353. orig_vars.pop(slots_var)
  354. orig_vars.pop('__dict__', None)
  355. orig_vars.pop('__weakref__', None)
  356. return metaclass(cls.__name__, cls.__bases__, orig_vars)
  357. return wrapper
  358. def raise_error_if_module_name_forbidden(full_module_name):
  359. #it is bad idea to call the pyx-file cython.pyx, so fail early
  360. if full_module_name == 'cython' or full_module_name.startswith('cython.'):
  361. raise ValueError('cython is a special module, cannot be used as a module name')
  362. def build_hex_version(version_string):
  363. """
  364. Parse and translate '4.3a1' into the readable hex representation '0x040300A1' (like PY_VERSION_HEX).
  365. """
  366. # First, parse '4.12a1' into [4, 12, 0, 0xA01].
  367. digits = []
  368. release_status = 0xF0
  369. for digit in re.split('([.abrc]+)', version_string):
  370. if digit in ('a', 'b', 'rc'):
  371. release_status = {'a': 0xA0, 'b': 0xB0, 'rc': 0xC0}[digit]
  372. digits = (digits + [0, 0])[:3] # 1.2a1 -> 1.2.0a1
  373. elif digit != '.':
  374. digits.append(int(digit))
  375. digits = (digits + [0] * 3)[:4]
  376. digits[3] += release_status
  377. # Then, build a single hex value, two hex digits per version part.
  378. hexversion = 0
  379. for digit in digits:
  380. hexversion = (hexversion << 8) + digit
  381. return '0x%08X' % hexversion