install.py 21.7 KB
Newer Older
1 2 3 4 5 6
"""distutils.command.install

Implements the Distutils 'install' command."""

# created 1999/03/13, Greg Ward

7
__revision__ = "$Id$"
8 9

import sys, os, string
10
from types import *
11
from distutils.core import Command, DEBUG
12
from distutils.sysconfig import get_config_vars
13 14
from distutils.file_util import write_file
from distutils.util import convert_path, subst_vars, change_root
15
from distutils.errors import DistutilsOptionError
16
from glob import glob
17

18 19 20 21
INSTALL_SCHEMES = {
    'unix_prefix': {
        'purelib': '$base/lib/python$py_version_short/site-packages',
        'platlib': '$platbase/lib/python$py_version_short/site-packages',
22
        'headers': '$base/include/python$py_version_short/$dist_name',
23
        'scripts': '$base/bin',
24
        'data'   : '$base',
25 26 27 28
        },
    'unix_home': {
        'purelib': '$base/lib/python',
        'platlib': '$base/lib/python',
29
        'headers': '$base/include/python/$dist_name',
30
        'scripts': '$base/bin',
31
        'data'   : '$base',
32 33 34 35
        },
    'nt': {
        'purelib': '$base',
        'platlib': '$base',
36 37
        'headers': '$base/Include/$dist_name',
        'scripts': '$base/Scripts',
38
        'data'   : '$base',
39 40
        },
    'mac': {
41 42 43 44
        'purelib': '$base/Lib/site-packages',
        'platlib': '$base/Lib/site-packages',
        'headers': '$base/Include/$dist_name',
        'scripts': '$base/Scripts',
45
        'data'   : '$base',
46 47 48
        }
    }

49 50 51 52 53
# The keys to an installation scheme; if any new types of files are to be
# installed, be sure to add an entry to every installation scheme above,
# and to SCHEME_KEYS here.
SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')

54

55
class install (Command):
56

57 58
    description = "install everything from build directory"

59
    user_options = [
60 61 62
        # Select installation scheme and set base director(y|ies)
        ('prefix=', None,
         "installation prefix"),
63
        ('exec-prefix=', None,
64 65 66 67 68 69 70 71 72 73
         "(Unix only) prefix for platform-specific files"),
        ('home=', None,
         "(Unix only) home directory to install under"),

        # Or, just set the base director(y|ies)
        ('install-base=', None,
         "base installation directory (instead of --prefix or --home)"),
        ('install-platbase=', None,
         "base installation directory for platform-specific files " +
         "(instead of --exec-prefix or --home)"),
74 75
        ('root=', None,
         "install everything relative to this alternate root directory"),
76 77 78 79

        # Or, explicitly set the installation scheme
        ('install-purelib=', None,
         "installation directory for pure Python module distributions"),
80
        ('install-platlib=', None,
81 82 83 84 85
         "installation directory for non-pure module distributions"),
        ('install-lib=', None,
         "installation directory for all module distributions " +
         "(overrides --install-purelib and --install-platlib)"),

86 87
        ('install-headers=', None,
         "installation directory for C/C++ headers"),
88 89 90 91
        ('install-scripts=', None,
         "installation directory for Python scripts"),
        ('install-data=', None,
         "installation directory for data files"),
92

93 94 95 96 97 98 99 100 101
        # Byte-compilation options -- see install_lib.py for details, as
        # these are duplicated from there (but only install_lib does
        # anything with them).
        ('compile', 'c', "compile .py to .pyc [default]"),
        ('no-compile', None, "don't compile .py files"),
        ('optimize=', 'O',
         "also compile with optimization: -O1 for \"python -O\", "
         "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
         
102 103 104
        # Miscellaneous control options
        ('force', 'f',
         "force installation (overwrite any existing files)"),
105 106 107
        ('skip-build', None,
         "skip rebuilding everything (for testing/debugging)"),

108
        # Where to install documentation (eventually!)
109 110 111 112
        #('doc-format=', None, "format of documentation to generate"),
        #('install-man=', None, "directory for Unix man pages"),
        #('install-html=', None, "directory for HTML documentation"),
        #('install-info=', None, "directory for GNU info files"),
113

114 115
        ('record=', None,
         "filename in which to record list of installed files"),
116
        ]
117

118
    boolean_options = ['force', 'skip-build']
119
    negative_opt = {'no-compile' : 'compile'}
120

121

122
    def initialize_options (self):
123

124 125
        # High-level options: these select both an installation base
        # and scheme.
126 127
        self.prefix = None
        self.exec_prefix = None
128 129
        self.home = None

130 131 132
        # These select only the installation base; it's up to the user to
        # specify the installation scheme (currently, that means supplying
        # the --install-{platlib,purelib,scripts,data} options).
133 134
        self.install_base = None
        self.install_platbase = None
135
        self.root = None
136

137 138 139 140 141 142
        # These options are the actual installation directories; if not
        # supplied by the user, they are filled in using the installation
        # scheme implied by prefix/exec-prefix/home and the contents of
        # that installation scheme.
        self.install_purelib = None     # for pure module distributions
        self.install_platlib = None     # non-pure (dists w/ extensions)
143
        self.install_headers = None     # for C/C++ headers
144
        self.install_lib = None         # set to either purelib or platlib
145 146
        self.install_scripts = None
        self.install_data = None
147

148
        self.compile = None
149
        self.no_compile = None
150 151
        self.optimize = None

152 153
        # These two are for putting non-packagized distributions into their
        # own directory and creating a .pth file if it makes sense.
154 155 156 157 158 159
        # 'extra_path' comes from the setup file; 'install_path_file' can
        # be turned off if it makes no sense to install a .pth file.  (But
        # better to install it uselessly than to guess wrong and not
        # install it when it's necessary and would be used!)  Currently,
        # 'install_path_file' is always true unless some outsider meddles
        # with it.
160
        self.extra_path = None
161 162 163 164 165 166 167 168
        self.install_path_file = 1

        # 'force' forces installation, even if target files are not
        # out-of-date.  'skip_build' skips running the "build" command,
        # handy if you know it's not necessary.  'warn_dir' (which is *not*
        # a user option, it's just there so the bdist_* commands can turn
        # it off) determines whether we warn about installing to a
        # directory not in sys.path.
169
        self.force = 0
170
        self.skip_build = 0
171
        self.warn_dir = 1
172

173 174 175 176 177 178 179 180 181
        # These are only here as a conduit from the 'build' command to the
        # 'install_*' commands that do the real work.  ('build_base' isn't
        # actually used anywhere, but it might be useful in future.)  They
        # are not user options, because if the user told the install
        # command where the build directory is, that wouldn't affect the
        # build command.
        self.build_base = None
        self.build_lib = None

182 183
        # Not defined yet because we don't know anything about
        # documentation yet.
184 185 186
        #self.install_man = None
        #self.install_html = None
        #self.install_info = None
187

188
        self.record = None
189

190 191 192 193 194 195 196

    # -- Option finalizing methods -------------------------------------
    # (This is rather more involved than for most commands,
    # because this is where the policy for installing third-
    # party Python modules on various platforms given a wide
    # array of user input is decided.  Yes, it's quite complex!)

197
    def finalize_options (self):
198

199 200 201 202 203 204 205 206 207 208
        # This method (and its pliant slaves, like 'finalize_unix()',
        # 'finalize_other()', and 'select_scheme()') is where the default
        # installation directories for modules, extension modules, and
        # anything else we care to install from a Python module
        # distribution.  Thus, this code makes a pretty important policy
        # statement about how third-party stuff is added to a Python
        # installation!  Note that the actual work of installation is done
        # by the relatively simple 'install_*' commands; they just take
        # their orders from the installation directory options determined
        # here.
209

210 211
        # Check for errors/inconsistencies in the options; first, stuff
        # that's wrong on any platform.
212 213 214 215 216 217 218

        if ((self.prefix or self.exec_prefix or self.home) and
            (self.install_base or self.install_platbase)):
            raise DistutilsOptionError, \
                  ("must supply either prefix/exec-prefix/home or " +
                   "install-base/install-platbase -- not both")

219
        # Next, stuff that's wrong (or dubious) only on certain platforms.
220 221
        if os.name == 'posix':
            if self.home and (self.prefix or self.exec_prefix):
222
                raise DistutilsOptionError, \
223 224
                      ("must supply either home or prefix/exec-prefix -- " +
                       "not both")
225
        else:
226
            if self.exec_prefix:
227
                self.warn("exec-prefix option ignored on this platform")
228 229
                self.exec_prefix = None
            if self.home:
230
                self.warn("home option ignored on this platform")
231 232 233 234 235 236 237 238 239
                self.home = None

        # Now the interesting logic -- so interesting that we farm it out
        # to other methods.  The goal of these methods is to set the final
        # values for the install_{lib,scripts,data,...}  options, using as
        # input a heady brew of prefix, exec_prefix, home, install_base,
        # install_platbase, user-supplied versions of
        # install_{purelib,platlib,lib,scripts,data,...}, and the
        # INSTALL_SCHEME dictionary above.  Phew!
240

241
        self.dump_dirs("pre-finalize_{unix,other}")
242

243
        if os.name == 'posix':
244
            self.finalize_unix()
245
        else:
246
            self.finalize_other()
247

248
        self.dump_dirs("post-finalize_{unix,other}()")
249 250 251 252 253 254

        # Expand configuration variables, tilde, etc. in self.install_base
        # and self.install_platbase -- that way, we can use $base or
        # $platbase in the other installation directories and not worry
        # about needing recursive variable expansion (shudder).

255
        py_version = (string.split(sys.version))[0]
Greg Ward's avatar
Greg Ward committed
256
        (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
257 258 259 260 261
        self.config_vars = {'dist_name': self.distribution.get_name(),
                            'dist_version': self.distribution.get_version(),
                            'dist_fullname': self.distribution.get_fullname(),
                            'py_version': py_version,
                            'py_version_short': py_version[0:3],
262 263 264 265
                            'sys_prefix': prefix,
                            'prefix': prefix,
                            'sys_exec_prefix': exec_prefix,
                            'exec_prefix': exec_prefix,
266
                           }
267
        self.expand_basedirs()
268

269
        self.dump_dirs("post-expand_basedirs()")
270 271 272 273 274 275

        # Now define config vars for the base directories so we can expand
        # everything else.
        self.config_vars['base'] = self.install_base
        self.config_vars['platbase'] = self.install_platbase

276 277 278
        if DEBUG:
            from pprint import pprint
            print "config vars:"
279
            pprint(self.config_vars)
280

281 282
        # Expand "~" and configuration variables in the installation
        # directories.
283
        self.expand_dirs()
284

285
        self.dump_dirs("post-expand_dirs()")
286

287 288 289 290 291 292 293 294 295 296
        # Pick the actual directory to install all modules to: either
        # install_purelib or install_platlib, depending on whether this
        # module distribution is pure or not.  Of course, if the user
        # already specified install_lib, use their selection.
        if self.install_lib is None:
            if self.distribution.ext_modules: # has extensions: non-pure
                self.install_lib = self.install_platlib
            else:
                self.install_lib = self.install_purelib
                    
297 298 299 300 301 302

        # Convert directories from Unix /-separated syntax to the local
        # convention.
        self.convert_paths('lib', 'purelib', 'platlib',
                           'scripts', 'data', 'headers')

303 304 305 306
        # Well, we're not actually fully completely finalized yet: we still
        # have to deal with 'extra_path', which is the hack for allowing
        # non-packagized module distributions (hello, Numerical Python!) to
        # get their own directories.
307
        self.handle_extra_path()
308
        self.install_libbase = self.install_lib # needed for .pth file
309
        self.install_lib = os.path.join(self.install_lib, self.extra_dirs)
310

311 312 313
        # If a new root directory was supplied, make all the installation
        # dirs relative to it.
        if self.root is not None:
314 315
            self.change_roots('libbase', 'lib', 'purelib', 'platlib',
                              'scripts', 'data', 'headers')
316

317
        self.dump_dirs("after prepending root")
318

319
        # Find out the build directories, ie. where to install from.
320 321 322
        self.set_undefined_options('build',
                                   ('build_base', 'build_base'),
                                   ('build_lib', 'build_lib'))
323 324 325

        # Punt on doc directories for now -- after all, we're punting on
        # documentation completely!
326

327 328 329
    # finalize_options ()


330
    def dump_dirs (self, msg):
331 332 333 334 335 336 337
        if DEBUG:
            from distutils.fancy_getopt import longopt_xlate
            print msg + ":"
            for opt in self.user_options:
                opt_name = opt[0]
                if opt_name[-1] == "=":
                    opt_name = opt_name[0:-1]
338 339
                opt_name = string.translate(opt_name, longopt_xlate)
                val = getattr(self, opt_name)
340
                print "  %s: %s" % (opt_name, val)
341 342


343 344 345 346 347 348
    def finalize_unix (self):
        
        if self.install_base is not None or self.install_platbase is not None:
            if ((self.install_lib is None and
                 self.install_purelib is None and
                 self.install_platlib is None) or
349
                self.install_headers is None or
350 351 352 353 354 355 356 357 358
                self.install_scripts is None or
                self.install_data is None):
                raise DistutilsOptionError, \
                      "install-base or install-platbase supplied, but " + \
                      "installation scheme is incomplete"
            return

        if self.home is not None:
            self.install_base = self.install_platbase = self.home
359
            self.select_scheme("unix_home")
360
        else:
361 362 363 364 365
            if self.prefix is None:
                if self.exec_prefix is not None:
                    raise DistutilsOptionError, \
                          "must not supply exec-prefix without prefix"

366 367
                self.prefix = os.path.normpath(sys.prefix)
                self.exec_prefix = os.path.normpath(sys.exec_prefix)
368 369 370 371 372 373 374

            else:
                if self.exec_prefix is None:
                    self.exec_prefix = self.prefix

            self.install_base = self.prefix
            self.install_platbase = self.exec_prefix
375
            self.select_scheme("unix_prefix")
376 377 378 379 380 381 382

    # finalize_unix ()


    def finalize_other (self):          # Windows and Mac OS for now

        if self.prefix is None:
383
            self.prefix = os.path.normpath(sys.prefix)
384 385 386

        self.install_base = self.install_platbase = self.prefix
        try:
387
            self.select_scheme(os.name)
388
        except KeyError:
389
            raise DistutilsPlatformError, \
390
                  "I don't know how to install stuff on '%s'" % os.name
391

392 393 394 395 396 397
    # finalize_other ()


    def select_scheme (self, name):
        # it's the caller's problem if they supply a bad name!
        scheme = INSTALL_SCHEMES[name]
398
        for key in SCHEME_KEYS:
399 400 401
            attrname = 'install_' + key
            if getattr(self, attrname) is None:
                setattr(self, attrname, scheme[key])
402 403


404 405
    def _expand_attrs (self, attrs):
        for attr in attrs:
406
            val = getattr(self, attr)
407 408
            if val is not None:
                if os.name == 'posix':
409 410 411
                    val = os.path.expanduser(val)
                val = subst_vars(val, self.config_vars)
                setattr(self, attr, val)
412 413


414
    def expand_basedirs (self):
415 416 417
        self._expand_attrs(['install_base',
                            'install_platbase',
                            'root'])        
418 419

    def expand_dirs (self):
420 421 422 423 424 425
        self._expand_attrs(['install_purelib',
                            'install_platlib',
                            'install_lib',
                            'install_headers',
                            'install_scripts',
                            'install_data',])
426 427


428 429 430 431 432 433
    def convert_paths (self, *names):
        for name in names:
            attr = "install_" + name
            setattr(self, attr, convert_path(getattr(self, attr)))


434
    def handle_extra_path (self):
435

436 437 438 439
        if self.extra_path is None:
            self.extra_path = self.distribution.extra_path

        if self.extra_path is not None:
440 441
            if type(self.extra_path) is StringType:
                self.extra_path = string.split(self.extra_path, ',')
442

443
            if len(self.extra_path) == 1:
444
                path_file = extra_dirs = self.extra_path[0]
445
            elif len(self.extra_path) == 2:
446
                (path_file, extra_dirs) = self.extra_path
447
            else:
448
                raise DistutilsOptionError, \
449
                      "'extra_path' option must be a list, tuple, or " + \
450 451
                      "comma-separated string with 1 or 2 elements"

452 453
            # convert to local form in case Unix notation used (as it
            # should be in setup scripts)
454
            extra_dirs = convert_path(extra_dirs)
455

456 457 458 459
        else:
            path_file = None
            extra_dirs = ''

460 461
        # XXX should we warn if path_file and not extra_dirs? (in which
        # case the path file would be harmless but pointless)
462 463 464
        self.path_file = path_file
        self.extra_dirs = extra_dirs

465
    # handle_extra_path ()
466 467


468 469 470 471 472 473
    def change_roots (self, *names):
        for name in names:
            attr = "install_" + name
            setattr(self, attr, change_root(self.root, getattr(self, attr)))


474 475
    # -- Command execution methods -------------------------------------

476 477
    def run (self):

478
        # Obviously have to build before we can install
479
        if not self.skip_build:
480
            self.run_command('build')
481

482 483
        # Run all sub-commands (at least those that need to be run)
        for cmd_name in self.get_sub_commands():
484
            self.run_command(cmd_name)
485 486

        if self.path_file:
487
            self.create_path_file()
488

489 490 491
        # write list of installed files, if requested.
        if self.record:
            outputs = self.get_outputs()
492
            if self.root:               # strip any package prefix
493
                root_len = len(self.root)
494
                for counter in xrange(len(outputs)):
495 496
                    outputs[counter] = outputs[counter][root_len:]
            self.execute(write_file,
497 498 499
                         (self.record, outputs),
                         "writing list of installed files to '%s'" %
                         self.record)
500

501
        sys_path = map(os.path.normpath, sys.path)
Greg Ward's avatar
Greg Ward committed
502
        sys_path = map(os.path.normcase, sys_path)
503
        install_lib = os.path.normcase(os.path.normpath(self.install_lib))
504 505
        if (self.warn_dir and
            not (self.path_file and self.install_path_file) and
506
            install_lib not in sys_path):
507 508 509 510
            self.warn(("modules installed to '%s', which is not in " +
                       "Python's module search path (sys.path) -- " +
                       "you'll have to change the search path yourself") %
                      self.install_lib)
511

512 513
    # run ()

514
    def create_path_file (self):
515 516
        filename = os.path.join(self.install_libbase,
                                self.path_file + ".pth")
517
        if self.install_path_file:
518 519 520
            self.execute(write_file,
                         (filename, [self.extra_dirs]),
                         "creating %s" % filename)
521 522
        else:
            self.warn("path file '%s' not created" % filename)
523

524

525
    # -- Reporting methods ---------------------------------------------
526

527 528 529 530
    def get_outputs (self):
        # This command doesn't have any outputs of its own, so just
        # get the outputs of all its sub-commands.
        outputs = []
531
        for cmd_name in self.get_sub_commands():
532
            cmd = self.get_finalized_command(cmd_name)
533 534 535 536 537
            # Add the contents of cmd.get_outputs(), ensuring
            # that outputs doesn't contain duplicate entries
            for filename in cmd.get_outputs():
                if filename not in outputs:
                    outputs.append(filename)
538 539 540

        return outputs

541 542 543
    def get_inputs (self):
        # XXX gee, this looks familiar ;-(
        inputs = []
544
        for cmd_name in self.get_sub_commands():
545 546
            cmd = self.get_finalized_command(cmd_name)
            inputs.extend(cmd.get_inputs())
547 548 549 550

        return inputs


551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
    # -- Predicates for sub-command list -------------------------------

    def has_lib (self):
        """Return true if the current distribution has any Python
        modules to install."""
        return (self.distribution.has_pure_modules() or
                self.distribution.has_ext_modules())

    def has_headers (self):
        return self.distribution.has_headers()

    def has_scripts (self):
        return self.distribution.has_scripts()

    def has_data (self):
        return self.distribution.has_data_files()

568

569 570 571 572 573 574 575 576
    # 'sub_commands': a list of commands this command might have to run to
    # get its work done.  See cmd.py for more info.
    sub_commands = [('install_lib',     has_lib),
                    ('install_headers', has_headers),
                    ('install_scripts', has_scripts),
                    ('install_data',    has_data),
                   ]

577
# class install