mesonlib.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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 functools
  13. import sys
  14. import stat
  15. import time
  16. import platform, subprocess, operator, os, shutil, re
  17. import collections
  18. from enum import Enum
  19. from functools import lru_cache
  20. from mesonbuild import mlog
  21. have_fcntl = False
  22. have_msvcrt = False
  23. # {subproject: project_meson_version}
  24. project_meson_versions = {}
  25. try:
  26. import fcntl
  27. have_fcntl = True
  28. except Exception:
  29. pass
  30. try:
  31. import msvcrt
  32. have_msvcrt = True
  33. except Exception:
  34. pass
  35. from glob import glob
  36. if os.path.basename(sys.executable) == 'meson.exe':
  37. # In Windows and using the MSI installed executable.
  38. python_command = [sys.executable, 'runpython']
  39. else:
  40. python_command = [sys.executable]
  41. meson_command = None
  42. def set_meson_command(mainfile):
  43. global python_command
  44. global meson_command
  45. # On UNIX-like systems `meson` is a Python script
  46. # On Windows `meson` and `meson.exe` are wrapper exes
  47. if not mainfile.endswith('.py'):
  48. meson_command = [mainfile]
  49. elif os.path.isabs(mainfile) and mainfile.endswith('mesonmain.py'):
  50. # Can't actually run meson with an absolute path to mesonmain.py, it must be run as -m mesonbuild.mesonmain
  51. meson_command = python_command + ['-m', 'mesonbuild.mesonmain']
  52. else:
  53. # Either run uninstalled, or full path to meson-script.py
  54. meson_command = python_command + [mainfile]
  55. # We print this value for unit tests.
  56. if 'MESON_COMMAND_TESTS' in os.environ:
  57. mlog.log('meson_command is {!r}'.format(meson_command))
  58. def is_ascii_string(astring):
  59. try:
  60. if isinstance(astring, str):
  61. astring.encode('ascii')
  62. if isinstance(astring, bytes):
  63. astring.decode('ascii')
  64. except UnicodeDecodeError:
  65. return False
  66. return True
  67. def check_direntry_issues(direntry_array):
  68. import locale
  69. # Warn if the locale is not UTF-8. This can cause various unfixable issues
  70. # such as os.stat not being able to decode filenames with unicode in them.
  71. # There is no way to reset both the preferred encoding and the filesystem
  72. # encoding, so we can just warn about it.
  73. e = locale.getpreferredencoding()
  74. if e.upper() != 'UTF-8' and not is_windows():
  75. if not isinstance(direntry_array, list):
  76. direntry_array = [direntry_array]
  77. for de in direntry_array:
  78. if is_ascii_string(de):
  79. continue
  80. mlog.warning('''You are using {!r} which is not a Unicode-compatible '
  81. locale but you are trying to access a file system entry called {!r} which is
  82. not pure ASCII. This may cause problems.
  83. '''.format(e, de), file=sys.stderr)
  84. # Put this in objects that should not get dumped to pickle files
  85. # by accident.
  86. import threading
  87. an_unpicklable_object = threading.Lock()
  88. class MesonException(Exception):
  89. '''Exceptions thrown by Meson'''
  90. def get_msg_with_context(self):
  91. s = ''
  92. if hasattr(self, 'lineno') and hasattr(self, 'file'):
  93. s = get_error_location_string(self.file, self.lineno) + ' '
  94. s += str(self)
  95. return s
  96. class EnvironmentException(MesonException):
  97. '''Exceptions thrown while processing and creating the build environment'''
  98. class FileMode:
  99. # The first triad is for owner permissions, the second for group permissions,
  100. # and the third for others (everyone else).
  101. # For the 1st character:
  102. # 'r' means can read
  103. # '-' means not allowed
  104. # For the 2nd character:
  105. # 'w' means can write
  106. # '-' means not allowed
  107. # For the 3rd character:
  108. # 'x' means can execute
  109. # 's' means can execute and setuid/setgid is set (owner/group triads only)
  110. # 'S' means cannot execute and setuid/setgid is set (owner/group triads only)
  111. # 't' means can execute and sticky bit is set ("others" triads only)
  112. # 'T' means cannot execute and sticky bit is set ("others" triads only)
  113. # '-' means none of these are allowed
  114. #
  115. # The meanings of 'rwx' perms is not obvious for directories; see:
  116. # https://www.hackinglinuxexposed.com/articles/20030424.html
  117. #
  118. # For information on this notation such as setuid/setgid/sticky bits, see:
  119. # https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
  120. symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
  121. '[r-][w-][xsS-]' # Group perms
  122. '[r-][w-][xtT-]') # Others perms
  123. def __init__(self, perms=None, owner=None, group=None):
  124. self.perms_s = perms
  125. self.perms = self.perms_s_to_bits(perms)
  126. self.owner = owner
  127. self.group = group
  128. def __repr__(self):
  129. ret = '<FileMode: {!r} owner={} group={}'
  130. return ret.format(self.perms_s, self.owner, self.group)
  131. @classmethod
  132. def perms_s_to_bits(cls, perms_s):
  133. '''
  134. Does the opposite of stat.filemode(), converts strings of the form
  135. 'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
  136. '''
  137. if perms_s is None:
  138. # No perms specified, we will not touch the permissions
  139. return -1
  140. eg = 'rwxr-xr-x'
  141. if not isinstance(perms_s, str):
  142. msg = 'Install perms must be a string. For example, {!r}'
  143. raise MesonException(msg.format(eg))
  144. if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
  145. msg = 'File perms {!r} must be exactly 9 chars. For example, {!r}'
  146. raise MesonException(msg.format(perms_s, eg))
  147. perms = 0
  148. # Owner perms
  149. if perms_s[0] == 'r':
  150. perms |= stat.S_IRUSR
  151. if perms_s[1] == 'w':
  152. perms |= stat.S_IWUSR
  153. if perms_s[2] == 'x':
  154. perms |= stat.S_IXUSR
  155. elif perms_s[2] == 'S':
  156. perms |= stat.S_ISUID
  157. elif perms_s[2] == 's':
  158. perms |= stat.S_IXUSR
  159. perms |= stat.S_ISUID
  160. # Group perms
  161. if perms_s[3] == 'r':
  162. perms |= stat.S_IRGRP
  163. if perms_s[4] == 'w':
  164. perms |= stat.S_IWGRP
  165. if perms_s[5] == 'x':
  166. perms |= stat.S_IXGRP
  167. elif perms_s[5] == 'S':
  168. perms |= stat.S_ISGID
  169. elif perms_s[5] == 's':
  170. perms |= stat.S_IXGRP
  171. perms |= stat.S_ISGID
  172. # Others perms
  173. if perms_s[6] == 'r':
  174. perms |= stat.S_IROTH
  175. if perms_s[7] == 'w':
  176. perms |= stat.S_IWOTH
  177. if perms_s[8] == 'x':
  178. perms |= stat.S_IXOTH
  179. elif perms_s[8] == 'T':
  180. perms |= stat.S_ISVTX
  181. elif perms_s[8] == 't':
  182. perms |= stat.S_IXOTH
  183. perms |= stat.S_ISVTX
  184. return perms
  185. class File:
  186. def __init__(self, is_built, subdir, fname):
  187. self.is_built = is_built
  188. self.subdir = subdir
  189. self.fname = fname
  190. assert(isinstance(self.subdir, str))
  191. assert(isinstance(self.fname, str))
  192. def __str__(self):
  193. return self.relative_name()
  194. def __repr__(self):
  195. ret = '<File: {0}'
  196. if not self.is_built:
  197. ret += ' (not built)'
  198. ret += '>'
  199. return ret.format(self.relative_name())
  200. @staticmethod
  201. @lru_cache(maxsize=None)
  202. def from_source_file(source_root, subdir, fname):
  203. if not os.path.isfile(os.path.join(source_root, subdir, fname)):
  204. raise MesonException('File %s does not exist.' % fname)
  205. return File(False, subdir, fname)
  206. @staticmethod
  207. def from_built_file(subdir, fname):
  208. return File(True, subdir, fname)
  209. @staticmethod
  210. def from_absolute_file(fname):
  211. return File(False, '', fname)
  212. @lru_cache(maxsize=None)
  213. def rel_to_builddir(self, build_to_src):
  214. if self.is_built:
  215. return self.relative_name()
  216. else:
  217. return os.path.join(build_to_src, self.subdir, self.fname)
  218. @lru_cache(maxsize=None)
  219. def absolute_path(self, srcdir, builddir):
  220. absdir = srcdir
  221. if self.is_built:
  222. absdir = builddir
  223. return os.path.join(absdir, self.relative_name())
  224. def endswith(self, ending):
  225. return self.fname.endswith(ending)
  226. def split(self, s):
  227. return self.fname.split(s)
  228. def __eq__(self, other):
  229. return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
  230. def __hash__(self):
  231. return hash((self.fname, self.subdir, self.is_built))
  232. @lru_cache(maxsize=None)
  233. def relative_name(self):
  234. return os.path.join(self.subdir, self.fname)
  235. def get_compiler_for_source(compilers, src):
  236. for comp in compilers:
  237. if comp.can_compile(src):
  238. return comp
  239. raise MesonException('No specified compiler can handle file {!s}'.format(src))
  240. def classify_unity_sources(compilers, sources):
  241. compsrclist = {}
  242. for src in sources:
  243. comp = get_compiler_for_source(compilers, src)
  244. if comp not in compsrclist:
  245. compsrclist[comp] = [src]
  246. else:
  247. compsrclist[comp].append(src)
  248. return compsrclist
  249. class OrderedEnum(Enum):
  250. """
  251. An Enum which additionally offers homogeneous ordered comparison.
  252. """
  253. def __ge__(self, other):
  254. if self.__class__ is other.__class__:
  255. return self.value >= other.value
  256. return NotImplemented
  257. def __gt__(self, other):
  258. if self.__class__ is other.__class__:
  259. return self.value > other.value
  260. return NotImplemented
  261. def __le__(self, other):
  262. if self.__class__ is other.__class__:
  263. return self.value <= other.value
  264. return NotImplemented
  265. def __lt__(self, other):
  266. if self.__class__ is other.__class__:
  267. return self.value < other.value
  268. return NotImplemented
  269. MachineChoice = OrderedEnum('MachineChoice', ['BUILD', 'HOST', 'TARGET'])
  270. class PerMachine:
  271. def __init__(self, build, host, target):
  272. self.build = build
  273. self.host = host
  274. self.target = target
  275. def __getitem__(self, machine: MachineChoice):
  276. return {
  277. MachineChoice.BUILD: self.build,
  278. MachineChoice.HOST: self.host,
  279. MachineChoice.TARGET: self.target
  280. }[machine]
  281. def __setitem__(self, machine: MachineChoice, val):
  282. key = {
  283. MachineChoice.BUILD: 'build',
  284. MachineChoice.HOST: 'host',
  285. MachineChoice.TARGET: 'target'
  286. }[machine]
  287. setattr(self, key, val)
  288. def is_osx():
  289. return platform.system().lower() == 'darwin'
  290. def is_linux():
  291. return platform.system().lower() == 'linux'
  292. def is_android():
  293. return platform.system().lower() == 'android'
  294. def is_haiku():
  295. return platform.system().lower() == 'haiku'
  296. def is_openbsd():
  297. return platform.system().lower() == 'openbsd'
  298. def is_windows():
  299. platname = platform.system().lower()
  300. return platname == 'windows' or 'mingw' in platname
  301. def is_cygwin():
  302. platname = platform.system().lower()
  303. return platname.startswith('cygwin')
  304. def is_debianlike():
  305. return os.path.isfile('/etc/debian_version')
  306. def is_dragonflybsd():
  307. return platform.system().lower() == 'dragonfly'
  308. def is_freebsd():
  309. return platform.system().lower() == 'freebsd'
  310. def _get_machine_is_cross(env, is_cross):
  311. """
  312. This is not morally correct, but works for now. For cross builds the build
  313. and host machines differ. `is_cross == true` means the host machine, while
  314. `is_cross == false` means the build machine. Both are used in practice,
  315. even though the documentation refers to the host machine implying we should
  316. hard-code it. For non-cross builds `is_cross == false` is passed but the
  317. host and build machines are identical so it doesn't matter.
  318. Users for `for_*` should instead specify up front which machine they want
  319. and query that like:
  320. env.machines[MachineChoice.HOST].is_haiku()
  321. """
  322. for_machine = MachineChoice.HOST if is_cross else MachineChoice.BUILD
  323. return env.machines[for_machine]
  324. def for_windows(is_cross, env):
  325. """
  326. Host machine is windows?
  327. Deprecated: Please use `env.machines[for_machine].is_windows()`.
  328. Note: 'host' is the machine on which compiled binaries will run
  329. """
  330. return _get_machine_is_cross(env, is_cross).is_windows()
  331. def for_cygwin(is_cross, env):
  332. """
  333. Host machine is cygwin?
  334. Deprecated: Please use `env.machines[for_machine].is_cygwin()`.
  335. Note: 'host' is the machine on which compiled binaries will run
  336. """
  337. return _get_machine_is_cross(env, is_cross).is_cygwin()
  338. def for_linux(is_cross, env):
  339. """
  340. Host machine is linux?
  341. Deprecated: Please use `env.machines[for_machine].is_linux()`.
  342. Note: 'host' is the machine on which compiled binaries will run
  343. """
  344. return _get_machine_is_cross(env, is_cross).is_linux()
  345. def for_darwin(is_cross, env):
  346. """
  347. Host machine is Darwin (iOS/OS X)?
  348. Deprecated: Please use `env.machines[for_machine].is_darwin()`.
  349. Note: 'host' is the machine on which compiled binaries will run
  350. """
  351. return _get_machine_is_cross(env, is_cross).is_darwin()
  352. def for_android(is_cross, env):
  353. """
  354. Host machine is Android?
  355. Deprecated: Please use `env.machines[for_machine].is_android()`.
  356. Note: 'host' is the machine on which compiled binaries will run
  357. """
  358. return _get_machine_is_cross(env, is_cross).is_android()
  359. def for_haiku(is_cross, env):
  360. """
  361. Host machine is Haiku?
  362. Deprecated: Please use `env.machines[for_machine].is_haiku()`.
  363. Note: 'host' is the machine on which compiled binaries will run
  364. """
  365. return _get_machine_is_cross(env, is_cross).is_haiku()
  366. def for_openbsd(is_cross, env):
  367. """
  368. Host machine is OpenBSD?
  369. Deprecated: Please use `env.machines[for_machine].is_openbsd()`.
  370. Note: 'host' is the machine on which compiled binaries will run
  371. """
  372. return _get_machine_is_cross(env, is_cross).is_openbsd()
  373. def exe_exists(arglist):
  374. try:
  375. p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  376. p.communicate()
  377. if p.returncode == 0:
  378. return True
  379. except FileNotFoundError:
  380. pass
  381. return False
  382. lru_cache(maxsize=None)
  383. def darwin_get_object_archs(objpath):
  384. '''
  385. For a specific object (executable, static library, dylib, etc), run `lipo`
  386. to fetch the list of archs supported by it. Supports both thin objects and
  387. 'fat' objects.
  388. '''
  389. _, stdo, stderr = Popen_safe(['lipo', '-info', objpath])
  390. if not stdo:
  391. mlog.debug('lipo {}: {}'.format(objpath, stderr))
  392. return None
  393. stdo = stdo.rsplit(': ', 1)[1]
  394. # Convert from lipo-style archs to meson-style CPUs
  395. stdo = stdo.replace('i386', 'x86')
  396. stdo = stdo.replace('arm64', 'aarch64')
  397. # Add generic name for armv7 and armv7s
  398. if 'armv7' in stdo:
  399. stdo += ' arm'
  400. return stdo.split()
  401. def detect_vcs(source_dir):
  402. vcs_systems = [
  403. dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
  404. dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
  405. dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
  406. dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
  407. ]
  408. segs = source_dir.replace('\\', '/').split('/')
  409. for i in range(len(segs), -1, -1):
  410. curdir = '/'.join(segs[:i])
  411. for vcs in vcs_systems:
  412. if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
  413. vcs['wc_dir'] = curdir
  414. return vcs
  415. return None
  416. # a helper class which implements the same version ordering as RPM
  417. @functools.total_ordering
  418. class Version:
  419. def __init__(self, s):
  420. self._s = s
  421. # split into numeric, alphabetic and non-alphanumeric sequences
  422. sequences = re.finditer(r'(\d+|[a-zA-Z]+|[^a-zA-Z\d]+)', s)
  423. # non-alphanumeric separators are discarded
  424. sequences = [m for m in sequences if not re.match(r'[^a-zA-Z\d]+', m.group(1))]
  425. # numeric sequences have leading zeroes discarded
  426. sequences = [re.sub(r'^0+(\d)', r'\1', m.group(1), 1) for m in sequences]
  427. self._v = sequences
  428. def __str__(self):
  429. return '%s (V=%s)' % (self._s, str(self._v))
  430. def __repr__(self):
  431. return '<Version: {}>'.format(self._s)
  432. def __lt__(self, other):
  433. return self.__cmp__(other) == -1
  434. def __eq__(self, other):
  435. return self.__cmp__(other) == 0
  436. def __cmp__(self, other):
  437. def cmp(a, b):
  438. return (a > b) - (a < b)
  439. # compare each sequence in order
  440. for i in range(0, min(len(self._v), len(other._v))):
  441. # sort a non-digit sequence before a digit sequence
  442. if self._v[i].isdigit() != other._v[i].isdigit():
  443. return 1 if self._v[i].isdigit() else -1
  444. # compare as numbers
  445. if self._v[i].isdigit():
  446. # because leading zeros have already been removed, if one number
  447. # has more digits, it is greater
  448. c = cmp(len(self._v[i]), len(other._v[i]))
  449. if c != 0:
  450. return c
  451. # fallthrough
  452. # compare lexicographically
  453. c = cmp(self._v[i], other._v[i])
  454. if c != 0:
  455. return c
  456. # if equal length, all components have matched, so equal
  457. # otherwise, the version with a suffix remaining is greater
  458. return cmp(len(self._v), len(other._v))
  459. def _version_extract_cmpop(vstr2):
  460. if vstr2.startswith('>='):
  461. cmpop = operator.ge
  462. vstr2 = vstr2[2:]
  463. elif vstr2.startswith('<='):
  464. cmpop = operator.le
  465. vstr2 = vstr2[2:]
  466. elif vstr2.startswith('!='):
  467. cmpop = operator.ne
  468. vstr2 = vstr2[2:]
  469. elif vstr2.startswith('=='):
  470. cmpop = operator.eq
  471. vstr2 = vstr2[2:]
  472. elif vstr2.startswith('='):
  473. cmpop = operator.eq
  474. vstr2 = vstr2[1:]
  475. elif vstr2.startswith('>'):
  476. cmpop = operator.gt
  477. vstr2 = vstr2[1:]
  478. elif vstr2.startswith('<'):
  479. cmpop = operator.lt
  480. vstr2 = vstr2[1:]
  481. else:
  482. cmpop = operator.eq
  483. return (cmpop, vstr2)
  484. def version_compare(vstr1, vstr2):
  485. (cmpop, vstr2) = _version_extract_cmpop(vstr2)
  486. return cmpop(Version(vstr1), Version(vstr2))
  487. def version_compare_many(vstr1, conditions):
  488. if not isinstance(conditions, (list, tuple, frozenset)):
  489. conditions = [conditions]
  490. found = []
  491. not_found = []
  492. for req in conditions:
  493. if not version_compare(vstr1, req):
  494. not_found.append(req)
  495. else:
  496. found.append(req)
  497. return not_found == [], not_found, found
  498. # determine if the minimum version satisfying the condition |condition| exceeds
  499. # the minimum version for a feature |minimum|
  500. def version_compare_condition_with_min(condition, minimum):
  501. if condition.startswith('>='):
  502. cmpop = operator.le
  503. condition = condition[2:]
  504. elif condition.startswith('<='):
  505. return False
  506. elif condition.startswith('!='):
  507. return False
  508. elif condition.startswith('=='):
  509. cmpop = operator.le
  510. condition = condition[2:]
  511. elif condition.startswith('='):
  512. cmpop = operator.le
  513. condition = condition[1:]
  514. elif condition.startswith('>'):
  515. cmpop = operator.lt
  516. condition = condition[1:]
  517. elif condition.startswith('<'):
  518. return False
  519. else:
  520. cmpop = operator.le
  521. # Declaring a project(meson_version: '>=0.46') and then using features in
  522. # 0.46.0 is valid, because (knowing the meson versioning scheme) '0.46.0' is
  523. # the lowest version which satisfies the constraint '>=0.46'.
  524. #
  525. # But this will fail here, because the minimum version required by the
  526. # version constraint ('0.46') is strictly less (in our version comparison)
  527. # than the minimum version needed for the feature ('0.46.0').
  528. #
  529. # Map versions in the constraint of the form '0.46' to '0.46.0', to embed
  530. # this knowledge of the meson versioning scheme.
  531. condition = condition.strip()
  532. if re.match(r'^\d+.\d+$', condition):
  533. condition += '.0'
  534. return cmpop(Version(minimum), Version(condition))
  535. def default_libdir():
  536. if is_debianlike():
  537. try:
  538. pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
  539. stdout=subprocess.PIPE,
  540. stderr=subprocess.DEVNULL)
  541. (stdo, _) = pc.communicate()
  542. if pc.returncode == 0:
  543. archpath = stdo.decode().strip()
  544. return 'lib/' + archpath
  545. except Exception:
  546. pass
  547. if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
  548. return 'lib64'
  549. return 'lib'
  550. def default_libexecdir():
  551. # There is no way to auto-detect this, so it must be set at build time
  552. return 'libexec'
  553. def default_prefix():
  554. return 'c:/' if is_windows() else '/usr/local'
  555. def get_library_dirs():
  556. if is_windows():
  557. return ['C:/mingw/lib'] # Fixme
  558. if is_osx():
  559. return ['/usr/lib'] # Fix me as well.
  560. # The following is probably Debian/Ubuntu specific.
  561. # /usr/local/lib is first because it contains stuff
  562. # installed by the sysadmin and is probably more up-to-date
  563. # than /usr/lib. If you feel that this search order is
  564. # problematic, please raise the issue on the mailing list.
  565. unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
  566. plat = subprocess.check_output(['uname', '-m']).decode().strip()
  567. # This is a terrible hack. I admit it and I'm really sorry.
  568. # I just don't know what the correct solution is.
  569. if plat == 'i686':
  570. plat = 'i386'
  571. if plat.startswith('arm'):
  572. plat = 'arm'
  573. unixdirs += glob('/usr/lib/' + plat + '*')
  574. if os.path.exists('/usr/lib64'):
  575. unixdirs.append('/usr/lib64')
  576. unixdirs += glob('/lib/' + plat + '*')
  577. if os.path.exists('/lib64'):
  578. unixdirs.append('/lib64')
  579. unixdirs += glob('/lib/' + plat + '*')
  580. return unixdirs
  581. def has_path_sep(name, sep='/\\'):
  582. 'Checks if any of the specified @sep path separators are in @name'
  583. for each in sep:
  584. if each in name:
  585. return True
  586. return False
  587. def do_replacement(regex, line, format, confdata):
  588. missing_variables = set()
  589. start_tag = '@'
  590. backslash_tag = '\\@'
  591. if format == 'cmake':
  592. start_tag = '${'
  593. backslash_tag = '\\${'
  594. def variable_replace(match):
  595. # Pairs of escape characters before '@' or '\@'
  596. if match.group(0).endswith('\\'):
  597. num_escapes = match.end(0) - match.start(0)
  598. return '\\' * (num_escapes // 2)
  599. # Single escape character and '@'
  600. elif match.group(0) == backslash_tag:
  601. return start_tag
  602. # Template variable to be replaced
  603. else:
  604. varname = match.group(1)
  605. if varname in confdata:
  606. (var, desc) = confdata.get(varname)
  607. if isinstance(var, str):
  608. pass
  609. elif isinstance(var, int):
  610. var = str(var)
  611. else:
  612. msg = 'Tried to replace variable {!r} value with ' \
  613. 'something other than a string or int: {!r}'
  614. raise MesonException(msg.format(varname, var))
  615. else:
  616. missing_variables.add(varname)
  617. var = ''
  618. return var
  619. return re.sub(regex, variable_replace, line), missing_variables
  620. def do_mesondefine(line, confdata):
  621. arr = line.split()
  622. if len(arr) != 2:
  623. raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
  624. varname = arr[1]
  625. try:
  626. (v, desc) = confdata.get(varname)
  627. except KeyError:
  628. return '/* #undef %s */\n' % varname
  629. if isinstance(v, bool):
  630. if v:
  631. return '#define %s\n' % varname
  632. else:
  633. return '#undef %s\n' % varname
  634. elif isinstance(v, int):
  635. return '#define %s %d\n' % (varname, v)
  636. elif isinstance(v, str):
  637. return '#define %s %s\n' % (varname, v)
  638. else:
  639. raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
  640. def do_conf_file(src, dst, confdata, format, encoding='utf-8'):
  641. try:
  642. with open(src, encoding=encoding, newline='') as f:
  643. data = f.readlines()
  644. except Exception as e:
  645. raise MesonException('Could not read input file %s: %s' % (src, str(e)))
  646. # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
  647. # Also allow escaping '@' with '\@'
  648. if format in ['meson', 'cmake@']:
  649. regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
  650. elif format == 'cmake':
  651. regex = re.compile(r'(?:\\\\)+(?=\\?\$)|\\\${|\${([-a-zA-Z0-9_]+)}')
  652. else:
  653. raise MesonException('Format "{}" not handled'.format(format))
  654. search_token = '#mesondefine'
  655. if format != 'meson':
  656. search_token = '#cmakedefine'
  657. result = []
  658. missing_variables = set()
  659. # Detect when the configuration data is empty and no tokens were found
  660. # during substitution so we can warn the user to use the `copy:` kwarg.
  661. confdata_useless = not confdata.keys()
  662. for line in data:
  663. if line.startswith(search_token):
  664. confdata_useless = False
  665. line = do_mesondefine(line, confdata)
  666. else:
  667. line, missing = do_replacement(regex, line, format, confdata)
  668. missing_variables.update(missing)
  669. if missing:
  670. confdata_useless = False
  671. result.append(line)
  672. dst_tmp = dst + '~'
  673. try:
  674. with open(dst_tmp, 'w', encoding=encoding, newline='') as f:
  675. f.writelines(result)
  676. except Exception as e:
  677. raise MesonException('Could not write output file %s: %s' % (dst, str(e)))
  678. shutil.copymode(src, dst_tmp)
  679. replace_if_different(dst, dst_tmp)
  680. return missing_variables, confdata_useless
  681. CONF_C_PRELUDE = '''/*
  682. * Autogenerated by the Meson build system.
  683. * Do not edit, your changes will be lost.
  684. */
  685. #pragma once
  686. '''
  687. CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
  688. ; Do not edit, your changes will be lost.
  689. '''
  690. def dump_conf_header(ofilename, cdata, output_format):
  691. if output_format == 'c':
  692. prelude = CONF_C_PRELUDE
  693. prefix = '#'
  694. elif output_format == 'nasm':
  695. prelude = CONF_NASM_PRELUDE
  696. prefix = '%'
  697. ofilename_tmp = ofilename + '~'
  698. with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
  699. ofile.write(prelude)
  700. for k in sorted(cdata.keys()):
  701. (v, desc) = cdata.get(k)
  702. if desc:
  703. if output_format == 'c':
  704. ofile.write('/* %s */\n' % desc)
  705. elif output_format == 'nasm':
  706. for line in desc.split('\n'):
  707. ofile.write('; %s\n' % line)
  708. if isinstance(v, bool):
  709. if v:
  710. ofile.write('%sdefine %s\n\n' % (prefix, k))
  711. else:
  712. ofile.write('%sundef %s\n\n' % (prefix, k))
  713. elif isinstance(v, (int, str)):
  714. ofile.write('%sdefine %s %s\n\n' % (prefix, k, v))
  715. else:
  716. raise MesonException('Unknown data type in configuration file entry: ' + k)
  717. replace_if_different(ofilename, ofilename_tmp)
  718. def replace_if_different(dst, dst_tmp):
  719. # If contents are identical, don't touch the file to prevent
  720. # unnecessary rebuilds.
  721. different = True
  722. try:
  723. with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
  724. if f1.read() == f2.read():
  725. different = False
  726. except FileNotFoundError:
  727. pass
  728. if different:
  729. os.replace(dst_tmp, dst)
  730. else:
  731. os.unlink(dst_tmp)
  732. def listify(item, flatten=True, unholder=False):
  733. '''
  734. Returns a list with all args embedded in a list if they are not a list.
  735. This function preserves order.
  736. @flatten: Convert lists of lists to a flat list
  737. @unholder: Replace each item with the object it holds, if required
  738. Note: unholding only works recursively when flattening
  739. '''
  740. if not isinstance(item, list):
  741. if unholder and hasattr(item, 'held_object'):
  742. item = item.held_object
  743. return [item]
  744. result = []
  745. for i in item:
  746. if unholder and hasattr(i, 'held_object'):
  747. i = i.held_object
  748. if flatten and isinstance(i, list):
  749. result += listify(i, flatten=True, unholder=unholder)
  750. else:
  751. result.append(i)
  752. return result
  753. def extract_as_list(dict_object, *keys, pop=False, **kwargs):
  754. '''
  755. Extracts all values from given dict_object and listifies them.
  756. '''
  757. result = []
  758. fetch = dict_object.get
  759. if pop:
  760. fetch = dict_object.pop
  761. # If there's only one key, we don't return a list with one element
  762. if len(keys) == 1:
  763. return listify(fetch(keys[0], []), **kwargs)
  764. # Return a list of values corresponding to *keys
  765. for key in keys:
  766. result.append(listify(fetch(key, []), **kwargs))
  767. return result
  768. def typeslistify(item, types):
  769. '''
  770. Ensure that type(@item) is one of @types or a
  771. list of items all of which are of type @types
  772. '''
  773. if isinstance(item, types):
  774. item = [item]
  775. if not isinstance(item, list):
  776. raise MesonException('Item must be a list or one of {!r}'.format(types))
  777. for i in item:
  778. if i is not None and not isinstance(i, types):
  779. raise MesonException('List item must be one of {!r}'.format(types))
  780. return item
  781. def stringlistify(item):
  782. return typeslistify(item, str)
  783. def expand_arguments(args):
  784. expended_args = []
  785. for arg in args:
  786. if not arg.startswith('@'):
  787. expended_args.append(arg)
  788. continue
  789. args_file = arg[1:]
  790. try:
  791. with open(args_file) as f:
  792. extended_args = f.read().split()
  793. expended_args += extended_args
  794. except Exception as e:
  795. print('Error expanding command line arguments, %s not found' % args_file)
  796. print(e)
  797. return None
  798. return expended_args
  799. def Popen_safe(args, write=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
  800. import locale
  801. encoding = locale.getpreferredencoding()
  802. if sys.version_info < (3, 6) or not sys.stdout.encoding or encoding.upper() != 'UTF-8':
  803. return Popen_safe_legacy(args, write=write, stdout=stdout, stderr=stderr, **kwargs)
  804. p = subprocess.Popen(args, universal_newlines=True, close_fds=False,
  805. stdout=stdout, stderr=stderr, **kwargs)
  806. o, e = p.communicate(write)
  807. return p, o, e
  808. def Popen_safe_legacy(args, write=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
  809. p = subprocess.Popen(args, universal_newlines=False,
  810. stdout=stdout, stderr=stderr, **kwargs)
  811. if write is not None:
  812. write = write.encode('utf-8')
  813. o, e = p.communicate(write)
  814. if o is not None:
  815. if sys.stdout.encoding:
  816. o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
  817. else:
  818. o = o.decode(errors='replace').replace('\r\n', '\n')
  819. if e is not None:
  820. if sys.stderr.encoding:
  821. e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
  822. else:
  823. e = e.decode(errors='replace').replace('\r\n', '\n')
  824. return p, o, e
  825. def iter_regexin_iter(regexiter, initer):
  826. '''
  827. Takes each regular expression in @regexiter and tries to search for it in
  828. every item in @initer. If there is a match, returns that match.
  829. Else returns False.
  830. '''
  831. for regex in regexiter:
  832. for ii in initer:
  833. if not isinstance(ii, str):
  834. continue
  835. match = re.search(regex, ii)
  836. if match:
  837. return match.group()
  838. return False
  839. def _substitute_values_check_errors(command, values):
  840. # Error checking
  841. inregex = ('@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@')
  842. outregex = ('@OUTPUT([0-9]+)?@', '@OUTDIR@')
  843. if '@INPUT@' not in values:
  844. # Error out if any input-derived templates are present in the command
  845. match = iter_regexin_iter(inregex, command)
  846. if match:
  847. m = 'Command cannot have {!r}, since no input files were specified'
  848. raise MesonException(m.format(match))
  849. else:
  850. if len(values['@INPUT@']) > 1:
  851. # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
  852. match = iter_regexin_iter(inregex[1:], command)
  853. if match:
  854. raise MesonException('Command cannot have {!r} when there is '
  855. 'more than one input file'.format(match))
  856. # Error out if an invalid @INPUTnn@ template was specified
  857. for each in command:
  858. if not isinstance(each, str):
  859. continue
  860. match = re.search(inregex[0], each)
  861. if match and match.group() not in values:
  862. m = 'Command cannot have {!r} since there are only {!r} inputs'
  863. raise MesonException(m.format(match.group(), len(values['@INPUT@'])))
  864. if '@OUTPUT@' not in values:
  865. # Error out if any output-derived templates are present in the command
  866. match = iter_regexin_iter(outregex, command)
  867. if match:
  868. m = 'Command cannot have {!r} since there are no outputs'
  869. raise MesonException(m.format(match))
  870. else:
  871. # Error out if an invalid @OUTPUTnn@ template was specified
  872. for each in command:
  873. if not isinstance(each, str):
  874. continue
  875. match = re.search(outregex[0], each)
  876. if match and match.group() not in values:
  877. m = 'Command cannot have {!r} since there are only {!r} outputs'
  878. raise MesonException(m.format(match.group(), len(values['@OUTPUT@'])))
  879. def substitute_values(command, values):
  880. '''
  881. Substitute the template strings in the @values dict into the list of
  882. strings @command and return a new list. For a full list of the templates,
  883. see get_filenames_templates_dict()
  884. If multiple inputs/outputs are given in the @values dictionary, we
  885. substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
  886. just a part of it, and in that case we substitute *all* of them.
  887. '''
  888. # Error checking
  889. _substitute_values_check_errors(command, values)
  890. # Substitution
  891. outcmd = []
  892. rx_keys = [re.escape(key) for key in values if key not in ('@INPUT@', '@OUTPUT@')]
  893. value_rx = re.compile('|'.join(rx_keys)) if rx_keys else None
  894. for vv in command:
  895. if not isinstance(vv, str):
  896. outcmd.append(vv)
  897. elif '@INPUT@' in vv:
  898. inputs = values['@INPUT@']
  899. if vv == '@INPUT@':
  900. outcmd += inputs
  901. elif len(inputs) == 1:
  902. outcmd.append(vv.replace('@INPUT@', inputs[0]))
  903. else:
  904. raise MesonException("Command has '@INPUT@' as part of a "
  905. "string and more than one input file")
  906. elif '@OUTPUT@' in vv:
  907. outputs = values['@OUTPUT@']
  908. if vv == '@OUTPUT@':
  909. outcmd += outputs
  910. elif len(outputs) == 1:
  911. outcmd.append(vv.replace('@OUTPUT@', outputs[0]))
  912. else:
  913. raise MesonException("Command has '@OUTPUT@' as part of a "
  914. "string and more than one output file")
  915. # Append values that are exactly a template string.
  916. # This is faster than a string replace.
  917. elif vv in values:
  918. outcmd.append(values[vv])
  919. # Substitute everything else with replacement
  920. elif value_rx:
  921. outcmd.append(value_rx.sub(lambda m: values[m.group(0)], vv))
  922. else:
  923. outcmd.append(vv)
  924. return outcmd
  925. def get_filenames_templates_dict(inputs, outputs):
  926. '''
  927. Create a dictionary with template strings as keys and values as values for
  928. the following templates:
  929. @INPUT@ - the full path to one or more input files, from @inputs
  930. @OUTPUT@ - the full path to one or more output files, from @outputs
  931. @OUTDIR@ - the full path to the directory containing the output files
  932. If there is only one input file, the following keys are also created:
  933. @PLAINNAME@ - the filename of the input file
  934. @BASENAME@ - the filename of the input file with the extension removed
  935. If there is more than one input file, the following keys are also created:
  936. @INPUT0@, @INPUT1@, ... one for each input file
  937. If there is more than one output file, the following keys are also created:
  938. @OUTPUT0@, @OUTPUT1@, ... one for each output file
  939. '''
  940. values = {}
  941. # Gather values derived from the input
  942. if inputs:
  943. # We want to substitute all the inputs.
  944. values['@INPUT@'] = inputs
  945. for (ii, vv) in enumerate(inputs):
  946. # Write out @INPUT0@, @INPUT1@, ...
  947. values['@INPUT{}@'.format(ii)] = vv
  948. if len(inputs) == 1:
  949. # Just one value, substitute @PLAINNAME@ and @BASENAME@
  950. values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
  951. values['@BASENAME@'] = os.path.splitext(plain)[0]
  952. if outputs:
  953. # Gather values derived from the outputs, similar to above.
  954. values['@OUTPUT@'] = outputs
  955. for (ii, vv) in enumerate(outputs):
  956. values['@OUTPUT{}@'.format(ii)] = vv
  957. # Outdir should be the same for all outputs
  958. values['@OUTDIR@'] = os.path.dirname(outputs[0])
  959. # Many external programs fail on empty arguments.
  960. if values['@OUTDIR@'] == '':
  961. values['@OUTDIR@'] = '.'
  962. return values
  963. def _make_tree_writable(topdir):
  964. # Ensure all files and directories under topdir are writable
  965. # (and readable) by owner.
  966. for d, _, files in os.walk(topdir):
  967. os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
  968. for fname in files:
  969. fpath = os.path.join(d, fname)
  970. if os.path.isfile(fpath):
  971. os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
  972. def windows_proof_rmtree(f):
  973. # On Windows if anyone is holding a file open you can't
  974. # delete it. As an example an anti virus scanner might
  975. # be scanning files you are trying to delete. The only
  976. # way to fix this is to try again and again.
  977. delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
  978. # Start by making the tree wriable.
  979. _make_tree_writable(f)
  980. for d in delays:
  981. try:
  982. shutil.rmtree(f)
  983. return
  984. except FileNotFoundError:
  985. return
  986. except (OSError, PermissionError):
  987. time.sleep(d)
  988. # Try one last time and throw if it fails.
  989. shutil.rmtree(f)
  990. def windows_proof_rm(fpath):
  991. """Like windows_proof_rmtree, but for a single file."""
  992. if os.path.isfile(fpath):
  993. os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
  994. delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
  995. for d in delays:
  996. try:
  997. os.unlink(fpath)
  998. return
  999. except FileNotFoundError:
  1000. return
  1001. except (OSError, PermissionError):
  1002. time.sleep(d)
  1003. os.unlink(fpath)
  1004. def detect_subprojects(spdir_name, current_dir='', result=None):
  1005. if result is None:
  1006. result = {}
  1007. spdir = os.path.join(current_dir, spdir_name)
  1008. if not os.path.exists(spdir):
  1009. return result
  1010. for trial in glob(os.path.join(spdir, '*')):
  1011. basename = os.path.basename(trial)
  1012. if trial == 'packagecache':
  1013. continue
  1014. append_this = True
  1015. if os.path.isdir(trial):
  1016. detect_subprojects(spdir_name, trial, result)
  1017. elif trial.endswith('.wrap') and os.path.isfile(trial):
  1018. basename = os.path.splitext(basename)[0]
  1019. else:
  1020. append_this = False
  1021. if append_this:
  1022. if basename in result:
  1023. result[basename].append(trial)
  1024. else:
  1025. result[basename] = [trial]
  1026. return result
  1027. def get_error_location_string(fname, lineno):
  1028. return '{}:{}:'.format(fname, lineno)
  1029. def substring_is_in_list(substr, strlist):
  1030. for s in strlist:
  1031. if substr in s:
  1032. return True
  1033. return False
  1034. class OrderedSet(collections.abc.MutableSet):
  1035. """A set that preserves the order in which items are added, by first
  1036. insertion.
  1037. """
  1038. def __init__(self, iterable=None):
  1039. self.__container = collections.OrderedDict()
  1040. if iterable:
  1041. self.update(iterable)
  1042. def __contains__(self, value):
  1043. return value in self.__container
  1044. def __iter__(self):
  1045. return iter(self.__container.keys())
  1046. def __len__(self):
  1047. return len(self.__container)
  1048. def __repr__(self):
  1049. # Don't print 'OrderedSet("")' for an empty set.
  1050. if self.__container:
  1051. return 'OrderedSet("{}")'.format(
  1052. '", "'.join(repr(e) for e in self.__container.keys()))
  1053. return 'OrderedSet()'
  1054. def __reversed__(self):
  1055. return reversed(self.__container)
  1056. def add(self, value):
  1057. self.__container[value] = None
  1058. def discard(self, value):
  1059. if value in self.__container:
  1060. del self.__container[value]
  1061. def update(self, iterable):
  1062. for item in iterable:
  1063. self.__container[item] = None
  1064. def difference(self, set_):
  1065. return type(self)(e for e in self if e not in set_)
  1066. class BuildDirLock:
  1067. def __init__(self, builddir):
  1068. self.lockfilename = os.path.join(builddir, 'meson-private/meson.lock')
  1069. def __enter__(self):
  1070. self.lockfile = open(self.lockfilename, 'w')
  1071. try:
  1072. if have_fcntl:
  1073. fcntl.flock(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
  1074. elif have_msvcrt:
  1075. msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_NBLCK, 1)
  1076. except (BlockingIOError, PermissionError):
  1077. self.lockfile.close()
  1078. raise MesonException('Some other Meson process is already using this build directory. Exiting.')
  1079. def __exit__(self, *args):
  1080. if have_fcntl:
  1081. fcntl.flock(self.lockfile, fcntl.LOCK_UN)
  1082. elif have_msvcrt:
  1083. msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_UNLCK, 1)
  1084. self.lockfile.close()
  1085. def relpath(path, start):
  1086. # On Windows a relative path can't be evaluated for paths on two different
  1087. # drives (i.e. c:\foo and f:\bar). The only thing left to do is to use the
  1088. # original absolute path.
  1089. try:
  1090. return os.path.relpath(path, start)
  1091. except ValueError:
  1092. return path