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

/python/lib/Lib/distutils/util.py

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