PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/krono/pypy
Python | 477 lines | 451 code | 5 blank | 21 comment | 15 complexity | 413fff49ac6f33846122150a49e9254f MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  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. # Set for cross builds explicitly
  47. if "_PYTHON_HOST_PLATFORM" in os.environ:
  48. return os.environ["_PYTHON_HOST_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 = string.lower(osname)
  58. osname = string.replace(osname, '/', '')
  59. machine = string.replace(machine, ' ', '_')
  60. machine = string.replace(machine, '/', '-')
  61. if osname[:5] == "linux":
  62. # At least on Linux/Intel, 'machine' is the processor --
  63. # i386, etc.
  64. # XXX what about Alpha, SPARC, etc?
  65. return "%s-%s" % (osname, machine)
  66. elif osname[:5] == "sunos":
  67. if release[0] >= "5": # SunOS 5 == Solaris 2
  68. osname = "solaris"
  69. release = "%d.%s" % (int(release[0]) - 3, release[2:])
  70. # We can't use "platform.architecture()[0]" because a
  71. # bootstrap problem. We use a dict to get an error
  72. # if some suspicious happens.
  73. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
  74. machine += ".%s" % bitness[sys.maxint]
  75. # fall through to standard osname-release-machine representation
  76. elif osname[:4] == "irix": # could be "irix64"!
  77. return "%s-%s" % (osname, release)
  78. elif osname[:3] == "aix":
  79. return "%s-%s.%s" % (osname, version, release)
  80. elif osname[:6] == "cygwin":
  81. osname = "cygwin"
  82. rel_re = re.compile (r'[\d.]+')
  83. m = rel_re.match(release)
  84. if m:
  85. release = m.group()
  86. elif osname[:6] == "darwin":
  87. import _osx_support, distutils.sysconfig
  88. osname, release, machine = _osx_support.get_platform_osx(
  89. distutils.sysconfig.get_config_vars(),
  90. osname, release, machine)
  91. return "%s-%s-%s" % (osname, release, machine)
  92. # get_platform ()
  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 = string.split(pathname, '/')
  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. elif os.name == 'os2':
  134. (drive, path) = os.path.splitdrive(pathname)
  135. if path[0] == os.sep:
  136. path = path[1:]
  137. return os.path.join(new_root, path)
  138. else:
  139. raise DistutilsPlatformError, \
  140. "nothing known about platform '%s'" % os.name
  141. _environ_checked = 0
  142. def check_environ ():
  143. """Ensure that 'os.environ' has all the environment variables we
  144. guarantee that users can use in config files, command-line options,
  145. etc. Currently this includes:
  146. HOME - user's home directory (Unix only)
  147. PLAT - description of the current platform, including hardware
  148. and OS (see 'get_platform()')
  149. """
  150. global _environ_checked
  151. if _environ_checked:
  152. return
  153. if os.name == 'posix' and 'HOME' not in os.environ:
  154. import pwd
  155. os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  156. if 'PLAT' not in os.environ:
  157. os.environ['PLAT'] = get_platform()
  158. _environ_checked = 1
  159. def subst_vars (s, local_vars):
  160. """Perform shell/Perl-style variable substitution on 'string'. Every
  161. occurrence of '$' followed by a name is considered a variable, and
  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. def _subst (match, local_vars=local_vars):
  170. var_name = match.group(1)
  171. if var_name in local_vars:
  172. return str(local_vars[var_name])
  173. else:
  174. return os.environ[var_name]
  175. try:
  176. return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  177. except KeyError, var:
  178. raise ValueError, "invalid variable '$%s'" % var
  179. # subst_vars ()
  180. def grok_environment_error (exc, prefix="error: "):
  181. # Function kept for backward compatibility.
  182. # Used to try clever things with EnvironmentErrors,
  183. # but nowadays str(exception) produces good messages.
  184. return prefix + str(exc)
  185. # Needed by 'split_quoted()'
  186. _wordchars_re = _squote_re = _dquote_re = None
  187. def _init_regex():
  188. global _wordchars_re, _squote_re, _dquote_re
  189. _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
  190. _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
  191. _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
  192. def split_quoted (s):
  193. """Split a string up according to Unix shell-like rules for quotes and
  194. backslashes. In short: words are delimited by spaces, as long as those
  195. spaces are not escaped by a backslash, or inside a quoted string.
  196. Single and double quotes are equivalent, and the quote characters can
  197. be backslash-escaped. The backslash is stripped from any two-character
  198. escape sequence, leaving only the escaped character. The quote
  199. characters are stripped from any quoted string. Returns a list of
  200. words.
  201. """
  202. # This is a nice algorithm for splitting up a single string, since it
  203. # doesn't require character-by-character examination. It was a little
  204. # bit of a brain-bender to get it working right, though...
  205. if _wordchars_re is None: _init_regex()
  206. s = string.strip(s)
  207. words = []
  208. pos = 0
  209. while s:
  210. m = _wordchars_re.match(s, pos)
  211. end = m.end()
  212. if end == len(s):
  213. words.append(s[:end])
  214. break
  215. if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
  216. words.append(s[:end]) # we definitely have a word delimiter
  217. s = string.lstrip(s[end:])
  218. pos = 0
  219. elif s[end] == '\\': # preserve whatever is being escaped;
  220. # will become part of the current word
  221. s = s[:end] + s[end+1:]
  222. pos = end+1
  223. else:
  224. if s[end] == "'": # slurp singly-quoted string
  225. m = _squote_re.match(s, end)
  226. elif s[end] == '"': # slurp doubly-quoted string
  227. m = _dquote_re.match(s, end)
  228. else:
  229. raise RuntimeError, \
  230. "this can't happen (bad char '%c')" % s[end]
  231. if m is None:
  232. raise ValueError, \
  233. "bad string (mismatched %s quotes?)" % s[end]
  234. (beg, end) = m.span()
  235. s = s[:beg] + s[beg+1:end-1] + s[end:]
  236. pos = m.end() - 2
  237. if pos >= len(s):
  238. words.append(s)
  239. break
  240. return words
  241. # split_quoted ()
  242. def execute (func, args, msg=None, verbose=0, dry_run=0):
  243. """Perform some action that affects the outside world (eg. by
  244. writing to the filesystem). Such actions are special because they
  245. are disabled by the 'dry_run' flag. This method takes care of all
  246. that bureaucracy for you; all you have to do is supply the
  247. function to call and an argument tuple for it (to embody the
  248. "external action" being performed), and an optional message to
  249. print.
  250. """
  251. if msg is None:
  252. msg = "%s%r" % (func.__name__, args)
  253. if msg[-2:] == ',)': # correct for singleton tuple
  254. msg = msg[0:-2] + ')'
  255. log.info(msg)
  256. if not dry_run:
  257. func(*args)
  258. def strtobool (val):
  259. """Convert a string representation of truth to true (1) or false (0).
  260. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  261. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  262. 'val' is anything else.
  263. """
  264. val = string.lower(val)
  265. if val in ('y', 'yes', 't', 'true', 'on', '1'):
  266. return 1
  267. elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  268. return 0
  269. else:
  270. raise ValueError, "invalid truth value %r" % (val,)
  271. def byte_compile (py_files,
  272. optimize=0, force=0,
  273. prefix=None, base_dir=None,
  274. verbose=1, dry_run=0,
  275. direct=None):
  276. """Byte-compile a collection of Python source files to either .pyc
  277. or .pyo files in the same directory. 'py_files' is a list of files
  278. to compile; any files that don't end in ".py" are silently skipped.
  279. 'optimize' must be one of the following:
  280. 0 - don't optimize (generate .pyc)
  281. 1 - normal optimization (like "python -O")
  282. 2 - extra optimization (like "python -OO")
  283. If 'force' is true, all files are recompiled regardless of
  284. timestamps.
  285. The source filename encoded in each bytecode file defaults to the
  286. filenames listed in 'py_files'; you can modify these with 'prefix' and
  287. 'basedir'. 'prefix' is a string that will be stripped off of each
  288. source filename, and 'base_dir' is a directory name that will be
  289. prepended (after 'prefix' is stripped). You can supply either or both
  290. (or neither) of 'prefix' and 'base_dir', as you wish.
  291. If 'dry_run' is true, doesn't actually do anything that would
  292. affect the filesystem.
  293. Byte-compilation is either done directly in this interpreter process
  294. with the standard py_compile module, or indirectly by writing a
  295. temporary script and executing it. Normally, you should let
  296. 'byte_compile()' figure out to use direct compilation or not (see
  297. the source for details). The 'direct' flag is used by the script
  298. generated in indirect mode; unless you know what you're doing, leave
  299. it set to None.
  300. """
  301. # nothing is done if sys.dont_write_bytecode is True
  302. if sys.dont_write_bytecode:
  303. raise DistutilsByteCompileError('byte-compiling is disabled.')
  304. # First, if the caller didn't force us into direct or indirect mode,
  305. # figure out which mode we should be in. We take a conservative
  306. # approach: choose direct mode *only* if the current interpreter is
  307. # in debug mode and optimize is 0. If we're not in debug mode (-O
  308. # or -OO), we don't know which level of optimization this
  309. # interpreter is running with, so we can't do direct
  310. # byte-compilation and be certain that it's the right thing. Thus,
  311. # always compile indirectly if the current interpreter is in either
  312. # optimize mode, or if either optimization level was requested by
  313. # the caller.
  314. if direct is None:
  315. direct = (__debug__ and optimize == 0)
  316. # "Indirect" byte-compilation: write a temporary script and then
  317. # run it with the appropriate flags.
  318. if not direct:
  319. try:
  320. from tempfile import mkstemp
  321. (script_fd, script_name) = mkstemp(".py")
  322. except ImportError:
  323. from tempfile import mktemp
  324. (script_fd, script_name) = None, mktemp(".py")
  325. log.info("writing byte-compilation script '%s'", script_name)
  326. if not dry_run:
  327. if script_fd is not None:
  328. script = os.fdopen(script_fd, "w")
  329. else:
  330. script = open(script_name, "w")
  331. script.write("""\
  332. from distutils.util import byte_compile
  333. files = [
  334. """)
  335. # XXX would be nice to write absolute filenames, just for
  336. # safety's sake (script should be more robust in the face of
  337. # chdir'ing before running it). But this requires abspath'ing
  338. # 'prefix' as well, and that breaks the hack in build_lib's
  339. # 'byte_compile()' method that carefully tacks on a trailing
  340. # slash (os.sep really) to make sure the prefix here is "just
  341. # right". This whole prefix business is rather delicate -- the
  342. # problem is that it's really a directory, but I'm treating it
  343. # as a dumb string, so trailing slashes and so forth matter.
  344. #py_files = map(os.path.abspath, py_files)
  345. #if prefix:
  346. # prefix = os.path.abspath(prefix)
  347. script.write(string.join(map(repr, py_files), ",\n") + "]\n")
  348. script.write("""
  349. byte_compile(files, optimize=%r, force=%r,
  350. prefix=%r, base_dir=%r,
  351. verbose=%r, dry_run=0,
  352. direct=1)
  353. """ % (optimize, force, prefix, base_dir, verbose))
  354. script.close()
  355. cmd = [sys.executable, script_name]
  356. if optimize == 1:
  357. cmd.insert(1, "-O")
  358. elif optimize == 2:
  359. cmd.insert(1, "-OO")
  360. spawn(cmd, dry_run=dry_run)
  361. execute(os.remove, (script_name,), "removing %s" % script_name,
  362. dry_run=dry_run)
  363. # "Direct" byte-compilation: use the py_compile module to compile
  364. # right here, right now. Note that the script generated in indirect
  365. # mode simply calls 'byte_compile()' in direct mode, a weird sort of
  366. # cross-process recursion. Hey, it works!
  367. else:
  368. from py_compile import compile
  369. for file in py_files:
  370. if file[-3:] != ".py":
  371. # This lets us be lazy and not filter filenames in
  372. # the "install_lib" command.
  373. continue
  374. # Terminology from the py_compile module:
  375. # cfile - byte-compiled file
  376. # dfile - purported source filename (same as 'file' by default)
  377. cfile = file + (__debug__ and "c" or "o")
  378. dfile = file
  379. if prefix:
  380. if file[:len(prefix)] != prefix:
  381. raise ValueError, \
  382. ("invalid prefix: filename %r doesn't start with %r"
  383. % (file, prefix))
  384. dfile = dfile[len(prefix):]
  385. if base_dir:
  386. dfile = os.path.join(base_dir, dfile)
  387. cfile_base = os.path.basename(cfile)
  388. if direct:
  389. if force or newer(file, cfile):
  390. log.info("byte-compiling %s to %s", file, cfile_base)
  391. if not dry_run:
  392. compile(file, cfile, dfile)
  393. else:
  394. log.debug("skipping byte-compilation of %s to %s",
  395. file, cfile_base)
  396. # byte_compile ()
  397. def rfc822_escape (header):
  398. """Return a version of the string escaped for inclusion in an
  399. RFC-822 header, by ensuring there are 8 spaces space after each newline.
  400. """
  401. lines = string.split(header, '\n')
  402. header = string.join(lines, '\n' + 8*' ')
  403. return header