PageRenderTime 74ms CodeModel.GetById 46ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/chrish42/pypy
Python | 492 lines | 466 code | 5 blank | 21 comment | 15 complexity | 4c298c30ed3dbda64dac309430ccca44 MD5 | raw file
Possible License(s): 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. """Generate a useful error message from an EnvironmentError (IOError or
  182. OSError) exception object. Handles Python 1.5.1 and 1.5.2 styles, and
  183. does what it can to deal with exception objects that don't have a
  184. filename (which happens when the error is due to a two-file operation,
  185. such as 'rename()' or 'link()'. Returns the error message as a string
  186. prefixed with 'prefix'.
  187. """
  188. # check for Python 1.5.2-style {IO,OS}Error exception objects
  189. if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
  190. if exc.filename:
  191. error = prefix + "%s: %s" % (exc.filename, exc.strerror)
  192. else:
  193. # two-argument functions in posix module don't
  194. # include the filename in the exception object!
  195. error = prefix + "%s" % exc.strerror
  196. else:
  197. error = prefix + str(exc[-1])
  198. return error
  199. # Needed by 'split_quoted()'
  200. _wordchars_re = _squote_re = _dquote_re = None
  201. def _init_regex():
  202. global _wordchars_re, _squote_re, _dquote_re
  203. _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
  204. _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
  205. _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
  206. def split_quoted (s):
  207. """Split a string up according to Unix shell-like rules for quotes and
  208. backslashes. In short: words are delimited by spaces, as long as those
  209. spaces are not escaped by a backslash, or inside a quoted string.
  210. Single and double quotes are equivalent, and the quote characters can
  211. be backslash-escaped. The backslash is stripped from any two-character
  212. escape sequence, leaving only the escaped character. The quote
  213. characters are stripped from any quoted string. Returns a list of
  214. words.
  215. """
  216. # This is a nice algorithm for splitting up a single string, since it
  217. # doesn't require character-by-character examination. It was a little
  218. # bit of a brain-bender to get it working right, though...
  219. if _wordchars_re is None: _init_regex()
  220. s = string.strip(s)
  221. words = []
  222. pos = 0
  223. while s:
  224. m = _wordchars_re.match(s, pos)
  225. end = m.end()
  226. if end == len(s):
  227. words.append(s[:end])
  228. break
  229. if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
  230. words.append(s[:end]) # we definitely have a word delimiter
  231. s = string.lstrip(s[end:])
  232. pos = 0
  233. elif s[end] == '\\': # preserve whatever is being escaped;
  234. # will become part of the current word
  235. s = s[:end] + s[end+1:]
  236. pos = end+1
  237. else:
  238. if s[end] == "'": # slurp singly-quoted string
  239. m = _squote_re.match(s, end)
  240. elif s[end] == '"': # slurp doubly-quoted string
  241. m = _dquote_re.match(s, end)
  242. else:
  243. raise RuntimeError, \
  244. "this can't happen (bad char '%c')" % s[end]
  245. if m is None:
  246. raise ValueError, \
  247. "bad string (mismatched %s quotes?)" % s[end]
  248. (beg, end) = m.span()
  249. s = s[:beg] + s[beg+1:end-1] + s[end:]
  250. pos = m.end() - 2
  251. if pos >= len(s):
  252. words.append(s)
  253. break
  254. return words
  255. # split_quoted ()
  256. def execute (func, args, msg=None, verbose=0, dry_run=0):
  257. """Perform some action that affects the outside world (eg. by
  258. writing to the filesystem). Such actions are special because they
  259. are disabled by the 'dry_run' flag. This method takes care of all
  260. that bureaucracy for you; all you have to do is supply the
  261. function to call and an argument tuple for it (to embody the
  262. "external action" being performed), and an optional message to
  263. print.
  264. """
  265. if msg is None:
  266. msg = "%s%r" % (func.__name__, args)
  267. if msg[-2:] == ',)': # correct for singleton tuple
  268. msg = msg[0:-2] + ')'
  269. log.info(msg)
  270. if not dry_run:
  271. func(*args)
  272. def strtobool (val):
  273. """Convert a string representation of truth to true (1) or false (0).
  274. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  275. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  276. 'val' is anything else.
  277. """
  278. val = string.lower(val)
  279. if val in ('y', 'yes', 't', 'true', 'on', '1'):
  280. return 1
  281. elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  282. return 0
  283. else:
  284. raise ValueError, "invalid truth value %r" % (val,)
  285. def byte_compile (py_files,
  286. optimize=0, force=0,
  287. prefix=None, base_dir=None,
  288. verbose=1, dry_run=0,
  289. direct=None):
  290. """Byte-compile a collection of Python source files to either .pyc
  291. or .pyo files in the same directory. 'py_files' is a list of files
  292. to compile; any files that don't end in ".py" are silently skipped.
  293. 'optimize' must be one of the following:
  294. 0 - don't optimize (generate .pyc)
  295. 1 - normal optimization (like "python -O")
  296. 2 - extra optimization (like "python -OO")
  297. If 'force' is true, all files are recompiled regardless of
  298. timestamps.
  299. The source filename encoded in each bytecode file defaults to the
  300. filenames listed in 'py_files'; you can modify these with 'prefix' and
  301. 'basedir'. 'prefix' is a string that will be stripped off of each
  302. source filename, and 'base_dir' is a directory name that will be
  303. prepended (after 'prefix' is stripped). You can supply either or both
  304. (or neither) of 'prefix' and 'base_dir', as you wish.
  305. If 'dry_run' is true, doesn't actually do anything that would
  306. affect the filesystem.
  307. Byte-compilation is either done directly in this interpreter process
  308. with the standard py_compile module, or indirectly by writing a
  309. temporary script and executing it. Normally, you should let
  310. 'byte_compile()' figure out to use direct compilation or not (see
  311. the source for details). The 'direct' flag is used by the script
  312. generated in indirect mode; unless you know what you're doing, leave
  313. it set to None.
  314. """
  315. # nothing is done if sys.dont_write_bytecode is True
  316. if sys.dont_write_bytecode:
  317. raise DistutilsByteCompileError('byte-compiling is disabled.')
  318. # First, if the caller didn't force us into direct or indirect mode,
  319. # figure out which mode we should be in. We take a conservative
  320. # approach: choose direct mode *only* if the current interpreter is
  321. # in debug mode and optimize is 0. If we're not in debug mode (-O
  322. # or -OO), we don't know which level of optimization this
  323. # interpreter is running with, so we can't do direct
  324. # byte-compilation and be certain that it's the right thing. Thus,
  325. # always compile indirectly if the current interpreter is in either
  326. # optimize mode, or if either optimization level was requested by
  327. # the caller.
  328. if direct is None:
  329. direct = (__debug__ and optimize == 0)
  330. # "Indirect" byte-compilation: write a temporary script and then
  331. # run it with the appropriate flags.
  332. if not direct:
  333. try:
  334. from tempfile import mkstemp
  335. (script_fd, script_name) = mkstemp(".py")
  336. except ImportError:
  337. from tempfile import mktemp
  338. (script_fd, script_name) = None, mktemp(".py")
  339. log.info("writing byte-compilation script '%s'", script_name)
  340. if not dry_run:
  341. if script_fd is not None:
  342. script = os.fdopen(script_fd, "w")
  343. else:
  344. script = open(script_name, "w")
  345. script.write("""\
  346. from distutils.util import byte_compile
  347. files = [
  348. """)
  349. # XXX would be nice to write absolute filenames, just for
  350. # safety's sake (script should be more robust in the face of
  351. # chdir'ing before running it). But this requires abspath'ing
  352. # 'prefix' as well, and that breaks the hack in build_lib's
  353. # 'byte_compile()' method that carefully tacks on a trailing
  354. # slash (os.sep really) to make sure the prefix here is "just
  355. # right". This whole prefix business is rather delicate -- the
  356. # problem is that it's really a directory, but I'm treating it
  357. # as a dumb string, so trailing slashes and so forth matter.
  358. #py_files = map(os.path.abspath, py_files)
  359. #if prefix:
  360. # prefix = os.path.abspath(prefix)
  361. script.write(string.join(map(repr, py_files), ",\n") + "]\n")
  362. script.write("""
  363. byte_compile(files, optimize=%r, force=%r,
  364. prefix=%r, base_dir=%r,
  365. verbose=%r, dry_run=0,
  366. direct=1)
  367. """ % (optimize, force, prefix, base_dir, verbose))
  368. script.close()
  369. cmd = [sys.executable, script_name]
  370. if optimize == 1:
  371. cmd.insert(1, "-O")
  372. elif optimize == 2:
  373. cmd.insert(1, "-OO")
  374. spawn(cmd, dry_run=dry_run)
  375. execute(os.remove, (script_name,), "removing %s" % script_name,
  376. dry_run=dry_run)
  377. # "Direct" byte-compilation: use the py_compile module to compile
  378. # right here, right now. Note that the script generated in indirect
  379. # mode simply calls 'byte_compile()' in direct mode, a weird sort of
  380. # cross-process recursion. Hey, it works!
  381. else:
  382. from py_compile import compile
  383. for file in py_files:
  384. if file[-3:] != ".py":
  385. # This lets us be lazy and not filter filenames in
  386. # the "install_lib" command.
  387. continue
  388. # Terminology from the py_compile module:
  389. # cfile - byte-compiled file
  390. # dfile - purported source filename (same as 'file' by default)
  391. cfile = file + (__debug__ and "c" or "o")
  392. dfile = file
  393. if prefix:
  394. if file[:len(prefix)] != prefix:
  395. raise ValueError, \
  396. ("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 = string.split(header, '\n')
  416. header = string.join(lines, '\n' + 8*' ')
  417. return header