/Lib/distutils/util.py

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