mesonlib.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. # Copyright 2012-2020 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. from pathlib import Path
  13. import sys
  14. import stat
  15. import time
  16. import platform, subprocess, operator, os, shlex, shutil, re
  17. import collections
  18. from enum import Enum
  19. from functools import lru_cache, wraps
  20. from itertools import tee, filterfalse
  21. import typing as T
  22. import uuid
  23. import textwrap
  24. from mesonbuild import mlog
  25. if T.TYPE_CHECKING:
  26. from .build import ConfigurationData
  27. from .coredata import OptionDictType, UserOption
  28. from .compilers.compilers import CompilerType
  29. from .interpreterbase import ObjectHolder
  30. _T = T.TypeVar('_T')
  31. _U = T.TypeVar('_U')
  32. have_fcntl = False
  33. have_msvcrt = False
  34. # {subproject: project_meson_version}
  35. project_meson_versions = {} # type: T.Dict[str, str]
  36. try:
  37. import fcntl
  38. have_fcntl = True
  39. except Exception:
  40. pass
  41. try:
  42. import msvcrt
  43. have_msvcrt = True
  44. except Exception:
  45. pass
  46. from glob import glob
  47. if os.path.basename(sys.executable) == 'meson.exe':
  48. # In Windows and using the MSI installed executable.
  49. python_command = [sys.executable, 'runpython']
  50. else:
  51. python_command = [sys.executable]
  52. meson_command = None
  53. GIT = shutil.which('git')
  54. def git(cmd: T.List[str], workingdir: str, **kwargs: T.Any) -> subprocess.CompletedProcess:
  55. pc = subprocess.run([GIT, '-C', workingdir] + cmd,
  56. # Redirect stdin to DEVNULL otherwise git messes up the
  57. # console and ANSI colors stop working on Windows.
  58. stdin=subprocess.DEVNULL, **kwargs)
  59. # Sometimes git calls git recursively, such as `git submodule update
  60. # --recursive` which will be without the above workaround, so set the
  61. # console mode again just in case.
  62. mlog.setup_console()
  63. return pc
  64. def set_meson_command(mainfile: str) -> None:
  65. global python_command
  66. global meson_command
  67. # On UNIX-like systems `meson` is a Python script
  68. # On Windows `meson` and `meson.exe` are wrapper exes
  69. if not mainfile.endswith('.py'):
  70. meson_command = [mainfile]
  71. elif os.path.isabs(mainfile) and mainfile.endswith('mesonmain.py'):
  72. # Can't actually run meson with an absolute path to mesonmain.py, it must be run as -m mesonbuild.mesonmain
  73. meson_command = python_command + ['-m', 'mesonbuild.mesonmain']
  74. else:
  75. # Either run uninstalled, or full path to meson-script.py
  76. meson_command = python_command + [mainfile]
  77. # We print this value for unit tests.
  78. if 'MESON_COMMAND_TESTS' in os.environ:
  79. mlog.log('meson_command is {!r}'.format(meson_command))
  80. def is_ascii_string(astring: T.Union[str, bytes]) -> bool:
  81. try:
  82. if isinstance(astring, str):
  83. astring.encode('ascii')
  84. elif isinstance(astring, bytes):
  85. astring.decode('ascii')
  86. except UnicodeDecodeError:
  87. return False
  88. return True
  89. def check_direntry_issues(direntry_array: T.Union[T.List[T.Union[str, bytes]], str, bytes]) -> None:
  90. import locale
  91. # Warn if the locale is not UTF-8. This can cause various unfixable issues
  92. # such as os.stat not being able to decode filenames with unicode in them.
  93. # There is no way to reset both the preferred encoding and the filesystem
  94. # encoding, so we can just warn about it.
  95. e = locale.getpreferredencoding()
  96. if e.upper() != 'UTF-8' and not is_windows():
  97. if not isinstance(direntry_array, list):
  98. direntry_array = [direntry_array]
  99. for de in direntry_array:
  100. if is_ascii_string(de):
  101. continue
  102. mlog.warning(textwrap.dedent('''
  103. You are using {!r} which is not a Unicode-compatible
  104. locale but you are trying to access a file system entry called {!r} which is
  105. not pure ASCII. This may cause problems.
  106. '''.format(e, de)), file=sys.stderr)
  107. # Put this in objects that should not get dumped to pickle files
  108. # by accident.
  109. import threading
  110. an_unpicklable_object = threading.Lock()
  111. class MesonException(Exception):
  112. '''Exceptions thrown by Meson'''
  113. file = None # type: T.Optional[str]
  114. lineno = None # type: T.Optional[int]
  115. colno = None # type: T.Optional[int]
  116. class EnvironmentException(MesonException):
  117. '''Exceptions thrown while processing and creating the build environment'''
  118. class FileMode:
  119. # The first triad is for owner permissions, the second for group permissions,
  120. # and the third for others (everyone else).
  121. # For the 1st character:
  122. # 'r' means can read
  123. # '-' means not allowed
  124. # For the 2nd character:
  125. # 'w' means can write
  126. # '-' means not allowed
  127. # For the 3rd character:
  128. # 'x' means can execute
  129. # 's' means can execute and setuid/setgid is set (owner/group triads only)
  130. # 'S' means cannot execute and setuid/setgid is set (owner/group triads only)
  131. # 't' means can execute and sticky bit is set ("others" triads only)
  132. # 'T' means cannot execute and sticky bit is set ("others" triads only)
  133. # '-' means none of these are allowed
  134. #
  135. # The meanings of 'rwx' perms is not obvious for directories; see:
  136. # https://www.hackinglinuxexposed.com/articles/20030424.html
  137. #
  138. # For information on this notation such as setuid/setgid/sticky bits, see:
  139. # https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
  140. symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
  141. '[r-][w-][xsS-]' # Group perms
  142. '[r-][w-][xtT-]') # Others perms
  143. def __init__(self, perms: T.Optional[str] = None, owner: T.Optional[str] = None,
  144. group: T.Optional[str] = None):
  145. self.perms_s = perms
  146. self.perms = self.perms_s_to_bits(perms)
  147. self.owner = owner
  148. self.group = group
  149. def __repr__(self) -> str:
  150. ret = '<FileMode: {!r} owner={} group={}'
  151. return ret.format(self.perms_s, self.owner, self.group)
  152. @classmethod
  153. def perms_s_to_bits(cls, perms_s: T.Optional[str]) -> int:
  154. '''
  155. Does the opposite of stat.filemode(), converts strings of the form
  156. 'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
  157. '''
  158. if perms_s is None:
  159. # No perms specified, we will not touch the permissions
  160. return -1
  161. eg = 'rwxr-xr-x'
  162. if not isinstance(perms_s, str):
  163. msg = 'Install perms must be a string. For example, {!r}'
  164. raise MesonException(msg.format(eg))
  165. if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
  166. msg = 'File perms {!r} must be exactly 9 chars. For example, {!r}'
  167. raise MesonException(msg.format(perms_s, eg))
  168. perms = 0
  169. # Owner perms
  170. if perms_s[0] == 'r':
  171. perms |= stat.S_IRUSR
  172. if perms_s[1] == 'w':
  173. perms |= stat.S_IWUSR
  174. if perms_s[2] == 'x':
  175. perms |= stat.S_IXUSR
  176. elif perms_s[2] == 'S':
  177. perms |= stat.S_ISUID
  178. elif perms_s[2] == 's':
  179. perms |= stat.S_IXUSR
  180. perms |= stat.S_ISUID
  181. # Group perms
  182. if perms_s[3] == 'r':
  183. perms |= stat.S_IRGRP
  184. if perms_s[4] == 'w':
  185. perms |= stat.S_IWGRP
  186. if perms_s[5] == 'x':
  187. perms |= stat.S_IXGRP
  188. elif perms_s[5] == 'S':
  189. perms |= stat.S_ISGID
  190. elif perms_s[5] == 's':
  191. perms |= stat.S_IXGRP
  192. perms |= stat.S_ISGID
  193. # Others perms
  194. if perms_s[6] == 'r':
  195. perms |= stat.S_IROTH
  196. if perms_s[7] == 'w':
  197. perms |= stat.S_IWOTH
  198. if perms_s[8] == 'x':
  199. perms |= stat.S_IXOTH
  200. elif perms_s[8] == 'T':
  201. perms |= stat.S_ISVTX
  202. elif perms_s[8] == 't':
  203. perms |= stat.S_IXOTH
  204. perms |= stat.S_ISVTX
  205. return perms
  206. class File:
  207. def __init__(self, is_built: bool, subdir: str, fname: str):
  208. self.is_built = is_built
  209. self.subdir = subdir
  210. self.fname = fname
  211. def __str__(self) -> str:
  212. return self.relative_name()
  213. def __repr__(self) -> str:
  214. ret = '<File: {0}'
  215. if not self.is_built:
  216. ret += ' (not built)'
  217. ret += '>'
  218. return ret.format(self.relative_name())
  219. @staticmethod
  220. @lru_cache(maxsize=None)
  221. def from_source_file(source_root: str, subdir: str, fname: str) -> 'File':
  222. if not os.path.isfile(os.path.join(source_root, subdir, fname)):
  223. raise MesonException('File %s does not exist.' % fname)
  224. return File(False, subdir, fname)
  225. @staticmethod
  226. def from_built_file(subdir: str, fname: str) -> 'File':
  227. return File(True, subdir, fname)
  228. @staticmethod
  229. def from_absolute_file(fname: str) -> 'File':
  230. return File(False, '', fname)
  231. @lru_cache(maxsize=None)
  232. def rel_to_builddir(self, build_to_src: str) -> str:
  233. if self.is_built:
  234. return self.relative_name()
  235. else:
  236. return os.path.join(build_to_src, self.subdir, self.fname)
  237. @lru_cache(maxsize=None)
  238. def absolute_path(self, srcdir: str, builddir: str) -> str:
  239. absdir = srcdir
  240. if self.is_built:
  241. absdir = builddir
  242. return os.path.join(absdir, self.relative_name())
  243. def endswith(self, ending: str) -> bool:
  244. return self.fname.endswith(ending)
  245. def split(self, s: str) -> T.List[str]:
  246. return self.fname.split(s)
  247. def __eq__(self, other) -> bool:
  248. if not isinstance(other, File):
  249. return NotImplemented
  250. return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
  251. def __hash__(self) -> int:
  252. return hash((self.fname, self.subdir, self.is_built))
  253. @lru_cache(maxsize=None)
  254. def relative_name(self) -> str:
  255. return os.path.join(self.subdir, self.fname)
  256. def get_compiler_for_source(compilers: T.Iterable['CompilerType'], src: str) -> 'CompilerType':
  257. """Given a set of compilers and a source, find the compiler for that source type."""
  258. for comp in compilers:
  259. if comp.can_compile(src):
  260. return comp
  261. raise MesonException('No specified compiler can handle file {!s}'.format(src))
  262. def classify_unity_sources(compilers: T.Iterable['CompilerType'], sources: T.Iterable[str]) -> T.Dict['CompilerType', T.List[str]]:
  263. compsrclist = {} # type: T.Dict[CompilerType, T.List[str]]
  264. for src in sources:
  265. comp = get_compiler_for_source(compilers, src)
  266. if comp not in compsrclist:
  267. compsrclist[comp] = [src]
  268. else:
  269. compsrclist[comp].append(src)
  270. return compsrclist
  271. class OrderedEnum(Enum):
  272. """
  273. An Enum which additionally offers homogeneous ordered comparison.
  274. """
  275. def __ge__(self, other):
  276. if self.__class__ is other.__class__:
  277. return self.value >= other.value
  278. return NotImplemented
  279. def __gt__(self, other):
  280. if self.__class__ is other.__class__:
  281. return self.value > other.value
  282. return NotImplemented
  283. def __le__(self, other):
  284. if self.__class__ is other.__class__:
  285. return self.value <= other.value
  286. return NotImplemented
  287. def __lt__(self, other):
  288. if self.__class__ is other.__class__:
  289. return self.value < other.value
  290. return NotImplemented
  291. class MachineChoice(OrderedEnum):
  292. """Enum class representing one of the two abstract machine names used in
  293. most places: the build, and host, machines.
  294. """
  295. BUILD = 0
  296. HOST = 1
  297. def get_lower_case_name(self) -> str:
  298. return PerMachine('build', 'host')[self]
  299. def get_prefix(self) -> str:
  300. return PerMachine('build.', '')[self]
  301. class PerMachine(T.Generic[_T]):
  302. def __init__(self, build: _T, host: _T):
  303. self.build = build
  304. self.host = host
  305. def __getitem__(self, machine: MachineChoice) -> _T:
  306. return {
  307. MachineChoice.BUILD: self.build,
  308. MachineChoice.HOST: self.host,
  309. }[machine]
  310. def __setitem__(self, machine: MachineChoice, val: _T) -> None:
  311. setattr(self, machine.get_lower_case_name(), val)
  312. def miss_defaulting(self) -> "PerMachineDefaultable[T.Optional[_T]]":
  313. """Unset definition duplicated from their previous to None
  314. This is the inverse of ''default_missing''. By removing defaulted
  315. machines, we can elaborate the original and then redefault them and thus
  316. avoid repeating the elaboration explicitly.
  317. """
  318. unfreeze = PerMachineDefaultable() # type: PerMachineDefaultable[T.Optional[_T]]
  319. unfreeze.build = self.build
  320. unfreeze.host = self.host
  321. if unfreeze.host == unfreeze.build:
  322. unfreeze.host = None
  323. return unfreeze
  324. class PerThreeMachine(PerMachine[_T]):
  325. """Like `PerMachine` but includes `target` too.
  326. It turns out just one thing do we need track the target machine. There's no
  327. need to computer the `target` field so we don't bother overriding the
  328. `__getitem__`/`__setitem__` methods.
  329. """
  330. def __init__(self, build: _T, host: _T, target: _T):
  331. super().__init__(build, host)
  332. self.target = target
  333. def miss_defaulting(self) -> "PerThreeMachineDefaultable[T.Optional[_T]]":
  334. """Unset definition duplicated from their previous to None
  335. This is the inverse of ''default_missing''. By removing defaulted
  336. machines, we can elaborate the original and then redefault them and thus
  337. avoid repeating the elaboration explicitly.
  338. """
  339. unfreeze = PerThreeMachineDefaultable() # type: PerThreeMachineDefaultable[T.Optional[_T]]
  340. unfreeze.build = self.build
  341. unfreeze.host = self.host
  342. unfreeze.target = self.target
  343. if unfreeze.target == unfreeze.host:
  344. unfreeze.target = None
  345. if unfreeze.host == unfreeze.build:
  346. unfreeze.host = None
  347. return unfreeze
  348. def matches_build_machine(self, machine: MachineChoice) -> bool:
  349. return self.build == self[machine]
  350. class PerMachineDefaultable(PerMachine[T.Optional[_T]]):
  351. """Extends `PerMachine` with the ability to default from `None`s.
  352. """
  353. def __init__(self):
  354. super().__init__(None, None)
  355. def default_missing(self) -> "PerMachine[T.Optional[_T]]":
  356. """Default host to build
  357. This allows just specifying nothing in the native case, and just host in the
  358. cross non-compiler case.
  359. """
  360. freeze = PerMachine(self.build, self.host)
  361. if freeze.host is None:
  362. freeze.host = freeze.build
  363. return freeze
  364. class PerThreeMachineDefaultable(PerMachineDefaultable, PerThreeMachine[T.Optional[_T]]):
  365. """Extends `PerThreeMachine` with the ability to default from `None`s.
  366. """
  367. def __init__(self):
  368. PerThreeMachine.__init__(self, None, None, None)
  369. def default_missing(self) -> "PerThreeMachine[T.Optional[_T]]":
  370. """Default host to build and target to host.
  371. This allows just specifying nothing in the native case, just host in the
  372. cross non-compiler case, and just target in the native-built
  373. cross-compiler case.
  374. """
  375. freeze = PerThreeMachine(self.build, self.host, self.target)
  376. if freeze.host is None:
  377. freeze.host = freeze.build
  378. if freeze.target is None:
  379. freeze.target = freeze.host
  380. return freeze
  381. def is_sunos() -> bool:
  382. return platform.system().lower() == 'sunos'
  383. def is_osx() -> bool:
  384. return platform.system().lower() == 'darwin'
  385. def is_linux() -> bool:
  386. return platform.system().lower() == 'linux'
  387. def is_android() -> bool:
  388. return platform.system().lower() == 'android'
  389. def is_haiku() -> bool:
  390. return platform.system().lower() == 'haiku'
  391. def is_openbsd() -> bool:
  392. return platform.system().lower() == 'openbsd'
  393. def is_windows() -> bool:
  394. platname = platform.system().lower()
  395. return platname == 'windows' or 'mingw' in platname
  396. def is_cygwin() -> bool:
  397. return platform.system().lower().startswith('cygwin')
  398. def is_debianlike() -> bool:
  399. return os.path.isfile('/etc/debian_version')
  400. def is_dragonflybsd() -> bool:
  401. return platform.system().lower() == 'dragonfly'
  402. def is_netbsd() -> bool:
  403. return platform.system().lower() == 'netbsd'
  404. def is_freebsd() -> bool:
  405. return platform.system().lower() == 'freebsd'
  406. def is_hurd() -> bool:
  407. return platform.system().lower() == 'gnu'
  408. def exe_exists(arglist: T.List[str]) -> bool:
  409. try:
  410. if subprocess.run(arglist, timeout=10).returncode == 0:
  411. return True
  412. except (FileNotFoundError, subprocess.TimeoutExpired):
  413. pass
  414. return False
  415. @lru_cache(maxsize=None)
  416. def darwin_get_object_archs(objpath: str) -> T.List[str]:
  417. '''
  418. For a specific object (executable, static library, dylib, etc), run `lipo`
  419. to fetch the list of archs supported by it. Supports both thin objects and
  420. 'fat' objects.
  421. '''
  422. _, stdo, stderr = Popen_safe(['lipo', '-info', objpath])
  423. if not stdo:
  424. mlog.debug('lipo {}: {}'.format(objpath, stderr))
  425. return None
  426. stdo = stdo.rsplit(': ', 1)[1]
  427. # Convert from lipo-style archs to meson-style CPUs
  428. stdo = stdo.replace('i386', 'x86')
  429. stdo = stdo.replace('arm64', 'aarch64')
  430. # Add generic name for armv7 and armv7s
  431. if 'armv7' in stdo:
  432. stdo += ' arm'
  433. return stdo.split()
  434. def detect_vcs(source_dir: str) -> T.Optional[T.Dict[str, str]]:
  435. vcs_systems = [
  436. dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
  437. dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
  438. dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
  439. dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
  440. ]
  441. # FIXME: this is much cleaner with pathlib.Path
  442. segs = source_dir.replace('\\', '/').split('/')
  443. for i in range(len(segs), -1, -1):
  444. curdir = '/'.join(segs[:i])
  445. for vcs in vcs_systems:
  446. if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
  447. vcs['wc_dir'] = curdir
  448. return vcs
  449. return None
  450. # a helper class which implements the same version ordering as RPM
  451. class Version:
  452. def __init__(self, s: str):
  453. self._s = s
  454. # split into numeric, alphabetic and non-alphanumeric sequences
  455. sequences1 = re.finditer(r'(\d+|[a-zA-Z]+|[^a-zA-Z\d]+)', s)
  456. # non-alphanumeric separators are discarded
  457. sequences2 = [m for m in sequences1 if not re.match(r'[^a-zA-Z\d]+', m.group(1))]
  458. # numeric sequences are converted from strings to ints
  459. sequences3 = [int(m.group(1)) if m.group(1).isdigit() else m.group(1) for m in sequences2]
  460. self._v = sequences3
  461. def __str__(self):
  462. return '%s (V=%s)' % (self._s, str(self._v))
  463. def __repr__(self):
  464. return '<Version: {}>'.format(self._s)
  465. def __lt__(self, other):
  466. if isinstance(other, Version):
  467. return self.__cmp(other, operator.lt)
  468. return NotImplemented
  469. def __gt__(self, other):
  470. if isinstance(other, Version):
  471. return self.__cmp(other, operator.gt)
  472. return NotImplemented
  473. def __le__(self, other):
  474. if isinstance(other, Version):
  475. return self.__cmp(other, operator.le)
  476. return NotImplemented
  477. def __ge__(self, other):
  478. if isinstance(other, Version):
  479. return self.__cmp(other, operator.ge)
  480. return NotImplemented
  481. def __eq__(self, other):
  482. if isinstance(other, Version):
  483. return self._v == other._v
  484. return NotImplemented
  485. def __ne__(self, other):
  486. if isinstance(other, Version):
  487. return self._v != other._v
  488. return NotImplemented
  489. def __cmp(self, other: 'Version', comparator: T.Callable[[T.Any, T.Any], bool]) -> bool:
  490. # compare each sequence in order
  491. for ours, theirs in zip(self._v, other._v):
  492. # sort a non-digit sequence before a digit sequence
  493. ours_is_int = isinstance(ours, int)
  494. theirs_is_int = isinstance(theirs, int)
  495. if ours_is_int != theirs_is_int:
  496. return comparator(ours_is_int, theirs_is_int)
  497. if ours != theirs:
  498. return comparator(ours, theirs)
  499. # if equal length, all components have matched, so equal
  500. # otherwise, the version with a suffix remaining is greater
  501. return comparator(len(self._v), len(other._v))
  502. def _version_extract_cmpop(vstr2: str) -> T.Tuple[T.Callable[[T.Any, T.Any], bool], str]:
  503. if vstr2.startswith('>='):
  504. cmpop = operator.ge
  505. vstr2 = vstr2[2:]
  506. elif vstr2.startswith('<='):
  507. cmpop = operator.le
  508. vstr2 = vstr2[2:]
  509. elif vstr2.startswith('!='):
  510. cmpop = operator.ne
  511. vstr2 = vstr2[2:]
  512. elif vstr2.startswith('=='):
  513. cmpop = operator.eq
  514. vstr2 = vstr2[2:]
  515. elif vstr2.startswith('='):
  516. cmpop = operator.eq
  517. vstr2 = vstr2[1:]
  518. elif vstr2.startswith('>'):
  519. cmpop = operator.gt
  520. vstr2 = vstr2[1:]
  521. elif vstr2.startswith('<'):
  522. cmpop = operator.lt
  523. vstr2 = vstr2[1:]
  524. else:
  525. cmpop = operator.eq
  526. return (cmpop, vstr2)
  527. def version_compare(vstr1: str, vstr2: str) -> bool:
  528. (cmpop, vstr2) = _version_extract_cmpop(vstr2)
  529. return cmpop(Version(vstr1), Version(vstr2))
  530. def version_compare_many(vstr1: str, conditions: T.Union[str, T.Iterable[str]]) -> T.Tuple[bool, T.List[str], T.List[str]]:
  531. if isinstance(conditions, str):
  532. conditions = [conditions]
  533. found = []
  534. not_found = []
  535. for req in conditions:
  536. if not version_compare(vstr1, req):
  537. not_found.append(req)
  538. else:
  539. found.append(req)
  540. return not_found == [], not_found, found
  541. # determine if the minimum version satisfying the condition |condition| exceeds
  542. # the minimum version for a feature |minimum|
  543. def version_compare_condition_with_min(condition: str, minimum: str) -> bool:
  544. if condition.startswith('>='):
  545. cmpop = operator.le
  546. condition = condition[2:]
  547. elif condition.startswith('<='):
  548. return False
  549. elif condition.startswith('!='):
  550. return False
  551. elif condition.startswith('=='):
  552. cmpop = operator.le
  553. condition = condition[2:]
  554. elif condition.startswith('='):
  555. cmpop = operator.le
  556. condition = condition[1:]
  557. elif condition.startswith('>'):
  558. cmpop = operator.lt
  559. condition = condition[1:]
  560. elif condition.startswith('<'):
  561. return False
  562. else:
  563. cmpop = operator.le
  564. # Declaring a project(meson_version: '>=0.46') and then using features in
  565. # 0.46.0 is valid, because (knowing the meson versioning scheme) '0.46.0' is
  566. # the lowest version which satisfies the constraint '>=0.46'.
  567. #
  568. # But this will fail here, because the minimum version required by the
  569. # version constraint ('0.46') is strictly less (in our version comparison)
  570. # than the minimum version needed for the feature ('0.46.0').
  571. #
  572. # Map versions in the constraint of the form '0.46' to '0.46.0', to embed
  573. # this knowledge of the meson versioning scheme.
  574. condition = condition.strip()
  575. if re.match(r'^\d+.\d+$', condition):
  576. condition += '.0'
  577. return cmpop(Version(minimum), Version(condition))
  578. def default_libdir() -> str:
  579. if is_debianlike():
  580. try:
  581. pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
  582. stdout=subprocess.PIPE,
  583. stderr=subprocess.DEVNULL)
  584. (stdo, _) = pc.communicate()
  585. if pc.returncode == 0:
  586. archpath = stdo.decode().strip()
  587. return 'lib/' + archpath
  588. except Exception:
  589. pass
  590. if is_freebsd():
  591. return 'lib'
  592. if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
  593. return 'lib64'
  594. return 'lib'
  595. def default_libexecdir() -> str:
  596. # There is no way to auto-detect this, so it must be set at build time
  597. return 'libexec'
  598. def default_prefix() -> str:
  599. return 'c:/' if is_windows() else '/usr/local'
  600. def get_library_dirs() -> T.List[str]:
  601. if is_windows():
  602. return ['C:/mingw/lib'] # TODO: get programmatically
  603. if is_osx():
  604. return ['/usr/lib'] # TODO: get programmatically
  605. # The following is probably Debian/Ubuntu specific.
  606. # /usr/local/lib is first because it contains stuff
  607. # installed by the sysadmin and is probably more up-to-date
  608. # than /usr/lib. If you feel that this search order is
  609. # problematic, please raise the issue on the mailing list.
  610. unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
  611. if is_freebsd():
  612. return unixdirs
  613. # FIXME: this needs to be further genericized for aarch64 etc.
  614. machine = platform.machine()
  615. if machine in ('i386', 'i486', 'i586', 'i686'):
  616. plat = 'i386'
  617. elif machine.startswith('arm'):
  618. plat = 'arm'
  619. else:
  620. plat = ''
  621. # Solaris puts 32-bit libraries in the main /lib & /usr/lib directories
  622. # and 64-bit libraries in platform specific subdirectories.
  623. if is_sunos():
  624. if machine == 'i86pc':
  625. plat = 'amd64'
  626. elif machine.startswith('sun4'):
  627. plat = 'sparcv9'
  628. usr_platdir = Path('/usr/lib/') / plat
  629. if usr_platdir.is_dir():
  630. unixdirs += [str(x) for x in (usr_platdir).iterdir() if x.is_dir()]
  631. if os.path.exists('/usr/lib64'):
  632. unixdirs.append('/usr/lib64')
  633. lib_platdir = Path('/lib/') / plat
  634. if lib_platdir.is_dir():
  635. unixdirs += [str(x) for x in (lib_platdir).iterdir() if x.is_dir()]
  636. if os.path.exists('/lib64'):
  637. unixdirs.append('/lib64')
  638. return unixdirs
  639. def has_path_sep(name: str, sep: str = '/\\') -> bool:
  640. 'Checks if any of the specified @sep path separators are in @name'
  641. for each in sep:
  642. if each in name:
  643. return True
  644. return False
  645. if is_windows():
  646. # shlex.split is not suitable for splitting command line on Window (https://bugs.python.org/issue1724822);
  647. # shlex.quote is similarly problematic. Below are "proper" implementations of these functions according to
  648. # https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments and
  649. # https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
  650. _whitespace = ' \t\n\r'
  651. _find_unsafe_char = re.compile(r'[{}"]'.format(_whitespace)).search
  652. def quote_arg(arg: str) -> str:
  653. if arg and not _find_unsafe_char(arg):
  654. return arg
  655. result = '"'
  656. num_backslashes = 0
  657. for c in arg:
  658. if c == '\\':
  659. num_backslashes += 1
  660. else:
  661. if c == '"':
  662. # Escape all backslashes and the following double quotation mark
  663. num_backslashes = num_backslashes * 2 + 1
  664. result += num_backslashes * '\\' + c
  665. num_backslashes = 0
  666. # Escape all backslashes, but let the terminating double quotation
  667. # mark we add below be interpreted as a metacharacter
  668. result += (num_backslashes * 2) * '\\' + '"'
  669. return result
  670. def split_args(cmd: str) -> T.List[str]:
  671. result = []
  672. arg = ''
  673. num_backslashes = 0
  674. num_quotes = 0
  675. in_quotes = False
  676. for c in cmd:
  677. if c == '\\':
  678. num_backslashes += 1
  679. else:
  680. if c == '"' and not (num_backslashes % 2):
  681. # unescaped quote, eat it
  682. arg += (num_backslashes // 2) * '\\'
  683. num_quotes += 1
  684. in_quotes = not in_quotes
  685. elif c in _whitespace and not in_quotes:
  686. if arg or num_quotes:
  687. # reached the end of the argument
  688. result.append(arg)
  689. arg = ''
  690. num_quotes = 0
  691. else:
  692. if c == '"':
  693. # escaped quote
  694. num_backslashes = (num_backslashes - 1) // 2
  695. arg += num_backslashes * '\\' + c
  696. num_backslashes = 0
  697. if arg or num_quotes:
  698. result.append(arg)
  699. return result
  700. else:
  701. def quote_arg(arg: str) -> str:
  702. return shlex.quote(arg)
  703. def split_args(cmd: str) -> T.List[str]:
  704. return shlex.split(cmd)
  705. def join_args(args: T.Iterable[str]) -> str:
  706. return ' '.join([quote_arg(x) for x in args])
  707. def do_replacement(regex: T.Pattern[str], line: str, variable_format: str,
  708. confdata: 'ConfigurationData') -> T.Tuple[str, T.Set[str]]:
  709. missing_variables = set() # type: T.Set[str]
  710. if variable_format == 'cmake':
  711. start_tag = '${'
  712. backslash_tag = '\\${'
  713. else:
  714. assert variable_format in ['meson', 'cmake@']
  715. start_tag = '@'
  716. backslash_tag = '\\@'
  717. def variable_replace(match: T.Match[str]) -> str:
  718. # Pairs of escape characters before '@' or '\@'
  719. if match.group(0).endswith('\\'):
  720. num_escapes = match.end(0) - match.start(0)
  721. return '\\' * (num_escapes // 2)
  722. # Single escape character and '@'
  723. elif match.group(0) == backslash_tag:
  724. return start_tag
  725. # Template variable to be replaced
  726. else:
  727. varname = match.group(1)
  728. if varname in confdata:
  729. (var, desc) = confdata.get(varname)
  730. if isinstance(var, str):
  731. pass
  732. elif isinstance(var, int):
  733. var = str(var)
  734. else:
  735. msg = 'Tried to replace variable {!r} value with ' \
  736. 'something other than a string or int: {!r}'
  737. raise MesonException(msg.format(varname, var))
  738. else:
  739. missing_variables.add(varname)
  740. var = ''
  741. return var
  742. return re.sub(regex, variable_replace, line), missing_variables
  743. def do_define(regex: T.Pattern[str], line: str, confdata: 'ConfigurationData', variable_format: str) -> str:
  744. def get_cmake_define(line: str, confdata: 'ConfigurationData') -> str:
  745. arr = line.split()
  746. define_value=[]
  747. for token in arr[2:]:
  748. try:
  749. (v, desc) = confdata.get(token)
  750. define_value += [v]
  751. except KeyError:
  752. define_value += [token]
  753. return ' '.join(define_value)
  754. arr = line.split()
  755. if variable_format == 'meson' and len(arr) != 2:
  756. raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
  757. varname = arr[1]
  758. try:
  759. (v, desc) = confdata.get(varname)
  760. except KeyError:
  761. return '/* #undef %s */\n' % varname
  762. if isinstance(v, bool):
  763. if v:
  764. return '#define %s\n' % varname
  765. else:
  766. return '#undef %s\n' % varname
  767. elif isinstance(v, int):
  768. return '#define %s %d\n' % (varname, v)
  769. elif isinstance(v, str):
  770. if variable_format == 'meson':
  771. result = v
  772. else:
  773. result = get_cmake_define(line, confdata)
  774. result = '#define %s %s\n' % (varname, result)
  775. (result, missing_variable) = do_replacement(regex, result, variable_format, confdata)
  776. return result
  777. else:
  778. raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
  779. def do_conf_str (data: list, confdata: 'ConfigurationData', variable_format: str,
  780. encoding: str = 'utf-8') -> T.Tuple[T.List[str],T.Set[str], bool]:
  781. def line_is_valid(line : str, variable_format: str):
  782. if variable_format == 'meson':
  783. if '#cmakedefine' in line:
  784. return False
  785. else: #cmake format
  786. if '#mesondefine' in line:
  787. return False
  788. return True
  789. # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
  790. # Also allow escaping '@' with '\@'
  791. if variable_format in ['meson', 'cmake@']:
  792. regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
  793. elif variable_format == 'cmake':
  794. regex = re.compile(r'(?:\\\\)+(?=\\?\$)|\\\${|\${([-a-zA-Z0-9_]+)}')
  795. else:
  796. raise MesonException('Format "{}" not handled'.format(variable_format))
  797. search_token = '#mesondefine'
  798. if variable_format != 'meson':
  799. search_token = '#cmakedefine'
  800. result = []
  801. missing_variables = set()
  802. # Detect when the configuration data is empty and no tokens were found
  803. # during substitution so we can warn the user to use the `copy:` kwarg.
  804. confdata_useless = not confdata.keys()
  805. for line in data:
  806. if line.startswith(search_token):
  807. confdata_useless = False
  808. line = do_define(regex, line, confdata, variable_format)
  809. else:
  810. if not line_is_valid(line,variable_format):
  811. raise MesonException('Format "{}" mismatched'.format(variable_format))
  812. line, missing = do_replacement(regex, line, variable_format, confdata)
  813. missing_variables.update(missing)
  814. if missing:
  815. confdata_useless = False
  816. result.append(line)
  817. return result, missing_variables, confdata_useless
  818. def do_conf_file(src: str, dst: str, confdata: 'ConfigurationData', variable_format: str,
  819. encoding: str = 'utf-8') -> T.Tuple[T.Set[str], bool]:
  820. try:
  821. with open(src, encoding=encoding, newline='') as f:
  822. data = f.readlines()
  823. except Exception as e:
  824. raise MesonException('Could not read input file %s: %s' % (src, str(e)))
  825. (result, missing_variables, confdata_useless) = do_conf_str(data, confdata, variable_format, encoding)
  826. dst_tmp = dst + '~'
  827. try:
  828. with open(dst_tmp, 'w', encoding=encoding, newline='') as f:
  829. f.writelines(result)
  830. except Exception as e:
  831. raise MesonException('Could not write output file %s: %s' % (dst, str(e)))
  832. shutil.copymode(src, dst_tmp)
  833. replace_if_different(dst, dst_tmp)
  834. return missing_variables, confdata_useless
  835. CONF_C_PRELUDE = '''/*
  836. * Autogenerated by the Meson build system.
  837. * Do not edit, your changes will be lost.
  838. */
  839. #pragma once
  840. '''
  841. CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
  842. ; Do not edit, your changes will be lost.
  843. '''
  844. def dump_conf_header(ofilename: str, cdata: 'ConfigurationData', output_format: str) -> None:
  845. if output_format == 'c':
  846. prelude = CONF_C_PRELUDE
  847. prefix = '#'
  848. elif output_format == 'nasm':
  849. prelude = CONF_NASM_PRELUDE
  850. prefix = '%'
  851. ofilename_tmp = ofilename + '~'
  852. with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
  853. ofile.write(prelude)
  854. for k in sorted(cdata.keys()):
  855. (v, desc) = cdata.get(k)
  856. if desc:
  857. if output_format == 'c':
  858. ofile.write('/* %s */\n' % desc)
  859. elif output_format == 'nasm':
  860. for line in desc.split('\n'):
  861. ofile.write('; %s\n' % line)
  862. if isinstance(v, bool):
  863. if v:
  864. ofile.write('%sdefine %s\n\n' % (prefix, k))
  865. else:
  866. ofile.write('%sundef %s\n\n' % (prefix, k))
  867. elif isinstance(v, (int, str)):
  868. ofile.write('%sdefine %s %s\n\n' % (prefix, k, v))
  869. else:
  870. raise MesonException('Unknown data type in configuration file entry: ' + k)
  871. replace_if_different(ofilename, ofilename_tmp)
  872. def replace_if_different(dst: str, dst_tmp: str) -> None:
  873. # If contents are identical, don't touch the file to prevent
  874. # unnecessary rebuilds.
  875. different = True
  876. try:
  877. with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
  878. if f1.read() == f2.read():
  879. different = False
  880. except FileNotFoundError:
  881. pass
  882. if different:
  883. os.replace(dst_tmp, dst)
  884. else:
  885. os.unlink(dst_tmp)
  886. @T.overload
  887. def unholder(item: 'ObjectHolder[_T]') -> _T: ...
  888. @T.overload
  889. def unholder(item: T.List['ObjectHolder[_T]']) -> T.List[_T]: ...
  890. @T.overload
  891. def unholder(item: T.List[_T]) -> T.List[_T]: ...
  892. @T.overload
  893. def unholder(item: T.List[T.Union[_T, 'ObjectHolder[_T]']]) -> T.List[_T]: ...
  894. def unholder(item):
  895. """Get the held item of an object holder or list of object holders."""
  896. if isinstance(item, list):
  897. return [i.held_object if hasattr(i, 'held_object') else i for i in item]
  898. if hasattr(item, 'held_object'):
  899. return item.held_object
  900. return item
  901. def listify(item: T.Any, flatten: bool = True) -> T.List[T.Any]:
  902. '''
  903. Returns a list with all args embedded in a list if they are not a list.
  904. This function preserves order.
  905. @flatten: Convert lists of lists to a flat list
  906. '''
  907. if not isinstance(item, list):
  908. return [item]
  909. result = [] # type: T.List[T.Any]
  910. for i in item:
  911. if flatten and isinstance(i, list):
  912. result += listify(i, flatten=True)
  913. else:
  914. result.append(i)
  915. return result
  916. def extract_as_list(dict_object: T.Dict[_T, _U], key: _T, pop: bool = False) -> T.List[_U]:
  917. '''
  918. Extracts all values from given dict_object and listifies them.
  919. '''
  920. fetch = dict_object.get
  921. if pop:
  922. fetch = dict_object.pop
  923. # If there's only one key, we don't return a list with one element
  924. return listify(fetch(key, []), flatten=True)
  925. def typeslistify(item: 'T.Union[_T, T.Sequence[_T]]',
  926. types: 'T.Union[T.Type[_T], T.Tuple[T.Type[_T]]]') -> T.List[_T]:
  927. '''
  928. Ensure that type(@item) is one of @types or a
  929. list of items all of which are of type @types
  930. '''
  931. if isinstance(item, types):
  932. item = T.cast(T.List[_T], [item])
  933. if not isinstance(item, list):
  934. raise MesonException('Item must be a list or one of {!r}'.format(types))
  935. for i in item:
  936. if i is not None and not isinstance(i, types):
  937. raise MesonException('List item must be one of {!r}'.format(types))
  938. return item
  939. def stringlistify(item: T.Union[T.Any, T.Sequence[T.Any]]) -> T.List[str]:
  940. return typeslistify(item, str)
  941. def expand_arguments(args: T.Iterable[str]) -> T.Optional[T.List[str]]:
  942. expended_args = [] # type: T.List[str]
  943. for arg in args:
  944. if not arg.startswith('@'):
  945. expended_args.append(arg)
  946. continue
  947. args_file = arg[1:]
  948. try:
  949. with open(args_file) as f:
  950. extended_args = f.read().split()
  951. expended_args += extended_args
  952. except Exception as e:
  953. mlog.error('Expanding command line arguments:', args_file, 'not found')
  954. mlog.exception(e)
  955. return None
  956. return expended_args
  957. def partition(pred: T.Callable[[_T], object], iterable: T.Iterator[_T]) -> T.Tuple[T.Iterator[_T], T.Iterator[_T]]:
  958. """Use a predicate to partition entries into false entries and true
  959. entries.
  960. >>> x, y = partition(is_odd, range(10))
  961. >>> (list(x), list(y))
  962. ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])
  963. """
  964. t1, t2 = tee(iterable)
  965. return filterfalse(pred, t1), filter(pred, t2)
  966. def Popen_safe(args: T.List[str], write: T.Optional[str] = None,
  967. stdout: T.Union[T.BinaryIO, int] = subprocess.PIPE,
  968. stderr: T.Union[T.BinaryIO, int] = subprocess.PIPE,
  969. **kwargs: T.Any) -> T.Tuple[subprocess.Popen, str, str]:
  970. import locale
  971. encoding = locale.getpreferredencoding()
  972. # Redirect stdin to DEVNULL otherwise the command run by us here might mess
  973. # up the console and ANSI colors will stop working on Windows.
  974. if 'stdin' not in kwargs:
  975. kwargs['stdin'] = subprocess.DEVNULL
  976. if sys.version_info < (3, 6) or not sys.stdout.encoding or encoding.upper() != 'UTF-8':
  977. p, o, e = Popen_safe_legacy(args, write=write, stdout=stdout, stderr=stderr, **kwargs)
  978. else:
  979. p = subprocess.Popen(args, universal_newlines=True, close_fds=False,
  980. stdout=stdout, stderr=stderr, **kwargs)
  981. o, e = p.communicate(write)
  982. # Sometimes the command that we run will call another command which will be
  983. # without the above stdin workaround, so set the console mode again just in
  984. # case.
  985. mlog.setup_console()
  986. return p, o, e
  987. def Popen_safe_legacy(args: T.List[str], write: T.Optional[str] = None,
  988. stdout: T.Union[T.BinaryIO, int] = subprocess.PIPE,
  989. stderr: T.Union[T.BinaryIO, int] = subprocess.PIPE,
  990. **kwargs: T.Any) -> T.Tuple[subprocess.Popen, str, str]:
  991. p = subprocess.Popen(args, universal_newlines=False, close_fds=False,
  992. stdout=stdout, stderr=stderr, **kwargs)
  993. input_ = None # type: T.Optional[bytes]
  994. if write is not None:
  995. input_ = write.encode('utf-8')
  996. o, e = p.communicate(input_)
  997. if o is not None:
  998. if sys.stdout.encoding:
  999. o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
  1000. else:
  1001. o = o.decode(errors='replace').replace('\r\n', '\n')
  1002. if e is not None:
  1003. if sys.stderr.encoding:
  1004. e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
  1005. else:
  1006. e = e.decode(errors='replace').replace('\r\n', '\n')
  1007. return p, o, e
  1008. def iter_regexin_iter(regexiter: T.Iterable[str], initer: T.Iterable[str]) -> T.Optional[str]:
  1009. '''
  1010. Takes each regular expression in @regexiter and tries to search for it in
  1011. every item in @initer. If there is a match, returns that match.
  1012. Else returns False.
  1013. '''
  1014. for regex in regexiter:
  1015. for ii in initer:
  1016. if not isinstance(ii, str):
  1017. continue
  1018. match = re.search(regex, ii)
  1019. if match:
  1020. return match.group()
  1021. return None
  1022. def _substitute_values_check_errors(command: T.List[str], values: T.Dict[str, str]) -> None:
  1023. # Error checking
  1024. inregex = ['@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@'] # type: T.List[str]
  1025. outregex = ['@OUTPUT([0-9]+)?@', '@OUTDIR@'] # type: T.List[str]
  1026. if '@INPUT@' not in values:
  1027. # Error out if any input-derived templates are present in the command
  1028. match = iter_regexin_iter(inregex, command)
  1029. if match:
  1030. m = 'Command cannot have {!r}, since no input files were specified'
  1031. raise MesonException(m.format(match))
  1032. else:
  1033. if len(values['@INPUT@']) > 1:
  1034. # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
  1035. match = iter_regexin_iter(inregex[1:], command)
  1036. if match:
  1037. raise MesonException('Command cannot have {!r} when there is '
  1038. 'more than one input file'.format(match))
  1039. # Error out if an invalid @INPUTnn@ template was specified
  1040. for each in command:
  1041. if not isinstance(each, str):
  1042. continue
  1043. match2 = re.search(inregex[0], each)
  1044. if match2 and match2.group() not in values:
  1045. m = 'Command cannot have {!r} since there are only {!r} inputs'
  1046. raise MesonException(m.format(match2.group(), len(values['@INPUT@'])))
  1047. if '@OUTPUT@' not in values:
  1048. # Error out if any output-derived templates are present in the command
  1049. match = iter_regexin_iter(outregex, command)
  1050. if match:
  1051. m = 'Command cannot have {!r} since there are no outputs'
  1052. raise MesonException(m.format(match))
  1053. else:
  1054. # Error out if an invalid @OUTPUTnn@ template was specified
  1055. for each in command:
  1056. if not isinstance(each, str):
  1057. continue
  1058. match2 = re.search(outregex[0], each)
  1059. if match2 and match2.group() not in values:
  1060. m = 'Command cannot have {!r} since there are only {!r} outputs'
  1061. raise MesonException(m.format(match2.group(), len(values['@OUTPUT@'])))
  1062. def substitute_values(command: T.List[str], values: T.Dict[str, str]) -> T.List[str]:
  1063. '''
  1064. Substitute the template strings in the @values dict into the list of
  1065. strings @command and return a new list. For a full list of the templates,
  1066. see get_filenames_templates_dict()
  1067. If multiple inputs/outputs are given in the @values dictionary, we
  1068. substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
  1069. just a part of it, and in that case we substitute *all* of them.
  1070. '''
  1071. # Error checking
  1072. _substitute_values_check_errors(command, values)
  1073. # Substitution
  1074. outcmd = [] # type: T.List[str]
  1075. rx_keys = [re.escape(key) for key in values if key not in ('@INPUT@', '@OUTPUT@')]
  1076. value_rx = re.compile('|'.join(rx_keys)) if rx_keys else None
  1077. for vv in command:
  1078. if not isinstance(vv, str):
  1079. outcmd.append(vv)
  1080. elif '@INPUT@' in vv:
  1081. inputs = values['@INPUT@']
  1082. if vv == '@INPUT@':
  1083. outcmd += inputs
  1084. elif len(inputs) == 1:
  1085. outcmd.append(vv.replace('@INPUT@', inputs[0]))
  1086. else:
  1087. raise MesonException("Command has '@INPUT@' as part of a "
  1088. "string and more than one input file")
  1089. elif '@OUTPUT@' in vv:
  1090. outputs = values['@OUTPUT@']
  1091. if vv == '@OUTPUT@':
  1092. outcmd += outputs
  1093. elif len(outputs) == 1:
  1094. outcmd.append(vv.replace('@OUTPUT@', outputs[0]))
  1095. else:
  1096. raise MesonException("Command has '@OUTPUT@' as part of a "
  1097. "string and more than one output file")
  1098. # Append values that are exactly a template string.
  1099. # This is faster than a string replace.
  1100. elif vv in values:
  1101. outcmd.append(values[vv])
  1102. # Substitute everything else with replacement
  1103. elif value_rx:
  1104. outcmd.append(value_rx.sub(lambda m: values[m.group(0)], vv))
  1105. else:
  1106. outcmd.append(vv)
  1107. return outcmd
  1108. def get_filenames_templates_dict(inputs: T.List[str], outputs: T.List[str]) -> T.Dict[str, T.Union[str, T.List[str]]]:
  1109. '''
  1110. Create a dictionary with template strings as keys and values as values for
  1111. the following templates:
  1112. @INPUT@ - the full path to one or more input files, from @inputs
  1113. @OUTPUT@ - the full path to one or more output files, from @outputs
  1114. @OUTDIR@ - the full path to the directory containing the output files
  1115. If there is only one input file, the following keys are also created:
  1116. @PLAINNAME@ - the filename of the input file
  1117. @BASENAME@ - the filename of the input file with the extension removed
  1118. If there is more than one input file, the following keys are also created:
  1119. @INPUT0@, @INPUT1@, ... one for each input file
  1120. If there is more than one output file, the following keys are also created:
  1121. @OUTPUT0@, @OUTPUT1@, ... one for each output file
  1122. '''
  1123. values = {} # type: T.Dict[str, T.Union[str, T.List[str]]]
  1124. # Gather values derived from the input
  1125. if inputs:
  1126. # We want to substitute all the inputs.
  1127. values['@INPUT@'] = inputs
  1128. for (ii, vv) in enumerate(inputs):
  1129. # Write out @INPUT0@, @INPUT1@, ...
  1130. values['@INPUT{}@'.format(ii)] = vv
  1131. if len(inputs) == 1:
  1132. # Just one value, substitute @PLAINNAME@ and @BASENAME@
  1133. values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
  1134. values['@BASENAME@'] = os.path.splitext(plain)[0]
  1135. if outputs:
  1136. # Gather values derived from the outputs, similar to above.
  1137. values['@OUTPUT@'] = outputs
  1138. for (ii, vv) in enumerate(outputs):
  1139. values['@OUTPUT{}@'.format(ii)] = vv
  1140. # Outdir should be the same for all outputs
  1141. values['@OUTDIR@'] = os.path.dirname(outputs[0])
  1142. # Many external programs fail on empty arguments.
  1143. if values['@OUTDIR@'] == '':
  1144. values['@OUTDIR@'] = '.'
  1145. return values
  1146. def _make_tree_writable(topdir: str) -> None:
  1147. # Ensure all files and directories under topdir are writable
  1148. # (and readable) by owner.
  1149. for d, _, files in os.walk(topdir):
  1150. os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
  1151. for fname in files:
  1152. fpath = os.path.join(d, fname)
  1153. if os.path.isfile(fpath):
  1154. os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
  1155. def windows_proof_rmtree(f: str) -> None:
  1156. # On Windows if anyone is holding a file open you can't
  1157. # delete it. As an example an anti virus scanner might
  1158. # be scanning files you are trying to delete. The only
  1159. # way to fix this is to try again and again.
  1160. delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
  1161. # Start by making the tree wriable.
  1162. _make_tree_writable(f)
  1163. for d in delays:
  1164. try:
  1165. shutil.rmtree(f)
  1166. return
  1167. except FileNotFoundError:
  1168. return
  1169. except OSError:
  1170. time.sleep(d)
  1171. # Try one last time and throw if it fails.
  1172. shutil.rmtree(f)
  1173. def windows_proof_rm(fpath: str) -> None:
  1174. """Like windows_proof_rmtree, but for a single file."""
  1175. if os.path.isfile(fpath):
  1176. os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
  1177. delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
  1178. for d in delays:
  1179. try:
  1180. os.unlink(fpath)
  1181. return
  1182. except FileNotFoundError:
  1183. return
  1184. except OSError:
  1185. time.sleep(d)
  1186. os.unlink(fpath)
  1187. def detect_subprojects(spdir_name: str, current_dir: str = '',
  1188. result: T.Optional[T.Dict[str, T.List[str]]] = None) -> T.Optional[T.Dict[str, T.List[str]]]:
  1189. if result is None:
  1190. result = {}
  1191. spdir = os.path.join(current_dir, spdir_name)
  1192. if not os.path.exists(spdir):
  1193. return result
  1194. for trial in glob(os.path.join(spdir, '*')):
  1195. basename = os.path.basename(trial)
  1196. if trial == 'packagecache':
  1197. continue
  1198. append_this = True
  1199. if os.path.isdir(trial):
  1200. detect_subprojects(spdir_name, trial, result)
  1201. elif trial.endswith('.wrap') and os.path.isfile(trial):
  1202. basename = os.path.splitext(basename)[0]
  1203. else:
  1204. append_this = False
  1205. if append_this:
  1206. if basename in result:
  1207. result[basename].append(trial)
  1208. else:
  1209. result[basename] = [trial]
  1210. return result
  1211. def substring_is_in_list(substr: str, strlist: T.List[str]) -> bool:
  1212. for s in strlist:
  1213. if substr in s:
  1214. return True
  1215. return False
  1216. class OrderedSet(T.MutableSet[_T]):
  1217. """A set that preserves the order in which items are added, by first
  1218. insertion.
  1219. """
  1220. def __init__(self, iterable: T.Optional[T.Iterable[_T]] = None):
  1221. # typing.OrderedDict is new in 3.7.2, so we can't use that, but we can
  1222. # use MutableMapping, which is fine in this case.
  1223. self.__container = collections.OrderedDict() # type: T.MutableMapping[_T, None]
  1224. if iterable:
  1225. self.update(iterable)
  1226. def __contains__(self, value: object) -> bool:
  1227. return value in self.__container
  1228. def __iter__(self) -> T.Iterator[_T]:
  1229. return iter(self.__container.keys())
  1230. def __len__(self) -> int:
  1231. return len(self.__container)
  1232. def __repr__(self) -> str:
  1233. # Don't print 'OrderedSet("")' for an empty set.
  1234. if self.__container:
  1235. return 'OrderedSet("{}")'.format(
  1236. '", "'.join(repr(e) for e in self.__container.keys()))
  1237. return 'OrderedSet()'
  1238. def __reversed__(self) -> T.Iterator[_T]:
  1239. # Mypy is complaining that sets cant be reversed, which is true for
  1240. # unordered sets, but this is an ordered, set so reverse() makes sense.
  1241. return reversed(self.__container.keys()) # type: ignore
  1242. def add(self, value: _T) -> None:
  1243. self.__container[value] = None
  1244. def discard(self, value: _T) -> None:
  1245. if value in self.__container:
  1246. del self.__container[value]
  1247. def update(self, iterable: T.Iterable[_T]) -> None:
  1248. for item in iterable:
  1249. self.__container[item] = None
  1250. def difference(self, set_: T.Union[T.Set[_T], 'OrderedSet[_T]']) -> 'OrderedSet[_T]':
  1251. return type(self)(e for e in self if e not in set_)
  1252. class BuildDirLock:
  1253. def __init__(self, builddir: str):
  1254. self.lockfilename = os.path.join(builddir, 'meson-private/meson.lock')
  1255. def __enter__(self):
  1256. self.lockfile = open(self.lockfilename, 'w')
  1257. try:
  1258. if have_fcntl:
  1259. fcntl.flock(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
  1260. elif have_msvcrt:
  1261. msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_NBLCK, 1)
  1262. except (BlockingIOError, PermissionError):
  1263. self.lockfile.close()
  1264. raise MesonException('Some other Meson process is already using this build directory. Exiting.')
  1265. def __exit__(self, *args):
  1266. if have_fcntl:
  1267. fcntl.flock(self.lockfile, fcntl.LOCK_UN)
  1268. elif have_msvcrt:
  1269. msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_UNLCK, 1)
  1270. self.lockfile.close()
  1271. def relpath(path: str, start: str) -> str:
  1272. # On Windows a relative path can't be evaluated for paths on two different
  1273. # drives (i.e. c:\foo and f:\bar). The only thing left to do is to use the
  1274. # original absolute path.
  1275. try:
  1276. return os.path.relpath(path, start)
  1277. except (TypeError, ValueError):
  1278. return path
  1279. class LibType(Enum):
  1280. """Enumeration for library types."""
  1281. SHARED = 0
  1282. STATIC = 1
  1283. PREFER_SHARED = 2
  1284. PREFER_STATIC = 3
  1285. class ProgressBarFallback: # lgtm [py/iter-returns-non-self]
  1286. '''
  1287. Fallback progress bar implementation when tqdm is not found
  1288. Since this class is not an actual iterator, but only provides a minimal
  1289. fallback, it is safe to ignore the 'Iterator does not return self from
  1290. __iter__ method' warning.
  1291. '''
  1292. def __init__(self, iterable: T.Optional[T.Iterable[str]] = None, total: T.Optional[int] = None,
  1293. bar_type: T.Optional[str] = None, desc: T.Optional[str] = None):
  1294. if iterable is not None:
  1295. self.iterable = iter(iterable)
  1296. return
  1297. self.total = total
  1298. self.done = 0
  1299. self.printed_dots = 0
  1300. if self.total and bar_type == 'download':
  1301. print('Download size:', self.total)
  1302. if desc:
  1303. print('{}: '.format(desc), end='')
  1304. # Pretend to be an iterator when called as one and don't print any
  1305. # progress
  1306. def __iter__(self) -> T.Iterator[str]:
  1307. return self.iterable
  1308. def __next__(self) -> str:
  1309. return next(self.iterable)
  1310. def print_dot(self) -> None:
  1311. print('.', end='')
  1312. sys.stdout.flush()
  1313. self.printed_dots += 1
  1314. def update(self, progress: int) -> None:
  1315. self.done += progress
  1316. if not self.total:
  1317. # Just print one dot per call if we don't have a total length
  1318. self.print_dot()
  1319. return
  1320. ratio = int(self.done / self.total * 10)
  1321. while self.printed_dots < ratio:
  1322. self.print_dot()
  1323. def close(self) -> None:
  1324. print('')
  1325. try:
  1326. from tqdm import tqdm
  1327. except ImportError:
  1328. # ideally we would use a typing.Protocol here, but it's part of typing_extensions until 3.8
  1329. ProgressBar = ProgressBarFallback # type: T.Union[T.Type[ProgressBarFallback], T.Type[ProgressBarTqdm]]
  1330. else:
  1331. class ProgressBarTqdm(tqdm):
  1332. def __init__(self, *args, bar_type: T.Optional[str] = None, **kwargs):
  1333. if bar_type == 'download':
  1334. kwargs.update({'unit': 'bytes', 'leave': True})
  1335. else:
  1336. kwargs.update({'leave': False})
  1337. kwargs['ncols'] = 100
  1338. super().__init__(*args, **kwargs)
  1339. ProgressBar = ProgressBarTqdm
  1340. def get_wine_shortpath(winecmd: T.List[str], wine_paths: T.Sequence[str]) -> str:
  1341. """Get A short version of @wine_paths to avoid reaching WINEPATH number
  1342. of char limit.
  1343. """
  1344. wine_paths = list(OrderedSet(wine_paths))
  1345. getShortPathScript = '%s.bat' % str(uuid.uuid4()).lower()[:5]
  1346. with open(getShortPathScript, mode='w') as f:
  1347. f.write("@ECHO OFF\nfor %%x in (%*) do (\n echo|set /p=;%~sx\n)\n")
  1348. f.flush()
  1349. try:
  1350. with open(os.devnull, 'w') as stderr:
  1351. wine_path = subprocess.check_output(
  1352. winecmd +
  1353. ['cmd', '/C', getShortPathScript] + wine_paths,
  1354. stderr=stderr).decode('utf-8')
  1355. except subprocess.CalledProcessError as e:
  1356. print("Could not get short paths: %s" % e)
  1357. wine_path = ';'.join(wine_paths)
  1358. finally:
  1359. os.remove(getShortPathScript)
  1360. if len(wine_path) > 2048:
  1361. raise MesonException(
  1362. 'WINEPATH size {} > 2048'
  1363. ' this will cause random failure.'.format(
  1364. len(wine_path)))
  1365. return wine_path.strip(';')
  1366. def run_once(func: T.Callable[..., _T]) -> T.Callable[..., _T]:
  1367. ret = [] # type: T.List[_T]
  1368. @wraps(func)
  1369. def wrapper(*args: T.Any, **kwargs: T.Any) -> _T:
  1370. if ret:
  1371. return ret[0]
  1372. val = func(*args, **kwargs)
  1373. ret.append(val)
  1374. return val
  1375. return wrapper
  1376. class OptionProxy(T.Generic[_T]):
  1377. def __init__(self, value: _T):
  1378. self.value = value
  1379. class OptionOverrideProxy:
  1380. '''Mimic an option list but transparently override selected option
  1381. values.
  1382. '''
  1383. # TODO: the typing here could be made more explicit using a TypeDict from
  1384. # python 3.8 or typing_extensions
  1385. def __init__(self, overrides: T.Dict[str, T.Any], *options: 'OptionDictType'):
  1386. self.overrides = overrides
  1387. self.options = options
  1388. def __getitem__(self, option_name: str) -> T.Any:
  1389. for opts in self.options:
  1390. if option_name in opts:
  1391. return self._get_override(option_name, opts[option_name])
  1392. raise KeyError('Option not found', option_name)
  1393. def _get_override(self, option_name: str, base_opt: 'UserOption[T.Any]') -> T.Union[OptionProxy[T.Any], 'UserOption[T.Any]']:
  1394. if option_name in self.overrides:
  1395. return OptionProxy(base_opt.validate_value(self.overrides[option_name]))
  1396. return base_opt
  1397. def copy(self) -> T.Dict[str, T.Any]:
  1398. result = {} # type: T.Dict[str, T.Any]
  1399. for opts in self.options:
  1400. for option_name in opts:
  1401. result[option_name] = self._get_override(option_name, opts[option_name])
  1402. return result