PageRenderTime 51ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/distutils/command/install.py

https://bitbucket.org/quangquach/pypy
Python | 681 lines | 551 code | 74 blank | 56 comment | 74 complexity | 4dd30e0db3335e034b75b47988f852bf MD5 | raw file
  1. """distutils.command.install
  2. Implements the Distutils 'install' command."""
  3. from distutils import log
  4. # This module should be kept compatible with Python 2.1.
  5. __revision__ = "$Id$"
  6. import sys, os, string
  7. from types import *
  8. from distutils.core import Command
  9. from distutils.debug import DEBUG
  10. from distutils.sysconfig import get_config_vars
  11. from distutils.errors import DistutilsPlatformError
  12. from distutils.file_util import write_file
  13. from distutils.util import convert_path, subst_vars, change_root
  14. from distutils.util import get_platform
  15. from distutils.errors import DistutilsOptionError
  16. from site import USER_BASE
  17. from site import USER_SITE
  18. if sys.version < "2.2":
  19. WINDOWS_SCHEME = {
  20. 'purelib': '$base',
  21. 'platlib': '$base',
  22. 'headers': '$base/Include/$dist_name',
  23. 'scripts': '$base/Scripts',
  24. 'data' : '$base',
  25. }
  26. else:
  27. WINDOWS_SCHEME = {
  28. 'purelib': '$base/Lib/site-packages',
  29. 'platlib': '$base/Lib/site-packages',
  30. 'headers': '$base/Include/$dist_name',
  31. 'scripts': '$base/Scripts',
  32. 'data' : '$base',
  33. }
  34. INSTALL_SCHEMES = {
  35. 'unix_prefix': {
  36. 'purelib': '$base/lib/python$py_version_short/site-packages',
  37. 'platlib': '$platbase/lib/python$py_version_short/site-packages',
  38. 'headers': '$base/include/python$py_version_short/$dist_name',
  39. 'scripts': '$base/bin',
  40. 'data' : '$base',
  41. },
  42. 'unix_home': {
  43. 'purelib': '$base/lib/python',
  44. 'platlib': '$base/lib/python',
  45. 'headers': '$base/include/python/$dist_name',
  46. 'scripts': '$base/bin',
  47. 'data' : '$base',
  48. },
  49. 'unix_user': {
  50. 'purelib': '$usersite',
  51. 'platlib': '$usersite',
  52. 'headers': '$userbase/include/python$py_version_short/$dist_name',
  53. 'scripts': '$userbase/bin',
  54. 'data' : '$userbase',
  55. },
  56. 'nt': WINDOWS_SCHEME,
  57. 'nt_user': {
  58. 'purelib': '$usersite',
  59. 'platlib': '$usersite',
  60. 'headers': '$userbase/Python$py_version_nodot/Include/$dist_name',
  61. 'scripts': '$userbase/Scripts',
  62. 'data' : '$userbase',
  63. },
  64. 'os2': {
  65. 'purelib': '$base/Lib/site-packages',
  66. 'platlib': '$base/Lib/site-packages',
  67. 'headers': '$base/Include/$dist_name',
  68. 'scripts': '$base/Scripts',
  69. 'data' : '$base',
  70. },
  71. 'os2_home': {
  72. 'purelib': '$usersite',
  73. 'platlib': '$usersite',
  74. 'headers': '$userbase/include/python$py_version_short/$dist_name',
  75. 'scripts': '$userbase/bin',
  76. 'data' : '$userbase',
  77. },
  78. 'pypy': {
  79. 'purelib': '$base/site-packages',
  80. 'platlib': '$base/site-packages',
  81. 'headers': '$base/include',
  82. 'scripts': '$base/bin',
  83. 'data' : '$base',
  84. },
  85. }
  86. # The keys to an installation scheme; if any new types of files are to be
  87. # installed, be sure to add an entry to every installation scheme above,
  88. # and to SCHEME_KEYS here.
  89. SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')
  90. class install (Command):
  91. description = "install everything from build directory"
  92. user_options = [
  93. # Select installation scheme and set base director(y|ies)
  94. ('prefix=', None,
  95. "installation prefix"),
  96. ('exec-prefix=', None,
  97. "(Unix only) prefix for platform-specific files"),
  98. ('home=', None,
  99. "(Unix only) home directory to install under"),
  100. ('user', None,
  101. "install in user site-package '%s'" % USER_SITE),
  102. # Or, just set the base director(y|ies)
  103. ('install-base=', None,
  104. "base installation directory (instead of --prefix or --home)"),
  105. ('install-platbase=', None,
  106. "base installation directory for platform-specific files " +
  107. "(instead of --exec-prefix or --home)"),
  108. ('root=', None,
  109. "install everything relative to this alternate root directory"),
  110. # Or, explicitly set the installation scheme
  111. ('install-purelib=', None,
  112. "installation directory for pure Python module distributions"),
  113. ('install-platlib=', None,
  114. "installation directory for non-pure module distributions"),
  115. ('install-lib=', None,
  116. "installation directory for all module distributions " +
  117. "(overrides --install-purelib and --install-platlib)"),
  118. ('install-headers=', None,
  119. "installation directory for C/C++ headers"),
  120. ('install-scripts=', None,
  121. "installation directory for Python scripts"),
  122. ('install-data=', None,
  123. "installation directory for data files"),
  124. # Byte-compilation options -- see install_lib.py for details, as
  125. # these are duplicated from there (but only install_lib does
  126. # anything with them).
  127. ('compile', 'c', "compile .py to .pyc [default]"),
  128. ('no-compile', None, "don't compile .py files"),
  129. ('optimize=', 'O',
  130. "also compile with optimization: -O1 for \"python -O\", "
  131. "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
  132. # Miscellaneous control options
  133. ('force', 'f',
  134. "force installation (overwrite any existing files)"),
  135. ('skip-build', None,
  136. "skip rebuilding everything (for testing/debugging)"),
  137. # Where to install documentation (eventually!)
  138. #('doc-format=', None, "format of documentation to generate"),
  139. #('install-man=', None, "directory for Unix man pages"),
  140. #('install-html=', None, "directory for HTML documentation"),
  141. #('install-info=', None, "directory for GNU info files"),
  142. ('record=', None,
  143. "filename in which to record list of installed files"),
  144. ]
  145. boolean_options = ['compile', 'force', 'skip-build', 'user']
  146. negative_opt = {'no-compile' : 'compile'}
  147. def initialize_options (self):
  148. # High-level options: these select both an installation base
  149. # and scheme.
  150. self.prefix = None
  151. self.exec_prefix = None
  152. self.home = None
  153. self.user = 0
  154. # These select only the installation base; it's up to the user to
  155. # specify the installation scheme (currently, that means supplying
  156. # the --install-{platlib,purelib,scripts,data} options).
  157. self.install_base = None
  158. self.install_platbase = None
  159. self.root = None
  160. # These options are the actual installation directories; if not
  161. # supplied by the user, they are filled in using the installation
  162. # scheme implied by prefix/exec-prefix/home and the contents of
  163. # that installation scheme.
  164. self.install_purelib = None # for pure module distributions
  165. self.install_platlib = None # non-pure (dists w/ extensions)
  166. self.install_headers = None # for C/C++ headers
  167. self.install_lib = None # set to either purelib or platlib
  168. self.install_scripts = None
  169. self.install_data = None
  170. self.install_userbase = USER_BASE
  171. self.install_usersite = USER_SITE
  172. self.compile = None
  173. self.optimize = None
  174. # These two are for putting non-packagized distributions into their
  175. # own directory and creating a .pth file if it makes sense.
  176. # 'extra_path' comes from the setup file; 'install_path_file' can
  177. # be turned off if it makes no sense to install a .pth file. (But
  178. # better to install it uselessly than to guess wrong and not
  179. # install it when it's necessary and would be used!) Currently,
  180. # 'install_path_file' is always true unless some outsider meddles
  181. # with it.
  182. self.extra_path = None
  183. self.install_path_file = 1
  184. # 'force' forces installation, even if target files are not
  185. # out-of-date. 'skip_build' skips running the "build" command,
  186. # handy if you know it's not necessary. 'warn_dir' (which is *not*
  187. # a user option, it's just there so the bdist_* commands can turn
  188. # it off) determines whether we warn about installing to a
  189. # directory not in sys.path.
  190. self.force = 0
  191. self.skip_build = 0
  192. self.warn_dir = 1
  193. # These are only here as a conduit from the 'build' command to the
  194. # 'install_*' commands that do the real work. ('build_base' isn't
  195. # actually used anywhere, but it might be useful in future.) They
  196. # are not user options, because if the user told the install
  197. # command where the build directory is, that wouldn't affect the
  198. # build command.
  199. self.build_base = None
  200. self.build_lib = None
  201. # Not defined yet because we don't know anything about
  202. # documentation yet.
  203. #self.install_man = None
  204. #self.install_html = None
  205. #self.install_info = None
  206. self.record = None
  207. # -- Option finalizing methods -------------------------------------
  208. # (This is rather more involved than for most commands,
  209. # because this is where the policy for installing third-
  210. # party Python modules on various platforms given a wide
  211. # array of user input is decided. Yes, it's quite complex!)
  212. def finalize_options (self):
  213. # This method (and its pliant slaves, like 'finalize_unix()',
  214. # 'finalize_other()', and 'select_scheme()') is where the default
  215. # installation directories for modules, extension modules, and
  216. # anything else we care to install from a Python module
  217. # distribution. Thus, this code makes a pretty important policy
  218. # statement about how third-party stuff is added to a Python
  219. # installation! Note that the actual work of installation is done
  220. # by the relatively simple 'install_*' commands; they just take
  221. # their orders from the installation directory options determined
  222. # here.
  223. # Check for errors/inconsistencies in the options; first, stuff
  224. # that's wrong on any platform.
  225. if ((self.prefix or self.exec_prefix or self.home) and
  226. (self.install_base or self.install_platbase)):
  227. raise DistutilsOptionError, \
  228. ("must supply either prefix/exec-prefix/home or " +
  229. "install-base/install-platbase -- not both")
  230. if self.home and (self.prefix or self.exec_prefix):
  231. raise DistutilsOptionError, \
  232. "must supply either home or prefix/exec-prefix -- not both"
  233. if self.user and (self.prefix or self.exec_prefix or self.home or
  234. self.install_base or self.install_platbase):
  235. raise DistutilsOptionError("can't combine user with with prefix/"
  236. "exec_prefix/home or install_(plat)base")
  237. # Next, stuff that's wrong (or dubious) only on certain platforms.
  238. if os.name != "posix":
  239. if self.exec_prefix:
  240. self.warn("exec-prefix option ignored on this platform")
  241. self.exec_prefix = None
  242. # Now the interesting logic -- so interesting that we farm it out
  243. # to other methods. The goal of these methods is to set the final
  244. # values for the install_{lib,scripts,data,...} options, using as
  245. # input a heady brew of prefix, exec_prefix, home, install_base,
  246. # install_platbase, user-supplied versions of
  247. # install_{purelib,platlib,lib,scripts,data,...}, and the
  248. # INSTALL_SCHEME dictionary above. Phew!
  249. self.dump_dirs("pre-finalize_{unix,other}")
  250. if os.name == 'posix':
  251. self.finalize_unix()
  252. else:
  253. self.finalize_other()
  254. self.dump_dirs("post-finalize_{unix,other}()")
  255. # Expand configuration variables, tilde, etc. in self.install_base
  256. # and self.install_platbase -- that way, we can use $base or
  257. # $platbase in the other installation directories and not worry
  258. # about needing recursive variable expansion (shudder).
  259. py_version = (string.split(sys.version))[0]
  260. (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
  261. self.config_vars = {'dist_name': self.distribution.get_name(),
  262. 'dist_version': self.distribution.get_version(),
  263. 'dist_fullname': self.distribution.get_fullname(),
  264. 'py_version': py_version,
  265. 'py_version_short': py_version[0:3],
  266. 'py_version_nodot': py_version[0] + py_version[2],
  267. 'sys_prefix': prefix,
  268. 'prefix': prefix,
  269. 'sys_exec_prefix': exec_prefix,
  270. 'exec_prefix': exec_prefix,
  271. 'userbase': self.install_userbase,
  272. 'usersite': self.install_usersite,
  273. }
  274. self.expand_basedirs()
  275. self.dump_dirs("post-expand_basedirs()")
  276. # Now define config vars for the base directories so we can expand
  277. # everything else.
  278. self.config_vars['base'] = self.install_base
  279. self.config_vars['platbase'] = self.install_platbase
  280. if DEBUG:
  281. from pprint import pprint
  282. print "config vars:"
  283. pprint(self.config_vars)
  284. # Expand "~" and configuration variables in the installation
  285. # directories.
  286. self.expand_dirs()
  287. self.dump_dirs("post-expand_dirs()")
  288. # Create directories in the home dir:
  289. if self.user:
  290. self.create_home_path()
  291. # Pick the actual directory to install all modules to: either
  292. # install_purelib or install_platlib, depending on whether this
  293. # module distribution is pure or not. Of course, if the user
  294. # already specified install_lib, use their selection.
  295. if self.install_lib is None:
  296. if self.distribution.ext_modules: # has extensions: non-pure
  297. self.install_lib = self.install_platlib
  298. else:
  299. self.install_lib = self.install_purelib
  300. # Convert directories from Unix /-separated syntax to the local
  301. # convention.
  302. self.convert_paths('lib', 'purelib', 'platlib',
  303. 'scripts', 'data', 'headers',
  304. 'userbase', 'usersite')
  305. # Well, we're not actually fully completely finalized yet: we still
  306. # have to deal with 'extra_path', which is the hack for allowing
  307. # non-packagized module distributions (hello, Numerical Python!) to
  308. # get their own directories.
  309. self.handle_extra_path()
  310. self.install_libbase = self.install_lib # needed for .pth file
  311. self.install_lib = os.path.join(self.install_lib, self.extra_dirs)
  312. # If a new root directory was supplied, make all the installation
  313. # dirs relative to it.
  314. if self.root is not None:
  315. self.change_roots('libbase', 'lib', 'purelib', 'platlib',
  316. 'scripts', 'data', 'headers')
  317. self.dump_dirs("after prepending root")
  318. # Find out the build directories, ie. where to install from.
  319. self.set_undefined_options('build',
  320. ('build_base', 'build_base'),
  321. ('build_lib', 'build_lib'))
  322. # Punt on doc directories for now -- after all, we're punting on
  323. # documentation completely!
  324. # finalize_options ()
  325. def dump_dirs (self, msg):
  326. if DEBUG:
  327. from distutils.fancy_getopt import longopt_xlate
  328. print msg + ":"
  329. for opt in self.user_options:
  330. opt_name = opt[0]
  331. if opt_name[-1] == "=":
  332. opt_name = opt_name[0:-1]
  333. if opt_name in self.negative_opt:
  334. opt_name = string.translate(self.negative_opt[opt_name],
  335. longopt_xlate)
  336. val = not getattr(self, opt_name)
  337. else:
  338. opt_name = string.translate(opt_name, longopt_xlate)
  339. val = getattr(self, opt_name)
  340. print " %s: %s" % (opt_name, val)
  341. def finalize_unix (self):
  342. if self.install_base is not None or self.install_platbase is not None:
  343. if ((self.install_lib is None and
  344. self.install_purelib is None and
  345. self.install_platlib is None) or
  346. self.install_headers is None or
  347. self.install_scripts is None or
  348. self.install_data is None):
  349. raise DistutilsOptionError, \
  350. ("install-base or install-platbase supplied, but "
  351. "installation scheme is incomplete")
  352. return
  353. if self.user:
  354. if self.install_userbase is None:
  355. raise DistutilsPlatformError(
  356. "User base directory is not specified")
  357. self.install_base = self.install_platbase = self.install_userbase
  358. self.select_scheme("unix_user")
  359. elif self.home is not None:
  360. self.install_base = self.install_platbase = self.home
  361. self.select_scheme("unix_home")
  362. else:
  363. if self.prefix is None:
  364. if self.exec_prefix is not None:
  365. raise DistutilsOptionError, \
  366. "must not supply exec-prefix without prefix"
  367. self.prefix = os.path.normpath(sys.prefix)
  368. self.exec_prefix = os.path.normpath(sys.exec_prefix)
  369. else:
  370. if self.exec_prefix is None:
  371. self.exec_prefix = self.prefix
  372. self.install_base = self.prefix
  373. self.install_platbase = self.exec_prefix
  374. self.select_scheme("unix_prefix")
  375. # finalize_unix ()
  376. def finalize_other (self): # Windows and Mac OS for now
  377. if self.user:
  378. if self.install_userbase is None:
  379. raise DistutilsPlatformError(
  380. "User base directory is not specified")
  381. self.install_base = self.install_platbase = self.install_userbase
  382. self.select_scheme(os.name + "_user")
  383. elif self.home is not None:
  384. self.install_base = self.install_platbase = self.home
  385. self.select_scheme("unix_home")
  386. else:
  387. if self.prefix is None:
  388. self.prefix = os.path.normpath(sys.prefix)
  389. self.install_base = self.install_platbase = self.prefix
  390. try:
  391. self.select_scheme(os.name)
  392. except KeyError:
  393. raise DistutilsPlatformError, \
  394. "I don't know how to install stuff on '%s'" % os.name
  395. # finalize_other ()
  396. def select_scheme (self, name):
  397. # it's the caller's problem if they supply a bad name!
  398. if hasattr(sys, 'pypy_version_info'):
  399. name = 'pypy'
  400. scheme = INSTALL_SCHEMES[name]
  401. for key in SCHEME_KEYS:
  402. attrname = 'install_' + key
  403. if getattr(self, attrname) is None:
  404. setattr(self, attrname, scheme[key])
  405. def _expand_attrs (self, attrs):
  406. for attr in attrs:
  407. val = getattr(self, attr)
  408. if val is not None:
  409. if os.name == 'posix' or os.name == 'nt':
  410. val = os.path.expanduser(val)
  411. val = subst_vars(val, self.config_vars)
  412. setattr(self, attr, val)
  413. def expand_basedirs (self):
  414. self._expand_attrs(['install_base',
  415. 'install_platbase',
  416. 'root'])
  417. def expand_dirs (self):
  418. self._expand_attrs(['install_purelib',
  419. 'install_platlib',
  420. 'install_lib',
  421. 'install_headers',
  422. 'install_scripts',
  423. 'install_data',])
  424. def convert_paths (self, *names):
  425. for name in names:
  426. attr = "install_" + name
  427. setattr(self, attr, convert_path(getattr(self, attr)))
  428. def handle_extra_path (self):
  429. if self.extra_path is None:
  430. self.extra_path = self.distribution.extra_path
  431. if self.extra_path is not None:
  432. if type(self.extra_path) is StringType:
  433. self.extra_path = string.split(self.extra_path, ',')
  434. if len(self.extra_path) == 1:
  435. path_file = extra_dirs = self.extra_path[0]
  436. elif len(self.extra_path) == 2:
  437. (path_file, extra_dirs) = self.extra_path
  438. else:
  439. raise DistutilsOptionError, \
  440. ("'extra_path' option must be a list, tuple, or "
  441. "comma-separated string with 1 or 2 elements")
  442. # convert to local form in case Unix notation used (as it
  443. # should be in setup scripts)
  444. extra_dirs = convert_path(extra_dirs)
  445. else:
  446. path_file = None
  447. extra_dirs = ''
  448. # XXX should we warn if path_file and not extra_dirs? (in which
  449. # case the path file would be harmless but pointless)
  450. self.path_file = path_file
  451. self.extra_dirs = extra_dirs
  452. # handle_extra_path ()
  453. def change_roots (self, *names):
  454. for name in names:
  455. attr = "install_" + name
  456. setattr(self, attr, change_root(self.root, getattr(self, attr)))
  457. def create_home_path(self):
  458. """Create directories under ~
  459. """
  460. if not self.user:
  461. return
  462. home = convert_path(os.path.expanduser("~"))
  463. for name, path in self.config_vars.iteritems():
  464. if path.startswith(home) and not os.path.isdir(path):
  465. self.debug_print("os.makedirs('%s', 0700)" % path)
  466. os.makedirs(path, 0700)
  467. # -- Command execution methods -------------------------------------
  468. def run (self):
  469. # Obviously have to build before we can install
  470. if not self.skip_build:
  471. self.run_command('build')
  472. # If we built for any other platform, we can't install.
  473. build_plat = self.distribution.get_command_obj('build').plat_name
  474. # check warn_dir - it is a clue that the 'install' is happening
  475. # internally, and not to sys.path, so we don't check the platform
  476. # matches what we are running.
  477. if self.warn_dir and build_plat != get_platform():
  478. raise DistutilsPlatformError("Can't install when "
  479. "cross-compiling")
  480. # Run all sub-commands (at least those that need to be run)
  481. for cmd_name in self.get_sub_commands():
  482. self.run_command(cmd_name)
  483. if self.path_file:
  484. self.create_path_file()
  485. # write list of installed files, if requested.
  486. if self.record:
  487. outputs = self.get_outputs()
  488. if self.root: # strip any package prefix
  489. root_len = len(self.root)
  490. for counter in xrange(len(outputs)):
  491. outputs[counter] = outputs[counter][root_len:]
  492. self.execute(write_file,
  493. (self.record, outputs),
  494. "writing list of installed files to '%s'" %
  495. self.record)
  496. sys_path = map(os.path.normpath, sys.path)
  497. sys_path = map(os.path.normcase, sys_path)
  498. install_lib = os.path.normcase(os.path.normpath(self.install_lib))
  499. if (self.warn_dir and
  500. not (self.path_file and self.install_path_file) and
  501. install_lib not in sys_path):
  502. log.debug(("modules installed to '%s', which is not in "
  503. "Python's module search path (sys.path) -- "
  504. "you'll have to change the search path yourself"),
  505. self.install_lib)
  506. # run ()
  507. def create_path_file (self):
  508. filename = os.path.join(self.install_libbase,
  509. self.path_file + ".pth")
  510. if self.install_path_file:
  511. self.execute(write_file,
  512. (filename, [self.extra_dirs]),
  513. "creating %s" % filename)
  514. else:
  515. self.warn("path file '%s' not created" % filename)
  516. # -- Reporting methods ---------------------------------------------
  517. def get_outputs (self):
  518. # Assemble the outputs of all the sub-commands.
  519. outputs = []
  520. for cmd_name in self.get_sub_commands():
  521. cmd = self.get_finalized_command(cmd_name)
  522. # Add the contents of cmd.get_outputs(), ensuring
  523. # that outputs doesn't contain duplicate entries
  524. for filename in cmd.get_outputs():
  525. if filename not in outputs:
  526. outputs.append(filename)
  527. if self.path_file and self.install_path_file:
  528. outputs.append(os.path.join(self.install_libbase,
  529. self.path_file + ".pth"))
  530. return outputs
  531. def get_inputs (self):
  532. # XXX gee, this looks familiar ;-(
  533. inputs = []
  534. for cmd_name in self.get_sub_commands():
  535. cmd = self.get_finalized_command(cmd_name)
  536. inputs.extend(cmd.get_inputs())
  537. return inputs
  538. # -- Predicates for sub-command list -------------------------------
  539. def has_lib (self):
  540. """Return true if the current distribution has any Python
  541. modules to install."""
  542. return (self.distribution.has_pure_modules() or
  543. self.distribution.has_ext_modules())
  544. def has_headers (self):
  545. return self.distribution.has_headers()
  546. def has_scripts (self):
  547. return self.distribution.has_scripts()
  548. def has_data (self):
  549. return self.distribution.has_data_files()
  550. # 'sub_commands': a list of commands this command might have to run to
  551. # get its work done. See cmd.py for more info.
  552. sub_commands = [('install_lib', has_lib),
  553. ('install_headers', has_headers),
  554. ('install_scripts', has_scripts),
  555. ('install_data', has_data),
  556. ('install_egg_info', lambda self:True),
  557. ]
  558. # class install