You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

653 lines
24 KiB

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