PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/distutils/util.py

http://github.com/nriley/jython
Python | 516 lines | 490 code | 5 blank | 21 comment | 15 complexity | 5f870509289065f84d46599c58444423 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: 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. if os.name == 'posix' or os.name == 'java':
  135. if not os.path.isabs(pathname):
  136. return os.path.join(new_root, pathname)
  137. else:
  138. return os.path.join(new_root, pathname[1:])
  139. elif os.name == 'nt':
  140. (drive, path) = os.path.splitdrive(pathname)
  141. if path[0] == '\\':
  142. path = path[1:]
  143. return os.path.join(new_root, path)
  144. elif os.name == 'os2':
  145. (drive, path) = os.path.splitdrive(pathname)
  146. if path[0] == os.sep:
  147. path = path[1:]
  148. return os.path.join(new_root, path)
  149. elif os.name == 'mac':
  150. if not os.path.isabs(pathname):
  151. return os.path.join(new_root, pathname)
  152. else:
  153. # Chop off volume name from start of path
  154. elements = string.split(pathname, ":", 1)
  155. pathname = ":" + elements[1]
  156. return os.path.join(new_root, pathname)
  157. else:
  158. raise DistutilsPlatformError, \
  159. "nothing known about platform '%s'" % os.name
  160. _environ_checked = 0
  161. def check_environ ():
  162. """Ensure that 'os.environ' has all the environment variables we
  163. guarantee that users can use in config files, command-line options,
  164. etc. Currently this includes:
  165. HOME - user's home directory (Unix only)
  166. PLAT - description of the current platform, including hardware
  167. and OS (see 'get_platform()')
  168. """
  169. global _environ_checked
  170. if _environ_checked:
  171. return
  172. if os.name == 'posix' and not os.environ.has_key('HOME'):
  173. import pwd
  174. os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  175. if not os.environ.has_key('PLAT'):
  176. os.environ['PLAT'] = get_platform()
  177. _environ_checked = 1
  178. def subst_vars (s, local_vars):
  179. """Perform shell/Perl-style variable substitution on 'string'. Every
  180. occurrence of '$' followed by a name is considered a variable, and
  181. variable is substituted by the value found in the 'local_vars'
  182. dictionary, or in 'os.environ' if it's not in 'local_vars'.
  183. 'os.environ' is first checked/augmented to guarantee that it contains
  184. certain values: see 'check_environ()'. Raise ValueError for any
  185. variables not found in either 'local_vars' or 'os.environ'.
  186. """
  187. check_environ()
  188. def _subst (match, local_vars=local_vars):
  189. var_name = match.group(1)
  190. if local_vars.has_key(var_name):
  191. return str(local_vars[var_name])
  192. else:
  193. return os.environ[var_name]
  194. try:
  195. return re.sub(r'\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  196. except KeyError, var:
  197. raise ValueError, "invalid variable '$%s'" % var
  198. # subst_vars ()
  199. def grok_environment_error (exc, prefix="error: "):
  200. """Generate a useful error message from an EnvironmentError (IOError or
  201. OSError) exception object. Handles Python 1.5.1 and 1.5.2 styles, and
  202. does what it can to deal with exception objects that don't have a
  203. filename (which happens when the error is due to a two-file operation,
  204. such as 'rename()' or 'link()'. Returns the error message as a string
  205. prefixed with 'prefix'.
  206. """
  207. # check for Python 1.5.2-style {IO,OS}Error exception objects
  208. if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
  209. if exc.filename:
  210. error = prefix + "%s: %s" % (exc.filename, exc.strerror)
  211. else:
  212. # two-argument functions in posix module don't
  213. # include the filename in the exception object!
  214. error = prefix + "%s" % exc.strerror
  215. else:
  216. error = prefix + str(exc[-1])
  217. return error
  218. # Needed by 'split_quoted()'
  219. _wordchars_re = _squote_re = _dquote_re = None
  220. def _init_regex():
  221. global _wordchars_re, _squote_re, _dquote_re
  222. _wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
  223. _squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
  224. _dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
  225. def split_quoted (s):
  226. """Split a string up according to Unix shell-like rules for quotes and
  227. backslashes. In short: words are delimited by spaces, as long as those
  228. spaces are not escaped by a backslash, or inside a quoted string.
  229. Single and double quotes are equivalent, and the quote characters can
  230. be backslash-escaped. The backslash is stripped from any two-character
  231. escape sequence, leaving only the escaped character. The quote
  232. characters are stripped from any quoted string. Returns a list of
  233. words.
  234. """
  235. # This is a nice algorithm for splitting up a single string, since it
  236. # doesn't require character-by-character examination. It was a little
  237. # bit of a brain-bender to get it working right, though...
  238. if _wordchars_re is None: _init_regex()
  239. s = string.strip(s)
  240. words = []
  241. pos = 0
  242. while s:
  243. m = _wordchars_re.match(s, pos)
  244. end = m.end()
  245. if end == len(s):
  246. words.append(s[:end])
  247. break
  248. if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
  249. words.append(s[:end]) # we definitely have a word delimiter
  250. s = string.lstrip(s[end:])
  251. pos = 0
  252. elif s[end] == '\\': # preserve whatever is being escaped;
  253. # will become part of the current word
  254. s = s[:end] + s[end+1:]
  255. pos = end+1
  256. else:
  257. if s[end] == "'": # slurp singly-quoted string
  258. m = _squote_re.match(s, end)
  259. elif s[end] == '"': # slurp doubly-quoted string
  260. m = _dquote_re.match(s, end)
  261. else:
  262. raise RuntimeError, \
  263. "this can't happen (bad char '%c')" % s[end]
  264. if m is None:
  265. raise ValueError, \
  266. "bad string (mismatched %s quotes?)" % s[end]
  267. (beg, end) = m.span()
  268. s = s[:beg] + s[beg+1:end-1] + s[end:]
  269. pos = m.end() - 2
  270. if pos >= len(s):
  271. words.append(s)
  272. break
  273. return words
  274. # split_quoted ()
  275. def execute (func, args, msg=None, verbose=0, dry_run=0):
  276. """Perform some action that affects the outside world (eg. by
  277. writing to the filesystem). Such actions are special because they
  278. are disabled by the 'dry_run' flag. This method takes care of all
  279. that bureaucracy for you; all you have to do is supply the
  280. function to call and an argument tuple for it (to embody the
  281. "external action" being performed), and an optional message to
  282. print.
  283. """
  284. if msg is None:
  285. msg = "%s%r" % (func.__name__, args)
  286. if msg[-2:] == ',)': # correct for singleton tuple
  287. msg = msg[0:-2] + ')'
  288. log.info(msg)
  289. if not dry_run:
  290. apply(func, args)
  291. def strtobool (val):
  292. """Convert a string representation of truth to true (1) or false (0).
  293. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  294. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  295. 'val' is anything else.
  296. """
  297. val = string.lower(val)
  298. if val in ('y', 'yes', 't', 'true', 'on', '1'):
  299. return 1
  300. elif val in ('n', 'no', 'f', 'false', 'off', '0'):
  301. return 0
  302. else:
  303. raise ValueError, "invalid truth value %r" % (val,)
  304. def byte_compile (py_files,
  305. optimize=0, force=0,
  306. prefix=None, base_dir=None,
  307. verbose=1, dry_run=0,
  308. direct=None):
  309. """Byte-compile a collection of Python source files to either .pyc
  310. or .pyo files in the same directory. 'py_files' is a list of files
  311. to compile; any files that don't end in ".py" are silently skipped.
  312. 'optimize' must be one of the following:
  313. 0 - don't optimize (generate .pyc)
  314. 1 - normal optimization (like "python -O")
  315. 2 - extra optimization (like "python -OO")
  316. If 'force' is true, all files are recompiled regardless of
  317. timestamps.
  318. The source filename encoded in each bytecode file defaults to the
  319. filenames listed in 'py_files'; you can modify these with 'prefix' and
  320. 'basedir'. 'prefix' is a string that will be stripped off of each
  321. source filename, and 'base_dir' is a directory name that will be
  322. prepended (after 'prefix' is stripped). You can supply either or both
  323. (or neither) of 'prefix' and 'base_dir', as you wish.
  324. If 'dry_run' is true, doesn't actually do anything that would
  325. affect the filesystem.
  326. Byte-compilation is either done directly in this interpreter process
  327. with the standard py_compile module, or indirectly by writing a
  328. temporary script and executing it. Normally, you should let
  329. 'byte_compile()' figure out to use direct compilation or not (see
  330. the source for details). The 'direct' flag is used by the script
  331. generated in indirect mode; unless you know what you're doing, leave
  332. it set to None.
  333. """
  334. # First, if the caller didn't force us into direct or indirect mode,
  335. # figure out which mode we should be in. We take a conservative
  336. # approach: choose direct mode *only* if the current interpreter is
  337. # in debug mode and optimize is 0. If we're not in debug mode (-O
  338. # or -OO), we don't know which level of optimization this
  339. # interpreter is running with, so we can't do direct
  340. # byte-compilation and be certain that it's the right thing. Thus,
  341. # always compile indirectly if the current interpreter is in either
  342. # optimize mode, or if either optimization level was requested by
  343. # the caller.
  344. if direct is None:
  345. direct = (__debug__ and optimize == 0)
  346. # "Indirect" byte-compilation: write a temporary script and then
  347. # run it with the appropriate flags.
  348. if not direct:
  349. try:
  350. from tempfile import mkstemp
  351. (script_fd, script_name) = mkstemp(".py")
  352. except ImportError:
  353. from tempfile import mktemp
  354. (script_fd, script_name) = None, mktemp(".py")
  355. log.info("writing byte-compilation script '%s'", script_name)
  356. if not dry_run:
  357. if script_fd is not None:
  358. script = os.fdopen(script_fd, "w")
  359. else:
  360. script = open(script_name, "w")
  361. script.write("""\
  362. from distutils.util import byte_compile
  363. files = [
  364. """)
  365. # XXX would be nice to write absolute filenames, just for
  366. # safety's sake (script should be more robust in the face of
  367. # chdir'ing before running it). But this requires abspath'ing
  368. # 'prefix' as well, and that breaks the hack in build_lib's
  369. # 'byte_compile()' method that carefully tacks on a trailing
  370. # slash (os.sep really) to make sure the prefix here is "just
  371. # right". This whole prefix business is rather delicate -- the
  372. # problem is that it's really a directory, but I'm treating it
  373. # as a dumb string, so trailing slashes and so forth matter.
  374. #py_files = map(os.path.abspath, py_files)
  375. #if prefix:
  376. # prefix = os.path.abspath(prefix)
  377. script.write(string.join(map(repr, py_files), ",\n") + "]\n")
  378. script.write("""
  379. byte_compile(files, optimize=%r, force=%r,
  380. prefix=%r, base_dir=%r,
  381. verbose=%r, dry_run=0,
  382. direct=1)
  383. """ % (optimize, force, prefix, base_dir, verbose))
  384. script.close()
  385. cmd = [sys.executable, script_name]
  386. if optimize == 1:
  387. cmd.insert(1, "-O")
  388. elif optimize == 2:
  389. cmd.insert(1, "-OO")
  390. spawn(cmd, dry_run=dry_run)
  391. execute(os.remove, (script_name,), "removing %s" % script_name,
  392. dry_run=dry_run)
  393. # "Direct" byte-compilation: use the py_compile module to compile
  394. # right here, right now. Note that the script generated in indirect
  395. # mode simply calls 'byte_compile()' in direct mode, a weird sort of
  396. # cross-process recursion. Hey, it works!
  397. else:
  398. from py_compile import compile
  399. for file in py_files:
  400. if file[-3:] != ".py":
  401. # This lets us be lazy and not filter filenames in
  402. # the "install_lib" command.
  403. continue
  404. # Terminology from the py_compile module:
  405. # cfile - byte-compiled file
  406. # dfile - purported source filename (same as 'file' by default)
  407. if sys.platform.startswith('java'):
  408. cfile = file[:-3] + '$py.class'
  409. else:
  410. cfile = file + (__debug__ and "c" or "o")
  411. dfile = file
  412. if prefix:
  413. if file[:len(prefix)] != prefix:
  414. raise ValueError, \
  415. ("invalid prefix: filename %r doesn't start with %r"
  416. % (file, prefix))
  417. dfile = dfile[len(prefix):]
  418. if base_dir:
  419. dfile = os.path.join(base_dir, dfile)
  420. cfile_base = os.path.basename(cfile)
  421. if direct:
  422. if force or newer(file, cfile):
  423. log.info("byte-compiling %s to %s", file, cfile_base)
  424. if not dry_run:
  425. compile(file, cfile, dfile)
  426. else:
  427. log.debug("skipping byte-compilation of %s to %s",
  428. file, cfile_base)
  429. # byte_compile ()
  430. def rfc822_escape (header):
  431. """Return a version of the string escaped for inclusion in an
  432. RFC-822 header, by ensuring there are 8 spaces space after each newline.
  433. """
  434. lines = string.split(header, '\n')
  435. lines = map(string.strip, lines)
  436. header = string.join(lines, '\n' + 8*' ')
  437. return header