mesonlib.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. # Copyright 2012-2015 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. """A library of random helper functionality."""
  12. import stat
  13. import time
  14. import platform, subprocess, operator, os, shutil, re
  15. import collections
  16. from glob import glob
  17. class MesonException(Exception):
  18. '''Exceptions thrown by Meson'''
  19. class EnvironmentException(MesonException):
  20. '''Exceptions thrown while processing and creating the build environment'''
  21. class FileMode:
  22. # The first triad is for owner permissions, the second for group permissions,
  23. # and the third for others (everyone else).
  24. # For the 1st character:
  25. # 'r' means can read
  26. # '-' means not allowed
  27. # For the 2nd character:
  28. # 'w' means can write
  29. # '-' means not allowed
  30. # For the 3rd character:
  31. # 'x' means can execute
  32. # 's' means can execute and setuid/setgid is set (owner/group triads only)
  33. # 'S' means cannot execute and setuid/setgid is set (owner/group triads only)
  34. # 't' means can execute and sticky bit is set ("others" triads only)
  35. # 'T' means cannot execute and sticky bit is set ("others" triads only)
  36. # '-' means none of these are allowed
  37. #
  38. # The meanings of 'rwx' perms is not obvious for directories; see:
  39. # https://www.hackinglinuxexposed.com/articles/20030424.html
  40. #
  41. # For information on this notation such as setuid/setgid/sticky bits, see:
  42. # https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
  43. symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
  44. '[r-][w-][xsS-]' # Group perms
  45. '[r-][w-][xtT-]') # Others perms
  46. def __init__(self, perms=None, owner=None, group=None):
  47. self.perms_s = perms
  48. self.perms = self.perms_s_to_bits(perms)
  49. self.owner = owner
  50. self.group = group
  51. def __repr__(self):
  52. ret = '<FileMode: {!r} owner={} group={}'
  53. return ret.format(self.perms_s, self.owner, self.group)
  54. @classmethod
  55. def perms_s_to_bits(cls, perms_s):
  56. '''
  57. Does the opposite of stat.filemode(), converts strings of the form
  58. 'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
  59. '''
  60. if perms_s is None:
  61. # No perms specified, we will not touch the permissions
  62. return -1
  63. eg = 'rwxr-xr-x'
  64. if not isinstance(perms_s, str):
  65. msg = 'Install perms must be a string. For example, {!r}'
  66. raise MesonException(msg.format(eg))
  67. if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
  68. msg = 'File perms {!r} must be exactly 9 chars. For example, {!r}'
  69. raise MesonException(msg.format(perms_s, eg))
  70. perms = 0
  71. # Owner perms
  72. if perms_s[0] == 'r':
  73. perms |= stat.S_IRUSR
  74. if perms_s[1] == 'w':
  75. perms |= stat.S_IWUSR
  76. if perms_s[2] == 'x':
  77. perms |= stat.S_IXUSR
  78. elif perms_s[2] == 'S':
  79. perms |= stat.S_ISUID
  80. elif perms_s[2] == 's':
  81. perms |= stat.S_IXUSR
  82. perms |= stat.S_ISUID
  83. # Group perms
  84. if perms_s[3] == 'r':
  85. perms |= stat.S_IRGRP
  86. if perms_s[4] == 'w':
  87. perms |= stat.S_IWGRP
  88. if perms_s[5] == 'x':
  89. perms |= stat.S_IXGRP
  90. elif perms_s[5] == 'S':
  91. perms |= stat.S_ISGID
  92. elif perms_s[5] == 's':
  93. perms |= stat.S_IXGRP
  94. perms |= stat.S_ISGID
  95. # Others perms
  96. if perms_s[6] == 'r':
  97. perms |= stat.S_IROTH
  98. if perms_s[7] == 'w':
  99. perms |= stat.S_IWOTH
  100. if perms_s[8] == 'x':
  101. perms |= stat.S_IXOTH
  102. elif perms_s[8] == 'T':
  103. perms |= stat.S_ISVTX
  104. elif perms_s[8] == 't':
  105. perms |= stat.S_IXOTH
  106. perms |= stat.S_ISVTX
  107. return perms
  108. class File:
  109. def __init__(self, is_built, subdir, fname):
  110. self.is_built = is_built
  111. self.subdir = subdir
  112. self.fname = fname
  113. assert(isinstance(self.subdir, str))
  114. assert(isinstance(self.fname, str))
  115. def __str__(self):
  116. return self.relative_name()
  117. def __repr__(self):
  118. ret = '<File: {0}'
  119. if not self.is_built:
  120. ret += ' (not built)'
  121. ret += '>'
  122. return ret.format(self.relative_name())
  123. @staticmethod
  124. def from_source_file(source_root, subdir, fname):
  125. if not os.path.isfile(os.path.join(source_root, subdir, fname)):
  126. raise MesonException('File %s does not exist.' % fname)
  127. return File(False, subdir, fname)
  128. @staticmethod
  129. def from_built_file(subdir, fname):
  130. return File(True, subdir, fname)
  131. @staticmethod
  132. def from_absolute_file(fname):
  133. return File(False, '', fname)
  134. def rel_to_builddir(self, build_to_src):
  135. if self.is_built:
  136. return self.relative_name()
  137. else:
  138. return os.path.join(build_to_src, self.subdir, self.fname)
  139. def absolute_path(self, srcdir, builddir):
  140. absdir = srcdir
  141. if self.is_built:
  142. absdir = builddir
  143. return os.path.join(absdir, self.relative_name())
  144. def endswith(self, ending):
  145. return self.fname.endswith(ending)
  146. def split(self, s):
  147. return self.fname.split(s)
  148. def __eq__(self, other):
  149. return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
  150. def __hash__(self):
  151. return hash((self.fname, self.subdir, self.is_built))
  152. def relative_name(self):
  153. return os.path.join(self.subdir, self.fname)
  154. def get_meson_script(env, script):
  155. '''
  156. Given the path of `meson.py`/`meson`, get the path of a meson script such
  157. as `mesonintrospect` or `mesontest`.
  158. '''
  159. meson_py = env.get_build_command()
  160. (base, ext) = os.path.splitext(meson_py)
  161. return os.path.join(os.path.dirname(base), script + ext)
  162. def get_compiler_for_source(compilers, src):
  163. for comp in compilers:
  164. if comp.can_compile(src):
  165. return comp
  166. raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
  167. def classify_unity_sources(compilers, sources):
  168. compsrclist = {}
  169. for src in sources:
  170. comp = get_compiler_for_source(compilers, src)
  171. if comp not in compsrclist:
  172. compsrclist[comp] = [src]
  173. else:
  174. compsrclist[comp].append(src)
  175. return compsrclist
  176. def flatten(item):
  177. if not isinstance(item, list):
  178. return [item]
  179. result = []
  180. for i in item:
  181. if isinstance(i, list):
  182. result += flatten(i)
  183. else:
  184. result.append(i)
  185. return result
  186. def is_osx():
  187. return platform.system().lower() == 'darwin'
  188. def is_linux():
  189. return platform.system().lower() == 'linux'
  190. def is_windows():
  191. platname = platform.system().lower()
  192. return platname == 'windows' or 'mingw' in platname
  193. def is_cygwin():
  194. platname = platform.system().lower()
  195. return platname.startswith('cygwin')
  196. def is_debianlike():
  197. return os.path.isfile('/etc/debian_version')
  198. def exe_exists(arglist):
  199. try:
  200. p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  201. p.communicate()
  202. if p.returncode == 0:
  203. return True
  204. except FileNotFoundError:
  205. pass
  206. return False
  207. def detect_vcs(source_dir):
  208. vcs_systems = [
  209. dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
  210. dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
  211. dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
  212. dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
  213. ]
  214. segs = source_dir.replace('\\', '/').split('/')
  215. for i in range(len(segs), -1, -1):
  216. curdir = '/'.join(segs[:i])
  217. for vcs in vcs_systems:
  218. if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
  219. vcs['wc_dir'] = curdir
  220. return vcs
  221. return None
  222. def grab_leading_numbers(vstr, strict=False):
  223. result = []
  224. for x in vstr.split('.'):
  225. try:
  226. result.append(int(x))
  227. except ValueError as e:
  228. if strict:
  229. msg = 'Invalid version to compare against: {!r}; only ' \
  230. 'numeric digits separated by "." are allowed: ' + str(e)
  231. raise MesonException(msg.format(vstr))
  232. break
  233. return result
  234. numpart = re.compile('[0-9.]+')
  235. def version_compare(vstr1, vstr2, strict=False):
  236. match = numpart.match(vstr1.strip())
  237. if match is None:
  238. msg = 'Uncomparable version string {!r}.'
  239. raise MesonException(msg.format(vstr1))
  240. vstr1 = match.group(0)
  241. if vstr2.startswith('>='):
  242. cmpop = operator.ge
  243. vstr2 = vstr2[2:]
  244. elif vstr2.startswith('<='):
  245. cmpop = operator.le
  246. vstr2 = vstr2[2:]
  247. elif vstr2.startswith('!='):
  248. cmpop = operator.ne
  249. vstr2 = vstr2[2:]
  250. elif vstr2.startswith('=='):
  251. cmpop = operator.eq
  252. vstr2 = vstr2[2:]
  253. elif vstr2.startswith('='):
  254. cmpop = operator.eq
  255. vstr2 = vstr2[1:]
  256. elif vstr2.startswith('>'):
  257. cmpop = operator.gt
  258. vstr2 = vstr2[1:]
  259. elif vstr2.startswith('<'):
  260. cmpop = operator.lt
  261. vstr2 = vstr2[1:]
  262. else:
  263. cmpop = operator.eq
  264. varr1 = grab_leading_numbers(vstr1, strict)
  265. varr2 = grab_leading_numbers(vstr2, strict)
  266. return cmpop(varr1, varr2)
  267. def version_compare_many(vstr1, conditions):
  268. if not isinstance(conditions, (list, tuple, frozenset)):
  269. conditions = [conditions]
  270. found = []
  271. not_found = []
  272. for req in conditions:
  273. if not version_compare(vstr1, req, strict=True):
  274. not_found.append(req)
  275. else:
  276. found.append(req)
  277. return not_found == [], not_found, found
  278. def default_libdir():
  279. if is_debianlike():
  280. try:
  281. pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
  282. stdout=subprocess.PIPE,
  283. stderr=subprocess.DEVNULL)
  284. (stdo, _) = pc.communicate()
  285. if pc.returncode == 0:
  286. archpath = stdo.decode().strip()
  287. return 'lib/' + archpath
  288. except Exception:
  289. pass
  290. if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
  291. return 'lib64'
  292. return 'lib'
  293. def default_libexecdir():
  294. # There is no way to auto-detect this, so it must be set at build time
  295. return 'libexec'
  296. def default_prefix():
  297. return 'c:/' if is_windows() else '/usr/local'
  298. def get_library_dirs():
  299. if is_windows():
  300. return ['C:/mingw/lib'] # Fixme
  301. if is_osx():
  302. return ['/usr/lib'] # Fix me as well.
  303. # The following is probably Debian/Ubuntu specific.
  304. # /usr/local/lib is first because it contains stuff
  305. # installed by the sysadmin and is probably more up-to-date
  306. # than /usr/lib. If you feel that this search order is
  307. # problematic, please raise the issue on the mailing list.
  308. unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
  309. plat = subprocess.check_output(['uname', '-m']).decode().strip()
  310. # This is a terrible hack. I admit it and I'm really sorry.
  311. # I just don't know what the correct solution is.
  312. if plat == 'i686':
  313. plat = 'i386'
  314. if plat.startswith('arm'):
  315. plat = 'arm'
  316. unixdirs += glob('/usr/lib/' + plat + '*')
  317. if os.path.exists('/usr/lib64'):
  318. unixdirs.append('/usr/lib64')
  319. unixdirs += glob('/lib/' + plat + '*')
  320. if os.path.exists('/lib64'):
  321. unixdirs.append('/lib64')
  322. unixdirs += glob('/lib/' + plat + '*')
  323. return unixdirs
  324. def do_replacement(regex, line, confdata):
  325. match = re.search(regex, line)
  326. while match:
  327. varname = match.group(1)
  328. if varname in confdata:
  329. (var, desc) = confdata.get(varname)
  330. if isinstance(var, str):
  331. pass
  332. elif isinstance(var, int):
  333. var = str(var)
  334. else:
  335. raise RuntimeError('Tried to replace a variable with something other than a string or int.')
  336. else:
  337. var = ''
  338. line = line.replace('@' + varname + '@', var)
  339. match = re.search(regex, line)
  340. return line
  341. def do_mesondefine(line, confdata):
  342. arr = line.split()
  343. if len(arr) != 2:
  344. raise MesonException('#mesondefine does not contain exactly two tokens: %s', line.strip())
  345. varname = arr[1]
  346. try:
  347. (v, desc) = confdata.get(varname)
  348. except KeyError:
  349. return '/* #undef %s */\n' % varname
  350. if isinstance(v, bool):
  351. if v:
  352. return '#define %s\n' % varname
  353. else:
  354. return '#undef %s\n' % varname
  355. elif isinstance(v, int):
  356. return '#define %s %d\n' % (varname, v)
  357. elif isinstance(v, str):
  358. return '#define %s %s\n' % (varname, v)
  359. else:
  360. raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
  361. def do_conf_file(src, dst, confdata):
  362. try:
  363. with open(src, encoding='utf-8') as f:
  364. data = f.readlines()
  365. except Exception as e:
  366. raise MesonException('Could not read input file %s: %s' % (src, str(e)))
  367. # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
  368. # Also allow escaping '@' with '\@'
  369. regex = re.compile(r'[^\\]?@([-a-zA-Z0-9_]+)@')
  370. result = []
  371. for line in data:
  372. if line.startswith('#mesondefine'):
  373. line = do_mesondefine(line, confdata)
  374. else:
  375. line = do_replacement(regex, line, confdata)
  376. result.append(line)
  377. dst_tmp = dst + '~'
  378. with open(dst_tmp, 'w', encoding='utf-8') as f:
  379. f.writelines(result)
  380. shutil.copymode(src, dst_tmp)
  381. replace_if_different(dst, dst_tmp)
  382. def dump_conf_header(ofilename, cdata):
  383. with open(ofilename, 'w', encoding='utf-8') as ofile:
  384. ofile.write('''/*
  385. * Autogenerated by the Meson build system.
  386. * Do not edit, your changes will be lost.
  387. */
  388. #pragma once
  389. ''')
  390. for k in sorted(cdata.keys()):
  391. (v, desc) = cdata.get(k)
  392. if desc:
  393. ofile.write('/* %s */\n' % desc)
  394. if isinstance(v, bool):
  395. if v:
  396. ofile.write('#define %s\n\n' % k)
  397. else:
  398. ofile.write('#undef %s\n\n' % k)
  399. elif isinstance(v, (int, str)):
  400. ofile.write('#define %s %s\n\n' % (k, v))
  401. else:
  402. raise MesonException('Unknown data type in configuration file entry: ' + k)
  403. def replace_if_different(dst, dst_tmp):
  404. # If contents are identical, don't touch the file to prevent
  405. # unnecessary rebuilds.
  406. different = True
  407. try:
  408. with open(dst, 'r') as f1, open(dst_tmp, 'r') as f2:
  409. if f1.read() == f2.read():
  410. different = False
  411. except FileNotFoundError:
  412. pass
  413. if different:
  414. os.replace(dst_tmp, dst)
  415. else:
  416. os.unlink(dst_tmp)
  417. def typeslistify(item, types):
  418. '''
  419. Ensure that type(@item) is one of @types or a
  420. list of items all of which are of type @types
  421. '''
  422. if isinstance(item, types):
  423. item = [item]
  424. if not isinstance(item, list):
  425. raise MesonException('Item must be a list or one of {!r}'.format(types))
  426. for i in item:
  427. if i is not None and not isinstance(i, types):
  428. raise MesonException('List item must be one of {!r}'.format(types))
  429. return item
  430. def stringlistify(item):
  431. return typeslistify(item, str)
  432. def expand_arguments(args):
  433. expended_args = []
  434. for arg in args:
  435. if not arg.startswith('@'):
  436. expended_args.append(arg)
  437. continue
  438. args_file = arg[1:]
  439. try:
  440. with open(args_file) as f:
  441. extended_args = f.read().split()
  442. expended_args += extended_args
  443. except Exception as e:
  444. print('Error expanding command line arguments, %s not found' % args_file)
  445. print(e)
  446. return None
  447. return expended_args
  448. def Popen_safe(args, write=None, stderr=subprocess.PIPE, **kwargs):
  449. p = subprocess.Popen(args, universal_newlines=True,
  450. close_fds=False,
  451. stdout=subprocess.PIPE,
  452. stderr=stderr, **kwargs)
  453. o, e = p.communicate(write)
  454. return p, o, e
  455. def commonpath(paths):
  456. '''
  457. For use on Python 3.4 where os.path.commonpath is not available.
  458. We currently use it everywhere so this receives enough testing.
  459. '''
  460. # XXX: Replace me with os.path.commonpath when we start requiring Python 3.5
  461. import pathlib
  462. if not paths:
  463. raise ValueError('arg is an empty sequence')
  464. common = pathlib.PurePath(paths[0])
  465. for path in paths[1:]:
  466. new = []
  467. path = pathlib.PurePath(path)
  468. for c, p in zip(common.parts, path.parts):
  469. if c != p:
  470. break
  471. new.append(c)
  472. # Don't convert '' into '.'
  473. if not new:
  474. common = ''
  475. break
  476. new = os.path.join(*new)
  477. common = pathlib.PurePath(new)
  478. return str(common)
  479. def iter_regexin_iter(regexiter, initer):
  480. '''
  481. Takes each regular expression in @regexiter and tries to search for it in
  482. every item in @initer. If there is a match, returns that match.
  483. Else returns False.
  484. '''
  485. for regex in regexiter:
  486. for ii in initer:
  487. if not isinstance(ii, str):
  488. continue
  489. match = re.search(regex, ii)
  490. if match:
  491. return match.group()
  492. return False
  493. def _substitute_values_check_errors(command, values):
  494. # Error checking
  495. inregex = ('@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@')
  496. outregex = ('@OUTPUT([0-9]+)?@', '@OUTDIR@')
  497. if '@INPUT@' not in values:
  498. # Error out if any input-derived templates are present in the command
  499. match = iter_regexin_iter(inregex, command)
  500. if match:
  501. m = 'Command cannot have {!r}, since no input files were specified'
  502. raise MesonException(m.format(match))
  503. else:
  504. if len(values['@INPUT@']) > 1:
  505. # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
  506. match = iter_regexin_iter(inregex[1:], command)
  507. if match:
  508. raise MesonException('Command cannot have {!r} when there is '
  509. 'more than one input file'.format(match))
  510. # Error out if an invalid @INPUTnn@ template was specified
  511. for each in command:
  512. if not isinstance(each, str):
  513. continue
  514. match = re.search(inregex[0], each)
  515. if match and match.group() not in values:
  516. m = 'Command cannot have {!r} since there are only {!r} inputs'
  517. raise MesonException(m.format(match.group(), len(values['@INPUT@'])))
  518. if '@OUTPUT@' not in values:
  519. # Error out if any output-derived templates are present in the command
  520. match = iter_regexin_iter(outregex, command)
  521. if match:
  522. m = 'Command cannot have {!r} since there are no outputs'
  523. raise MesonException(m.format(match))
  524. else:
  525. # Error out if an invalid @OUTPUTnn@ template was specified
  526. for each in command:
  527. if not isinstance(each, str):
  528. continue
  529. match = re.search(outregex[0], each)
  530. if match and match.group() not in values:
  531. m = 'Command cannot have {!r} since there are only {!r} outputs'
  532. raise MesonException(m.format(match.group(), len(values['@OUTPUT@'])))
  533. def substitute_values(command, values):
  534. '''
  535. Substitute the template strings in the @values dict into the list of
  536. strings @command and return a new list. For a full list of the templates,
  537. see get_filenames_templates_dict()
  538. If multiple inputs/outputs are given in the @values dictionary, we
  539. substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
  540. just a part of it, and in that case we substitute *all* of them.
  541. '''
  542. # Error checking
  543. _substitute_values_check_errors(command, values)
  544. # Substitution
  545. outcmd = []
  546. for vv in command:
  547. if not isinstance(vv, str):
  548. outcmd.append(vv)
  549. elif '@INPUT@' in vv:
  550. inputs = values['@INPUT@']
  551. if vv == '@INPUT@':
  552. outcmd += inputs
  553. elif len(inputs) == 1:
  554. outcmd.append(vv.replace('@INPUT@', inputs[0]))
  555. else:
  556. raise MesonException("Command has '@INPUT@' as part of a "
  557. "string and more than one input file")
  558. elif '@OUTPUT@' in vv:
  559. outputs = values['@OUTPUT@']
  560. if vv == '@OUTPUT@':
  561. outcmd += outputs
  562. elif len(outputs) == 1:
  563. outcmd.append(vv.replace('@OUTPUT@', outputs[0]))
  564. else:
  565. raise MesonException("Command has '@OUTPUT@' as part of a "
  566. "string and more than one output file")
  567. # Append values that are exactly a template string.
  568. # This is faster than a string replace.
  569. elif vv in values:
  570. outcmd.append(values[vv])
  571. # Substitute everything else with replacement
  572. else:
  573. for key, value in values.items():
  574. if key in ('@INPUT@', '@OUTPUT@'):
  575. # Already done above
  576. continue
  577. vv = vv.replace(key, value)
  578. outcmd.append(vv)
  579. return outcmd
  580. def get_filenames_templates_dict(inputs, outputs):
  581. '''
  582. Create a dictionary with template strings as keys and values as values for
  583. the following templates:
  584. @INPUT@ - the full path to one or more input files, from @inputs
  585. @OUTPUT@ - the full path to one or more output files, from @outputs
  586. @OUTDIR@ - the full path to the directory containing the output files
  587. If there is only one input file, the following keys are also created:
  588. @PLAINNAME@ - the filename of the input file
  589. @BASENAME@ - the filename of the input file with the extension removed
  590. If there is more than one input file, the following keys are also created:
  591. @INPUT0@, @INPUT1@, ... one for each input file
  592. If there is more than one output file, the following keys are also created:
  593. @OUTPUT0@, @OUTPUT1@, ... one for each output file
  594. '''
  595. values = {}
  596. # Gather values derived from the input
  597. if inputs:
  598. # We want to substitute all the inputs.
  599. values['@INPUT@'] = inputs
  600. for (ii, vv) in enumerate(inputs):
  601. # Write out @INPUT0@, @INPUT1@, ...
  602. values['@INPUT{}@'.format(ii)] = vv
  603. if len(inputs) == 1:
  604. # Just one value, substitute @PLAINNAME@ and @BASENAME@
  605. values['@PLAINNAME@'] = plain = os.path.split(inputs[0])[1]
  606. values['@BASENAME@'] = os.path.splitext(plain)[0]
  607. if outputs:
  608. # Gather values derived from the outputs, similar to above.
  609. values['@OUTPUT@'] = outputs
  610. for (ii, vv) in enumerate(outputs):
  611. values['@OUTPUT{}@'.format(ii)] = vv
  612. # Outdir should be the same for all outputs
  613. values['@OUTDIR@'] = os.path.split(outputs[0])[0]
  614. # Many external programs fail on empty arguments.
  615. if values['@OUTDIR@'] == '':
  616. values['@OUTDIR@'] = '.'
  617. return values
  618. def windows_proof_rmtree(f):
  619. # On Windows if anyone is holding a file open you can't
  620. # delete it. As an example an anti virus scanner might
  621. # be scanning files you are trying to delete. The only
  622. # way to fix this is to try again and again.
  623. delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
  624. for d in delays:
  625. try:
  626. shutil.rmtree(f)
  627. return
  628. except (OSError, PermissionError):
  629. time.sleep(d)
  630. # Try one last time and throw if it fails.
  631. shutil.rmtree(f)
  632. class OrderedSet(collections.MutableSet):
  633. """A set that preserves the order in which items are added, by first
  634. insertion.
  635. """
  636. def __init__(self, iterable=None):
  637. self.__container = collections.OrderedDict()
  638. if iterable:
  639. self.update(iterable)
  640. def __contains__(self, value):
  641. return value in self.__container
  642. def __iter__(self):
  643. return iter(self.__container.keys())
  644. def __len__(self):
  645. return len(self.__container)
  646. def __repr__(self):
  647. # Don't print 'OrderedSet("")' for an empty set.
  648. if self.__container:
  649. return 'OrderedSet("{}")'.format(
  650. '", "'.join(repr(e) for e in self.__container.keys()))
  651. return 'OrderedSet()'
  652. def add(self, value):
  653. self.__container[value] = None
  654. def discard(self, value):
  655. if value in self.__container:
  656. del self.__container[value]
  657. def update(self, iterable):
  658. for item in iterable:
  659. self.__container[item] = None
  660. def difference(self, set_):
  661. return type(self)(e for e in self if e not in set_)