install.py 29 KB

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