util.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. """distutils.util
  2. Miscellaneous utility functions -- anything that doesn't fit into
  3. one of the other *util.py modules.
  4. """
  5. import importlib.util
  6. import os
  7. import re
  8. import string
  9. import subprocess
  10. import sys
  11. import sysconfig
  12. import functools
  13. from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
  14. from distutils.dep_util import newer
  15. from distutils.spawn import spawn
  16. from distutils import log
  17. def get_host_platform():
  18. """
  19. Return a string that identifies the current platform. Use this
  20. function to distinguish platform-specific build directories and
  21. platform-specific built distributions.
  22. """
  23. # This function initially exposed platforms as defined in Python 3.9
  24. # even with older Python versions when distutils was split out.
  25. # Now it delegates to stdlib sysconfig, but maintains compatibility.
  26. if sys.version_info < (3, 8):
  27. if os.name == 'nt':
  28. if '(arm)' in sys.version.lower():
  29. return 'win-arm32'
  30. if '(arm64)' in sys.version.lower():
  31. return 'win-arm64'
  32. if sys.version_info < (3, 9):
  33. if os.name == "posix" and hasattr(os, 'uname'):
  34. osname, host, release, version, machine = os.uname()
  35. if osname[:3] == "aix":
  36. from .py38compat import aix_platform
  37. return aix_platform(osname, version, release)
  38. return sysconfig.get_platform()
  39. def get_platform():
  40. if os.name == 'nt':
  41. TARGET_TO_PLAT = {
  42. 'x86': 'win32',
  43. 'x64': 'win-amd64',
  44. 'arm': 'win-arm32',
  45. 'arm64': 'win-arm64',
  46. }
  47. target = os.environ.get('VSCMD_ARG_TGT_ARCH')
  48. return TARGET_TO_PLAT.get(target) or get_host_platform()
  49. return get_host_platform()
  50. if sys.platform == 'darwin':
  51. _syscfg_macosx_ver = None # cache the version pulled from sysconfig
  52. MACOSX_VERSION_VAR = 'MACOSX_DEPLOYMENT_TARGET'
  53. def _clear_cached_macosx_ver():
  54. """For testing only. Do not call."""
  55. global _syscfg_macosx_ver
  56. _syscfg_macosx_ver = None
  57. def get_macosx_target_ver_from_syscfg():
  58. """Get the version of macOS latched in the Python interpreter configuration.
  59. Returns the version as a string or None if can't obtain one. Cached."""
  60. global _syscfg_macosx_ver
  61. if _syscfg_macosx_ver is None:
  62. from distutils import sysconfig
  63. ver = sysconfig.get_config_var(MACOSX_VERSION_VAR) or ''
  64. if ver:
  65. _syscfg_macosx_ver = ver
  66. return _syscfg_macosx_ver
  67. def get_macosx_target_ver():
  68. """Return the version of macOS for which we are building.
  69. The target version defaults to the version in sysconfig latched at time
  70. the Python interpreter was built, unless overridden by an environment
  71. variable. If neither source has a value, then None is returned"""
  72. syscfg_ver = get_macosx_target_ver_from_syscfg()
  73. env_ver = os.environ.get(MACOSX_VERSION_VAR)
  74. if env_ver:
  75. # Validate overridden version against sysconfig version, if have both.
  76. # Ensure that the deployment target of the build process is not less
  77. # than 10.3 if the interpreter was built for 10.3 or later. This
  78. # ensures extension modules are built with correct compatibility
  79. # values, specifically LDSHARED which can use
  80. # '-undefined dynamic_lookup' which only works on >= 10.3.
  81. if (
  82. syscfg_ver
  83. and split_version(syscfg_ver) >= [10, 3]
  84. and split_version(env_ver) < [10, 3]
  85. ):
  86. my_msg = (
  87. '$' + MACOSX_VERSION_VAR + ' mismatch: '
  88. 'now "%s" but "%s" during configure; '
  89. 'must use 10.3 or later' % (env_ver, syscfg_ver)
  90. )
  91. raise DistutilsPlatformError(my_msg)
  92. return env_ver
  93. return syscfg_ver
  94. def split_version(s):
  95. """Convert a dot-separated string into a list of numbers for comparisons"""
  96. return [int(n) for n in s.split('.')]
  97. def convert_path(pathname):
  98. """Return 'pathname' as a name that will work on the native filesystem,
  99. i.e. split it on '/' and put it back together again using the current
  100. directory separator. Needed because filenames in the setup script are
  101. always supplied in Unix style, and have to be converted to the local
  102. convention before we can actually use them in the filesystem. Raises
  103. ValueError on non-Unix-ish systems if 'pathname' either starts or
  104. ends with a slash.
  105. """
  106. if os.sep == '/':
  107. return pathname
  108. if not pathname:
  109. return pathname
  110. if pathname[0] == '/':
  111. raise ValueError("path '%s' cannot be absolute" % pathname)
  112. if pathname[-1] == '/':
  113. raise ValueError("path '%s' cannot end with '/'" % pathname)
  114. paths = pathname.split('/')
  115. while '.' in paths:
  116. paths.remove('.')
  117. if not paths:
  118. return os.curdir
  119. return os.path.join(*paths)
  120. # convert_path ()
  121. def change_root(new_root, pathname):
  122. """Return 'pathname' with 'new_root' prepended. If 'pathname' is
  123. relative, this is equivalent to "os.path.join(new_root,pathname)".
  124. Otherwise, it requires making 'pathname' relative and then joining the
  125. two, which is tricky on DOS/Windows and Mac OS.
  126. """
  127. if os.name == 'posix':
  128. if not os.path.isabs(pathname):
  129. return os.path.join(new_root, pathname)
  130. else:
  131. return os.path.join(new_root, pathname[1:])
  132. elif os.name == 'nt':
  133. (drive, path) = os.path.splitdrive(pathname)
  134. if path[0] == '\\':
  135. path = path[1:]
  136. return os.path.join(new_root, path)
  137. raise DistutilsPlatformError(f"nothing known about platform '{os.name}'")
  138. @functools.lru_cache()
  139. def check_environ():
  140. """Ensure that 'os.environ' has all the environment variables we
  141. guarantee that users can use in config files, command-line options,
  142. etc. Currently this includes:
  143. HOME - user's home directory (Unix only)
  144. PLAT - description of the current platform, including hardware
  145. and OS (see 'get_platform()')
  146. """
  147. if os.name == 'posix' and 'HOME' not in os.environ:
  148. try:
  149. import pwd
  150. os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  151. except (ImportError, KeyError):
  152. # bpo-10496: if the current user identifier doesn't exist in the
  153. # password database, do nothing
  154. pass
  155. if 'PLAT' not in os.environ:
  156. os.environ['PLAT'] = get_platform()
  157. def subst_vars(s, local_vars):
  158. """
  159. Perform variable substitution on 'string'.
  160. Variables are indicated by format-style braces ("{var}").
  161. Variable is substituted by the value found in the 'local_vars'
  162. dictionary or in 'os.environ' if it's not in 'local_vars'.
  163. 'os.environ' is first checked/augmented to guarantee that it contains
  164. certain values: see 'check_environ()'. Raise ValueError for any
  165. variables not found in either 'local_vars' or 'os.environ'.
  166. """
  167. check_environ()
  168. lookup = dict(os.environ)
  169. lookup.update((name, str(value)) for name, value in local_vars.items())
  170. try:
  171. return _subst_compat(s).format_map(lookup)
  172. except KeyError as var:
  173. raise ValueError(f"invalid variable {var}")
  174. def _subst_compat(s):
  175. """
  176. Replace shell/Perl-style variable substitution with
  177. format-style. For compatibility.
  178. """
  179. def _subst(match):
  180. return f'{{{match.group(1)}}}'
  181. repl = re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  182. if repl != s:
  183. import warnings
  184. warnings.warn(
  185. "shell/Perl-style substitions are deprecated",
  186. DeprecationWarning,
  187. )
  188. return repl
  189. def grok_environment_error(exc, prefix="error: "):
  190. # Function kept for backward compatibility.
  191. # Used to try clever things with EnvironmentErrors,
  192. # but nowadays str(exception) produces good messages.
  193. return prefix + str(exc)
  194. # Needed by 'split_quoted()'
  195. _wordchars_re = _squote_re = _dquote_re = None
  196. def _init_regex():
  197. global _wordchars_re, _squote_re, _dquote_re
  198. _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
  199. _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
  200. _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
  201. def split_quoted(s):
  202. """Split a string up according to Unix shell-like rules for quotes and
  203. backslashes. In short: words are delimited by spaces, as long as those
  204. spaces are not escaped by a backslash, or inside a quoted string.
  205. Single and double quotes are equivalent, and the quote characters can
  206. be backslash-escaped. The backslash is stripped from any two-character
  207. escape sequence, leaving only the escaped character. The quote
  208. characters are stripped from any quoted string. Returns a list of
  209. words.
  210. """
  211. # This is a nice algorithm for splitting up a single string, since it
  212. # doesn't require character-by-character examination. It was a little
  213. # bit of a brain-bender to get it working right, though...
  214. if _wordchars_re is None:
  215. _init_regex()
  216. s = s.strip()
  217. words = []
  218. pos = 0
  219. while s:
  220. m = _wordchars_re.match(s, pos)
  221. end = m.end()
  222. if end == len(s):
  223. words.append(s[:end])
  224. break
  225. if s[end] in string.whitespace:
  226. # unescaped, unquoted whitespace: now
  227. # we definitely have a word delimiter
  228. words.append(s[:end])
  229. s = s[end:].lstrip()
  230. pos = 0
  231. elif s[end] == '\\':
  232. # preserve whatever is being escaped;
  233. # will become part of the current word
  234. s = s[:end] + s[end + 1 :]
  235. pos = end + 1
  236. else:
  237. if s[end] == "'": # slurp singly-quoted string
  238. m = _squote_re.match(s, end)
  239. elif s[end] == '"': # slurp doubly-quoted string
  240. m = _dquote_re.match(s, end)
  241. else:
  242. raise RuntimeError("this can't happen (bad char '%c')" % s[end])
  243. if m is None:
  244. raise ValueError("bad string (mismatched %s quotes?)" % s[end])
  245. (beg, end) = m.span()
  246. s = s[:beg] + s[beg + 1 : end - 1] + s[end:]
  247. pos = m.end() - 2
  248. if pos >= len(s):
  249. words.append(s)
  250. break
  251. return words
  252. # split_quoted ()
  253. def execute(func, args, msg=None, verbose=0, dry_run=0):
  254. """Perform some action that affects the outside world (eg. by
  255. writing to the filesystem). Such actions are special because they
  256. are disabled by the 'dry_run' flag. This method takes care of all
  257. that bureaucracy for you; all you have to do is supply the
  258. function to call and an argument tuple for it (to embody the
  259. "external action" being performed), and an optional message to
  260. print.
  261. """
  262. if msg is None:
  263. msg = "{}{!r}".format(func.__name__, args)
  264. if msg[-2:] == ',)': # correct for singleton tuple
  265. msg = msg[0:-2] + ')'
  266. log.info(msg)
  267. if not dry_run:
  268. func(*args)
  269. def strtobool(val):
  270. """Convert a string representation of truth to true (1) or false (0).
  271. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  272. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  273. 'val' is anything else.
  274. """
  275. val = val.lower()
  276. if val in ('y', 'yes', 't', 'true', 'on', '1'):
  277. return 1
  278. elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  279. return 0
  280. else:
  281. raise ValueError("invalid truth value {!r}".format(val))
  282. def byte_compile( # noqa: C901
  283. py_files,
  284. optimize=0,
  285. force=0,
  286. prefix=None,
  287. base_dir=None,
  288. verbose=1,
  289. dry_run=0,
  290. direct=None,
  291. ):
  292. """Byte-compile a collection of Python source files to .pyc
  293. files in a __pycache__ subdirectory. 'py_files' is a list
  294. of files to compile; any files that don't end in ".py" are silently
  295. skipped. 'optimize' must be one of the following:
  296. 0 - don't optimize
  297. 1 - normal optimization (like "python -O")
  298. 2 - extra optimization (like "python -OO")
  299. If 'force' is true, all files are recompiled regardless of
  300. timestamps.
  301. The source filename encoded in each bytecode file defaults to the
  302. filenames listed in 'py_files'; you can modify these with 'prefix' and
  303. 'basedir'. 'prefix' is a string that will be stripped off of each
  304. source filename, and 'base_dir' is a directory name that will be
  305. prepended (after 'prefix' is stripped). You can supply either or both
  306. (or neither) of 'prefix' and 'base_dir', as you wish.
  307. If 'dry_run' is true, doesn't actually do anything that would
  308. affect the filesystem.
  309. Byte-compilation is either done directly in this interpreter process
  310. with the standard py_compile module, or indirectly by writing a
  311. temporary script and executing it. Normally, you should let
  312. 'byte_compile()' figure out to use direct compilation or not (see
  313. the source for details). The 'direct' flag is used by the script
  314. generated in indirect mode; unless you know what you're doing, leave
  315. it set to None.
  316. """
  317. # nothing is done if sys.dont_write_bytecode is True
  318. if sys.dont_write_bytecode:
  319. raise DistutilsByteCompileError('byte-compiling is disabled.')
  320. # First, if the caller didn't force us into direct or indirect mode,
  321. # figure out which mode we should be in. We take a conservative
  322. # approach: choose direct mode *only* if the current interpreter is
  323. # in debug mode and optimize is 0. If we're not in debug mode (-O
  324. # or -OO), we don't know which level of optimization this
  325. # interpreter is running with, so we can't do direct
  326. # byte-compilation and be certain that it's the right thing. Thus,
  327. # always compile indirectly if the current interpreter is in either
  328. # optimize mode, or if either optimization level was requested by
  329. # the caller.
  330. if direct is None:
  331. direct = __debug__ and optimize == 0
  332. # "Indirect" byte-compilation: write a temporary script and then
  333. # run it with the appropriate flags.
  334. if not direct:
  335. try:
  336. from tempfile import mkstemp
  337. (script_fd, script_name) = mkstemp(".py")
  338. except ImportError:
  339. from tempfile import mktemp
  340. (script_fd, script_name) = None, mktemp(".py")
  341. log.info("writing byte-compilation script '%s'", script_name)
  342. if not dry_run:
  343. if script_fd is not None:
  344. script = os.fdopen(script_fd, "w")
  345. else:
  346. script = open(script_name, "w")
  347. with script:
  348. script.write(
  349. """\
  350. from distutils.util import byte_compile
  351. files = [
  352. """
  353. )
  354. # XXX would be nice to write absolute filenames, just for
  355. # safety's sake (script should be more robust in the face of
  356. # chdir'ing before running it). But this requires abspath'ing
  357. # 'prefix' as well, and that breaks the hack in build_lib's
  358. # 'byte_compile()' method that carefully tacks on a trailing
  359. # slash (os.sep really) to make sure the prefix here is "just
  360. # right". This whole prefix business is rather delicate -- the
  361. # problem is that it's really a directory, but I'm treating it
  362. # as a dumb string, so trailing slashes and so forth matter.
  363. script.write(",\n".join(map(repr, py_files)) + "]\n")
  364. script.write(
  365. """
  366. byte_compile(files, optimize=%r, force=%r,
  367. prefix=%r, base_dir=%r,
  368. verbose=%r, dry_run=0,
  369. direct=1)
  370. """
  371. % (optimize, force, prefix, base_dir, verbose)
  372. )
  373. cmd = [sys.executable]
  374. cmd.extend(subprocess._optim_args_from_interpreter_flags())
  375. cmd.append(script_name)
  376. spawn(cmd, dry_run=dry_run)
  377. execute(os.remove, (script_name,), "removing %s" % script_name, dry_run=dry_run)
  378. # "Direct" byte-compilation: use the py_compile module to compile
  379. # right here, right now. Note that the script generated in indirect
  380. # mode simply calls 'byte_compile()' in direct mode, a weird sort of
  381. # cross-process recursion. Hey, it works!
  382. else:
  383. from py_compile import compile
  384. for file in py_files:
  385. if file[-3:] != ".py":
  386. # This lets us be lazy and not filter filenames in
  387. # the "install_lib" command.
  388. continue
  389. # Terminology from the py_compile module:
  390. # cfile - byte-compiled file
  391. # dfile - purported source filename (same as 'file' by default)
  392. if optimize >= 0:
  393. opt = '' if optimize == 0 else optimize
  394. cfile = importlib.util.cache_from_source(file, optimization=opt)
  395. else:
  396. cfile = importlib.util.cache_from_source(file)
  397. dfile = file
  398. if prefix:
  399. if file[: len(prefix)] != prefix:
  400. raise ValueError(
  401. "invalid prefix: filename %r doesn't start with %r"
  402. % (file, prefix)
  403. )
  404. dfile = dfile[len(prefix) :]
  405. if base_dir:
  406. dfile = os.path.join(base_dir, dfile)
  407. cfile_base = os.path.basename(cfile)
  408. if direct:
  409. if force or newer(file, cfile):
  410. log.info("byte-compiling %s to %s", file, cfile_base)
  411. if not dry_run:
  412. compile(file, cfile, dfile)
  413. else:
  414. log.debug("skipping byte-compilation of %s to %s", file, cfile_base)
  415. def rfc822_escape(header):
  416. """Return a version of the string escaped for inclusion in an
  417. RFC-822 header, by ensuring there are 8 spaces space after each newline.
  418. """
  419. lines = header.split('\n')
  420. sep = '\n' + 8 * ' '
  421. return sep.join(lines)