PageRenderTime 63ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-src/lv2/sord/waflib/Utils.py

https://bitbucket.org/jamescrook/audacity
Python | 1035 lines | 939 code | 32 blank | 64 comment | 52 complexity | 60d891e38b67002fd28fc72d521c811b MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, BSD-3-Clause, LGPL-2.1, 0BSD
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. """
  5. Utilities and platform-specific fixes
  6. The portability fixes try to provide a consistent behavior of the Waf API
  7. through Python versions 2.5 to 3.X and across different platforms (win32, linux, etc)
  8. """
  9. from __future__ import with_statement
  10. import atexit, os, sys, errno, inspect, re, datetime, platform, base64, signal, functools, time
  11. try:
  12. import cPickle
  13. except ImportError:
  14. import pickle as cPickle
  15. # leave this
  16. if os.name == 'posix' and sys.version_info[0] < 3:
  17. try:
  18. import subprocess32 as subprocess
  19. except ImportError:
  20. import subprocess
  21. else:
  22. import subprocess
  23. try:
  24. TimeoutExpired = subprocess.TimeoutExpired
  25. except AttributeError:
  26. class TimeoutExpired(Exception):
  27. pass
  28. from collections import deque, defaultdict
  29. try:
  30. import _winreg as winreg
  31. except ImportError:
  32. try:
  33. import winreg
  34. except ImportError:
  35. winreg = None
  36. from waflib import Errors
  37. try:
  38. from hashlib import md5
  39. except ImportError:
  40. try:
  41. from hashlib import sha1 as md5
  42. except ImportError:
  43. # never fail to enable potential fixes from another module
  44. pass
  45. else:
  46. try:
  47. md5().digest()
  48. except ValueError:
  49. # Fips? #2213
  50. from hashlib import sha1 as md5
  51. try:
  52. import threading
  53. except ImportError:
  54. if not 'JOBS' in os.environ:
  55. # no threading :-(
  56. os.environ['JOBS'] = '1'
  57. class threading(object):
  58. """
  59. A fake threading class for platforms lacking the threading module.
  60. Use ``waf -j1`` on those platforms
  61. """
  62. pass
  63. class Lock(object):
  64. """Fake Lock class"""
  65. def acquire(self):
  66. pass
  67. def release(self):
  68. pass
  69. threading.Lock = threading.Thread = Lock
  70. SIG_NIL = 'SIG_NIL_SIG_NIL_'.encode()
  71. """Arbitrary null value for hashes. Modify this value according to the hash function in use"""
  72. O644 = 420
  73. """Constant representing the permissions for regular files (0644 raises a syntax error on python 3)"""
  74. O755 = 493
  75. """Constant representing the permissions for executable files (0755 raises a syntax error on python 3)"""
  76. rot_chr = ['\\', '|', '/', '-']
  77. "List of characters to use when displaying the throbber (progress bar)"
  78. rot_idx = 0
  79. "Index of the current throbber character (progress bar)"
  80. class ordered_iter_dict(dict):
  81. """Ordered dictionary that provides iteration from the most recently inserted keys first"""
  82. def __init__(self, *k, **kw):
  83. self.lst = deque()
  84. dict.__init__(self, *k, **kw)
  85. def clear(self):
  86. dict.clear(self)
  87. self.lst = deque()
  88. def __setitem__(self, key, value):
  89. if key in dict.keys(self):
  90. self.lst.remove(key)
  91. dict.__setitem__(self, key, value)
  92. self.lst.append(key)
  93. def __delitem__(self, key):
  94. dict.__delitem__(self, key)
  95. try:
  96. self.lst.remove(key)
  97. except ValueError:
  98. pass
  99. def __iter__(self):
  100. return reversed(self.lst)
  101. def keys(self):
  102. return reversed(self.lst)
  103. class lru_node(object):
  104. """
  105. Used by :py:class:`waflib.Utils.lru_cache`
  106. """
  107. __slots__ = ('next', 'prev', 'key', 'val')
  108. def __init__(self):
  109. self.next = self
  110. self.prev = self
  111. self.key = None
  112. self.val = None
  113. class lru_cache(object):
  114. """
  115. A simple least-recently used cache with lazy allocation
  116. """
  117. __slots__ = ('maxlen', 'table', 'head')
  118. def __init__(self, maxlen=100):
  119. self.maxlen = maxlen
  120. """
  121. Maximum amount of elements in the cache
  122. """
  123. self.table = {}
  124. """
  125. Mapping key-value
  126. """
  127. self.head = lru_node()
  128. self.head.next = self.head
  129. self.head.prev = self.head
  130. def __getitem__(self, key):
  131. node = self.table[key]
  132. # assert(key==node.key)
  133. if node is self.head:
  134. return node.val
  135. # detach the node found
  136. node.prev.next = node.next
  137. node.next.prev = node.prev
  138. # replace the head
  139. node.next = self.head.next
  140. node.prev = self.head
  141. self.head = node.next.prev = node.prev.next = node
  142. return node.val
  143. def __setitem__(self, key, val):
  144. if key in self.table:
  145. # update the value for an existing key
  146. node = self.table[key]
  147. node.val = val
  148. self.__getitem__(key)
  149. else:
  150. if len(self.table) < self.maxlen:
  151. # the very first item is unused until the maximum is reached
  152. node = lru_node()
  153. node.prev = self.head
  154. node.next = self.head.next
  155. node.prev.next = node.next.prev = node
  156. else:
  157. node = self.head = self.head.next
  158. try:
  159. # that's another key
  160. del self.table[node.key]
  161. except KeyError:
  162. pass
  163. node.key = key
  164. node.val = val
  165. self.table[key] = node
  166. class lazy_generator(object):
  167. def __init__(self, fun, params):
  168. self.fun = fun
  169. self.params = params
  170. def __iter__(self):
  171. return self
  172. def __next__(self):
  173. try:
  174. it = self.it
  175. except AttributeError:
  176. it = self.it = self.fun(*self.params)
  177. return next(it)
  178. next = __next__
  179. is_win32 = os.sep == '\\' or sys.platform == 'win32' or os.name == 'nt' # msys2
  180. """
  181. Whether this system is a Windows series
  182. """
  183. def readf(fname, m='r', encoding='latin-1'):
  184. """
  185. Reads an entire file into a string. See also :py:meth:`waflib.Node.Node.readf`::
  186. def build(ctx):
  187. from waflib import Utils
  188. txt = Utils.readf(self.path.find_node('wscript').abspath())
  189. txt = ctx.path.find_node('wscript').read()
  190. :type fname: string
  191. :param fname: Path to file
  192. :type m: string
  193. :param m: Open mode
  194. :type encoding: string
  195. :param encoding: encoding value, only used for python 3
  196. :rtype: string
  197. :return: Content of the file
  198. """
  199. if sys.hexversion > 0x3000000 and not 'b' in m:
  200. m += 'b'
  201. with open(fname, m) as f:
  202. txt = f.read()
  203. if encoding:
  204. txt = txt.decode(encoding)
  205. else:
  206. txt = txt.decode()
  207. else:
  208. with open(fname, m) as f:
  209. txt = f.read()
  210. return txt
  211. def writef(fname, data, m='w', encoding='latin-1'):
  212. """
  213. Writes an entire file from a string.
  214. See also :py:meth:`waflib.Node.Node.writef`::
  215. def build(ctx):
  216. from waflib import Utils
  217. txt = Utils.writef(self.path.make_node('i_like_kittens').abspath(), 'some data')
  218. self.path.make_node('i_like_kittens').write('some data')
  219. :type fname: string
  220. :param fname: Path to file
  221. :type data: string
  222. :param data: The contents to write to the file
  223. :type m: string
  224. :param m: Open mode
  225. :type encoding: string
  226. :param encoding: encoding value, only used for python 3
  227. """
  228. if sys.hexversion > 0x3000000 and not 'b' in m:
  229. data = data.encode(encoding)
  230. m += 'b'
  231. with open(fname, m) as f:
  232. f.write(data)
  233. def h_file(fname):
  234. """
  235. Computes a hash value for a file by using md5. Use the md5_tstamp
  236. extension to get faster build hashes if necessary.
  237. :type fname: string
  238. :param fname: path to the file to hash
  239. :return: hash of the file contents
  240. :rtype: string or bytes
  241. """
  242. m = md5()
  243. with open(fname, 'rb') as f:
  244. while fname:
  245. fname = f.read(200000)
  246. m.update(fname)
  247. return m.digest()
  248. def readf_win32(f, m='r', encoding='latin-1'):
  249. flags = os.O_NOINHERIT | os.O_RDONLY
  250. if 'b' in m:
  251. flags |= os.O_BINARY
  252. if '+' in m:
  253. flags |= os.O_RDWR
  254. try:
  255. fd = os.open(f, flags)
  256. except OSError:
  257. raise IOError('Cannot read from %r' % f)
  258. if sys.hexversion > 0x3000000 and not 'b' in m:
  259. m += 'b'
  260. with os.fdopen(fd, m) as f:
  261. txt = f.read()
  262. if encoding:
  263. txt = txt.decode(encoding)
  264. else:
  265. txt = txt.decode()
  266. else:
  267. with os.fdopen(fd, m) as f:
  268. txt = f.read()
  269. return txt
  270. def writef_win32(f, data, m='w', encoding='latin-1'):
  271. if sys.hexversion > 0x3000000 and not 'b' in m:
  272. data = data.encode(encoding)
  273. m += 'b'
  274. flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | os.O_NOINHERIT
  275. if 'b' in m:
  276. flags |= os.O_BINARY
  277. if '+' in m:
  278. flags |= os.O_RDWR
  279. try:
  280. fd = os.open(f, flags)
  281. except OSError:
  282. raise OSError('Cannot write to %r' % f)
  283. with os.fdopen(fd, m) as f:
  284. f.write(data)
  285. def h_file_win32(fname):
  286. try:
  287. fd = os.open(fname, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT)
  288. except OSError:
  289. raise OSError('Cannot read from %r' % fname)
  290. m = md5()
  291. with os.fdopen(fd, 'rb') as f:
  292. while fname:
  293. fname = f.read(200000)
  294. m.update(fname)
  295. return m.digest()
  296. # always save these
  297. readf_unix = readf
  298. writef_unix = writef
  299. h_file_unix = h_file
  300. if hasattr(os, 'O_NOINHERIT') and sys.hexversion < 0x3040000:
  301. # replace the default functions
  302. readf = readf_win32
  303. writef = writef_win32
  304. h_file = h_file_win32
  305. try:
  306. x = ''.encode('hex')
  307. except LookupError:
  308. import binascii
  309. def to_hex(s):
  310. ret = binascii.hexlify(s)
  311. if not isinstance(ret, str):
  312. ret = ret.decode('utf-8')
  313. return ret
  314. else:
  315. def to_hex(s):
  316. return s.encode('hex')
  317. to_hex.__doc__ = """
  318. Return the hexadecimal representation of a string
  319. :param s: string to convert
  320. :type s: string
  321. """
  322. def listdir_win32(s):
  323. """
  324. Lists the contents of a folder in a portable manner.
  325. On Win32, returns the list of drive letters: ['C:', 'X:', 'Z:'] when an empty string is given.
  326. :type s: string
  327. :param s: a string, which can be empty on Windows
  328. """
  329. if not s:
  330. try:
  331. import ctypes
  332. except ImportError:
  333. # there is nothing much we can do
  334. return [x + ':\\' for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']
  335. else:
  336. dlen = 4 # length of "?:\\x00"
  337. maxdrives = 26
  338. buf = ctypes.create_string_buffer(maxdrives * dlen)
  339. ndrives = ctypes.windll.kernel32.GetLogicalDriveStringsA(maxdrives*dlen, ctypes.byref(buf))
  340. return [ str(buf.raw[4*i:4*i+2].decode('ascii')) for i in range(int(ndrives/dlen)) ]
  341. if len(s) == 2 and s[1] == ":":
  342. s += os.sep
  343. if not os.path.isdir(s):
  344. e = OSError('%s is not a directory' % s)
  345. e.errno = errno.ENOENT
  346. raise e
  347. return os.listdir(s)
  348. listdir = os.listdir
  349. if is_win32:
  350. listdir = listdir_win32
  351. def num2ver(ver):
  352. """
  353. Converts a string, tuple or version number into an integer. The number is supposed to have at most 4 digits::
  354. from waflib.Utils import num2ver
  355. num2ver('1.3.2') == num2ver((1,3,2)) == num2ver((1,3,2,0))
  356. :type ver: string or tuple of numbers
  357. :param ver: a version number
  358. """
  359. if isinstance(ver, str):
  360. ver = tuple(ver.split('.'))
  361. if isinstance(ver, tuple):
  362. ret = 0
  363. for i in range(4):
  364. if i < len(ver):
  365. ret += 256**(3 - i) * int(ver[i])
  366. return ret
  367. return ver
  368. def to_list(val):
  369. """
  370. Converts a string argument to a list by splitting it by spaces.
  371. Returns the object if not a string::
  372. from waflib.Utils import to_list
  373. lst = to_list('a b c d')
  374. :param val: list of string or space-separated string
  375. :rtype: list
  376. :return: Argument converted to list
  377. """
  378. if isinstance(val, str):
  379. return val.split()
  380. else:
  381. return val
  382. def console_encoding():
  383. try:
  384. import ctypes
  385. except ImportError:
  386. pass
  387. else:
  388. try:
  389. codepage = ctypes.windll.kernel32.GetConsoleCP()
  390. except AttributeError:
  391. pass
  392. else:
  393. if codepage:
  394. return 'cp%d' % codepage
  395. return sys.stdout.encoding or ('cp1252' if is_win32 else 'latin-1')
  396. def split_path_unix(path):
  397. return path.split('/')
  398. def split_path_cygwin(path):
  399. if path.startswith('//'):
  400. ret = path.split('/')[2:]
  401. ret[0] = '/' + ret[0]
  402. return ret
  403. return path.split('/')
  404. re_sp = re.compile('[/\\\\]+')
  405. def split_path_win32(path):
  406. if path.startswith('\\\\'):
  407. ret = re_sp.split(path)[1:]
  408. ret[0] = '\\\\' + ret[0]
  409. if ret[0] == '\\\\?':
  410. return ret[1:]
  411. return ret
  412. return re_sp.split(path)
  413. msysroot = None
  414. def split_path_msys(path):
  415. if path.startswith(('/', '\\')) and not path.startswith(('//', '\\\\')):
  416. # msys paths can be in the form /usr/bin
  417. global msysroot
  418. if not msysroot:
  419. # msys has python 2.7 or 3, so we can use this
  420. msysroot = subprocess.check_output(['cygpath', '-w', '/']).decode(sys.stdout.encoding or 'latin-1')
  421. msysroot = msysroot.strip()
  422. path = os.path.normpath(msysroot + os.sep + path)
  423. return split_path_win32(path)
  424. if sys.platform == 'cygwin':
  425. split_path = split_path_cygwin
  426. elif is_win32:
  427. # Consider this an MSYSTEM environment if $MSYSTEM is set and python
  428. # reports is executable from a unix like path on a windows host.
  429. if os.environ.get('MSYSTEM') and sys.executable.startswith('/'):
  430. split_path = split_path_msys
  431. else:
  432. split_path = split_path_win32
  433. else:
  434. split_path = split_path_unix
  435. split_path.__doc__ = """
  436. Splits a path by / or \\; do not confuse this function with with ``os.path.split``
  437. :type path: string
  438. :param path: path to split
  439. :return: list of string
  440. """
  441. def check_dir(path):
  442. """
  443. Ensures that a directory exists (similar to ``mkdir -p``).
  444. :type path: string
  445. :param path: Path to directory
  446. :raises: :py:class:`waflib.Errors.WafError` if the folder cannot be added.
  447. """
  448. if not os.path.isdir(path):
  449. try:
  450. os.makedirs(path)
  451. except OSError as e:
  452. if not os.path.isdir(path):
  453. raise Errors.WafError('Cannot create the folder %r' % path, ex=e)
  454. def check_exe(name, env=None):
  455. """
  456. Ensures that a program exists
  457. :type name: string
  458. :param name: path to the program
  459. :param env: configuration object
  460. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  461. :return: path of the program or None
  462. :raises: :py:class:`waflib.Errors.WafError` if the folder cannot be added.
  463. """
  464. if not name:
  465. raise ValueError('Cannot execute an empty string!')
  466. def is_exe(fpath):
  467. return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  468. fpath, fname = os.path.split(name)
  469. if fpath and is_exe(name):
  470. return os.path.abspath(name)
  471. else:
  472. env = env or os.environ
  473. for path in env['PATH'].split(os.pathsep):
  474. path = path.strip('"')
  475. exe_file = os.path.join(path, name)
  476. if is_exe(exe_file):
  477. return os.path.abspath(exe_file)
  478. return None
  479. def def_attrs(cls, **kw):
  480. """
  481. Sets default attributes on a class instance
  482. :type cls: class
  483. :param cls: the class to update the given attributes in.
  484. :type kw: dict
  485. :param kw: dictionary of attributes names and values.
  486. """
  487. for k, v in kw.items():
  488. if not hasattr(cls, k):
  489. setattr(cls, k, v)
  490. def quote_define_name(s):
  491. """
  492. Converts a string into an identifier suitable for C defines.
  493. :type s: string
  494. :param s: String to convert
  495. :rtype: string
  496. :return: Identifier suitable for C defines
  497. """
  498. fu = re.sub('[^a-zA-Z0-9]', '_', s)
  499. fu = re.sub('_+', '_', fu)
  500. fu = fu.upper()
  501. return fu
  502. re_sh = re.compile('\\s|\'|"')
  503. """
  504. Regexp used for shell_escape below
  505. """
  506. def shell_escape(cmd):
  507. """
  508. Escapes a command:
  509. ['ls', '-l', 'arg space'] -> ls -l 'arg space'
  510. """
  511. if isinstance(cmd, str):
  512. return cmd
  513. return ' '.join(repr(x) if re_sh.search(x) else x for x in cmd)
  514. def h_list(lst):
  515. """
  516. Hashes lists of ordered data.
  517. Using hash(tup) for tuples would be much more efficient,
  518. but Python now enforces hash randomization
  519. :param lst: list to hash
  520. :type lst: list of strings
  521. :return: hash of the list
  522. """
  523. return md5(repr(lst).encode()).digest()
  524. if sys.hexversion < 0x3000000:
  525. def h_list_python2(lst):
  526. return md5(repr(lst)).digest()
  527. h_list_python2.__doc__ = h_list.__doc__
  528. h_list = h_list_python2
  529. def h_fun(fun):
  530. """
  531. Hash functions
  532. :param fun: function to hash
  533. :type fun: function
  534. :return: hash of the function
  535. :rtype: string or bytes
  536. """
  537. try:
  538. return fun.code
  539. except AttributeError:
  540. if isinstance(fun, functools.partial):
  541. code = list(fun.args)
  542. # The method items() provides a sequence of tuples where the first element
  543. # represents an optional argument of the partial function application
  544. #
  545. # The sorting result outcome will be consistent because:
  546. # 1. tuples are compared in order of their elements
  547. # 2. optional argument namess are unique
  548. code.extend(sorted(fun.keywords.items()))
  549. code.append(h_fun(fun.func))
  550. fun.code = h_list(code)
  551. return fun.code
  552. try:
  553. h = inspect.getsource(fun)
  554. except EnvironmentError:
  555. h = 'nocode'
  556. try:
  557. fun.code = h
  558. except AttributeError:
  559. pass
  560. return h
  561. def h_cmd(ins):
  562. """
  563. Hashes objects recursively
  564. :param ins: input object
  565. :type ins: string or list or tuple or function
  566. :rtype: string or bytes
  567. """
  568. # this function is not meant to be particularly fast
  569. if isinstance(ins, str):
  570. # a command is either a string
  571. ret = ins
  572. elif isinstance(ins, list) or isinstance(ins, tuple):
  573. # or a list of functions/strings
  574. ret = str([h_cmd(x) for x in ins])
  575. else:
  576. # or just a python function
  577. ret = str(h_fun(ins))
  578. if sys.hexversion > 0x3000000:
  579. ret = ret.encode('latin-1', 'xmlcharrefreplace')
  580. return ret
  581. reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}")
  582. def subst_vars(expr, params):
  583. """
  584. Replaces ${VAR} with the value of VAR taken from a dict or a config set::
  585. from waflib import Utils
  586. s = Utils.subst_vars('${PREFIX}/bin', env)
  587. :type expr: string
  588. :param expr: String to perform substitution on
  589. :param params: Dictionary or config set to look up variable values.
  590. """
  591. def repl_var(m):
  592. if m.group(1):
  593. return '\\'
  594. if m.group(2):
  595. return '$'
  596. try:
  597. # ConfigSet instances may contain lists
  598. return params.get_flat(m.group(3))
  599. except AttributeError:
  600. return params[m.group(3)]
  601. # if you get a TypeError, it means that 'expr' is not a string...
  602. # Utils.subst_vars(None, env) will not work
  603. return reg_subst.sub(repl_var, expr)
  604. def destos_to_binfmt(key):
  605. """
  606. Returns the binary format based on the unversioned platform name,
  607. and defaults to ``elf`` if nothing is found.
  608. :param key: platform name
  609. :type key: string
  610. :return: string representing the binary format
  611. """
  612. if key == 'darwin':
  613. return 'mac-o'
  614. elif key in ('win32', 'cygwin', 'uwin', 'msys'):
  615. return 'pe'
  616. return 'elf'
  617. def unversioned_sys_platform():
  618. """
  619. Returns the unversioned platform name.
  620. Some Python platform names contain versions, that depend on
  621. the build environment, e.g. linux2, freebsd6, etc.
  622. This returns the name without the version number. Exceptions are
  623. os2 and win32, which are returned verbatim.
  624. :rtype: string
  625. :return: Unversioned platform name
  626. """
  627. s = sys.platform
  628. if s.startswith('java'):
  629. # The real OS is hidden under the JVM.
  630. from java.lang import System
  631. s = System.getProperty('os.name')
  632. # see http://lopica.sourceforge.net/os.html for a list of possible values
  633. if s == 'Mac OS X':
  634. return 'darwin'
  635. elif s.startswith('Windows '):
  636. return 'win32'
  637. elif s == 'OS/2':
  638. return 'os2'
  639. elif s == 'HP-UX':
  640. return 'hp-ux'
  641. elif s in ('SunOS', 'Solaris'):
  642. return 'sunos'
  643. else: s = s.lower()
  644. # powerpc == darwin for our purposes
  645. if s == 'powerpc':
  646. return 'darwin'
  647. if s == 'win32' or s == 'os2':
  648. return s
  649. if s == 'cli' and os.name == 'nt':
  650. # ironpython is only on windows as far as we know
  651. return 'win32'
  652. return re.split(r'\d+$', s)[0]
  653. def nada(*k, **kw):
  654. """
  655. Does nothing
  656. :return: None
  657. """
  658. pass
  659. class Timer(object):
  660. """
  661. Simple object for timing the execution of commands.
  662. Its string representation is the duration::
  663. from waflib.Utils import Timer
  664. timer = Timer()
  665. a_few_operations()
  666. s = str(timer)
  667. """
  668. def __init__(self):
  669. self.start_time = self.now()
  670. def __str__(self):
  671. delta = self.now() - self.start_time
  672. if not isinstance(delta, datetime.timedelta):
  673. delta = datetime.timedelta(seconds=delta)
  674. days = delta.days
  675. hours, rem = divmod(delta.seconds, 3600)
  676. minutes, seconds = divmod(rem, 60)
  677. seconds += delta.microseconds * 1e-6
  678. result = ''
  679. if days:
  680. result += '%dd' % days
  681. if days or hours:
  682. result += '%dh' % hours
  683. if days or hours or minutes:
  684. result += '%dm' % minutes
  685. return '%s%.3fs' % (result, seconds)
  686. def now(self):
  687. return datetime.datetime.utcnow()
  688. if hasattr(time, 'perf_counter'):
  689. def now(self):
  690. return time.perf_counter()
  691. def read_la_file(path):
  692. """
  693. Reads property files, used by msvc.py
  694. :param path: file to read
  695. :type path: string
  696. """
  697. sp = re.compile(r'^([^=]+)=\'(.*)\'$')
  698. dc = {}
  699. for line in readf(path).splitlines():
  700. try:
  701. _, left, right, _ = sp.split(line.strip())
  702. dc[left] = right
  703. except ValueError:
  704. pass
  705. return dc
  706. def run_once(fun):
  707. """
  708. Decorator: let a function cache its results, use like this::
  709. @run_once
  710. def foo(k):
  711. return 345*2343
  712. .. note:: in practice this can cause memory leaks, prefer a :py:class:`waflib.Utils.lru_cache`
  713. :param fun: function to execute
  714. :type fun: function
  715. :return: the return value of the function executed
  716. """
  717. cache = {}
  718. def wrap(*k):
  719. try:
  720. return cache[k]
  721. except KeyError:
  722. ret = fun(*k)
  723. cache[k] = ret
  724. return ret
  725. wrap.__cache__ = cache
  726. wrap.__name__ = fun.__name__
  727. return wrap
  728. def get_registry_app_path(key, filename):
  729. """
  730. Returns the value of a registry key for an executable
  731. :type key: string
  732. :type filename: list of string
  733. """
  734. if not winreg:
  735. return None
  736. try:
  737. result = winreg.QueryValue(key, "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s.exe" % filename[0])
  738. except OSError:
  739. pass
  740. else:
  741. if os.path.isfile(result):
  742. return result
  743. def lib64():
  744. """
  745. Guess the default ``/usr/lib`` extension for 64-bit applications
  746. :return: '64' or ''
  747. :rtype: string
  748. """
  749. # default settings for /usr/lib
  750. if os.sep == '/':
  751. if platform.architecture()[0] == '64bit':
  752. if os.path.exists('/usr/lib64') and not os.path.exists('/usr/lib32'):
  753. return '64'
  754. return ''
  755. def sane_path(p):
  756. # private function for the time being!
  757. return os.path.abspath(os.path.expanduser(p))
  758. process_pool = []
  759. """
  760. List of processes started to execute sub-process commands
  761. """
  762. def get_process():
  763. """
  764. Returns a process object that can execute commands as sub-processes
  765. :rtype: subprocess.Popen
  766. """
  767. try:
  768. return process_pool.pop()
  769. except IndexError:
  770. filepath = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'processor.py'
  771. cmd = [sys.executable, '-c', readf(filepath)]
  772. return subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=0, close_fds=not is_win32)
  773. def run_prefork_process(cmd, kwargs, cargs):
  774. """
  775. Delegates process execution to a pre-forked process instance.
  776. """
  777. if not 'env' in kwargs:
  778. kwargs['env'] = dict(os.environ)
  779. try:
  780. obj = base64.b64encode(cPickle.dumps([cmd, kwargs, cargs]))
  781. except (TypeError, AttributeError):
  782. return run_regular_process(cmd, kwargs, cargs)
  783. proc = get_process()
  784. if not proc:
  785. return run_regular_process(cmd, kwargs, cargs)
  786. proc.stdin.write(obj)
  787. proc.stdin.write('\n'.encode())
  788. proc.stdin.flush()
  789. obj = proc.stdout.readline()
  790. if not obj:
  791. raise OSError('Preforked sub-process %r died' % proc.pid)
  792. process_pool.append(proc)
  793. lst = cPickle.loads(base64.b64decode(obj))
  794. # Jython wrapper failures (bash/execvp)
  795. assert len(lst) == 5
  796. ret, out, err, ex, trace = lst
  797. if ex:
  798. if ex == 'OSError':
  799. raise OSError(trace)
  800. elif ex == 'ValueError':
  801. raise ValueError(trace)
  802. elif ex == 'TimeoutExpired':
  803. exc = TimeoutExpired(cmd, timeout=cargs['timeout'], output=out)
  804. exc.stderr = err
  805. raise exc
  806. else:
  807. raise Exception(trace)
  808. return ret, out, err
  809. def lchown(path, user=-1, group=-1):
  810. """
  811. Change the owner/group of a path, raises an OSError if the
  812. ownership change fails.
  813. :param user: user to change
  814. :type user: int or str
  815. :param group: group to change
  816. :type group: int or str
  817. """
  818. if isinstance(user, str):
  819. import pwd
  820. entry = pwd.getpwnam(user)
  821. if not entry:
  822. raise OSError('Unknown user %r' % user)
  823. user = entry[2]
  824. if isinstance(group, str):
  825. import grp
  826. entry = grp.getgrnam(group)
  827. if not entry:
  828. raise OSError('Unknown group %r' % group)
  829. group = entry[2]
  830. return os.lchown(path, user, group)
  831. def run_regular_process(cmd, kwargs, cargs={}):
  832. """
  833. Executes a subprocess command by using subprocess.Popen
  834. """
  835. proc = subprocess.Popen(cmd, **kwargs)
  836. if kwargs.get('stdout') or kwargs.get('stderr'):
  837. try:
  838. out, err = proc.communicate(**cargs)
  839. except TimeoutExpired:
  840. if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
  841. os.killpg(proc.pid, signal.SIGKILL)
  842. else:
  843. proc.kill()
  844. out, err = proc.communicate()
  845. exc = TimeoutExpired(proc.args, timeout=cargs['timeout'], output=out)
  846. exc.stderr = err
  847. raise exc
  848. status = proc.returncode
  849. else:
  850. out, err = (None, None)
  851. try:
  852. status = proc.wait(**cargs)
  853. except TimeoutExpired as e:
  854. if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
  855. os.killpg(proc.pid, signal.SIGKILL)
  856. else:
  857. proc.kill()
  858. proc.wait()
  859. raise e
  860. return status, out, err
  861. def run_process(cmd, kwargs, cargs={}):
  862. """
  863. Executes a subprocess by using a pre-forked process when possible
  864. or falling back to subprocess.Popen. See :py:func:`waflib.Utils.run_prefork_process`
  865. and :py:func:`waflib.Utils.run_regular_process`
  866. """
  867. if kwargs.get('stdout') and kwargs.get('stderr'):
  868. return run_prefork_process(cmd, kwargs, cargs)
  869. else:
  870. return run_regular_process(cmd, kwargs, cargs)
  871. def alloc_process_pool(n, force=False):
  872. """
  873. Allocates an amount of processes to the default pool so its size is at least *n*.
  874. It is useful to call this function early so that the pre-forked
  875. processes use as little memory as possible.
  876. :param n: pool size
  877. :type n: integer
  878. :param force: if True then *n* more processes are added to the existing pool
  879. :type force: bool
  880. """
  881. # mandatory on python2, unnecessary on python >= 3.2
  882. global run_process, get_process, alloc_process_pool
  883. if not force:
  884. n = max(n - len(process_pool), 0)
  885. try:
  886. lst = [get_process() for x in range(n)]
  887. except OSError:
  888. run_process = run_regular_process
  889. get_process = alloc_process_pool = nada
  890. else:
  891. for x in lst:
  892. process_pool.append(x)
  893. def atexit_pool():
  894. for k in process_pool:
  895. try:
  896. os.kill(k.pid, 9)
  897. except OSError:
  898. pass
  899. else:
  900. k.wait()
  901. # see #1889
  902. if (sys.hexversion<0x207000f and not is_win32) or sys.hexversion>=0x306000f:
  903. atexit.register(atexit_pool)
  904. if os.environ.get('WAF_NO_PREFORK') or sys.platform == 'cli' or not sys.executable:
  905. run_process = run_regular_process
  906. get_process = alloc_process_pool = nada