install.py 30 KB

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