PageRenderTime 81ms CodeModel.GetById 49ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/distutils/util.py

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