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