util.py 20 KB

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