mesonlib.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 platform, subprocess, operator, os, shutil, re
  13. from glob import glob
  14. from coredata import MesonException
  15. class File:
  16. def __init__(self, is_built, subdir, fname):
  17. self.is_built = is_built
  18. self.subdir = subdir
  19. self.fname = fname
  20. @staticmethod
  21. def from_source_file(source_root, subdir, fname):
  22. if not os.path.isfile(os.path.join(source_root, subdir, fname)):
  23. raise MesonException('File %s does not exist.' % fname)
  24. return File(False, subdir, fname)
  25. @staticmethod
  26. def from_built_file(subdir, fname):
  27. return File(True, subdir, fname)
  28. @staticmethod
  29. def from_absolute_file(fname):
  30. return File(False, '', fname)
  31. def rel_to_builddir(self, build_to_src):
  32. if self.is_built:
  33. return os.path.join(self.subdir, self.fname)
  34. else:
  35. return os.path.join(build_to_src, self.subdir, self.fname)
  36. def endswith(self, ending):
  37. return self.fname.endswith(ending)
  38. def split(self, s):
  39. return self.fname.split(s)
  40. def __eq__(self, other):
  41. return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
  42. def __hash__(self):
  43. return hash((self.fname, self.subdir, self.is_built))
  44. def flatten(item):
  45. if not isinstance(item, list):
  46. return item
  47. result = []
  48. for i in item:
  49. if isinstance(i, list):
  50. result += flatten(i)
  51. else:
  52. result.append(i)
  53. return result
  54. def is_osx():
  55. return platform.system().lower() == 'darwin'
  56. def is_linux():
  57. return platform.system().lower() == 'linux'
  58. def is_windows():
  59. return platform.system().lower() == 'windows'
  60. def is_debianlike():
  61. try:
  62. open('/etc/debian_version', 'r')
  63. return True
  64. except FileNotFoundError:
  65. return False
  66. def exe_exists(arglist):
  67. try:
  68. p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  69. p.communicate()
  70. if p.returncode == 0:
  71. return True
  72. except FileNotFoundError:
  73. pass
  74. return False
  75. def detect_vcs(source_dir):
  76. vcs_systems = [
  77. dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
  78. dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -n', rev_regex = '(.*)', dep = '.hg/dirstate'),
  79. dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
  80. dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
  81. ]
  82. segs = source_dir.replace('\\', '/').split('/')
  83. for i in range(len(segs), -1, -1):
  84. curdir = '/'.join(segs[:i])
  85. for vcs in vcs_systems:
  86. if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
  87. vcs['wc_dir'] = curdir
  88. return vcs
  89. return None
  90. def version_compare(vstr1, vstr2):
  91. if '-' in vstr1:
  92. vstr1 = vstr1.split('-')[0]
  93. if vstr2.startswith('>='):
  94. cmpop = operator.ge
  95. vstr2 = vstr2[2:]
  96. elif vstr2.startswith('<='):
  97. cmpop = operator.le
  98. vstr2 = vstr2[2:]
  99. elif vstr2.startswith('!='):
  100. cmpop = operator.ne
  101. vstr2 = vstr2[2:]
  102. elif vstr2.startswith('=='):
  103. cmpop = operator.eq
  104. vstr2 = vstr2[2:]
  105. elif vstr2.startswith('='):
  106. cmpop = operator.eq
  107. vstr2 = vstr2[1:]
  108. elif vstr2.startswith('>'):
  109. cmpop = operator.gt
  110. vstr2 = vstr2[1:]
  111. elif vstr2.startswith('<'):
  112. cmpop = operator.lt
  113. vstr2 = vstr2[1:]
  114. else:
  115. cmpop = operator.eq
  116. varr1 = [int(x) for x in vstr1.split('.')]
  117. varr2 = [int(x) for x in vstr2.split('.')]
  118. return cmpop(varr1, varr2)
  119. def default_libdir():
  120. try:
  121. archpath = subprocess.check_output(['dpkg-architecture', '-qDEB_HOST_MULTIARCH']).decode().strip()
  122. return 'lib/' + archpath
  123. except FileNotFoundError:
  124. pass
  125. if os.path.isdir('/usr/lib64'):
  126. return 'lib64'
  127. return 'lib'
  128. def get_library_dirs():
  129. if is_windows():
  130. return ['C:/mingw/lib'] # Fixme
  131. if is_osx():
  132. return ['/usr/lib'] # Fix me as well.
  133. # The following is probably Debian/Ubuntu specific.
  134. # /usr/local/lib is first because it contains stuff
  135. # installed by the sysadmin and is probably more up-to-date
  136. # than /usr/lib. If you feel that this search order is
  137. # problematic, please raise the issue on the mailing list.
  138. unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
  139. plat = subprocess.check_output(['uname', '-m']).decode().strip()
  140. # This is a terrible hack. I admit it and I'm really sorry.
  141. # I just don't know what the correct solution is.
  142. if plat == 'i686':
  143. plat = 'i386'
  144. if plat.startswith('arm'):
  145. plat = 'arm'
  146. unixdirs += glob('/usr/lib/' + plat + '*')
  147. if os.path.exists('/usr/lib64'):
  148. unixdirs.append('/usr/lib64')
  149. unixdirs += glob('/lib/' + plat + '*')
  150. if os.path.exists('/lib64'):
  151. unixdirs.append('/lib64')
  152. unixdirs += glob('/lib/' + plat + '*')
  153. return unixdirs
  154. def do_replacement(regex, line, confdata):
  155. match = re.search(regex, line)
  156. while match:
  157. varname = match.group(1)
  158. if varname in confdata.keys():
  159. var = confdata.get(varname)
  160. if isinstance(var, str):
  161. pass
  162. elif isinstance(var, int):
  163. var = str(var)
  164. else:
  165. raise RuntimeError('Tried to replace a variable with something other than a string or int.')
  166. else:
  167. var = ''
  168. line = line.replace('@' + varname + '@', var)
  169. match = re.search(regex, line)
  170. return line
  171. def do_mesondefine(line, confdata):
  172. arr = line.split()
  173. if len(arr) != 2:
  174. raise MesonException('#mesondefine does not contain exactly two tokens: %s', line.strip())
  175. varname = arr[1]
  176. try:
  177. v = confdata.get(varname)
  178. except KeyError:
  179. return '/* undef %s */\n' % varname
  180. if isinstance(v, bool):
  181. if v:
  182. return '#define %s\n' % varname
  183. else:
  184. return '#undef %s\n' % varname
  185. elif isinstance(v, int):
  186. return '#define %s %d\n' % (varname, v)
  187. elif isinstance(v, str):
  188. return '#define %s %s\n' % (varname, v)
  189. else:
  190. raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
  191. def do_conf_file(src, dst, confdata):
  192. data = open(src).readlines()
  193. regex = re.compile('@(.*?)@')
  194. result = []
  195. for line in data:
  196. if line.startswith('#mesondefine'):
  197. line = do_mesondefine(line, confdata)
  198. else:
  199. line = do_replacement(regex, line, confdata)
  200. result.append(line)
  201. dst_tmp = dst + '~'
  202. open(dst_tmp, 'w').writelines(result)
  203. shutil.copymode(src, dst_tmp)
  204. replace_if_different(dst, dst_tmp)
  205. def replace_if_different(dst, dst_tmp):
  206. # If contents are identical, don't touch the file to prevent
  207. # unnecessary rebuilds.
  208. try:
  209. if open(dst, 'r').read() == open(dst_tmp, 'r').read():
  210. os.unlink(dst_tmp)
  211. return
  212. except FileNotFoundError:
  213. pass
  214. os.replace(dst_tmp, dst)