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