util.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. from distutils.errors import DistutilsPlatformError
  13. from distutils.dep_util import newer
  14. from distutils.spawn import spawn
  15. from distutils import log
  16. from distutils.errors import DistutilsByteCompileError
  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. _environ_checked = 0
  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. global _environ_checked
  148. if _environ_checked:
  149. return
  150. if os.name == 'posix' and 'HOME' not in os.environ:
  151. try:
  152. import pwd
  153. os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  154. except (ImportError, KeyError):
  155. # bpo-10496: if the current user identifier doesn't exist in the
  156. # password database, do nothing
  157. pass
  158. if 'PLAT' not in os.environ:
  159. os.environ['PLAT'] = get_platform()
  160. _environ_checked = 1
  161. def subst_vars(s, local_vars):
  162. """
  163. Perform variable substitution on 'string'.
  164. Variables are indicated by format-style braces ("{var}").
  165. Variable is substituted by the value found in the 'local_vars'
  166. dictionary or in 'os.environ' if it's not in 'local_vars'.
  167. 'os.environ' is first checked/augmented to guarantee that it contains
  168. certain values: see 'check_environ()'. Raise ValueError for any
  169. variables not found in either 'local_vars' or 'os.environ'.
  170. """
  171. check_environ()
  172. lookup = dict(os.environ)
  173. lookup.update((name, str(value)) for name, value in local_vars.items())
  174. try:
  175. return _subst_compat(s).format_map(lookup)
  176. except KeyError as var:
  177. raise ValueError(f"invalid variable {var}")
  178. def _subst_compat(s):
  179. """
  180. Replace shell/Perl-style variable substitution with
  181. format-style. For compatibility.
  182. """
  183. def _subst(match):
  184. return f'{{{match.group(1)}}}'
  185. repl = re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  186. if repl != s:
  187. import warnings
  188. warnings.warn(
  189. "shell/Perl-style substitions are deprecated",
  190. DeprecationWarning,
  191. )
  192. return repl
  193. def grok_environment_error(exc, prefix="error: "):
  194. # Function kept for backward compatibility.
  195. # Used to try clever things with EnvironmentErrors,
  196. # but nowadays str(exception) produces good messages.
  197. return prefix + str(exc)
  198. # Needed by 'split_quoted()'
  199. _wordchars_re = _squote_re = _dquote_re = None
  200. def _init_regex():
  201. global _wordchars_re, _squote_re, _dquote_re
  202. _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
  203. _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
  204. _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
  205. def split_quoted(s):
  206. """Split a string up according to Unix shell-like rules for quotes and
  207. backslashes. In short: words are delimited by spaces, as long as those
  208. spaces are not escaped by a backslash, or inside a quoted string.
  209. Single and double quotes are equivalent, and the quote characters can
  210. be backslash-escaped. The backslash is stripped from any two-character
  211. escape sequence, leaving only the escaped character. The quote
  212. characters are stripped from any quoted string. Returns a list of
  213. words.
  214. """
  215. # This is a nice algorithm for splitting up a single string, since it
  216. # doesn't require character-by-character examination. It was a little
  217. # bit of a brain-bender to get it working right, though...
  218. if _wordchars_re is None:
  219. _init_regex()
  220. s = s.strip()
  221. words = []
  222. pos = 0
  223. while s:
  224. m = _wordchars_re.match(s, pos)
  225. end = m.end()
  226. if end == len(s):
  227. words.append(s[:end])
  228. break
  229. if s[end] in string.whitespace:
  230. # unescaped, unquoted whitespace: now
  231. # we definitely have a word delimiter
  232. words.append(s[:end])
  233. s = s[end:].lstrip()
  234. pos = 0
  235. elif s[end] == '\\':
  236. # preserve whatever is being escaped;
  237. # will become part of the current word
  238. s = s[:end] + s[end + 1 :]
  239. pos = end + 1
  240. else:
  241. if s[end] == "'": # slurp singly-quoted string
  242. m = _squote_re.match(s, end)
  243. elif s[end] == '"': # slurp doubly-quoted string
  244. m = _dquote_re.match(s, end)
  245. else:
  246. raise RuntimeError("this can't happen (bad char '%c')" % s[end])
  247. if m is None:
  248. raise ValueError("bad string (mismatched %s quotes?)" % s[end])
  249. (beg, end) = m.span()
  250. s = s[:beg] + s[beg + 1 : end - 1] + s[end:]
  251. pos = m.end() - 2
  252. if pos >= len(s):
  253. words.append(s)
  254. break
  255. return words
  256. # split_quoted ()
  257. def execute(func, args, msg=None, verbose=0, dry_run=0):
  258. """Perform some action that affects the outside world (eg. by
  259. writing to the filesystem). Such actions are special because they
  260. are disabled by the 'dry_run' flag. This method takes care of all
  261. that bureaucracy for you; all you have to do is supply the
  262. function to call and an argument tuple for it (to embody the
  263. "external action" being performed), and an optional message to
  264. print.
  265. """
  266. if msg is None:
  267. msg = "%s%r" % (func.__name__, args)
  268. if msg[-2:] == ',)': # correct for singleton tuple
  269. msg = msg[0:-2] + ')'
  270. log.info(msg)
  271. if not dry_run:
  272. func(*args)
  273. def strtobool(val):
  274. """Convert a string representation of truth to true (1) or false (0).
  275. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  276. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  277. 'val' is anything else.
  278. """
  279. val = val.lower()
  280. if val in ('y', 'yes', 't', 'true', 'on', '1'):
  281. return 1
  282. elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  283. return 0
  284. else:
  285. raise ValueError("invalid truth value %r" % (val,))
  286. def byte_compile(
  287. py_files,
  288. optimize=0,
  289. force=0,
  290. prefix=None,
  291. base_dir=None,
  292. verbose=1,
  293. dry_run=0,
  294. direct=None,
  295. ):
  296. """Byte-compile a collection of Python source files to .pyc
  297. files in a __pycache__ subdirectory. 'py_files' is a list
  298. of files to compile; any files that don't end in ".py" are silently
  299. skipped. 'optimize' must be one of the following:
  300. 0 - don't optimize
  301. 1 - normal optimization (like "python -O")
  302. 2 - extra optimization (like "python -OO")
  303. If 'force' is true, all files are recompiled regardless of
  304. timestamps.
  305. The source filename encoded in each bytecode file defaults to the
  306. filenames listed in 'py_files'; you can modify these with 'prefix' and
  307. 'basedir'. 'prefix' is a string that will be stripped off of each
  308. source filename, and 'base_dir' is a directory name that will be
  309. prepended (after 'prefix' is stripped). You can supply either or both
  310. (or neither) of 'prefix' and 'base_dir', as you wish.
  311. If 'dry_run' is true, doesn't actually do anything that would
  312. affect the filesystem.
  313. Byte-compilation is either done directly in this interpreter process
  314. with the standard py_compile module, or indirectly by writing a
  315. temporary script and executing it. Normally, you should let
  316. 'byte_compile()' figure out to use direct compilation or not (see
  317. the source for details). The 'direct' flag is used by the script
  318. generated in indirect mode; unless you know what you're doing, leave
  319. it set to None.
  320. """
  321. # nothing is done if sys.dont_write_bytecode is True
  322. if sys.dont_write_bytecode:
  323. raise DistutilsByteCompileError('byte-compiling is disabled.')
  324. # First, if the caller didn't force us into direct or indirect mode,
  325. # figure out which mode we should be in. We take a conservative
  326. # approach: choose direct mode *only* if the current interpreter is
  327. # in debug mode and optimize is 0. If we're not in debug mode (-O
  328. # or -OO), we don't know which level of optimization this
  329. # interpreter is running with, so we can't do direct
  330. # byte-compilation and be certain that it's the right thing. Thus,
  331. # always compile indirectly if the current interpreter is in either
  332. # optimize mode, or if either optimization level was requested by
  333. # the caller.
  334. if direct is None:
  335. direct = __debug__ and optimize == 0
  336. # "Indirect" byte-compilation: write a temporary script and then
  337. # run it with the appropriate flags.
  338. if not direct:
  339. try:
  340. from tempfile import mkstemp
  341. (script_fd, script_name) = mkstemp(".py")
  342. except ImportError:
  343. from tempfile import mktemp
  344. (script_fd, script_name) = None, mktemp(".py")
  345. log.info("writing byte-compilation script '%s'", script_name)
  346. if not dry_run:
  347. if script_fd is not None:
  348. script = os.fdopen(script_fd, "w")
  349. else:
  350. script = open(script_name, "w")
  351. with script:
  352. script.write(
  353. """\
  354. from distutils.util import byte_compile
  355. files = [
  356. """
  357. )
  358. # XXX would be nice to write absolute filenames, just for
  359. # safety's sake (script should be more robust in the face of
  360. # chdir'ing before running it). But this requires abspath'ing
  361. # 'prefix' as well, and that breaks the hack in build_lib's
  362. # 'byte_compile()' method that carefully tacks on a trailing
  363. # slash (os.sep really) to make sure the prefix here is "just
  364. # right". This whole prefix business is rather delicate -- the
  365. # problem is that it's really a directory, but I'm treating it
  366. # as a dumb string, so trailing slashes and so forth matter.
  367. script.write(",\n".join(map(repr, py_files)) + "]\n")
  368. script.write(
  369. """
  370. byte_compile(files, optimize=%r, force=%r,
  371. prefix=%r, base_dir=%r,
  372. verbose=%r, dry_run=0,
  373. direct=1)
  374. """
  375. % (optimize, force, prefix, base_dir, verbose)
  376. )
  377. cmd = [sys.executable]
  378. cmd.extend(subprocess._optim_args_from_interpreter_flags())
  379. cmd.append(script_name)
  380. spawn(cmd, dry_run=dry_run)
  381. execute(os.remove, (script_name,), "removing %s" % script_name, dry_run=dry_run)
  382. # "Direct" byte-compilation: use the py_compile module to compile
  383. # right here, right now. Note that the script generated in indirect
  384. # mode simply calls 'byte_compile()' in direct mode, a weird sort of
  385. # cross-process recursion. Hey, it works!
  386. else:
  387. from py_compile import compile
  388. for file in py_files:
  389. if file[-3:] != ".py":
  390. # This lets us be lazy and not filter filenames in
  391. # the "install_lib" command.
  392. continue
  393. # Terminology from the py_compile module:
  394. # cfile - byte-compiled file
  395. # dfile - purported source filename (same as 'file' by default)
  396. if optimize >= 0:
  397. opt = '' if optimize == 0 else optimize
  398. cfile = importlib.util.cache_from_source(file, optimization=opt)
  399. else:
  400. cfile = importlib.util.cache_from_source(file)
  401. dfile = file
  402. if prefix:
  403. if file[: len(prefix)] != prefix:
  404. raise ValueError(
  405. "invalid prefix: filename %r doesn't start with %r"
  406. % (file, prefix)
  407. )
  408. dfile = dfile[len(prefix) :]
  409. if base_dir:
  410. dfile = os.path.join(base_dir, dfile)
  411. cfile_base = os.path.basename(cfile)
  412. if direct:
  413. if force or newer(file, cfile):
  414. log.info("byte-compiling %s to %s", file, cfile_base)
  415. if not dry_run:
  416. compile(file, cfile, dfile)
  417. else:
  418. log.debug("skipping byte-compilation of %s to %s", file, cfile_base)
  419. def rfc822_escape(header):
  420. """Return a version of the string escaped for inclusion in an
  421. RFC-822 header, by ensuring there are 8 spaces space after each newline.
  422. """
  423. lines = header.split('\n')
  424. sep = '\n' + 8 * ' '
  425. return sep.join(lines)