util.py 18 KB

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