util.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. from distutils.errors import DistutilsPlatformError
  11. from distutils.dep_util import newer
  12. from distutils.spawn import spawn
  13. from distutils import log
  14. from distutils.errors import DistutilsByteCompileError
  15. def get_platform ():
  16. """Return a string that identifies the current platform. This is used mainly to
  17. distinguish platform-specific build directories and platform-specific built
  18. distributions. Typically includes the OS name and version and the
  19. architecture (as supplied by 'os.uname()'), although the exact information
  20. included depends on the OS; eg. on Linux, the kernel version isn't
  21. particularly important.
  22. Examples of returned values:
  23. linux-i586
  24. linux-alpha (?)
  25. solaris-2.6-sun4u
  26. Windows will return one of:
  27. win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
  28. win32 (all others - specifically, sys.platform is returned)
  29. For other non-POSIX platforms, currently just returns 'sys.platform'.
  30. """
  31. if os.name == 'nt':
  32. if 'amd64' in sys.version.lower():
  33. return 'win-amd64'
  34. return sys.platform
  35. # Set for cross builds explicitly
  36. if "_PYTHON_HOST_PLATFORM" in os.environ:
  37. return os.environ["_PYTHON_HOST_PLATFORM"]
  38. if os.name != "posix" or not hasattr(os, 'uname'):
  39. # XXX what about the architecture? NT is Intel or Alpha,
  40. # Mac OS is M68k or PPC, etc.
  41. return sys.platform
  42. # Try to distinguish various flavours of Unix
  43. (osname, host, release, version, machine) = os.uname()
  44. # Convert the OS name to lowercase, remove '/' characters, and translate
  45. # spaces (for "Power Macintosh")
  46. osname = osname.lower().replace('/', '')
  47. machine = machine.replace(' ', '_')
  48. machine = machine.replace('/', '-')
  49. if osname[:5] == "linux":
  50. # At least on Linux/Intel, 'machine' is the processor --
  51. # i386, etc.
  52. # XXX what about Alpha, SPARC, etc?
  53. return "%s-%s" % (osname, machine)
  54. elif osname[:5] == "sunos":
  55. if release[0] >= "5": # SunOS 5 == Solaris 2
  56. osname = "solaris"
  57. release = "%d.%s" % (int(release[0]) - 3, release[2:])
  58. # We can't use "platform.architecture()[0]" because a
  59. # bootstrap problem. We use a dict to get an error
  60. # if some suspicious happens.
  61. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
  62. machine += ".%s" % bitness[sys.maxsize]
  63. # fall through to standard osname-release-machine representation
  64. elif osname[:3] == "aix":
  65. return "%s-%s.%s" % (osname, version, release)
  66. elif osname[:6] == "cygwin":
  67. osname = "cygwin"
  68. rel_re = re.compile (r'[\d.]+', re.ASCII)
  69. m = rel_re.match(release)
  70. if m:
  71. release = m.group()
  72. elif osname[:6] == "darwin":
  73. import _osx_support, distutils.sysconfig
  74. osname, release, machine = _osx_support.get_platform_osx(
  75. distutils.sysconfig.get_config_vars(),
  76. osname, release, machine)
  77. return "%s-%s-%s" % (osname, release, machine)
  78. # get_platform ()
  79. def convert_path (pathname):
  80. """Return 'pathname' as a name that will work on the native filesystem,
  81. i.e. split it on '/' and put it back together again using the current
  82. directory separator. Needed because filenames in the setup script are
  83. always supplied in Unix style, and have to be converted to the local
  84. convention before we can actually use them in the filesystem. Raises
  85. ValueError on non-Unix-ish systems if 'pathname' either starts or
  86. ends with a slash.
  87. """
  88. if os.sep == '/':
  89. return pathname
  90. if not pathname:
  91. return pathname
  92. if pathname[0] == '/':
  93. raise ValueError("path '%s' cannot be absolute" % pathname)
  94. if pathname[-1] == '/':
  95. raise ValueError("path '%s' cannot end with '/'" % pathname)
  96. paths = pathname.split('/')
  97. while '.' in paths:
  98. paths.remove('.')
  99. if not paths:
  100. return os.curdir
  101. return os.path.join(*paths)
  102. # convert_path ()
  103. def change_root (new_root, pathname):
  104. """Return 'pathname' with 'new_root' prepended. If 'pathname' is
  105. relative, this is equivalent to "os.path.join(new_root,pathname)".
  106. Otherwise, it requires making 'pathname' relative and then joining the
  107. two, which is tricky on DOS/Windows and Mac OS.
  108. """
  109. if os.name == 'posix':
  110. if not os.path.isabs(pathname):
  111. return os.path.join(new_root, pathname)
  112. else:
  113. return os.path.join(new_root, pathname[1:])
  114. elif os.name == 'nt':
  115. (drive, path) = os.path.splitdrive(pathname)
  116. if path[0] == '\\':
  117. path = path[1:]
  118. return os.path.join(new_root, path)
  119. else:
  120. raise DistutilsPlatformError("nothing known about platform '%s'" % os.name)
  121. _environ_checked = 0
  122. def check_environ ():
  123. """Ensure that 'os.environ' has all the environment variables we
  124. guarantee that users can use in config files, command-line options,
  125. etc. Currently this includes:
  126. HOME - user's home directory (Unix only)
  127. PLAT - description of the current platform, including hardware
  128. and OS (see 'get_platform()')
  129. """
  130. global _environ_checked
  131. if _environ_checked:
  132. return
  133. if os.name == 'posix' and 'HOME' not in os.environ:
  134. try:
  135. import pwd
  136. os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  137. except (ImportError, KeyError):
  138. # bpo-10496: if the current user identifier doesn't exist in the
  139. # password database, do nothing
  140. pass
  141. if 'PLAT' not in os.environ:
  142. os.environ['PLAT'] = get_platform()
  143. _environ_checked = 1
  144. def subst_vars (s, local_vars):
  145. """Perform shell/Perl-style variable substitution on 'string'. Every
  146. occurrence of '$' followed by a name is considered a variable, and
  147. variable is substituted by the value found in the 'local_vars'
  148. dictionary, or in 'os.environ' if it's not in 'local_vars'.
  149. 'os.environ' is first checked/augmented to guarantee that it contains
  150. certain values: see 'check_environ()'. Raise ValueError for any
  151. variables not found in either 'local_vars' or 'os.environ'.
  152. """
  153. check_environ()
  154. def _subst (match, local_vars=local_vars):
  155. var_name = match.group(1)
  156. if var_name in local_vars:
  157. return str(local_vars[var_name])
  158. else:
  159. return os.environ[var_name]
  160. try:
  161. return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  162. except KeyError as var:
  163. raise ValueError("invalid variable '$%s'" % var)
  164. # subst_vars ()
  165. def grok_environment_error (exc, prefix="error: "):
  166. # Function kept for backward compatibility.
  167. # Used to try clever things with EnvironmentErrors,
  168. # but nowadays str(exception) produces good messages.
  169. return prefix + str(exc)
  170. # Needed by 'split_quoted()'
  171. _wordchars_re = _squote_re = _dquote_re = None
  172. def _init_regex():
  173. global _wordchars_re, _squote_re, _dquote_re
  174. _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
  175. _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
  176. _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
  177. def split_quoted (s):
  178. """Split a string up according to Unix shell-like rules for quotes and
  179. backslashes. In short: words are delimited by spaces, as long as those
  180. spaces are not escaped by a backslash, or inside a quoted string.
  181. Single and double quotes are equivalent, and the quote characters can
  182. be backslash-escaped. The backslash is stripped from any two-character
  183. escape sequence, leaving only the escaped character. The quote
  184. characters are stripped from any quoted string. Returns a list of
  185. words.
  186. """
  187. # This is a nice algorithm for splitting up a single string, since it
  188. # doesn't require character-by-character examination. It was a little
  189. # bit of a brain-bender to get it working right, though...
  190. if _wordchars_re is None: _init_regex()
  191. s = s.strip()
  192. words = []
  193. pos = 0
  194. while s:
  195. m = _wordchars_re.match(s, pos)
  196. end = m.end()
  197. if end == len(s):
  198. words.append(s[:end])
  199. break
  200. if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
  201. words.append(s[:end]) # we definitely have a word delimiter
  202. s = s[end:].lstrip()
  203. pos = 0
  204. elif s[end] == '\\': # preserve whatever is being escaped;
  205. # will become part of the current word
  206. s = s[:end] + s[end+1:]
  207. pos = end+1
  208. else:
  209. if s[end] == "'": # slurp singly-quoted string
  210. m = _squote_re.match(s, end)
  211. elif s[end] == '"': # slurp doubly-quoted string
  212. m = _dquote_re.match(s, end)
  213. else:
  214. raise RuntimeError("this can't happen (bad char '%c')" % s[end])
  215. if m is None:
  216. raise ValueError("bad string (mismatched %s quotes?)" % s[end])
  217. (beg, end) = m.span()
  218. s = s[:beg] + s[beg+1:end-1] + s[end:]
  219. pos = m.end() - 2
  220. if pos >= len(s):
  221. words.append(s)
  222. break
  223. return words
  224. # split_quoted ()
  225. def execute (func, args, msg=None, verbose=0, dry_run=0):
  226. """Perform some action that affects the outside world (eg. by
  227. writing to the filesystem). Such actions are special because they
  228. are disabled by the 'dry_run' flag. This method takes care of all
  229. that bureaucracy for you; all you have to do is supply the
  230. function to call and an argument tuple for it (to embody the
  231. "external action" being performed), and an optional message to
  232. print.
  233. """
  234. if msg is None:
  235. msg = "%s%r" % (func.__name__, args)
  236. if msg[-2:] == ',)': # correct for singleton tuple
  237. msg = msg[0:-2] + ')'
  238. log.info(msg)
  239. if not dry_run:
  240. func(*args)
  241. def strtobool (val):
  242. """Convert a string representation of truth to true (1) or false (0).
  243. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  244. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  245. 'val' is anything else.
  246. """
  247. val = val.lower()
  248. if val in ('y', 'yes', 't', 'true', 'on', '1'):
  249. return 1
  250. elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  251. return 0
  252. else:
  253. raise ValueError("invalid truth value %r" % (val,))
  254. def byte_compile (py_files,
  255. optimize=0, force=0,
  256. prefix=None, base_dir=None,
  257. verbose=1, dry_run=0,
  258. direct=None):
  259. """Byte-compile a collection of Python source files to .pyc
  260. files in a __pycache__ subdirectory. 'py_files' is a list
  261. of files to compile; any files that don't end in ".py" are silently
  262. skipped. 'optimize' must be one of the following:
  263. 0 - don't optimize
  264. 1 - normal optimization (like "python -O")
  265. 2 - extra optimization (like "python -OO")
  266. If 'force' is true, all files are recompiled regardless of
  267. timestamps.
  268. The source filename encoded in each bytecode file defaults to the
  269. filenames listed in 'py_files'; you can modify these with 'prefix' and
  270. 'basedir'. 'prefix' is a string that will be stripped off of each
  271. source filename, and 'base_dir' is a directory name that will be
  272. prepended (after 'prefix' is stripped). You can supply either or both
  273. (or neither) of 'prefix' and 'base_dir', as you wish.
  274. If 'dry_run' is true, doesn't actually do anything that would
  275. affect the filesystem.
  276. Byte-compilation is either done directly in this interpreter process
  277. with the standard py_compile module, or indirectly by writing a
  278. temporary script and executing it. Normally, you should let
  279. 'byte_compile()' figure out to use direct compilation or not (see
  280. the source for details). The 'direct' flag is used by the script
  281. generated in indirect mode; unless you know what you're doing, leave
  282. it set to None.
  283. """
  284. # Late import to fix a bootstrap issue: _posixsubprocess is built by
  285. # setup.py, but setup.py uses distutils.
  286. import subprocess
  287. # nothing is done if sys.dont_write_bytecode is True
  288. if sys.dont_write_bytecode:
  289. raise DistutilsByteCompileError('byte-compiling is disabled.')
  290. # First, if the caller didn't force us into direct or indirect mode,
  291. # figure out which mode we should be in. We take a conservative
  292. # approach: choose direct mode *only* if the current interpreter is
  293. # in debug mode and optimize is 0. If we're not in debug mode (-O
  294. # or -OO), we don't know which level of optimization this
  295. # interpreter is running with, so we can't do direct
  296. # byte-compilation and be certain that it's the right thing. Thus,
  297. # always compile indirectly if the current interpreter is in either
  298. # optimize mode, or if either optimization level was requested by
  299. # the caller.
  300. if direct is None:
  301. direct = (__debug__ and optimize == 0)
  302. # "Indirect" byte-compilation: write a temporary script and then
  303. # run it with the appropriate flags.
  304. if not direct:
  305. try:
  306. from tempfile import mkstemp
  307. (script_fd, script_name) = mkstemp(".py")
  308. except ImportError:
  309. from tempfile import mktemp
  310. (script_fd, script_name) = None, mktemp(".py")
  311. log.info("writing byte-compilation script '%s'", script_name)
  312. if not dry_run:
  313. if script_fd is not None:
  314. script = os.fdopen(script_fd, "w")
  315. else:
  316. script = open(script_name, "w")
  317. script.write("""\
  318. from distutils.util import byte_compile
  319. files = [
  320. """)
  321. # XXX would be nice to write absolute filenames, just for
  322. # safety's sake (script should be more robust in the face of
  323. # chdir'ing before running it). But this requires abspath'ing
  324. # 'prefix' as well, and that breaks the hack in build_lib's
  325. # 'byte_compile()' method that carefully tacks on a trailing
  326. # slash (os.sep really) to make sure the prefix here is "just
  327. # right". This whole prefix business is rather delicate -- the
  328. # problem is that it's really a directory, but I'm treating it
  329. # as a dumb string, so trailing slashes and so forth matter.
  330. #py_files = map(os.path.abspath, py_files)
  331. #if prefix:
  332. # prefix = os.path.abspath(prefix)
  333. script.write(",\n".join(map(repr, py_files)) + "]\n")
  334. script.write("""
  335. byte_compile(files, optimize=%r, force=%r,
  336. prefix=%r, base_dir=%r,
  337. verbose=%r, dry_run=0,
  338. direct=1)
  339. """ % (optimize, force, prefix, base_dir, verbose))
  340. script.close()
  341. cmd = [sys.executable]
  342. cmd.extend(subprocess._optim_args_from_interpreter_flags())
  343. cmd.append(script_name)
  344. spawn(cmd, dry_run=dry_run)
  345. execute(os.remove, (script_name,), "removing %s" % script_name,
  346. dry_run=dry_run)
  347. # "Direct" byte-compilation: use the py_compile module to compile
  348. # right here, right now. Note that the script generated in indirect
  349. # mode simply calls 'byte_compile()' in direct mode, a weird sort of
  350. # cross-process recursion. Hey, it works!
  351. else:
  352. from py_compile import compile
  353. for file in py_files:
  354. if file[-3:] != ".py":
  355. # This lets us be lazy and not filter filenames in
  356. # the "install_lib" command.
  357. continue
  358. # Terminology from the py_compile module:
  359. # cfile - byte-compiled file
  360. # dfile - purported source filename (same as 'file' by default)
  361. if optimize >= 0:
  362. opt = '' if optimize == 0 else optimize
  363. cfile = importlib.util.cache_from_source(
  364. file, optimization=opt)
  365. else:
  366. cfile = importlib.util.cache_from_source(file)
  367. dfile = file
  368. if prefix:
  369. if file[:len(prefix)] != prefix:
  370. raise ValueError("invalid prefix: filename %r doesn't start with %r"
  371. % (file, prefix))
  372. dfile = dfile[len(prefix):]
  373. if base_dir:
  374. dfile = os.path.join(base_dir, dfile)
  375. cfile_base = os.path.basename(cfile)
  376. if direct:
  377. if force or newer(file, cfile):
  378. log.info("byte-compiling %s to %s", file, cfile_base)
  379. if not dry_run:
  380. compile(file, cfile, dfile)
  381. else:
  382. log.debug("skipping byte-compilation of %s to %s",
  383. file, cfile_base)
  384. # byte_compile ()
  385. def rfc822_escape (header):
  386. """Return a version of the string escaped for inclusion in an
  387. RFC-822 header, by ensuring there are 8 spaces space after each newline.
  388. """
  389. lines = header.split('\n')
  390. sep = '\n' + 8 * ' '
  391. return sep.join(lines)
  392. # 2to3 support
  393. def run_2to3(files, fixer_names=None, options=None, explicit=None):
  394. """Invoke 2to3 on a list of Python files.
  395. The files should all come from the build area, as the
  396. modification is done in-place. To reduce the build time,
  397. only files modified since the last invocation of this
  398. function should be passed in the files argument."""
  399. if not files:
  400. return
  401. # Make this class local, to delay import of 2to3
  402. from lib2to3.refactor import RefactoringTool, get_fixers_from_package
  403. class DistutilsRefactoringTool(RefactoringTool):
  404. def log_error(self, msg, *args, **kw):
  405. log.error(msg, *args)
  406. def log_message(self, msg, *args):
  407. log.info(msg, *args)
  408. def log_debug(self, msg, *args):
  409. log.debug(msg, *args)
  410. if fixer_names is None:
  411. fixer_names = get_fixers_from_package('lib2to3.fixes')
  412. r = DistutilsRefactoringTool(fixer_names, options=options)
  413. r.refactor(files, write=True)
  414. def copydir_run_2to3(src, dest, template=None, fixer_names=None,
  415. options=None, explicit=None):
  416. """Recursively copy a directory, only copying new and changed files,
  417. running run_2to3 over all newly copied Python modules afterward.
  418. If you give a template string, it's parsed like a MANIFEST.in.
  419. """
  420. from distutils.dir_util import mkpath
  421. from distutils.file_util import copy_file
  422. from distutils.filelist import FileList
  423. filelist = FileList()
  424. curdir = os.getcwd()
  425. os.chdir(src)
  426. try:
  427. filelist.findall()
  428. finally:
  429. os.chdir(curdir)
  430. filelist.files[:] = filelist.allfiles
  431. if template:
  432. for line in template.splitlines():
  433. line = line.strip()
  434. if not line: continue
  435. filelist.process_template_line(line)
  436. copied = []
  437. for filename in filelist.files:
  438. outname = os.path.join(dest, filename)
  439. mkpath(os.path.dirname(outname))
  440. res = copy_file(os.path.join(src, filename), outname, update=1)
  441. if res[1]: copied.append(outname)
  442. run_2to3([fn for fn in copied if fn.lower().endswith('.py')],
  443. fixer_names=fixer_names, options=options, explicit=explicit)
  444. return copied
  445. class Mixin2to3:
  446. '''Mixin class for commands that run 2to3.
  447. To configure 2to3, setup scripts may either change
  448. the class variables, or inherit from individual commands
  449. to override how 2to3 is invoked.'''
  450. # provide list of fixers to run;
  451. # defaults to all from lib2to3.fixers
  452. fixer_names = None
  453. # options dictionary
  454. options = None
  455. # list of fixers to invoke even though they are marked as explicit
  456. explicit = None
  457. def run_2to3(self, files):
  458. return run_2to3(files, self.fixer_names, self.options, self.explicit)