Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

Location:
python/vendor/current/Lib/distutils
Files:
27 added
1 deleted
70 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Lib/distutils/README

    r2 r388  
    1 This directory contains only a subset of the Distutils, specifically
    2 the Python modules in the 'distutils' and 'distutils.command'
    3 packages.  This is all you need to distribute and install Python
    4 modules using the Distutils.  There is also a separately packaged
    5 standalone version of the Distutils available for people who want to
    6 upgrade the Distutils without upgrading Python, available from the
    7 Distutils web page:
     1This directory contains the Distutils package.
     2
     3There's a full documentation available at:
     4
     5    http://docs.python.org/distutils/
     6
     7The Distutils-SIG web page is also a good starting point:
    88
    99    http://www.python.org/sigs/distutils-sig/
    1010
    11 The standalone version includes all of the code in this directory,
    12 plus documentation, test scripts, examples, etc.
     11WARNING : Distutils must remain compatible with 2.3
    1312
    14 The Distutils documentation is divided into two documents, "Installing
    15 Python Modules", which explains how to install Python packages, and
    16 "Distributing Python Modules", which explains how to write setup.py
    17 files.  Both documents are part of the standard Python documentation
    18 set, and are available from http://www.python.org/doc/current/ .
    19 
    20         Greg Ward (gward@python.net)
    21 
    22 $Id: README 29650 2002-11-13 13:26:59Z akuchling $
     13$Id$
  • python/vendor/current/Lib/distutils/__init__.py

    r2 r388  
    99"""
    1010
    11 # This module should be kept compatible with Python 2.1.
    12 
    13 __revision__ = "$Id: __init__.py 79063 2010-03-18 22:14:36Z barry.warsaw $"
     11__revision__ = "$Id$"
    1412
    1513# Distutils version
    1614#
    17 # Please coordinate with Marc-Andre Lemburg <mal@egenix.com> when adding
    18 # new features to distutils that would warrant bumping the version number.
     15# Updated automatically by the Python release process.
    1916#
    20 # In general, major and minor version should loosely follow the Python
    21 # version number the distutils code was shipped with.
    22 #
    23 
    2417#--start constants--
    25 __version__ = "2.6.5"
     18__version__ = "2.7.6"
    2619#--end constants--
  • python/vendor/current/Lib/distutils/archive_util.py

    r2 r388  
    44that sort of thing)."""
    55
    6 # This module should be kept compatible with Python 2.1.
    7 
    8 __revision__ = "$Id: archive_util.py 62904 2008-05-08 22:09:54Z benjamin.peterson $"
     6__revision__ = "$Id$"
    97
    108import os
     9from warnings import warn
     10import sys
     11
    1112from distutils.errors import DistutilsExecError
    1213from distutils.spawn import spawn
     
    1415from distutils import log
    1516
    16 def make_tarball (base_name, base_dir, compress="gzip",
    17                   verbose=0, dry_run=0):
     17try:
     18    from pwd import getpwnam
     19except ImportError:
     20    getpwnam = None
     21
     22try:
     23    from grp import getgrnam
     24except ImportError:
     25    getgrnam = None
     26
     27def _get_gid(name):
     28    """Returns a gid, given a group name."""
     29    if getgrnam is None or name is None:
     30        return None
     31    try:
     32        result = getgrnam(name)
     33    except KeyError:
     34        result = None
     35    if result is not None:
     36        return result[2]
     37    return None
     38
     39def _get_uid(name):
     40    """Returns an uid, given a user name."""
     41    if getpwnam is None or name is None:
     42        return None
     43    try:
     44        result = getpwnam(name)
     45    except KeyError:
     46        result = None
     47    if result is not None:
     48        return result[2]
     49    return None
     50
     51def make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
     52                 owner=None, group=None):
    1853    """Create a (possibly compressed) tar file from all the files under
    19     'base_dir'.  'compress' must be "gzip" (the default), "compress",
    20     "bzip2", or None.  Both "tar" and the compression utility named by
    21     'compress' must be on the default program search path, so this is
    22     probably Unix-specific.  The output tar file will be named 'base_dir' +
    23     ".tar", possibly plus the appropriate compression extension (".gz",
    24     ".bz2" or ".Z").  Return the output filename.
    25     """
    26     # XXX GNU tar 1.13 has a nifty option to add a prefix directory.
    27     # It's pretty new, though, so we certainly can't require it --
    28     # but it would be nice to take advantage of it to skip the
    29     # "create a tree of hardlinks" step!  (Would also be nice to
    30     # detect GNU tar to use its 'z' option and save a step.)
    31 
    32     compress_ext = { 'gzip': ".gz",
    33                      'bzip2': '.bz2',
    34                      'compress': ".Z" }
     54    'base_dir'.
     55
     56    'compress' must be "gzip" (the default), "compress", "bzip2", or None.
     57    (compress will be deprecated in Python 3.2)
     58
     59    'owner' and 'group' can be used to define an owner and a group for the
     60    archive that is being built. If not provided, the current owner and group
     61    will be used.
     62
     63    The output tar file will be named 'base_dir' +  ".tar", possibly plus
     64    the appropriate compression extension (".gz", ".bz2" or ".Z").
     65
     66    Returns the output filename.
     67    """
     68    tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: '', 'compress': ''}
     69    compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'compress': '.Z'}
    3570
    3671    # flags for compression program, each element of list will be an argument
    37     compress_flags = {'gzip': ["-f9"],
    38                       'compress': ["-f"],
    39                       'bzip2': ['-f9']}
    40 
    4172    if compress is not None and compress not in compress_ext.keys():
    4273        raise ValueError, \
    43               "bad value for 'compress': must be None, 'gzip', or 'compress'"
    44 
    45     archive_name = base_name + ".tar"
     74              ("bad value for 'compress': must be None, 'gzip', 'bzip2' "
     75               "or 'compress'")
     76
     77    archive_name = base_name + '.tar'
     78    if compress != 'compress':
     79        archive_name += compress_ext.get(compress, '')
     80
    4681    mkpath(os.path.dirname(archive_name), dry_run=dry_run)
    47     cmd = ["tar", "-cf", archive_name, base_dir]
    48     spawn(cmd, dry_run=dry_run)
    49 
    50     if compress:
    51         spawn([compress] + compress_flags[compress] + [archive_name],
    52               dry_run=dry_run)
    53         return archive_name + compress_ext[compress]
    54     else:
    55         return archive_name
    56 
    57 # make_tarball ()
    58 
    59 
    60 def make_zipfile (base_name, base_dir, verbose=0, dry_run=0):
    61     """Create a zip file from all the files under 'base_dir'.  The output
    62     zip file will be named 'base_dir' + ".zip".  Uses either the "zipfile"
    63     Python module (if available) or the InfoZIP "zip" utility (if installed
    64     and found on the default search path).  If neither tool is available,
    65     raises DistutilsExecError.  Returns the name of the output zip file.
     82
     83    # creating the tarball
     84    import tarfile  # late import so Python build itself doesn't break
     85
     86    log.info('Creating tar archive')
     87
     88    uid = _get_uid(owner)
     89    gid = _get_gid(group)
     90
     91    def _set_uid_gid(tarinfo):
     92        if gid is not None:
     93            tarinfo.gid = gid
     94            tarinfo.gname = group
     95        if uid is not None:
     96            tarinfo.uid = uid
     97            tarinfo.uname = owner
     98        return tarinfo
     99
     100    if not dry_run:
     101        tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
     102        try:
     103            tar.add(base_dir, filter=_set_uid_gid)
     104        finally:
     105            tar.close()
     106
     107    # compression using `compress`
     108    if compress == 'compress':
     109        warn("'compress' will be deprecated.", PendingDeprecationWarning)
     110        # the option varies depending on the platform
     111        compressed_name = archive_name + compress_ext[compress]
     112        if sys.platform == 'win32':
     113            cmd = [compress, archive_name, compressed_name]
     114        else:
     115            cmd = [compress, '-f', archive_name]
     116        spawn(cmd, dry_run=dry_run)
     117        return compressed_name
     118
     119    return archive_name
     120
     121def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
     122    """Create a zip file from all the files under 'base_dir'.
     123
     124    The output zip file will be named 'base_name' + ".zip".  Uses either the
     125    "zipfile" Python module (if available) or the InfoZIP "zip" utility
     126    (if installed and found on the default search path).  If neither tool is
     127    available, raises DistutilsExecError.  Returns the name of the output zip
     128    file.
    66129    """
    67130    try:
     
    97160
    98161        if not dry_run:
    99             z = zipfile.ZipFile(zip_filename, "w",
    100                                 compression=zipfile.ZIP_DEFLATED)
     162            zip = zipfile.ZipFile(zip_filename, "w",
     163                                  compression=zipfile.ZIP_DEFLATED)
    101164
    102165            for dirpath, dirnames, filenames in os.walk(base_dir):
     
    104167                    path = os.path.normpath(os.path.join(dirpath, name))
    105168                    if os.path.isfile(path):
    106                         z.write(path, path)
     169                        zip.write(path, path)
    107170                        log.info("adding '%s'" % path)
    108             z.close()
     171            zip.close()
    109172
    110173    return zip_filename
    111 
    112 # make_zipfile ()
    113 
    114174
    115175ARCHIVE_FORMATS = {
     
    121181    }
    122182
    123 def check_archive_formats (formats):
     183def check_archive_formats(formats):
     184    """Returns the first format from the 'format' list that is unknown.
     185
     186    If all formats are known, returns None
     187    """
    124188    for format in formats:
    125189        if format not in ARCHIVE_FORMATS:
    126190            return format
    127     else:
    128         return None
    129 
    130 def make_archive (base_name, format,
    131                   root_dir=None, base_dir=None,
    132                   verbose=0, dry_run=0):
    133     """Create an archive file (eg. zip or tar).  'base_name' is the name
    134     of the file to create, minus any format-specific extension; 'format'
    135     is the archive format: one of "zip", "tar", "ztar", or "gztar".
     191    return None
     192
     193def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
     194                 dry_run=0, owner=None, group=None):
     195    """Create an archive file (eg. zip or tar).
     196
     197    'base_name' is the name of the file to create, minus any format-specific
     198    extension; 'format' is the archive format: one of "zip", "tar", "ztar",
     199    or "gztar".
     200
    136201    'root_dir' is a directory that will be the root directory of the
    137202    archive; ie. we typically chdir into 'root_dir' before creating the
     
    140205    directories in the archive.  'root_dir' and 'base_dir' both default
    141206    to the current directory.  Returns the name of the archive file.
     207
     208    'owner' and 'group' are used when creating a tar archive. By default,
     209    uses the current owner and group.
    142210    """
    143211    save_cwd = os.getcwd()
     
    151219        base_dir = os.curdir
    152220
    153     kwargs = { 'dry_run': dry_run }
     221    kwargs = {'dry_run': dry_run}
    154222
    155223    try:
     
    159227
    160228    func = format_info[0]
    161     for (arg,val) in format_info[1]:
     229    for arg, val in format_info[1]:
    162230        kwargs[arg] = val
    163     filename = apply(func, (base_name, base_dir), kwargs)
    164 
    165     if root_dir is not None:
    166         log.debug("changing back to '%s'", save_cwd)
    167         os.chdir(save_cwd)
     231
     232    if format != 'zip':
     233        kwargs['owner'] = owner
     234        kwargs['group'] = group
     235
     236    try:
     237        filename = func(base_name, base_dir, **kwargs)
     238    finally:
     239        if root_dir is not None:
     240            log.debug("changing back to '%s'", save_cwd)
     241            os.chdir(save_cwd)
    168242
    169243    return filename
    170 
    171 # make_archive ()
  • python/vendor/current/Lib/distutils/bcppcompiler.py

    r2 r388  
    1212# WindowsCCompiler!  --GPW
    1313
    14 # This module should be kept compatible with Python 2.1.
    15 
    16 __revision__ = "$Id: bcppcompiler.py 61000 2008-02-23 17:40:11Z christian.heimes $"
    17 
     14__revision__ = "$Id$"
    1815
    1916import os
    20 from distutils.errors import \
    21      DistutilsExecError, DistutilsPlatformError, \
    22      CompileError, LibError, LinkError, UnknownFileError
    23 from distutils.ccompiler import \
    24      CCompiler, gen_preprocess_options, gen_lib_options
     17
     18from distutils.errors import (DistutilsExecError, CompileError, LibError,
     19                              LinkError, UnknownFileError)
     20from distutils.ccompiler import CCompiler, gen_preprocess_options
    2521from distutils.file_util import write_file
    2622from distutils.dep_util import newer
  • python/vendor/current/Lib/distutils/ccompiler.py

    r2 r388  
    44for the Distutils compiler abstraction model."""
    55
    6 # This module should be kept compatible with Python 2.1.
    7 
    8 __revision__ = "$Id: ccompiler.py 77425 2010-01-11 22:54:57Z tarek.ziade $"
    9 
    10 import sys, os, re
    11 from types import *
    12 from copy import copy
    13 from distutils.errors import *
     6__revision__ = "$Id$"
     7
     8import sys
     9import os
     10import re
     11
     12from distutils.errors import (CompileError, LinkError, UnknownFileError,
     13                              DistutilsPlatformError, DistutilsModuleError)
    1414from distutils.spawn import spawn
    1515from distutils.file_util import move_file
    1616from distutils.dir_util import mkpath
    17 from distutils.dep_util import newer_pairwise, newer_group
     17from distutils.dep_util import newer_group
    1818from distutils.util import split_quoted, execute
    1919from distutils import log
     20# following import is for backward compatibility
     21from distutils.sysconfig import customize_compiler
    2022
    2123class CCompiler:
     
    8991    language_order = ["c++", "objc", "c"]
    9092
    91     def __init__ (self,
    92                   verbose=0,
    93                   dry_run=0,
    94                   force=0):
    95 
     93    def __init__ (self, verbose=0, dry_run=0, force=0):
    9694        self.dry_run = dry_run
    9795        self.force = force
     
    129127            self.set_executable(key, self.executables[key])
    130128
    131     # __init__ ()
    132 
    133 
    134     def set_executables (self, **args):
    135 
     129    def set_executables(self, **args):
    136130        """Define the executables (and options for them) that will be run
    137131        to perform the various stages of compilation.  The exact set of
     
    166160            self.set_executable(key, args[key])
    167161
    168     # set_executables ()
    169 
    170162    def set_executable(self, key, value):
    171         if type(value) is StringType:
     163        if isinstance(value, str):
    172164            setattr(self, key, split_quoted(value))
    173165        else:
    174166            setattr(self, key, value)
    175167
    176 
    177     def _find_macro (self, name):
     168    def _find_macro(self, name):
    178169        i = 0
    179170        for defn in self.macros:
     
    181172                return i
    182173            i = i + 1
    183 
    184174        return None
    185175
    186 
    187     def _check_macro_definitions (self, definitions):
     176    def _check_macro_definitions(self, definitions):
    188177        """Ensures that every element of 'definitions' is a valid macro
    189178        definition, ie. either (name,value) 2-tuple or a (name,) tuple.  Do
     
    191180        """
    192181        for defn in definitions:
    193             if not (type (defn) is TupleType and
     182            if not (isinstance(defn, tuple) and
    194183                    (len (defn) == 1 or
    195184                     (len (defn) == 2 and
    196                       (type (defn[1]) is StringType or defn[1] is None))) and
    197                     type (defn[0]) is StringType):
     185                      (isinstance(defn[1], str) or defn[1] is None))) and
     186                    isinstance(defn[0], str)):
    198187                raise TypeError, \
    199188                      ("invalid macro definition '%s': " % defn) + \
     
    204193    # -- Bookkeeping methods -------------------------------------------
    205194
    206     def define_macro (self, name, value=None):
     195    def define_macro(self, name, value=None):
    207196        """Define a preprocessor macro for all compilations driven by this
    208197        compiler object.  The optional parameter 'value' should be a
     
    220209        self.macros.append (defn)
    221210
    222 
    223     def undefine_macro (self, name):
     211    def undefine_macro(self, name):
    224212        """Undefine a preprocessor macro for all compilations driven by
    225213        this compiler object.  If the same macro is defined by
     
    239227        self.macros.append (undefn)
    240228
    241 
    242     def add_include_dir (self, dir):
     229    def add_include_dir(self, dir):
    243230        """Add 'dir' to the list of directories that will be searched for
    244231        header files.  The compiler is instructed to search directories in
     
    248235        self.include_dirs.append (dir)
    249236
    250     def set_include_dirs (self, dirs):
     237    def set_include_dirs(self, dirs):
    251238        """Set the list of directories that will be searched to 'dirs' (a
    252239        list of strings).  Overrides any preceding calls to
     
    256243        search by default.
    257244        """
    258         self.include_dirs = copy (dirs)
    259 
    260 
    261     def add_library (self, libname):
     245        self.include_dirs = dirs[:]
     246
     247    def add_library(self, libname):
    262248        """Add 'libname' to the list of libraries that will be included in
    263249        all links driven by this compiler object.  Note that 'libname'
     
    275261        self.libraries.append (libname)
    276262
    277     def set_libraries (self, libnames):
     263    def set_libraries(self, libnames):
    278264        """Set the list of libraries to be included in all links driven by
    279265        this compiler object to 'libnames' (a list of strings).  This does
     
    281267        include by default.
    282268        """
    283         self.libraries = copy (libnames)
    284 
    285 
    286     def add_library_dir (self, dir):
     269        self.libraries = libnames[:]
     270
     271
     272    def add_library_dir(self, dir):
    287273        """Add 'dir' to the list of directories that will be searched for
    288274        libraries specified to 'add_library()' and 'set_libraries()'.  The
     
    290276        are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
    291277        """
    292         self.library_dirs.append (dir)
    293 
    294     def set_library_dirs (self, dirs):
     278        self.library_dirs.append(dir)
     279
     280    def set_library_dirs(self, dirs):
    295281        """Set the list of library search directories to 'dirs' (a list of
    296282        strings).  This does not affect any standard library search path
    297283        that the linker may search by default.
    298284        """
    299         self.library_dirs = copy (dirs)
    300 
    301 
    302     def add_runtime_library_dir (self, dir):
     285        self.library_dirs = dirs[:]
     286
     287    def add_runtime_library_dir(self, dir):
    303288        """Add 'dir' to the list of directories that will be searched for
    304289        shared libraries at runtime.
    305290        """
    306         self.runtime_library_dirs.append (dir)
    307 
    308     def set_runtime_library_dirs (self, dirs):
     291        self.runtime_library_dirs.append(dir)
     292
     293    def set_runtime_library_dirs(self, dirs):
    309294        """Set the list of directories to search for shared libraries at
    310295        runtime to 'dirs' (a list of strings).  This does not affect any
     
    312297        default.
    313298        """
    314         self.runtime_library_dirs = copy (dirs)
    315 
    316 
    317     def add_link_object (self, object):
     299        self.runtime_library_dirs = dirs[:]
     300
     301    def add_link_object(self, object):
    318302        """Add 'object' to the list of object files (or analogues, such as
    319303        explicitly named library files or the output of "resource
     
    321305        object.
    322306        """
    323         self.objects.append (object)
    324 
    325     def set_link_objects (self, objects):
     307        self.objects.append(object)
     308
     309    def set_link_objects(self, objects):
    326310        """Set the list of object files (or analogues) to be included in
    327311        every link to 'objects'.  This does not affect any standard object
     
    329313        libraries).
    330314        """
    331         self.objects = copy (objects)
     315        self.objects = objects[:]
    332316
    333317
     
    342326        if outdir is None:
    343327            outdir = self.output_dir
    344         elif type(outdir) is not StringType:
     328        elif not isinstance(outdir, str):
    345329            raise TypeError, "'output_dir' must be a string or None"
    346330
    347331        if macros is None:
    348332            macros = self.macros
    349         elif type(macros) is ListType:
     333        elif isinstance(macros, list):
    350334            macros = macros + (self.macros or [])
    351335        else:
     
    354338        if incdirs is None:
    355339            incdirs = self.include_dirs
    356         elif type(incdirs) in (ListType, TupleType):
     340        elif isinstance(incdirs, (list, tuple)):
    357341            incdirs = list(incdirs) + (self.include_dirs or [])
    358342        else:
     
    390374        return cc_args
    391375
    392     def _fix_compile_args (self, output_dir, macros, include_dirs):
     376    def _fix_compile_args(self, output_dir, macros, include_dirs):
    393377        """Typecheck and fix-up some of the arguments to the 'compile()'
    394378        method, and return fixed-up values.  Specifically: if 'output_dir'
     
    402386        if output_dir is None:
    403387            output_dir = self.output_dir
    404         elif type (output_dir) is not StringType:
     388        elif not isinstance(output_dir, str):
    405389            raise TypeError, "'output_dir' must be a string or None"
    406390
    407391        if macros is None:
    408392            macros = self.macros
    409         elif type (macros) is ListType:
     393        elif isinstance(macros, list):
    410394            macros = macros + (self.macros or [])
    411395        else:
     
    414398        if include_dirs is None:
    415399            include_dirs = self.include_dirs
    416         elif type (include_dirs) in (ListType, TupleType):
     400        elif isinstance(include_dirs, (list, tuple)):
    417401            include_dirs = list (include_dirs) + (self.include_dirs or [])
    418402        else:
     
    422406        return output_dir, macros, include_dirs
    423407
    424     # _fix_compile_args ()
    425 
    426     def _prep_compile(self, sources, output_dir, depends=None):
    427         """Decide which souce files must be recompiled.
    428 
    429         Determine the list of object files corresponding to 'sources',
    430         and figure out which ones really need to be recompiled.
    431         Return a list of all object files and a dictionary telling
    432         which source files can be skipped.
    433         """
    434         # Get the list of expected output (object) files
    435         objects = self.object_filenames(sources, output_dir=output_dir)
    436         assert len(objects) == len(sources)
    437 
    438         # Return an empty dict for the "which source files can be skipped"
    439         # return value to preserve API compatibility.
    440         return objects, {}
    441 
    442     def _fix_object_args (self, objects, output_dir):
     408    def _fix_object_args(self, objects, output_dir):
    443409        """Typecheck and fix up some arguments supplied to various methods.
    444410        Specifically: ensure that 'objects' is a list; if output_dir is
     
    446412        'objects' and 'output_dir'.
    447413        """
    448         if type (objects) not in (ListType, TupleType):
     414        if not isinstance(objects, (list, tuple)):
    449415            raise TypeError, \
    450416                  "'objects' must be a list or tuple of strings"
     
    453419        if output_dir is None:
    454420            output_dir = self.output_dir
    455         elif type (output_dir) is not StringType:
     421        elif not isinstance(output_dir, str):
    456422            raise TypeError, "'output_dir' must be a string or None"
    457423
    458424        return (objects, output_dir)
    459425
    460 
    461     def _fix_lib_args (self, libraries, library_dirs, runtime_library_dirs):
     426    def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
    462427        """Typecheck and fix up some of the arguments supplied to the
    463428        'link_*' methods.  Specifically: ensure that all arguments are
     
    468433        if libraries is None:
    469434            libraries = self.libraries
    470         elif type (libraries) in (ListType, TupleType):
     435        elif isinstance(libraries, (list, tuple)):
    471436            libraries = list (libraries) + (self.libraries or [])
    472437        else:
     
    476441        if library_dirs is None:
    477442            library_dirs = self.library_dirs
    478         elif type (library_dirs) in (ListType, TupleType):
     443        elif isinstance(library_dirs, (list, tuple)):
    479444            library_dirs = list (library_dirs) + (self.library_dirs or [])
    480445        else:
     
    484449        if runtime_library_dirs is None:
    485450            runtime_library_dirs = self.runtime_library_dirs
    486         elif type (runtime_library_dirs) in (ListType, TupleType):
     451        elif isinstance(runtime_library_dirs, (list, tuple)):
    487452            runtime_library_dirs = (list (runtime_library_dirs) +
    488453                                    (self.runtime_library_dirs or []))
     
    494459        return (libraries, library_dirs, runtime_library_dirs)
    495460
    496     # _fix_lib_args ()
    497 
    498 
    499     def _need_link (self, objects, output_file):
     461    def _need_link(self, objects, output_file):
    500462        """Return true if we need to relink the files listed in 'objects'
    501463        to recreate 'output_file'.
     
    510472            return newer
    511473
    512     # _need_link ()
    513 
    514     def detect_language (self, sources):
     474    def detect_language(self, sources):
    515475        """Detect the language of a given file, or list of files. Uses
    516476        language_map, and language_order to do the job.
    517477        """
    518         if type(sources) is not ListType:
     478        if not isinstance(sources, list):
    519479            sources = [sources]
    520480        lang = None
     
    532492        return lang
    533493
    534     # detect_language ()
    535 
    536494    # -- Worker methods ------------------------------------------------
    537495    # (must be implemented by subclasses)
    538496
    539     def preprocess (self,
    540                     source,
    541                     output_file=None,
    542                     macros=None,
    543                     include_dirs=None,
    544                     extra_preargs=None,
    545                     extra_postargs=None):
     497    def preprocess(self, source, output_file=None, macros=None,
     498                   include_dirs=None, extra_preargs=None, extra_postargs=None):
    546499        """Preprocess a single C/C++ source file, named in 'source'.
    547500        Output will be written to file named 'output_file', or stdout if
     
    631584        pass
    632585
    633     def create_static_lib (self,
    634                            objects,
    635                            output_libname,
    636                            output_dir=None,
    637                            debug=0,
    638                            target_lang=None):
     586    def create_static_lib(self, objects, output_libname, output_dir=None,
     587                          debug=0, target_lang=None):
    639588        """Link a bunch of stuff together to create a static library file.
    640589        The "bunch of stuff" consists of the list of object files supplied
     
    661610        pass
    662611
    663 
    664612    # values for target_desc parameter in link()
    665613    SHARED_OBJECT = "shared_object"
     
    667615    EXECUTABLE = "executable"
    668616
    669     def link (self,
    670               target_desc,
    671               objects,
    672               output_filename,
    673               output_dir=None,
    674               libraries=None,
    675               library_dirs=None,
    676               runtime_library_dirs=None,
    677               export_symbols=None,
    678               debug=0,
    679               extra_preargs=None,
    680               extra_postargs=None,
    681               build_temp=None,
    682               target_lang=None):
     617    def link(self, target_desc, objects, output_filename, output_dir=None,
     618             libraries=None, library_dirs=None, runtime_library_dirs=None,
     619             export_symbols=None, debug=0, extra_preargs=None,
     620             extra_postargs=None, build_temp=None, target_lang=None):
    683621        """Link a bunch of stuff together to create an executable or
    684622        shared library file.
     
    729667    # Old 'link_*()' methods, rewritten to use the new 'link()' method.
    730668
    731     def link_shared_lib (self,
    732                          objects,
    733                          output_libname,
    734                          output_dir=None,
    735                          libraries=None,
    736                          library_dirs=None,
    737                          runtime_library_dirs=None,
    738                          export_symbols=None,
    739                          debug=0,
    740                          extra_preargs=None,
    741                          extra_postargs=None,
    742                          build_temp=None,
    743                          target_lang=None):
     669    def link_shared_lib(self, objects, output_libname, output_dir=None,
     670                        libraries=None, library_dirs=None,
     671                        runtime_library_dirs=None, export_symbols=None,
     672                        debug=0, extra_preargs=None, extra_postargs=None,
     673                        build_temp=None, target_lang=None):
    744674        self.link(CCompiler.SHARED_LIBRARY, objects,
    745675                  self.library_filename(output_libname, lib_type='shared'),
     
    750680
    751681
    752     def link_shared_object (self,
    753                             objects,
    754                             output_filename,
    755                             output_dir=None,
    756                             libraries=None,
    757                             library_dirs=None,
    758                             runtime_library_dirs=None,
    759                             export_symbols=None,
    760                             debug=0,
    761                             extra_preargs=None,
    762                             extra_postargs=None,
    763                             build_temp=None,
    764                             target_lang=None):
     682    def link_shared_object(self, objects, output_filename, output_dir=None,
     683                           libraries=None, library_dirs=None,
     684                           runtime_library_dirs=None, export_symbols=None,
     685                           debug=0, extra_preargs=None, extra_postargs=None,
     686                           build_temp=None, target_lang=None):
    765687        self.link(CCompiler.SHARED_OBJECT, objects,
    766688                  output_filename, output_dir,
     
    769691                  extra_preargs, extra_postargs, build_temp, target_lang)
    770692
    771 
    772     def link_executable (self,
    773                          objects,
    774                          output_progname,
    775                          output_dir=None,
    776                          libraries=None,
    777                          library_dirs=None,
    778                          runtime_library_dirs=None,
    779                          debug=0,
    780                          extra_preargs=None,
    781                          extra_postargs=None,
    782                          target_lang=None):
     693    def link_executable(self, objects, output_progname, output_dir=None,
     694                        libraries=None, library_dirs=None,
     695                        runtime_library_dirs=None, debug=0, extra_preargs=None,
     696                        extra_postargs=None, target_lang=None):
    783697        self.link(CCompiler.EXECUTABLE, objects,
    784698                  self.executable_filename(output_progname), output_dir,
     
    792706    # implement all of these.
    793707
    794     def library_dir_option (self, dir):
     708    def library_dir_option(self, dir):
    795709        """Return the compiler option to add 'dir' to the list of
    796710        directories searched for libraries.
     
    798712        raise NotImplementedError
    799713
    800     def runtime_library_dir_option (self, dir):
     714    def runtime_library_dir_option(self, dir):
    801715        """Return the compiler option to add 'dir' to the list of
    802716        directories searched for runtime libraries.
     
    804718        raise NotImplementedError
    805719
    806     def library_option (self, lib):
     720    def library_option(self, lib):
    807721        """Return the compiler option to add 'dir' to the list of libraries
    808722        linked into the shared library or executable.
     
    810724        raise NotImplementedError
    811725
    812     def has_function(self, funcname,
    813                      includes=None,
    814                      include_dirs=None,
    815                      libraries=None,
    816                      library_dirs=None):
     726    def has_function(self, funcname, includes=None, include_dirs=None,
     727                     libraries=None, library_dirs=None):
    817728        """Return a boolean indicating whether funcname is supported on
    818729        the current platform.  The optional arguments can be used to
     
    834745        fd, fname = tempfile.mkstemp(".c", funcname, text=True)
    835746        f = os.fdopen(fd, "w")
    836         for incl in includes:
    837             f.write("""#include "%s"\n""" % incl)
    838         f.write("""\
     747        try:
     748            for incl in includes:
     749                f.write("""#include "%s"\n""" % incl)
     750            f.write("""\
    839751main (int argc, char **argv) {
    840752    %s();
    841753}
    842754""" % funcname)
    843         f.close()
     755        finally:
     756            f.close()
    844757        try:
    845758            objects = self.compile([fname], include_dirs=include_dirs)
     
    945858    # -- Utility methods -----------------------------------------------
    946859
    947     def announce (self, msg, level=1):
     860    def announce(self, msg, level=1):
    948861        log.debug(msg)
    949862
    950     def debug_print (self, msg):
     863    def debug_print(self, msg):
    951864        from distutils.debug import DEBUG
    952865        if DEBUG:
    953866            print msg
    954867
    955     def warn (self, msg):
    956         sys.stderr.write ("warning: %s\n" % msg)
    957 
    958     def execute (self, func, args, msg=None, level=1):
     868    def warn(self, msg):
     869        sys.stderr.write("warning: %s\n" % msg)
     870
     871    def execute(self, func, args, msg=None, level=1):
    959872        execute(func, args, msg, self.dry_run)
    960873
    961     def spawn (self, cmd):
    962         spawn (cmd, dry_run=self.dry_run)
    963 
    964     def move_file (self, src, dst):
    965         return move_file (src, dst, dry_run=self.dry_run)
    966 
    967     def mkpath (self, name, mode=0777):
    968         mkpath (name, mode, dry_run=self.dry_run)
     874    def spawn(self, cmd):
     875        spawn(cmd, dry_run=self.dry_run)
     876
     877    def move_file(self, src, dst):
     878        return move_file(src, dst, dry_run=self.dry_run)
     879
     880    def mkpath(self, name, mode=0777):
     881        mkpath(name, mode, dry_run=self.dry_run)
    969882
    970883
     
    988901    ('posix', 'unix'),
    989902    ('nt', 'msvc'),
    990     ('mac', 'mwerks'),
    991903
    992904    )
    993905
    994906def get_default_compiler(osname=None, platform=None):
    995 
    996907    """ Determine the default compiler to use for the given platform.
    997908
     
    1028939                   'bcpp':    ('bcppcompiler', 'BCPPCompiler',
    1029940                               "Borland C++ Compiler"),
    1030                    'mwerks':  ('mwerkscompiler', 'MWerksCompiler',
    1031                                "MetroWerks CodeWarrior"),
    1032941                   'emx':     ('emxccompiler', 'EMXCCompiler',
    1033942                               "EMX port of GNU C Compiler for OS/2"),
     
    1051960
    1052961
    1053 def new_compiler (plat=None,
    1054                   compiler=None,
    1055                   verbose=0,
    1056                   dry_run=0,
    1057                   force=0):
     962def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):
    1058963    """Generate an instance of some CCompiler subclass for the supplied
    1059964    platform/compiler combination.  'plat' defaults to 'os.name'
     
    10971002    # with classes that expect verbose to be the first positional
    10981003    # argument.
    1099     return klass (None, dry_run, force)
    1100 
    1101 
    1102 def gen_preprocess_options (macros, include_dirs):
     1004    return klass(None, dry_run, force)
     1005
     1006
     1007def gen_preprocess_options(macros, include_dirs):
    11031008    """Generate C pre-processor options (-D, -U, -I) as used by at least
    11041009    two types of compilers: the typical Unix compiler and Visual C++.
     
    11251030    for macro in macros:
    11261031
    1127         if not (type (macro) is TupleType and
     1032        if not (isinstance(macro, tuple) and
    11281033                1 <= len (macro) <= 2):
    11291034            raise TypeError, \
     
    11481053    return pp_opts
    11491054
    1150 # gen_preprocess_options ()
    1151 
    1152 
    1153 def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
     1055
     1056def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
    11541057    """Generate linker options for searching library directories and
    1155     linking with specific libraries.  'libraries' and 'library_dirs' are,
    1156     respectively, lists of library names (not filenames!) and search
    1157     directories.  Returns a list of command-line options suitable for use
    1158     with some compiler (depending on the two format strings passed in).
     1058    linking with specific libraries.
     1059
     1060    'libraries' and 'library_dirs' are, respectively, lists of library names
     1061    (not filenames!) and search directories.  Returns a list of command-line
     1062    options suitable for use with some compiler (depending on the two format
     1063    strings passed in).
    11591064    """
    11601065    lib_opts = []
    11611066
    11621067    for dir in library_dirs:
    1163         lib_opts.append (compiler.library_dir_option (dir))
     1068        lib_opts.append(compiler.library_dir_option(dir))
    11641069
    11651070    for dir in runtime_library_dirs:
    1166         opt = compiler.runtime_library_dir_option (dir)
    1167         if type(opt) is ListType:
    1168             lib_opts = lib_opts + opt
     1071        opt = compiler.runtime_library_dir_option(dir)
     1072        if isinstance(opt, list):
     1073            lib_opts.extend(opt)
    11691074        else:
    1170             lib_opts.append (opt)
     1075            lib_opts.append(opt)
    11711076
    11721077    # XXX it's important that we *not* remove redundant library mentions!
     
    11771082
    11781083    for lib in libraries:
    1179         (lib_dir, lib_name) = os.path.split (lib)
    1180         if lib_dir:
    1181             lib_file = compiler.find_library_file ([lib_dir], lib_name)
    1182             if lib_file:
    1183                 lib_opts.append (lib_file)
     1084        lib_dir, lib_name = os.path.split(lib)
     1085        if lib_dir != '':
     1086            lib_file = compiler.find_library_file([lib_dir], lib_name)
     1087            if lib_file is not None:
     1088                lib_opts.append(lib_file)
    11841089            else:
    1185                 compiler.warn ("no library file corresponding to "
    1186                                "'%s' found (skipping)" % lib)
     1090                compiler.warn("no library file corresponding to "
     1091                              "'%s' found (skipping)" % lib)
    11871092        else:
    1188             lib_opts.append (compiler.library_option (lib))
     1093            lib_opts.append(compiler.library_option(lib))
    11891094
    11901095    return lib_opts
    1191 
    1192 # gen_lib_options ()
  • python/vendor/current/Lib/distutils/cmd.py

    r2 r388  
    55"""
    66
    7 # This module should be kept compatible with Python 2.1.
    8 
    9 __revision__ = "$Id: cmd.py 37828 2004-11-10 22:23:15Z loewis $"
    10 
    11 import sys, os, string, re
    12 from types import *
    13 from distutils.errors import *
     7__revision__ = "$Id$"
     8
     9import sys, os, re
     10from distutils.errors import DistutilsOptionError
    1411from distutils import util, dir_util, file_util, archive_util, dep_util
    1512from distutils import log
     
    5047    # -- Creation/initialization methods -------------------------------
    5148
    52     def __init__ (self, dist):
     49    def __init__(self, dist):
    5350        """Create and initialize a new Command object.  Most importantly,
    5451        invokes the 'initialize_options()' method, which is the real
     
    9794        self.finalized = 0
    9895
    99     # __init__ ()
    100 
    101 
    10296    # XXX A more explicit way to customize dry_run would be better.
    103 
    104     def __getattr__ (self, attr):
     97    def __getattr__(self, attr):
    10598        if attr == 'dry_run':
    10699            myval = getattr(self, "_" + attr)
     
    112105            raise AttributeError, attr
    113106
    114 
    115     def ensure_finalized (self):
     107    def ensure_finalized(self):
    116108        if not self.finalized:
    117109            self.finalize_options()
    118110        self.finalized = 1
    119 
    120111
    121112    # Subclasses must define:
     
    132123    #     controlled by the command's various option values
    133124
    134     def initialize_options (self):
     125    def initialize_options(self):
    135126        """Set default values for all the options that this command
    136127        supports.  Note that these defaults may be overridden by other
     
    145136              "abstract method -- subclass %s must override" % self.__class__
    146137
    147     def finalize_options (self):
     138    def finalize_options(self):
    148139        """Set final values for all the options that this command supports.
    149140        This is always called as late as possible, ie.  after any option
     
    160151
    161152
    162     def dump_options (self, header=None, indent=""):
     153    def dump_options(self, header=None, indent=""):
    163154        from distutils.fancy_getopt import longopt_xlate
    164155        if header is None:
    165156            header = "command options for '%s':" % self.get_command_name()
    166         print indent + header
     157        self.announce(indent + header, level=log.INFO)
    167158        indent = indent + "  "
    168159        for (option, _, _) in self.user_options:
    169             option = string.translate(option, longopt_xlate)
     160            option = option.translate(longopt_xlate)
    170161            if option[-1] == "=":
    171162                option = option[:-1]
    172163            value = getattr(self, option)
    173             print indent + "%s = %s" % (option, value)
    174 
    175 
    176     def run (self):
     164            self.announce(indent + "%s = %s" % (option, value),
     165                          level=log.INFO)
     166
     167    def run(self):
    177168        """A command's raison d'etre: carry out the action it exists to
    178169        perform, controlled by the options initialized in
     
    184175        This method must be implemented by all command classes.
    185176        """
    186 
    187177        raise RuntimeError, \
    188178              "abstract method -- subclass %s must override" % self.__class__
    189179
    190     def announce (self, msg, level=1):
     180    def announce(self, msg, level=1):
    191181        """If the current verbosity level is of greater than or equal to
    192182        'level' print 'msg' to stdout.
     
    194184        log.log(level, msg)
    195185
    196     def debug_print (self, msg):
     186    def debug_print(self, msg):
    197187        """Print 'msg' to stdout if the global DEBUG (taken from the
    198188        DISTUTILS_DEBUG environment variable) flag is true.
     
    202192            print msg
    203193            sys.stdout.flush()
    204 
    205194
    206195
     
    218207    # a list of strings.
    219208
    220     def _ensure_stringlike (self, option, what, default=None):
     209    def _ensure_stringlike(self, option, what, default=None):
    221210        val = getattr(self, option)
    222211        if val is None:
    223212            setattr(self, option, default)
    224213            return default
    225         elif type(val) is not StringType:
     214        elif not isinstance(val, str):
    226215            raise DistutilsOptionError, \
    227216                  "'%s' must be a %s (got `%s`)" % (option, what, val)
    228217        return val
    229218
    230     def ensure_string (self, option, default=None):
     219    def ensure_string(self, option, default=None):
    231220        """Ensure that 'option' is a string; if not defined, set it to
    232221        'default'.
     
    234223        self._ensure_stringlike(option, "string", default)
    235224
    236     def ensure_string_list (self, option):
     225    def ensure_string_list(self, option):
    237226        """Ensure that 'option' is a list of strings.  If 'option' is
    238227        currently a string, we split it either on /,\s*/ or /\s+/, so
     
    243232        if val is None:
    244233            return
    245         elif type(val) is StringType:
     234        elif isinstance(val, str):
    246235            setattr(self, option, re.split(r',\s*|\s+', val))
    247236        else:
    248             if type(val) is ListType:
    249                 types = map(type, val)
    250                 ok = (types == [StringType] * len(val))
     237            if isinstance(val, list):
     238                # checks if all elements are str
     239                ok = 1
     240                for element in val:
     241                    if not isinstance(element, str):
     242                        ok = 0
     243                        break
    251244            else:
    252245                ok = 0
     
    254247            if not ok:
    255248                raise DistutilsOptionError, \
    256                       "'%s' must be a list of strings (got %r)" % \
    257                       (option, val)
    258 
    259     def _ensure_tested_string (self, option, tester,
    260                                what, error_fmt, default=None):
     249                    "'%s' must be a list of strings (got %r)" % \
     250                        (option, val)
     251
     252
     253    def _ensure_tested_string(self, option, tester,
     254                              what, error_fmt, default=None):
    261255        val = self._ensure_stringlike(option, what, default)
    262256        if val is not None and not tester(val):
     
    264258                  ("error in '%s' option: " + error_fmt) % (option, val)
    265259
    266     def ensure_filename (self, option):
     260    def ensure_filename(self, option):
    267261        """Ensure that 'option' is the name of an existing file."""
    268262        self._ensure_tested_string(option, os.path.isfile,
     
    270264                                   "'%s' does not exist or is not a file")
    271265
    272     def ensure_dirname (self, option):
     266    def ensure_dirname(self, option):
    273267        self._ensure_tested_string(option, os.path.isdir,
    274268                                   "directory name",
     
    278272    # -- Convenience methods for commands ------------------------------
    279273
    280     def get_command_name (self):
     274    def get_command_name(self):
    281275        if hasattr(self, 'command_name'):
    282276            return self.command_name
     
    284278            return self.__class__.__name__
    285279
    286 
    287     def set_undefined_options (self, src_cmd, *option_pairs):
     280    def set_undefined_options(self, src_cmd, *option_pairs):
    288281        """Set the values of any "undefined" options from corresponding
    289282        option values in some other command object.  "Undefined" here means
     
    310303
    311304
    312     def get_finalized_command (self, command, create=1):
     305    def get_finalized_command(self, command, create=1):
    313306        """Wrapper around Distribution's 'get_command_obj()' method: find
    314307        (create if necessary and 'create' is true) the command object for
     
    322315    # XXX rename to 'get_reinitialized_command()'? (should do the
    323316    # same in dist.py, if so)
    324     def reinitialize_command (self, command, reinit_subcommands=0):
     317    def reinitialize_command(self, command, reinit_subcommands=0):
    325318        return self.distribution.reinitialize_command(
    326319            command, reinit_subcommands)
    327320
    328     def run_command (self, command):
     321    def run_command(self, command):
    329322        """Run some other command: uses the 'run_command()' method of
    330323        Distribution, which creates and finalizes the command object if
     
    333326        self.distribution.run_command(command)
    334327
    335 
    336     def get_sub_commands (self):
     328    def get_sub_commands(self):
    337329        """Determine the sub-commands that are relevant in the current
    338330        distribution (ie., that need to be run).  This is based on the
     
    350342    # -- External world manipulation -----------------------------------
    351343
    352     def warn (self, msg):
    353         sys.stderr.write("warning: %s: %s\n" %
    354                          (self.get_command_name(), msg))
    355 
    356 
    357     def execute (self, func, args, msg=None, level=1):
     344    def warn(self, msg):
     345        log.warn("warning: %s: %s\n" %
     346                (self.get_command_name(), msg))
     347
     348    def execute(self, func, args, msg=None, level=1):
    358349        util.execute(func, args, msg, dry_run=self.dry_run)
    359350
    360 
    361     def mkpath (self, name, mode=0777):
     351    def mkpath(self, name, mode=0777):
    362352        dir_util.mkpath(name, mode, dry_run=self.dry_run)
    363353
    364 
    365     def copy_file (self, infile, outfile,
     354    def copy_file(self, infile, outfile,
    366355                   preserve_mode=1, preserve_times=1, link=None, level=1):
    367356        """Copy a file respecting verbose, dry-run and force flags.  (The
     
    376365            dry_run=self.dry_run)
    377366
    378 
    379     def copy_tree (self, infile, outfile,
     367    def copy_tree(self, infile, outfile,
    380368                   preserve_mode=1, preserve_times=1, preserve_symlinks=0,
    381369                   level=1):
     
    390378
    391379    def move_file (self, src, dst, level=1):
    392         """Move a file respectin dry-run flag."""
     380        """Move a file respecting dry-run flag."""
    393381        return file_util.move_file(src, dst, dry_run = self.dry_run)
    394382
     
    398386        spawn(cmd, search_path, dry_run= self.dry_run)
    399387
    400     def make_archive (self, base_name, format,
    401                       root_dir=None, base_dir=None):
    402         return archive_util.make_archive(
    403             base_name, format, root_dir, base_dir, dry_run=self.dry_run)
    404 
    405 
    406     def make_file (self, infiles, outfile, func, args,
    407                    exec_msg=None, skip_msg=None, level=1):
     388    def make_archive(self, base_name, format, root_dir=None, base_dir=None,
     389                     owner=None, group=None):
     390        return archive_util.make_archive(base_name, format, root_dir,
     391                                         base_dir, dry_run=self.dry_run,
     392                                         owner=owner, group=group)
     393
     394    def make_file(self, infiles, outfile, func, args,
     395                  exec_msg=None, skip_msg=None, level=1):
    408396        """Special case of 'execute()' for operations that process one or
    409397        more input files and generate one output file.  Works just like
     
    414402        timestamp checks.
    415403        """
     404        if skip_msg is None:
     405            skip_msg = "skipping %s (inputs unchanged)" % outfile
     406
     407        # Allow 'infiles' to be a single string
     408        if isinstance(infiles, str):
     409            infiles = (infiles,)
     410        elif not isinstance(infiles, (list, tuple)):
     411            raise TypeError, \
     412                  "'infiles' must be a string, or a list or tuple of strings"
     413
    416414        if exec_msg is None:
    417415            exec_msg = "generating %s from %s" % \
    418                        (outfile, string.join(infiles, ', '))
    419         if skip_msg is None:
    420             skip_msg = "skipping %s (inputs unchanged)" % outfile
    421 
    422 
    423         # Allow 'infiles' to be a single string
    424         if type(infiles) is StringType:
    425             infiles = (infiles,)
    426         elif type(infiles) not in (ListType, TupleType):
    427             raise TypeError, \
    428                   "'infiles' must be a string, or a list or tuple of strings"
     416                       (outfile, ', '.join(infiles))
    429417
    430418        # If 'outfile' must be regenerated (either because it doesn't
    431419        # exist, is out-of-date, or the 'force' flag is true) then
    432420        # perform the action that presumably regenerates it
    433         if self.force or dep_util.newer_group (infiles, outfile):
     421        if self.force or dep_util.newer_group(infiles, outfile):
    434422            self.execute(func, args, exec_msg, level)
    435423
     
    437425        else:
    438426            log.debug(skip_msg)
    439 
    440     # make_file ()
    441 
    442 # class Command
    443 
    444427
    445428# XXX 'install_misc' class not currently used -- it was the base class for
     
    448431# for the time being.
    449432
    450 class install_misc (Command):
     433class install_misc(Command):
    451434    """Common base class for installing some files in a subdirectory.
    452435    Currently used by install_data and install_scripts.
     
    459442        self.outfiles = []
    460443
    461     def _install_dir_from (self, dirname):
     444    def _install_dir_from(self, dirname):
    462445        self.set_undefined_options('install', (dirname, 'install_dir'))
    463446
    464     def _copy_files (self, filelist):
     447    def _copy_files(self, filelist):
    465448        self.outfiles = []
    466449        if not filelist:
     
    471454            self.outfiles.append(os.path.join(self.install_dir, f))
    472455
    473     def get_outputs (self):
     456    def get_outputs(self):
    474457        return self.outfiles
    475 
    476 
    477 if __name__ == "__main__":
    478     print "ok"
  • python/vendor/current/Lib/distutils/command/__init__.py

    r2 r388  
    44commands."""
    55
    6 # This module should be kept compatible with Python 2.1.
    7 
    8 __revision__ = "$Id: __init__.py 71272 2009-04-05 21:21:05Z georg.brandl $"
     6__revision__ = "$Id$"
    97
    108__all__ = ['build',
     
    2624           'bdist_wininst',
    2725           'upload',
    28 
     26           'check',
    2927           # These two are reserved for future use:
    3028           #'bdist_sdux',
  • python/vendor/current/Lib/distutils/command/bdist.py

    r2 r388  
    44distribution)."""
    55
    6 # This module should be kept compatible with Python 2.1.
    7 
    8 __revision__ = "$Id: bdist.py 62197 2008-04-07 01:53:39Z mark.hammond $"
     6__revision__ = "$Id$"
    97
    108import os
    11 from types import *
     9
     10from distutils.util import get_platform
    1211from distutils.core import Command
    13 from distutils.errors import *
    14 from distutils.util import get_platform
     12from distutils.errors import DistutilsPlatformError, DistutilsOptionError
    1513
    1614
    17 def show_formats ():
     15def show_formats():
    1816    """Print list of available formats (arguments to "--format" option).
    1917    """
    2018    from distutils.fancy_getopt import FancyGetopt
    21     formats=[]
     19    formats = []
    2220    for format in bdist.format_commands:
    2321        formats.append(("formats=" + format, None,
     
    2725
    2826
    29 class bdist (Command):
     27class bdist(Command):
    3028
    3129    description = "create a built (binary) distribution"
     
    4341                    ('skip-build', None,
    4442                     "skip rebuilding everything (for testing/debugging)"),
     43                    ('owner=', 'u',
     44                     "Owner name used when creating a tar file"
     45                     " [default: current user]"),
     46                    ('group=', 'g',
     47                     "Group name used when creating a tar file"
     48                     " [default: current group]"),
    4549                   ]
    4650
     
    5357
    5458    # The following commands do not take a format option from bdist
    55     no_format_option = ('bdist_rpm',
    56                         #'bdist_sdux', 'bdist_pkgtool'
    57                         )
     59    no_format_option = ('bdist_rpm',)
    5860
    5961    # This won't do in reality: will need to distinguish RPM-ish Linux,
    6062    # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.
    61     default_format = { 'posix': 'gztar',
    62                        'nt': 'zip',
    63                        'os2': 'zip', }
     63    default_format = {'posix': 'gztar',
     64                      'nt': 'zip',
     65                      'os2': 'zip'}
    6466
    6567    # Establish the preferred order (for the --help-formats option).
    6668    format_commands = ['rpm', 'gztar', 'bztar', 'ztar', 'tar',
    67                        'wininst', 'zip',
    68                        #'pkgtool', 'sdux'
    69                        ]
     69                       'wininst', 'zip', 'msi']
    7070
    7171    # And the real information.
    72     format_command = { 'rpm':   ('bdist_rpm',  "RPM distribution"),
    73                        'zip':   ('bdist_dumb', "ZIP file"),
    74                        'gztar': ('bdist_dumb', "gzip'ed tar file"),
    75                        'bztar': ('bdist_dumb', "bzip2'ed tar file"),
    76                        'ztar':  ('bdist_dumb', "compressed tar file"),
    77                        'tar':   ('bdist_dumb', "tar file"),
    78                        'wininst': ('bdist_wininst',
    79                                    "Windows executable installer"),
    80                        'zip':   ('bdist_dumb', "ZIP file"),
    81                        #'pkgtool': ('bdist_pkgtool',
    82                        #            "Solaris pkgtool distribution"),
    83                        #'sdux':  ('bdist_sdux', "HP-UX swinstall depot"),
     72    format_command = {'rpm':   ('bdist_rpm',  "RPM distribution"),
     73                      'gztar': ('bdist_dumb', "gzip'ed tar file"),
     74                      'bztar': ('bdist_dumb', "bzip2'ed tar file"),
     75                      'ztar':  ('bdist_dumb', "compressed tar file"),
     76                      'tar':   ('bdist_dumb', "tar file"),
     77                      'wininst': ('bdist_wininst',
     78                                  "Windows executable installer"),
     79                      'zip':   ('bdist_dumb', "ZIP file"),
     80                      'msi':   ('bdist_msi',  "Microsoft Installer")
    8481                      }
    8582
    8683
    87     def initialize_options (self):
     84    def initialize_options(self):
    8885        self.bdist_base = None
    8986        self.plat_name = None
     
    9188        self.dist_dir = None
    9289        self.skip_build = 0
     90        self.group = None
     91        self.owner = None
    9392
    94     # initialize_options()
    95 
    96 
    97     def finalize_options (self):
     93    def finalize_options(self):
    9894        # have to finalize 'plat_name' before 'bdist_base'
    9995        if self.plat_name is None:
     
    123119            self.dist_dir = "dist"
    124120
    125     # finalize_options()
    126 
    127     def run (self):
    128 
     121    def run(self):
    129122        # Figure out which sub-commands we need to run.
    130123        commands = []
     
    142135                sub_cmd.format = self.formats[i]
    143136
     137            # passing the owner and group names for tar archiving
     138            if cmd_name == 'bdist_dumb':
     139                sub_cmd.owner = self.owner
     140                sub_cmd.group = self.group
     141
    144142            # If we're going to need to run this command again, tell it to
    145143            # keep its temporary files around so subsequent runs go faster.
     
    147145                sub_cmd.keep_temp = 1
    148146            self.run_command(cmd_name)
    149 
    150     # run()
    151 
    152 # class bdist
  • python/vendor/current/Lib/distutils/command/bdist_dumb.py

    r2 r388  
    55$exec_prefix)."""
    66
    7 # This module should be kept compatible with Python 2.1.
    8 
    9 __revision__ = "$Id: bdist_dumb.py 61000 2008-02-23 17:40:11Z christian.heimes $"
     7__revision__ = "$Id$"
    108
    119import os
     10
     11from sysconfig import get_python_version
     12
     13from distutils.util import get_platform
    1214from distutils.core import Command
    13 from distutils.util import get_platform
    1415from distutils.dir_util import remove_tree, ensure_relative
    15 from distutils.errors import *
    16 from distutils.sysconfig import get_python_version
     16from distutils.errors import DistutilsPlatformError
    1717from distutils import log
    1818
    1919class bdist_dumb (Command):
    2020
    21     description = "create a \"dumb\" built distribution"
     21    description = 'create a "dumb" built distribution'
    2222
    2323    user_options = [('bdist-dir=', 'd',
     
    3838                     "build the archive using relative paths"
    3939                     "(default: false)"),
     40                    ('owner=', 'u',
     41                     "Owner name used when creating a tar file"
     42                     " [default: current user]"),
     43                    ('group=', 'g',
     44                     "Group name used when creating a tar file"
     45                     " [default: current group]"),
    4046                   ]
    4147
     
    5359        self.keep_temp = 0
    5460        self.dist_dir = None
    55         self.skip_build = 0
     61        self.skip_build = None
    5662        self.relative = 0
     63        self.owner = None
     64        self.group = None
    5765
    58     # initialize_options()
    59 
    60 
    61     def finalize_options (self):
    62 
     66    def finalize_options(self):
    6367        if self.bdist_dir is None:
    6468            bdist_base = self.get_finalized_command('bdist').bdist_base
     
    7579        self.set_undefined_options('bdist',
    7680                                   ('dist_dir', 'dist_dir'),
    77                                    ('plat_name', 'plat_name'))
     81                                   ('plat_name', 'plat_name'),
     82                                   ('skip_build', 'skip_build'))
    7883
    79     # finalize_options()
    80 
    81 
    82     def run (self):
    83 
     84    def run(self):
    8485        if not self.skip_build:
    8586            self.run_command('build')
     
    120121        # Make the archive
    121122        filename = self.make_archive(pseudoinstall_root,
    122                                      self.format, root_dir=archive_root)
     123                                     self.format, root_dir=archive_root,
     124                                     owner=self.owner, group=self.group)
    123125        if self.distribution.has_ext_modules():
    124126            pyversion = get_python_version()
     
    130132        if not self.keep_temp:
    131133            remove_tree(self.bdist_dir, dry_run=self.dry_run)
    132 
    133     # run()
    134 
    135 # class bdist_dumb
  • python/vendor/current/Lib/distutils/command/bdist_msi.py

    r2 r388  
    11# -*- coding: iso-8859-1 -*-
    2 # Copyright (C) 2005, 2006 Martin v. Löwis
     2# Copyright (C) 2005, 2006 Martin von Löwis
    33# Licensed to PSF under a Contributor Agreement.
    44# The bdist_wininst command proper
     
    77Implements the bdist_msi command.
    88"""
    9 
    109import sys, os
     10from sysconfig import get_python_version
     11
    1112from distutils.core import Command
    1213from distutils.dir_util import remove_tree
    13 from distutils.sysconfig import get_python_version
    1414from distutils.version import StrictVersion
    1515from distutils.errors import DistutilsOptionError
     16from distutils import log
    1617from distutils.util import get_platform
    17 from distutils import log
     18
    1819import msilib
    1920from msilib import schema, sequence, text
     
    2930        Dialog.__init__(self, *args)
    3031        ruler = self.h - 36
    31         bmwidth = 152*ruler/328
    3232        #if kw.get("bitmap", True):
    3333        #    self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin")
     
    118118                       'skip-build']
    119119
     120    all_versions = ['2.0', '2.1', '2.2', '2.3', '2.4',
     121                    '2.5', '2.6', '2.7', '2.8', '2.9',
     122                    '3.0', '3.1', '3.2', '3.3', '3.4',
     123                    '3.5', '3.6', '3.7', '3.8', '3.9']
     124    other_version = 'X'
     125
    120126    def initialize_options (self):
    121127        self.bdist_dir = None
     
    126132        self.target_version = None
    127133        self.dist_dir = None
    128         self.skip_build = 0
     134        self.skip_build = None
    129135        self.install_script = None
    130136        self.pre_install_script = None
     137        self.versions = None
    131138
    132139    def finalize_options (self):
     140        self.set_undefined_options('bdist', ('skip_build', 'skip_build'))
     141
    133142        if self.bdist_dir is None:
    134143            bdist_base = self.get_finalized_command('bdist').bdist_base
    135144            self.bdist_dir = os.path.join(bdist_base, 'msi')
     145
    136146        short_version = get_python_version()
     147        if (not self.target_version) and self.distribution.has_ext_modules():
     148            self.target_version = short_version
     149
    137150        if self.target_version:
     151            self.versions = [self.target_version]
    138152            if not self.skip_build and self.distribution.has_ext_modules()\
    139153               and self.target_version != short_version:
    140154                raise DistutilsOptionError, \
    141                       "target version can only be %s, or the '--skip_build'" \
     155                      "target version can only be %s, or the '--skip-build'" \
    142156                      " option must be specified" % (short_version,)
    143157        else:
    144             self.target_version = short_version
     158            self.versions = list(self.all_versions)
    145159
    146160        self.set_undefined_options('bdist',
     
    224238        # it sorts together with the other Python packages
    225239        # in Add-Remove-Programs (APR)
    226         product_name = "Python %s %s" % (self.target_version,
    227                        self.distribution.get_fullname())
     240        fullname = self.distribution.get_fullname()
     241        if self.target_version:
     242            product_name = "Python %s %s" % (self.target_version, fullname)
     243        else:
     244            product_name = "Python %s" % (fullname)
    228245        self.db = msilib.init_database(installer_name, schema,
    229246                product_name, msilib.gen_uuid(),
     
    246263
    247264        if hasattr(self.distribution, 'dist_files'):
    248             self.distribution.dist_files.append(('bdist_msi', self.target_version, fullname))
     265            tup = 'bdist_msi', self.target_version or 'any', fullname
     266            self.distribution.dist_files.append(tup)
    249267
    250268        if not self.keep_temp:
     
    254272        db = self.db
    255273        cab = msilib.CAB("distfiles")
    256         f = Feature(db, "default", "Default Feature", "Everything", 1, directory="TARGETDIR")
    257         f.set_current()
    258274        rootdir = os.path.abspath(self.bdist_dir)
     275
    259276        root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir")
     277        f = Feature(db, "Python", "Python", "Everything",
     278                    0, 1, directory="TARGETDIR")
     279
     280        items = [(f, root, '')]
     281        for version in self.versions + [self.other_version]:
     282            target = "TARGETDIR" + version
     283            name = default = "Python" + version
     284            desc = "Everything"
     285            if version is self.other_version:
     286                title = "Python from another location"
     287                level = 2
     288            else:
     289                title = "Python %s from registry" % version
     290                level = 1
     291            f = Feature(db, name, title, desc, 1, level, directory=target)
     292            dir = Directory(db, cab, root, rootdir, target, default)
     293            items.append((f, dir, version))
    260294        db.Commit()
    261         todo = [root]
    262         while todo:
    263             dir = todo.pop()
    264             for file in os.listdir(dir.absolute):
    265                 afile = os.path.join(dir.absolute, file)
    266                 if os.path.isdir(afile):
    267                     newdir = Directory(db, cab, dir, file, file, "%s|%s" % (dir.make_short(file), file))
    268                     todo.append(newdir)
    269                 else:
    270                     key = dir.add_file(file)
    271                     if file==self.install_script:
    272                         if self.install_script_key:
    273                             raise DistutilsOptionError, "Multiple files with name %s" % file
    274                         self.install_script_key = '[#%s]' % key
    275 
     295
     296        seen = {}
     297        for feature, dir, version in items:
     298            todo = [dir]
     299            while todo:
     300                dir = todo.pop()
     301                for file in os.listdir(dir.absolute):
     302                    afile = os.path.join(dir.absolute, file)
     303                    if os.path.isdir(afile):
     304                        short = "%s|%s" % (dir.make_short(file), file)
     305                        default = file + version
     306                        newdir = Directory(db, cab, dir, file, default, short)
     307                        todo.append(newdir)
     308                    else:
     309                        if not dir.component:
     310                            dir.start_component(dir.logical, feature, 0)
     311                        if afile not in seen:
     312                            key = seen[afile] = dir.add_file(file)
     313                            if file==self.install_script:
     314                                if self.install_script_key:
     315                                    raise DistutilsOptionError(
     316                                          "Multiple files with name %s" % file)
     317                                self.install_script_key = '[#%s]' % key
     318                        else:
     319                            key = seen[afile]
     320                            add_data(self.db, "DuplicateFile",
     321                                [(key + version, dir.component, key, None, dir.logical)])
     322            db.Commit()
    276323        cab.commit(db)
    277324
    278325    def add_find_python(self):
    279326        """Adds code to the installer to compute the location of Python.
    280         Properties PYTHON.MACHINE, PYTHON.USER, PYTHONDIR and PYTHON will be set
    281         in both the execute and UI sequences; PYTHONDIR will be set from
    282         PYTHON.USER if defined, else from PYTHON.MACHINE.
    283         PYTHON is PYTHONDIR\python.exe"""
    284         install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % self.target_version
    285         if msilib.Win64:
    286             # type: msidbLocatorTypeRawValue + msidbLocatorType64bit
    287             Type = 2+16
    288         else:
    289             Type = 2
    290         add_data(self.db, "RegLocator",
    291                 [("python.machine", 2, install_path, None, Type),
    292                  ("python.user", 1, install_path, None, Type)])
    293         add_data(self.db, "AppSearch",
    294                 [("PYTHON.MACHINE", "python.machine"),
    295                  ("PYTHON.USER", "python.user")])
    296         add_data(self.db, "CustomAction",
    297                 [("PythonFromMachine", 51+256, "PYTHONDIR", "[PYTHON.MACHINE]"),
    298                  ("PythonFromUser", 51+256, "PYTHONDIR", "[PYTHON.USER]"),
    299                  ("PythonExe", 51+256, "PYTHON", "[PYTHONDIR]\\python.exe"),
    300                  ("InitialTargetDir", 51+256, "TARGETDIR", "[PYTHONDIR]")])
    301         add_data(self.db, "InstallExecuteSequence",
    302                 [("PythonFromMachine", "PYTHON.MACHINE", 401),
    303                  ("PythonFromUser", "PYTHON.USER", 402),
    304                  ("PythonExe", None, 403),
    305                  ("InitialTargetDir", 'TARGETDIR=""', 404),
    306                 ])
    307         add_data(self.db, "InstallUISequence",
    308                 [("PythonFromMachine", "PYTHON.MACHINE", 401),
    309                  ("PythonFromUser", "PYTHON.USER", 402),
    310                  ("PythonExe", None, 403),
    311                  ("InitialTargetDir", 'TARGETDIR=""', 404),
    312                 ])
     327
     328        Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the
     329        registry for each version of Python.
     330
     331        Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined,
     332        else from PYTHON.MACHINE.X.Y.
     333
     334        Properties PYTHONX.Y will be set to TARGETDIRX.Y\\python.exe"""
     335
     336        start = 402
     337        for ver in self.versions:
     338            install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver
     339            machine_reg = "python.machine." + ver
     340            user_reg = "python.user." + ver
     341            machine_prop = "PYTHON.MACHINE." + ver
     342            user_prop = "PYTHON.USER." + ver
     343            machine_action = "PythonFromMachine" + ver
     344            user_action = "PythonFromUser" + ver
     345            exe_action = "PythonExe" + ver
     346            target_dir_prop = "TARGETDIR" + ver
     347            exe_prop = "PYTHON" + ver
     348            if msilib.Win64:
     349                # type: msidbLocatorTypeRawValue + msidbLocatorType64bit
     350                Type = 2+16
     351            else:
     352                Type = 2
     353            add_data(self.db, "RegLocator",
     354                    [(machine_reg, 2, install_path, None, Type),
     355                     (user_reg, 1, install_path, None, Type)])
     356            add_data(self.db, "AppSearch",
     357                    [(machine_prop, machine_reg),
     358                     (user_prop, user_reg)])
     359            add_data(self.db, "CustomAction",
     360                    [(machine_action, 51+256, target_dir_prop, "[" + machine_prop + "]"),
     361                     (user_action, 51+256, target_dir_prop, "[" + user_prop + "]"),
     362                     (exe_action, 51+256, exe_prop, "[" + target_dir_prop + "]\\python.exe"),
     363                    ])
     364            add_data(self.db, "InstallExecuteSequence",
     365                    [(machine_action, machine_prop, start),
     366                     (user_action, user_prop, start + 1),
     367                     (exe_action, None, start + 2),
     368                    ])
     369            add_data(self.db, "InstallUISequence",
     370                    [(machine_action, machine_prop, start),
     371                     (user_action, user_prop, start + 1),
     372                     (exe_action, None, start + 2),
     373                    ])
     374            add_data(self.db, "Condition",
     375                    [("Python" + ver, 0, "NOT TARGETDIR" + ver)])
     376            start += 4
     377            assert start < 500
    313378
    314379    def add_scripts(self):
    315380        if self.install_script:
    316             add_data(self.db, "CustomAction",
    317                     [("install_script", 50, "PYTHON", self.install_script_key)])
    318             add_data(self.db, "InstallExecuteSequence",
    319                     [("install_script", "NOT Installed", 6800)])
     381            start = 6800
     382            for ver in self.versions + [self.other_version]:
     383                install_action = "install_script." + ver
     384                exe_prop = "PYTHON" + ver
     385                add_data(self.db, "CustomAction",
     386                        [(install_action, 50, exe_prop, self.install_script_key)])
     387                add_data(self.db, "InstallExecuteSequence",
     388                        [(install_action, "&Python%s=3" % ver, start)])
     389                start += 1
     390        # XXX pre-install scripts are currently refused in finalize_options()
     391        #     but if this feature is completed, it will also need to add
     392        #     entries for each version as the above code does
    320393        if self.pre_install_script:
    321394            scriptfn = os.path.join(self.bdist_dir, "preinstall.bat")
     
    352425        modal = 3      # visible | modal
    353426        modeless = 1   # visible
    354         track_disk_space = 32
    355427
    356428        # UI customization properties
     
    381453                  ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141),
    382454                  # In the user interface, assume all-users installation if privileged.
    383                   ("SelectDirectoryDlg", "Not Installed", 1230),
     455                  ("SelectFeaturesDlg", "Not Installed", 1230),
    384456                  # XXX no support for resume installations yet
    385457                  #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240),
     
    504576
    505577        #####################################################################
    506         # Target directory selection
    507         seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title,
     578        # Feature (Python directory) selection
     579        seldlg = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal, title,
    508580                        "Next", "Next", "Cancel")
    509         seldlg.title("Select Destination Directory")
    510 
    511         version = sys.version[:3]+" "
    512         seldlg.text("Hint", 15, 30, 300, 40, 3,
    513                 "The destination directory should contain a Python %sinstallation" % version)
     581        seldlg.title("Select Python Installations")
     582
     583        seldlg.text("Hint", 15, 30, 300, 20, 3,
     584                    "Select the Python locations where %s should be installed."
     585                    % self.distribution.get_fullname())
    514586
    515587        seldlg.back("< Back", None, active=0)
    516588        c = seldlg.next("Next >", "Cancel")
    517         c.event("SetTargetPath", "TARGETDIR", ordering=1)
    518         c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=2)
    519         c.event("EndDialog", "Return", ordering=3)
    520 
    521         c = seldlg.cancel("Cancel", "DirectoryCombo")
     589        order = 1
     590        c.event("[TARGETDIR]", "[SourceDir]", ordering=order)
     591        for version in self.versions + [self.other_version]:
     592            order += 1
     593            c.event("[TARGETDIR]", "[TARGETDIR%s]" % version,
     594                    "FEATURE_SELECTED AND &Python%s=3" % version,
     595                    ordering=order)
     596        c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=order + 1)
     597        c.event("EndDialog", "Return", ordering=order + 2)
     598        c = seldlg.cancel("Cancel", "Features")
    522599        c.event("SpawnDialog", "CancelDlg")
    523600
    524         seldlg.control("DirectoryCombo", "DirectoryCombo", 15, 70, 272, 80, 393219,
    525                        "TARGETDIR", None, "DirectoryList", None)
    526         seldlg.control("DirectoryList", "DirectoryList", 15, 90, 308, 136, 3, "TARGETDIR",
    527                        None, "PathEdit", None)
    528         seldlg.control("PathEdit", "PathEdit", 15, 230, 306, 16, 3, "TARGETDIR", None, "Next", None)
    529         c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None)
    530         c.event("DirectoryListUp", "0")
    531         c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None)
    532         c.event("DirectoryListNew", "0")
     601        c = seldlg.control("Features", "SelectionTree", 15, 60, 300, 120, 3,
     602                           "FEATURE", None, "PathEdit", None)
     603        c.event("[FEATURE_SELECTED]", "1")
     604        ver = self.other_version
     605        install_other_cond = "FEATURE_SELECTED AND &Python%s=3" % ver
     606        dont_install_other_cond = "FEATURE_SELECTED AND &Python%s<>3" % ver
     607
     608        c = seldlg.text("Other", 15, 200, 300, 15, 3,
     609                        "Provide an alternate Python location")
     610        c.condition("Enable", install_other_cond)
     611        c.condition("Show", install_other_cond)
     612        c.condition("Disable", dont_install_other_cond)
     613        c.condition("Hide", dont_install_other_cond)
     614
     615        c = seldlg.control("PathEdit", "PathEdit", 15, 215, 300, 16, 1,
     616                           "TARGETDIR" + ver, None, "Next", None)
     617        c.condition("Enable", install_other_cond)
     618        c.condition("Show", install_other_cond)
     619        c.condition("Disable", dont_install_other_cond)
     620        c.condition("Hide", dont_install_other_cond)
    533621
    534622        #####################################################################
     
    646734    def get_installer_filename(self, fullname):
    647735        # Factored out to allow overriding in subclasses
    648         base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name,
    649                                         self.target_version)
     736        if self.target_version:
     737            base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name,
     738                                            self.target_version)
     739        else:
     740            base_name = "%s.%s.msi" % (fullname, self.plat_name)
    650741        installer_name = os.path.join(self.dist_dir, base_name)
    651742        return installer_name
  • python/vendor/current/Lib/distutils/command/bdist_rpm.py

    r2 r388  
    44distributions)."""
    55
    6 # This module should be kept compatible with Python 2.1.
    7 
    8 __revision__ = "$Id: bdist_rpm.py 61000 2008-02-23 17:40:11Z christian.heimes $"
    9 
    10 import sys, os, string
    11 from types import *
     6__revision__ = "$Id$"
     7
     8import sys
     9import os
     10import string
     11
    1212from distutils.core import Command
    1313from distutils.debug import DEBUG
    14 from distutils.util import get_platform
    1514from distutils.file_util import write_file
    16 from distutils.errors import *
    17 from distutils.sysconfig import get_python_version
     15from distutils.errors import (DistutilsOptionError, DistutilsPlatformError,
     16                              DistutilsFileError, DistutilsExecError)
    1817from distutils import log
    1918
     
    126125        ('force-arch=', None,
    127126         "Force an architecture onto the RPM build process"),
    128        ]
     127
     128        ('quiet', 'q',
     129         "Run the INSTALL phase of RPM building in quiet mode"),
     130        ]
    129131
    130132    boolean_options = ['keep-temp', 'use-rpm-opt-flags', 'rpm3-mode',
    131                        'no-autoreq']
     133                       'no-autoreq', 'quiet']
    132134
    133135    negative_opt = {'no-keep-temp': 'keep-temp',
     
    179181
    180182        self.force_arch = None
     183        self.quiet = 0
    181184
    182185    # initialize_options()
     
    224227        self.ensure_string('packager')
    225228        self.ensure_string_list('doc_files')
    226         if type(self.doc_files) is ListType:
     229        if isinstance(self.doc_files, list):
    227230            for readme in ('README', 'README.txt'):
    228231                if os.path.exists(readme) and readme not in self.doc_files:
     
    325328           os.path.exists('/bin/rpmbuild'):
    326329            rpm_cmd = ['rpmbuild']
     330
    327331        if self.source_only: # what kind of RPMs?
    328332            rpm_cmd.append('-bs')
     
    336340        if not self.keep_temp:
    337341            rpm_cmd.append('--clean')
     342
     343        if self.quiet:
     344            rpm_cmd.append('--quiet')
     345
    338346        rpm_cmd.append(spec_path)
    339347        # Determine the binary rpm names that should be built out of this spec
     
    348356
    349357        out = os.popen(q_cmd)
    350         binary_rpms = []
    351         source_rpm = None
    352         while 1:
    353             line = out.readline()
    354             if not line:
    355                 break
    356             l = string.split(string.strip(line))
    357             assert(len(l) == 2)
    358             binary_rpms.append(l[1])
    359             # The source rpm is named after the first entry in the spec file
    360             if source_rpm is None:
    361                 source_rpm = l[0]
    362 
    363         status = out.close()
    364         if status:
    365             raise DistutilsExecError("Failed to execute: %s" % repr(q_cmd))
     358        try:
     359            binary_rpms = []
     360            source_rpm = None
     361            while 1:
     362                line = out.readline()
     363                if not line:
     364                    break
     365                l = string.split(string.strip(line))
     366                assert(len(l) == 2)
     367                binary_rpms.append(l[1])
     368                # The source rpm is named after the first entry in the spec file
     369                if source_rpm is None:
     370                    source_rpm = l[0]
     371
     372            status = out.close()
     373            if status:
     374                raise DistutilsExecError("Failed to execute: %s" % repr(q_cmd))
     375
     376        finally:
     377            out.close()
    366378
    367379        self.spawn(rpm_cmd)
    368380
    369381        if not self.dry_run:
     382            if self.distribution.has_ext_modules():
     383                pyversion = get_python_version()
     384            else:
     385                pyversion = 'any'
     386
    370387            if not self.binary_only:
    371388                srpm = os.path.join(rpm_dir['SRPMS'], source_rpm)
    372389                assert(os.path.exists(srpm))
    373390                self.move_file(srpm, self.dist_dir)
     391                filename = os.path.join(self.dist_dir, source_rpm)
     392                self.distribution.dist_files.append(
     393                    ('bdist_rpm', pyversion, filename))
    374394
    375395            if not self.source_only:
     
    378398                    if os.path.exists(rpm):
    379399                        self.move_file(rpm, self.dist_dir)
     400                        filename = os.path.join(self.dist_dir,
     401                                                os.path.basename(rpm))
     402                        self.distribution.dist_files.append(
     403                            ('bdist_rpm', pyversion, filename))
    380404    # run()
    381405
     
    438462                      ):
    439463            val = getattr(self, string.lower(field))
    440             if type(val) is ListType:
     464            if isinstance(val, list):
    441465                spec_file.append('%s: %s' % (field, string.join(val)))
    442466            elif val is not None:
     
    489513        # are just text that we drop in as-is.  Hmmm.
    490514
     515        install_cmd = ('%s install -O1 --root=$RPM_BUILD_ROOT '
     516                       '--record=INSTALLED_FILES') % def_setup_call
     517
    491518        script_options = [
    492519            ('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"),
    493520            ('build', 'build_script', def_build),
    494             ('install', 'install_script',
    495              ("%s install "
    496               "--root=$RPM_BUILD_ROOT "
    497               "--record=INSTALLED_FILES") % def_setup_call),
     521            ('install', 'install_script', install_cmd),
    498522            ('clean', 'clean_script', "rm -rf $RPM_BUILD_ROOT"),
    499523            ('verifyscript', 'verify_script', None),
  • python/vendor/current/Lib/distutils/command/bdist_wininst.py

    r2 r388  
    44exe-program."""
    55
    6 # This module should be kept compatible with Python 2.1.
    7 
    8 __revision__ = "$Id: bdist_wininst.py 71422 2009-04-09 22:48:19Z tarek.ziade $"
    9 
    10 import sys, os, string
     6__revision__ = "$Id$"
     7
     8import sys
     9import os
     10import string
     11
     12from sysconfig import get_python_version
     13
    1114from distutils.core import Command
     15from distutils.dir_util import remove_tree
     16from distutils.errors import DistutilsOptionError, DistutilsPlatformError
     17from distutils import log
    1218from distutils.util import get_platform
    13 from distutils.dir_util import create_tree, remove_tree
    14 from distutils.errors import *
    15 from distutils.sysconfig import get_python_version
    16 from distutils import log
    1719
    1820class bdist_wininst (Command):
     
    7072        self.bitmap = None
    7173        self.title = None
    72         self.skip_build = 0
     74        self.skip_build = None
    7375        self.install_script = None
    7476        self.pre_install_script = None
     
    7981
    8082    def finalize_options (self):
     83        self.set_undefined_options('bdist', ('skip_build', 'skip_build'))
     84
    8185        if self.bdist_dir is None:
    8286            if self.skip_build and self.plat_name:
     
    8892            bdist_base = self.get_finalized_command('bdist').bdist_base
    8993            self.bdist_dir = os.path.join(bdist_base, 'wininst')
     94
    9095        if not self.target_version:
    9196            self.target_version = ""
     97
    9298        if not self.skip_build and self.distribution.has_ext_modules():
    9399            short_version = get_python_version()
    94100            if self.target_version and self.target_version != short_version:
    95101                raise DistutilsOptionError, \
    96                       "target version can only be %s, or the '--skip_build'" \
     102                      "target version can only be %s, or the '--skip-build'" \
    97103                      " option must be specified" % (short_version,)
    98104            self.target_version = short_version
     
    355361
    356362        filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix))
    357         return open(filename, "rb").read()
     363        f = open(filename, "rb")
     364        try:
     365            return f.read()
     366        finally:
     367            f.close()
    358368# class bdist_wininst
  • python/vendor/current/Lib/distutils/command/build.py

    r2 r388  
    33Implements the Distutils 'build' command."""
    44
    5 # This module should be kept compatible with Python 2.1.
    6 
    7 __revision__ = "$Id: build.py 62197 2008-04-07 01:53:39Z mark.hammond $"
     5__revision__ = "$Id$"
    86
    97import sys, os
     8
     9from distutils.util import get_platform
    1010from distutils.core import Command
    1111from distutils.errors import DistutilsOptionError
    12 from distutils.util import get_platform
    1312
    14 
    15 def show_compilers ():
     13def show_compilers():
    1614    from distutils.ccompiler import show_compilers
    1715    show_compilers()
    1816
    19 
    20 class build (Command):
     17class build(Command):
    2118
    2219    description = "build everything needed to install"
     
    5653        ]
    5754
    58     def initialize_options (self):
     55    def initialize_options(self):
    5956        self.build_base = 'build'
    6057        # these are decided only after 'build_base' has its final value
     
    7168        self.executable = None
    7269
    73     def finalize_options (self):
    74 
     70    def finalize_options(self):
    7571        if self.plat_name is None:
    7672            self.plat_name = get_platform()
     
    121117        if self.executable is None:
    122118            self.executable = os.path.normpath(sys.executable)
    123     # finalize_options ()
    124119
    125 
    126     def run (self):
    127 
     120    def run(self):
    128121        # Run all relevant sub-commands.  This will be some subset of:
    129122        #  - build_py      - pure Python modules
     
    133126        for cmd_name in self.get_sub_commands():
    134127            self.run_command(cmd_name)
    135 
    136128
    137129    # -- Predicates for the sub-command list ---------------------------
     
    149141        return self.distribution.has_scripts()
    150142
    151 
    152143    sub_commands = [('build_py',      has_pure_modules),
    153144                    ('build_clib',    has_c_libraries),
     
    155146                    ('build_scripts', has_scripts),
    156147                   ]
    157 
    158 # class build
  • python/vendor/current/Lib/distutils/command/build_clib.py

    r2 r388  
    55module."""
    66
    7 # This module should be kept compatible with Python 2.1.
    8 
    9 __revision__ = "$Id: build_clib.py 37828 2004-11-10 22:23:15Z loewis $"
     7__revision__ = "$Id$"
    108
    119
     
    1917# cut 'n paste.  Sigh.
    2018
    21 import os, string
    22 from types import *
     19import os
    2320from distutils.core import Command
    24 from distutils.errors import *
     21from distutils.errors import DistutilsSetupError
    2522from distutils.sysconfig import customize_compiler
    2623from distutils import log
    2724
    28 def show_compilers ():
     25def show_compilers():
    2926    from distutils.ccompiler import show_compilers
    3027    show_compilers()
    3128
    3229
    33 class build_clib (Command):
     30class build_clib(Command):
    3431
    3532    description = "build C/C++ libraries used by Python extensions"
    3633
    3734    user_options = [
    38         ('build-clib', 'b',
     35        ('build-clib=', 'b',
    3936         "directory to build C/C++ libraries to"),
    40         ('build-temp', 't',
     37        ('build-temp=', 't',
    4138         "directory to put temporary build by-products"),
    4239        ('debug', 'g',
     
    5552        ]
    5653
    57     def initialize_options (self):
     54    def initialize_options(self):
    5855        self.build_clib = None
    5956        self.build_temp = None
     
    7067        self.compiler = None
    7168
    72     # initialize_options()
    73 
    74 
    75     def finalize_options (self):
    76 
     69
     70    def finalize_options(self):
    7771        # This might be confusing: both build-clib and build-temp default
    7872        # to build-temp as defined by the "build" command.  This is because
     
    9387        if self.include_dirs is None:
    9488            self.include_dirs = self.distribution.include_dirs or []
    95         if type(self.include_dirs) is StringType:
    96             self.include_dirs = string.split(self.include_dirs,
    97                                              os.pathsep)
     89        if isinstance(self.include_dirs, str):
     90            self.include_dirs = self.include_dirs.split(os.pathsep)
    9891
    9992        # XXX same as for build_ext -- what about 'self.define' and
    10093        # 'self.undef' ?
    10194
    102     # finalize_options()
    103 
    104 
    105     def run (self):
    106 
     95    def run(self):
    10796        if not self.libraries:
    10897            return
     
    127116        self.build_libraries(self.libraries)
    128117
    129     # run()
    130 
    131 
    132     def check_library_list (self, libraries):
    133         """Ensure that the list of libraries (presumably provided as a
    134            command option 'libraries') is valid, i.e. it is a list of
    135            2-tuples, where the tuples are (library_name, build_info_dict).
    136            Raise DistutilsSetupError if the structure is invalid anywhere;
    137            just returns otherwise."""
    138 
    139         # Yechh, blecch, ackk: this is ripped straight out of build_ext.py,
    140         # with only names changed to protect the innocent!
    141 
    142         if type(libraries) is not ListType:
     118
     119    def check_library_list(self, libraries):
     120        """Ensure that the list of libraries is valid.
     121
     122        `library` is presumably provided as a command option 'libraries'.
     123        This method checks that it is a list of 2-tuples, where the tuples
     124        are (library_name, build_info_dict).
     125
     126        Raise DistutilsSetupError if the structure is invalid anywhere;
     127        just returns otherwise.
     128        """
     129        if not isinstance(libraries, list):
    143130            raise DistutilsSetupError, \
    144131                  "'libraries' option must be a list of tuples"
    145132
    146133        for lib in libraries:
    147             if type(lib) is not TupleType and len(lib) != 2:
     134            if not isinstance(lib, tuple) and len(lib) != 2:
    148135                raise DistutilsSetupError, \
    149136                      "each element of 'libraries' must a 2-tuple"
    150137
    151             if type(lib[0]) is not StringType:
     138            name, build_info = lib
     139
     140            if not isinstance(name, str):
    152141                raise DistutilsSetupError, \
    153142                      "first element of each tuple in 'libraries' " + \
    154143                      "must be a string (the library name)"
    155             if '/' in lib[0] or (os.sep != '/' and os.sep in lib[0]):
     144            if '/' in name or (os.sep != '/' and os.sep in name):
    156145                raise DistutilsSetupError, \
    157146                      ("bad library name '%s': " +
     
    159148                      lib[0]
    160149
    161             if type(lib[1]) is not DictionaryType:
     150            if not isinstance(build_info, dict):
    162151                raise DistutilsSetupError, \
    163152                      "second element of each tuple in 'libraries' " + \
    164153                      "must be a dictionary (build info)"
    165         # for lib
    166 
    167     # check_library_list ()
    168 
    169 
    170     def get_library_names (self):
     154
     155    def get_library_names(self):
    171156        # Assume the library list is valid -- 'check_library_list()' is
    172157        # called from 'finalize_options()', so it should be!
    173 
    174158        if not self.libraries:
    175159            return None
     
    180164        return lib_names
    181165
    182     # get_library_names ()
    183 
    184 
    185     def get_source_files (self):
     166
     167    def get_source_files(self):
    186168        self.check_library_list(self.libraries)
    187169        filenames = []
    188170        for (lib_name, build_info) in self.libraries:
    189171            sources = build_info.get('sources')
    190             if (sources is None or
    191                 type(sources) not in (ListType, TupleType) ):
     172            if sources is None or not isinstance(sources, (list, tuple)):
    192173                raise DistutilsSetupError, \
    193174                      ("in 'libraries' option (library '%s'), "
     
    196177
    197178            filenames.extend(sources)
    198 
    199179        return filenames
    200     # get_source_files ()
    201 
    202 
    203     def build_libraries (self, libraries):
    204 
     180
     181    def build_libraries(self, libraries):
    205182        for (lib_name, build_info) in libraries:
    206183            sources = build_info.get('sources')
    207             if sources is None or type(sources) not in (ListType, TupleType):
     184            if sources is None or not isinstance(sources, (list, tuple)):
    208185                raise DistutilsSetupError, \
    209186                      ("in 'libraries' option (library '%s'), " +
     
    231208                                            output_dir=self.build_clib,
    232209                                            debug=self.debug)
    233 
    234         # for libraries
    235 
    236     # build_libraries ()
    237 
    238 # class build_lib
  • python/vendor/current/Lib/distutils/command/build_ext.py

    r2 r388  
    77# This module should be kept compatible with Python 2.1.
    88
    9 __revision__ = "$Id: build_ext.py 75395 2009-10-13 21:17:34Z tarek.ziade $"
     9__revision__ = "$Id$"
    1010
    1111import sys, os, string, re
     
    161161            self.include_dirs.append(plat_py_include)
    162162
    163         if isinstance(self.libraries, str):
    164             self.libraries = [self.libraries]
     163        self.ensure_string_list('libraries')
    165164
    166165        # Life is easier if we're not forever checking for None, so
     
    208207            elif MSVC_VERSION == 8:
    209208                self.library_dirs.append(os.path.join(sys.exec_prefix,
    210                                          'PC', 'VS8.0', 'win32release'))
     209                                         'PC', 'VS8.0'))
    211210            elif MSVC_VERSION == 7:
    212211                self.library_dirs.append(os.path.join(sys.exec_prefix,
     
    233232                self.library_dirs.append('.')
    234233
    235         # for extensions under Linux or Solaris with a shared Python library,
     234        # For building extensions with a shared Python library,
    236235        # Python's library directory must be appended to library_dirs
    237         sysconfig.get_config_var('Py_ENABLE_SHARED')
    238         if ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')
    239              or sys.platform.startswith('sunos'))
    240             and sysconfig.get_config_var('Py_ENABLE_SHARED')):
     236        # See Issues: #1600860, #4366
     237        if (sysconfig.get_config_var('Py_ENABLE_SHARED')):
    241238            if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
    242239                # building third party extensions
     
    677674        so_ext = get_config_var('SO')
    678675        if os.name == 'nt' and self.debug:
    679             return apply(os.path.join, ext_path) + '_d' + so_ext
     676            return os.path.join(*ext_path) + '_d' + so_ext
    680677        return os.path.join(*ext_path) + so_ext
    681678
     
    754751            # Don't use the default code below
    755752            return ext.libraries
    756 
     753        elif sys.platform[:3] == 'aix':
     754            # Don't use the default code below
     755            return ext.libraries
    757756        else:
    758757            from distutils import sysconfig
  • python/vendor/current/Lib/distutils/command/build_py.py

    r2 r388  
    33Implements the Distutils 'build_py' command."""
    44
    5 # This module should be kept compatible with Python 2.1.
    6 
    7 __revision__ = "$Id: build_py.py 77376 2010-01-08 23:27:23Z tarek.ziade $"
    8 
    9 import string, os
    10 from types import *
     5__revision__ = "$Id$"
     6
     7import os
    118import sys
    129from glob import glob
    1310
    1411from distutils.core import Command
    15 from distutils.errors import *
     12from distutils.errors import DistutilsOptionError, DistutilsFileError
    1613from distutils.util import convert_path
    1714from distutils import log
    1815
    19 class build_py (Command):
     16class build_py(Command):
    2017
    2118    description = "\"build\" pure Python modules (copy to build directory)"
     
    3431    negative_opt = {'no-compile' : 'compile'}
    3532
    36 
    37     def initialize_options (self):
     33    def initialize_options(self):
    3834        self.build_lib = None
    3935        self.py_modules = None
     
    4541        self.force = None
    4642
    47     def finalize_options (self):
     43    def finalize_options(self):
    4844        self.set_undefined_options('build',
    4945                                   ('build_lib', 'build_lib'),
     
    6359        # Ick, copied straight from install_lib.py (fancy_getopt needs a
    6460        # type system!  Hell, *everything* needs a type system!!!)
    65         if type(self.optimize) is not IntType:
     61        if not isinstance(self.optimize, int):
    6662            try:
    6763                self.optimize = int(self.optimize)
    6864                assert 0 <= self.optimize <= 2
    6965            except (ValueError, AssertionError):
    70                 raise DistutilsOptionError, "optimize must be 0, 1, or 2"
    71 
    72     def run (self):
    73 
     66                raise DistutilsOptionError("optimize must be 0, 1, or 2")
     67
     68    def run(self):
    7469        # XXX copy_file by default preserves atime and mtime.  IMHO this is
    7570        # the right thing to do, but perhaps it should be an option -- in
     
    10196        self.byte_compile(self.get_outputs(include_bytecode=0))
    10297
    103     # run ()
    104 
    105     def get_data_files (self):
     98    def get_data_files(self):
    10699        """Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
    107100        data = []
     
    127120        return data
    128121
    129     def find_data_files (self, package, src_dir):
     122    def find_data_files(self, package, src_dir):
    130123        """Return filenames for package's data files in 'src_dir'"""
    131124        globs = (self.package_data.get('', [])
     
    139132        return files
    140133
    141     def build_package_data (self):
     134    def build_package_data(self):
    142135        """Copy data files into build directory"""
    143         lastdir = None
    144136        for package, src_dir, build_dir, filenames in self.data_files:
    145137            for filename in filenames:
     
    149141                               preserve_mode=False)
    150142
    151     def get_package_dir (self, package):
     143    def get_package_dir(self, package):
    152144        """Return the directory, relative to the top of the source
    153145           distribution, where package 'package' should be found
    154146           (at least according to the 'package_dir' option, if any)."""
    155147
    156         path = string.split(package, '.')
     148        path = package.split('.')
    157149
    158150        if not self.package_dir:
    159151            if path:
    160                 return apply(os.path.join, path)
     152                return os.path.join(*path)
    161153            else:
    162154                return ''
     
    165157            while path:
    166158                try:
    167                     pdir = self.package_dir[string.join(path, '.')]
     159                    pdir = self.package_dir['.'.join(path)]
    168160                except KeyError:
    169161                    tail.insert(0, path[-1])
     
    185177
    186178                if tail:
    187                     return apply(os.path.join, tail)
     179                    return os.path.join(*tail)
    188180                else:
    189181                    return ''
    190182
    191     # get_package_dir ()
    192 
    193 
    194     def check_package (self, package, package_dir):
    195 
     183    def check_package(self, package, package_dir):
    196184        # Empty dir name means current directory, which we can probably
    197185        # assume exists.  Also, os.path.exists and isdir don't know about
     
    200188        if package_dir != "":
    201189            if not os.path.exists(package_dir):
    202                 raise DistutilsFileError, \
    203                       "package directory '%s' does not exist" % package_dir
     190                raise DistutilsFileError(
     191                      "package directory '%s' does not exist" % package_dir)
    204192            if not os.path.isdir(package_dir):
    205                 raise DistutilsFileError, \
    206                       ("supposed package directory '%s' exists, " +
    207                        "but is not a directory") % package_dir
     193                raise DistutilsFileError(
     194                       "supposed package directory '%s' exists, "
     195                       "but is not a directory" % package_dir)
    208196
    209197        # Require __init__.py for all but the "root package"
     
    220208        return None
    221209
    222     # check_package ()
    223 
    224 
    225     def check_module (self, module, module_file):
     210    def check_module(self, module, module_file):
    226211        if not os.path.isfile(module_file):
    227212            log.warn("file %s (for module %s) not found", module_file, module)
    228             return 0
     213            return False
    229214        else:
    230             return 1
    231 
    232     # check_module ()
    233 
    234 
    235     def find_package_modules (self, package, package_dir):
     215            return True
     216
     217    def find_package_modules(self, package, package_dir):
    236218        self.check_package(package, package_dir)
    237219        module_files = glob(os.path.join(package_dir, "*.py"))
     
    248230        return modules
    249231
    250 
    251     def find_modules (self):
     232    def find_modules(self):
    252233        """Finds individually-specified Python modules, ie. those listed by
    253234        module name in 'self.py_modules'.  Returns a list of tuples (package,
     
    258239        module.
    259240        """
    260 
    261241        # Map package names to tuples of useful info about the package:
    262242        #    (package_dir, checked)
     
    274254        # string or empty list, depending on context).  Differences:
    275255        #   - don't check for __init__.py in directory for empty package
    276 
    277256        for module in self.py_modules:
    278             path = string.split(module, '.')
    279             package = string.join(path[0:-1], '.')
     257            path = module.split('.')
     258            package = '.'.join(path[0:-1])
    280259            module_base = path[-1]
    281260
     
    303282        return modules
    304283
    305     # find_modules ()
    306 
    307 
    308     def find_all_modules (self):
     284    def find_all_modules(self):
    309285        """Compute the list of all modules that will be built, whether
    310286        they are specified one-module-at-a-time ('self.py_modules') or
     
    312288        (package, module, module_file), just like 'find_modules()' and
    313289        'find_package_modules()' do."""
    314 
    315290        modules = []
    316291        if self.py_modules:
     
    321296                m = self.find_package_modules(package, package_dir)
    322297                modules.extend(m)
    323 
    324298        return modules
    325299
    326     # find_all_modules ()
    327 
    328 
    329     def get_source_files (self):
    330 
    331         modules = self.find_all_modules()
    332         filenames = []
    333         for module in modules:
    334             filenames.append(module[-1])
    335 
    336         return filenames
    337 
    338 
    339     def get_module_outfile (self, build_dir, package, module):
     300    def get_source_files(self):
     301        return [module[-1] for module in self.find_all_modules()]
     302
     303    def get_module_outfile(self, build_dir, package, module):
    340304        outfile_path = [build_dir] + list(package) + [module + ".py"]
    341305        return os.path.join(*outfile_path)
    342306
    343 
    344     def get_outputs (self, include_bytecode=1):
     307    def get_outputs(self, include_bytecode=1):
    345308        modules = self.find_all_modules()
    346309        outputs = []
    347310        for (package, module, module_file) in modules:
    348             package = string.split(package, '.')
     311            package = package.split('.')
    349312            filename = self.get_module_outfile(self.build_lib, package, module)
    350313            outputs.append(filename)
     
    363326        return outputs
    364327
    365 
    366     def build_module (self, module, module_file, package):
    367         if type(package) is StringType:
    368             package = string.split(package, '.')
    369         elif type(package) not in (ListType, TupleType):
    370             raise TypeError, \
    371                   "'package' must be a string (dot-separated), list, or tuple"
     328    def build_module(self, module, module_file, package):
     329        if isinstance(package, str):
     330            package = package.split('.')
     331        elif not isinstance(package, (list, tuple)):
     332            raise TypeError(
     333                  "'package' must be a string (dot-separated), list, or tuple")
    372334
    373335        # Now put the module source file into the "build" area -- this is
     
    379341        return self.copy_file(module_file, outfile, preserve_mode=0)
    380342
    381 
    382     def build_modules (self):
    383 
     343    def build_modules(self):
    384344        modules = self.find_modules()
    385345        for (package, module, module_file) in modules:
     
    391351            self.build_module(module, module_file, package)
    392352
    393     # build_modules ()
    394 
    395 
    396     def build_packages (self):
    397 
     353    def build_packages(self):
    398354        for package in self.packages:
    399355
     
    416372                self.build_module(module, module_file, package)
    417373
    418     # build_packages ()
    419 
    420 
    421     def byte_compile (self, files):
     374    def byte_compile(self, files):
    422375        if sys.dont_write_bytecode:
    423376            self.warn('byte-compiling is disabled, skipping.')
     
    439392            byte_compile(files, optimize=self.optimize,
    440393                         force=self.force, prefix=prefix, dry_run=self.dry_run)
    441 
    442 # class build_py
  • python/vendor/current/Lib/distutils/command/build_scripts.py

    r2 r388  
    33Implements the Distutils 'build_scripts' command."""
    44
    5 # This module should be kept compatible with Python 2.1.
    6 
    7 __revision__ = "$Id: build_scripts.py 69599 2009-02-13 23:02:44Z tarek.ziade $"
     5__revision__ = "$Id$"
    86
    97import os, re
    108from stat import ST_MODE
    11 from distutils import sysconfig
    129from distutils.core import Command
    1310from distutils.dep_util import newer
     
    6057        line to refer to the current Python interpreter as we copy.
    6158        """
     59        _sysconfig = __import__('sysconfig')
    6260        self.mkpath(self.build_dir)
    6361        outfiles = []
     
    9795                if not self.dry_run:
    9896                    outf = open(outfile, "w")
    99                     if not sysconfig.python_build:
     97                    if not _sysconfig.is_python_build():
    10098                        outf.write("#!%s%s\n" %
    10199                                   (self.executable,
     
    104102                        outf.write("#!%s%s\n" %
    105103                                   (os.path.join(
    106                             sysconfig.get_config_var("BINDIR"),
    107                            "python%s%s" % (sysconfig.get_config_var("VERSION"),
    108                                            sysconfig.get_config_var("EXE"))),
     104                            _sysconfig.get_config_var("BINDIR"),
     105                           "python%s%s" % (_sysconfig.get_config_var("VERSION"),
     106                                           _sysconfig.get_config_var("EXE"))),
    109107                                    post_interp))
    110108                    outf.writelines(f.readlines())
  • python/vendor/current/Lib/distutils/command/clean.py

    r2 r388  
    55# contributed by Bastian Kleineidam <calvin@cs.uni-sb.de>, added 2000-03-18
    66
    7 # This module should be kept compatible with Python 2.1.
    8 
    9 __revision__ = "$Id: clean.py 38532 2005-03-03 08:12:27Z loewis $"
     7__revision__ = "$Id$"
    108
    119import os
     
    1412from distutils import log
    1513
    16 class clean (Command):
     14class clean(Command):
    1715
    1816    description = "clean up temporary files from 'build' command"
  • python/vendor/current/Lib/distutils/command/config.py

    r2 r388  
    1010"""
    1111
    12 # This module should be kept compatible with Python 2.1.
    13 
    14 __revision__ = "$Id: config.py 37828 2004-11-10 22:23:15Z loewis $"
    15 
    16 import sys, os, string, re
    17 from types import *
     12__revision__ = "$Id$"
     13
     14import os
     15import re
     16
    1817from distutils.core import Command
    1918from distutils.errors import DistutilsExecError
     
    2120from distutils import log
    2221
    23 LANG_EXT = {'c': '.c',
    24             'c++': '.cxx'}
    25 
    26 class config (Command):
     22LANG_EXT = {'c': '.c', 'c++': '.cxx'}
     23
     24class config(Command):
    2725
    2826    description = "prepare to build"
     
    5452    # does nothing by default, these are empty.
    5553
    56     def initialize_options (self):
     54    def initialize_options(self):
    5755        self.compiler = None
    5856        self.cc = None
    5957        self.include_dirs = None
    60         #self.define = None
    61         #self.undef = None
    6258        self.libraries = None
    6359        self.library_dirs = None
     
    7167        self.temp_files = []
    7268
    73     def finalize_options (self):
     69    def finalize_options(self):
    7470        if self.include_dirs is None:
    7571            self.include_dirs = self.distribution.include_dirs or []
    76         elif type(self.include_dirs) is StringType:
    77             self.include_dirs = string.split(self.include_dirs, os.pathsep)
     72        elif isinstance(self.include_dirs, str):
     73            self.include_dirs = self.include_dirs.split(os.pathsep)
    7874
    7975        if self.libraries is None:
    8076            self.libraries = []
    81         elif type(self.libraries) is StringType:
     77        elif isinstance(self.libraries, str):
    8278            self.libraries = [self.libraries]
    8379
    8480        if self.library_dirs is None:
    8581            self.library_dirs = []
    86         elif type(self.library_dirs) is StringType:
    87             self.library_dirs = string.split(self.library_dirs, os.pathsep)
    88 
    89 
    90     def run (self):
     82        elif isinstance(self.library_dirs, str):
     83            self.library_dirs = self.library_dirs.split(os.pathsep)
     84
     85    def run(self):
    9186        pass
    9287
     
    9691    # may use these freely.
    9792
    98     def _check_compiler (self):
     93    def _check_compiler(self):
    9994        """Check that 'self.compiler' really is a CCompiler object;
    10095        if not, make it one.
     
    115110
    116111
    117     def _gen_temp_sourcefile (self, body, headers, lang):
     112    def _gen_temp_sourcefile(self, body, headers, lang):
    118113        filename = "_configtest" + LANG_EXT[lang]
    119114        file = open(filename, "w")
     
    128123        return filename
    129124
    130     def _preprocess (self, body, headers, include_dirs, lang):
     125    def _preprocess(self, body, headers, include_dirs, lang):
    131126        src = self._gen_temp_sourcefile(body, headers, lang)
    132127        out = "_configtest.i"
     
    135130        return (src, out)
    136131
    137     def _compile (self, body, headers, include_dirs, lang):
     132    def _compile(self, body, headers, include_dirs, lang):
    138133        src = self._gen_temp_sourcefile(body, headers, lang)
    139134        if self.dump_source:
     
    144139        return (src, obj)
    145140
    146     def _link (self, body,
    147                headers, include_dirs,
    148                libraries, library_dirs, lang):
     141    def _link(self, body, headers, include_dirs, libraries, library_dirs,
     142              lang):
    149143        (src, obj) = self._compile(body, headers, include_dirs, lang)
    150144        prog = os.path.splitext(os.path.basename(src))[0]
     
    160154        return (src, obj, prog)
    161155
    162     def _clean (self, *filenames):
     156    def _clean(self, *filenames):
    163157        if not filenames:
    164158            filenames = self.temp_files
    165159            self.temp_files = []
    166         log.info("removing: %s", string.join(filenames))
     160        log.info("removing: %s", ' '.join(filenames))
    167161        for filename in filenames:
    168162            try:
     
    182176    # XXX need access to the header search path and maybe default macros.
    183177
    184     def try_cpp (self, body=None, headers=None, include_dirs=None, lang="c"):
     178    def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
    185179        """Construct a source file from 'body' (a string containing lines
    186180        of C/C++ code) and 'headers' (a list of header files to include)
     
    200194        return ok
    201195
    202     def search_cpp (self, pattern, body=None,
    203                     headers=None, include_dirs=None, lang="c"):
     196    def search_cpp(self, pattern, body=None, headers=None, include_dirs=None,
     197                   lang="c"):
    204198        """Construct a source file (just like 'try_cpp()'), run it through
    205199        the preprocessor, and return true if any line of the output matches
     
    209203        symbols the preprocessor and compiler set by default.
    210204        """
    211 
    212         self._check_compiler()
    213         (src, out) = self._preprocess(body, headers, include_dirs, lang)
    214 
    215         if type(pattern) is StringType:
     205        self._check_compiler()
     206        src, out = self._preprocess(body, headers, include_dirs, lang)
     207
     208        if isinstance(pattern, str):
    216209            pattern = re.compile(pattern)
    217210
     
    230223        return match
    231224
    232     def try_compile (self, body, headers=None, include_dirs=None, lang="c"):
     225    def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
    233226        """Try to compile a source file built from 'body' and 'headers'.
    234227        Return true on success, false otherwise.
     
    246239        return ok
    247240
    248     def try_link (self, body,
    249                   headers=None, include_dirs=None,
    250                   libraries=None, library_dirs=None,
    251                   lang="c"):
     241    def try_link(self, body, headers=None, include_dirs=None, libraries=None,
     242                 library_dirs=None, lang="c"):
    252243        """Try to compile and link a source file, built from 'body' and
    253244        'headers', to executable form.  Return true on success, false
     
    267258        return ok
    268259
    269     def try_run (self, body,
    270                  headers=None, include_dirs=None,
    271                  libraries=None, library_dirs=None,
    272                  lang="c"):
     260    def try_run(self, body, headers=None, include_dirs=None, libraries=None,
     261                library_dirs=None, lang="c"):
    273262        """Try to compile, link to an executable, and run a program
    274263        built from 'body' and 'headers'.  Return true on success, false
     
    294283    # when implementing a real-world config command!)
    295284
    296     def check_func (self, func,
    297                     headers=None, include_dirs=None,
    298                     libraries=None, library_dirs=None,
    299                     decl=0, call=0):
     285    def check_func(self, func, headers=None, include_dirs=None,
     286                   libraries=None, library_dirs=None, decl=0, call=0):
    300287
    301288        """Determine if function 'func' is available by constructing a
     
    323310            body.append("  %s;" % func)
    324311        body.append("}")
    325         body = string.join(body, "\n") + "\n"
     312        body = "\n".join(body) + "\n"
    326313
    327314        return self.try_link(body, headers, include_dirs,
     
    330317    # check_func ()
    331318
    332     def check_lib (self, library, library_dirs=None,
    333                    headers=None, include_dirs=None, other_libraries=[]):
     319    def check_lib(self, library, library_dirs=None, headers=None,
     320                  include_dirs=None, other_libraries=[]):
    334321        """Determine if 'library' is available to be linked against,
    335322        without actually checking that any particular symbols are provided
     
    345332                             [library]+other_libraries, library_dirs)
    346333
    347     def check_header (self, header, include_dirs=None,
    348                       library_dirs=None, lang="c"):
     334    def check_header(self, header, include_dirs=None, library_dirs=None,
     335                     lang="c"):
    349336        """Determine if the system header file named by 'header_file'
    350337        exists and can be found by the preprocessor; return true if so,
     
    355342
    356343
    357 # class config
    358 
    359 
    360 def dump_file (filename, head=None):
     344def dump_file(filename, head=None):
     345    """Dumps a file content into log.info.
     346
     347    If head is not None, will be dumped before the file content.
     348    """
    361349    if head is None:
    362         print filename + ":"
     350        log.info('%s' % filename)
    363351    else:
    364         print head
    365 
     352        log.info(head)
    366353    file = open(filename)
    367     sys.stdout.write(file.read())
    368     file.close()
     354    try:
     355        log.info(file.read())
     356    finally:
     357        file.close()
  • python/vendor/current/Lib/distutils/command/install.py

    r2 r388  
    77# This module should be kept compatible with Python 2.1.
    88
    9 __revision__ = "$Id: install.py 62788 2008-05-06 22:41:46Z christian.heimes $"
     9__revision__ = "$Id$"
    1010
    1111import sys, os, string
     
    7070        'data'   : '$userbase',
    7171        },
    72     'mac': {
    73         'purelib': '$base/Lib/site-packages',
    74         'platlib': '$base/Lib/site-packages',
    75         'headers': '$base/Include/$dist_name',
    76         'scripts': '$base/Scripts',
    77         'data'   : '$base',
    78         },
    79     'mac_user': {
    80         'purelib': '$usersite',
    81         'platlib': '$usersite',
    82         'headers': '$userbase/$py_version_short/include/$dist_name',
    83         'scripts': '$userbase/bin',
    84         'data'   : '$userbase',
    85         },
    8672    'os2': {
    8773        'purelib': '$base/Lib/site-packages',
     
    280266        if self.user and (self.prefix or self.exec_prefix or self.home or
    281267                self.install_base or self.install_platbase):
    282             raise DistutilsOptionError("can't combine user with with prefix/"
    283                                        "exec_prefix/home or install_(plat)base")
     268            raise DistutilsOptionError("can't combine user with prefix, "
     269                                       "exec_prefix/home, or install_(plat)base")
    284270
    285271        # Next, stuff that's wrong (or dubious) only on certain platforms.
  • python/vendor/current/Lib/distutils/command/install_data.py

    r2 r388  
    66# contributed by Bastian Kleineidam
    77
    8 # This module should be kept compatible with Python 2.1.
    9 
    10 __revision__ = "$Id: install_data.py 37828 2004-11-10 22:23:15Z loewis $"
     8__revision__ = "$Id$"
    119
    1210import os
    13 from types import StringType
    1411from distutils.core import Command
    1512from distutils.util import change_root, convert_path
    1613
    17 class install_data (Command):
     14class install_data(Command):
    1815
    1916    description = "install data files"
     
    3027    boolean_options = ['force']
    3128
    32     def initialize_options (self):
     29    def initialize_options(self):
    3330        self.install_dir = None
    3431        self.outfiles = []
    3532        self.root = None
    3633        self.force = 0
    37 
    3834        self.data_files = self.distribution.data_files
    3935        self.warn_dir = 1
    4036
    41     def finalize_options (self):
     37    def finalize_options(self):
    4238        self.set_undefined_options('install',
    4339                                   ('install_data', 'install_dir'),
     
    4642                                  )
    4743
    48     def run (self):
     44    def run(self):
    4945        self.mkpath(self.install_dir)
    5046        for f in self.data_files:
    51             if type(f) is StringType:
     47            if isinstance(f, str):
    5248                # it's a simple file, so copy it
    5349                f = convert_path(f)
     
    7975                        self.outfiles.append(out)
    8076
    81     def get_inputs (self):
     77    def get_inputs(self):
    8278        return self.data_files or []
    8379
    84     def get_outputs (self):
     80    def get_outputs(self):
    8581        return self.outfiles
  • python/vendor/current/Lib/distutils/command/install_headers.py

    r2 r388  
    44files to the Python include directory."""
    55
    6 # This module should be kept compatible with Python 2.1.
    7 
    8 __revision__ = "$Id: install_headers.py 61000 2008-02-23 17:40:11Z christian.heimes $"
     6__revision__ = "$Id$"
    97
    108from distutils.core import Command
    119
    1210
    13 class install_headers (Command):
     11# XXX force is never used
     12class install_headers(Command):
    1413
    1514    description = "install C/C++ header files"
     
    2322    boolean_options = ['force']
    2423
    25     def initialize_options (self):
     24    def initialize_options(self):
    2625        self.install_dir = None
    2726        self.force = 0
    2827        self.outfiles = []
    2928
    30     def finalize_options (self):
     29    def finalize_options(self):
    3130        self.set_undefined_options('install',
    3231                                   ('install_headers', 'install_dir'),
     
    3433
    3534
    36     def run (self):
     35    def run(self):
    3736        headers = self.distribution.headers
    3837        if not headers:
     
    4443            self.outfiles.append(out)
    4544
    46     def get_inputs (self):
     45    def get_inputs(self):
    4746        return self.distribution.headers or []
    4847
    49     def get_outputs (self):
     48    def get_outputs(self):
    5049        return self.outfiles
    5150
  • python/vendor/current/Lib/distutils/command/install_lib.py

    r2 r388  
    1 # This module should be kept compatible with Python 2.1.
    2 
    3 __revision__ = "$Id: install_lib.py 77376 2010-01-08 23:27:23Z tarek.ziade $"
     1"""distutils.command.install_lib
     2
     3Implements the Distutils 'install_lib' command
     4(install all Python modules)."""
     5
     6__revision__ = "$Id$"
    47
    58import os
    6 from types import IntType
    79import sys
    810
     
    1719    PYTHON_SOURCE_EXTENSION = ".py"
    1820
    19 class install_lib (Command):
     21class install_lib(Command):
    2022
    2123    description = "install all Python modules (extensions and pure Python)"
     
    5153    negative_opt = {'no-compile' : 'compile'}
    5254
    53 
    54     def initialize_options (self):
     55    def initialize_options(self):
    5556        # let the 'install' command dictate our installation directory
    5657        self.install_dir = None
     
    6162        self.skip_build = None
    6263
    63     def finalize_options (self):
    64 
     64    def finalize_options(self):
    6565        # Get all the information we need to install pure Python modules
    6666        # from the umbrella 'install' command -- build (source) directory,
     
    8080            self.optimize = 0
    8181
    82         if type(self.optimize) is not IntType:
     82        if not isinstance(self.optimize, int):
    8383            try:
    8484                self.optimize = int(self.optimize)
     
    8888                raise DistutilsOptionError, "optimize must be 0, 1, or 2"
    8989
    90     def run (self):
    91 
     90    def run(self):
    9291        # Make sure we have built everything we need first
    9392        self.build()
     
    102101            self.byte_compile(outfiles)
    103102
    104     # run ()
    105 
    106 
    107103    # -- Top-level worker functions ------------------------------------
    108104    # (called from 'run()')
    109105
    110     def build (self):
     106    def build(self):
    111107        if not self.skip_build:
    112108            if self.distribution.has_pure_modules():
     
    115111                self.run_command('build_ext')
    116112
    117     def install (self):
     113    def install(self):
    118114        if os.path.isdir(self.build_dir):
    119115            outfiles = self.copy_tree(self.build_dir, self.install_dir)
     
    124120        return outfiles
    125121
    126     def byte_compile (self, files):
     122    def byte_compile(self, files):
    127123        if sys.dont_write_bytecode:
    128124            self.warn('byte-compiling is disabled, skipping.')
     
    149145    # -- Utility methods -----------------------------------------------
    150146
    151     def _mutate_outputs (self, has_any, build_cmd, cmd_option, output_dir):
    152 
     147    def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir):
    153148        if not has_any:
    154149            return []
     
    165160        return outputs
    166161
    167     # _mutate_outputs ()
    168 
    169     def _bytecode_filenames (self, py_filenames):
     162    def _bytecode_filenames(self, py_filenames):
    170163        bytecode_files = []
    171164        for py_file in py_filenames:
     
    187180    # (called by outsiders)
    188181
    189     def get_outputs (self):
     182    def get_outputs(self):
    190183        """Return the list of files that would be installed if this command
    191184        were actually run.  Not affected by the "dry-run" flag or whether
     
    208201        return pure_outputs + bytecode_outputs + ext_outputs
    209202
    210     # get_outputs ()
    211 
    212     def get_inputs (self):
     203    def get_inputs(self):
    213204        """Get the list of files that are input to this command, ie. the
    214205        files that get installed as they are named in the build tree.
     
    227218
    228219        return inputs
    229 
    230 # class install_lib
  • python/vendor/current/Lib/distutils/command/install_scripts.py

    r2 r388  
    66# contributed by Bastian Kleineidam
    77
    8 # This module should be kept compatible with Python 2.1.
    9 
    10 __revision__ = "$Id: install_scripts.py 37828 2004-11-10 22:23:15Z loewis $"
     8__revision__ = "$Id$"
    119
    1210import os
  • python/vendor/current/Lib/distutils/command/register.py

    r2 r388  
    66# created 2002/10/21, Richard Jones
    77
    8 __revision__ = "$Id: register.py 77719 2010-01-24 00:57:20Z tarek.ziade $"
    9 
    10 import os, string, urllib2, getpass, urlparse
    11 import StringIO
     8__revision__ = "$Id$"
     9
     10import urllib2
     11import getpass
     12import urlparse
     13from warnings import warn
    1214
    1315from distutils.core import PyPIRCCommand
    14 from distutils.errors import *
    1516from distutils import log
    1617
     
    2122        ('list-classifiers', None,
    2223         'list the valid Trove classifiers'),
     24        ('strict', None ,
     25         'Will stop the registering if the meta-data are not fully compliant')
    2326        ]
    2427    boolean_options = PyPIRCCommand.boolean_options + [
    25         'verify', 'list-classifiers']
     28        'verify', 'list-classifiers', 'strict']
     29
     30    sub_commands = [('check', lambda self: True)]
    2631
    2732    def initialize_options(self):
    2833        PyPIRCCommand.initialize_options(self)
    2934        self.list_classifiers = 0
     35        self.strict = 0
     36
     37    def finalize_options(self):
     38        PyPIRCCommand.finalize_options(self)
     39        # setting options for the `check` subcommand
     40        check_options = {'strict': ('register', self.strict),
     41                         'restructuredtext': ('register', 1)}
     42        self.distribution.command_options['check'] = check_options
    3043
    3144    def run(self):
    3245        self.finalize_options()
    3346        self._set_config()
    34         self.check_metadata()
     47
     48        # Run sub commands
     49        for cmd_name in self.get_sub_commands():
     50            self.run_command(cmd_name)
     51
    3552        if self.dry_run:
    3653            self.verify_metadata()
     
    4158
    4259    def check_metadata(self):
    43         """Ensure that all required elements of meta-data (name, version,
    44            URL, (author and author_email) or (maintainer and
    45            maintainer_email)) are supplied by the Distribution object; warn if
    46            any are missing.
    47         """
    48         metadata = self.distribution.metadata
    49 
    50         missing = []
    51         for attr in ('name', 'version', 'url'):
    52             if not (hasattr(metadata, attr) and getattr(metadata, attr)):
    53                 missing.append(attr)
    54 
    55         if missing:
    56             self.warn("missing required meta-data: " +
    57                       string.join(missing, ", "))
    58 
    59         if metadata.author:
    60             if not metadata.author_email:
    61                 self.warn("missing meta-data: if 'author' supplied, " +
    62                           "'author_email' must be supplied too")
    63         elif metadata.maintainer:
    64             if not metadata.maintainer_email:
    65                 self.warn("missing meta-data: if 'maintainer' supplied, " +
    66                           "'maintainer_email' must be supplied too")
    67         else:
    68             self.warn("missing meta-data: either (author and author_email) " +
    69                       "or (maintainer and maintainer_email) " +
    70                       "must be supplied")
     60        """Deprecated API."""
     61        warn("distutils.command.register.check_metadata is deprecated, \
     62              use the check command instead", PendingDeprecationWarning)
     63        check = self.distribution.get_command_obj('check')
     64        check.ensure_finalized()
     65        check.strict = self.strict
     66        check.restructuredtext = 1
     67        check.run()
    7168
    7269    def _set_config(self):
     
    9188        '''
    9289        response = urllib2.urlopen(self.repository+'?:action=list_classifiers')
    93         print response.read()
     90        log.info(response.read())
    9491
    9592    def verify_metadata(self):
     
    9895        # send the info to the server and report the result
    9996        (code, result) = self.post_to_server(self.build_post_data('verify'))
    100         print 'Server response (%s): %s'%(code, result)
     97        log.info('Server response (%s): %s' % (code, result))
    10198
    10299
     
    174171
    175172            # possibly save the login
    176             if not self.has_config and code == 200:
    177                 self.announce(('I can store your PyPI login so future '
    178                                'submissions will be faster.'), log.INFO)
    179                 self.announce('(the login will be stored in %s)' % \
    180                               self._get_rc_file(), log.INFO)
    181 
    182                 choice = 'X'
    183                 while choice.lower() not in 'yn':
    184                     choice = raw_input('Save your login (y/N)?')
    185                     if not choice:
    186                         choice = 'n'
    187                 if choice.lower() == 'y':
    188                     self._store_pypirc(username, password)
     173            if code == 200:
     174                if self.has_config:
     175                    # sharing the password in the distribution instance
     176                    # so the upload command can reuse it
     177                    self.distribution.password = password
     178                else:
     179                    self.announce(('I can store your PyPI login so future '
     180                                   'submissions will be faster.'), log.INFO)
     181                    self.announce('(the login will be stored in %s)' % \
     182                                  self._get_rc_file(), log.INFO)
     183                    choice = 'X'
     184                    while choice.lower() not in 'yn':
     185                        choice = raw_input('Save your login (y/N)?')
     186                        if not choice:
     187                            choice = 'n'
     188                    if choice.lower() == 'y':
     189                        self._store_pypirc(username, password)
    189190
    190191        elif choice == '2':
     
    207208            code, result = self.post_to_server(data)
    208209            if code != 200:
    209                 print 'Server response (%s): %s'%(code, result)
     210                log.info('Server response (%s): %s' % (code, result))
    210211            else:
    211                 print 'You will receive an email shortly.'
    212                 print 'Follow the instructions in it to complete registration.'
     212                log.info('You will receive an email shortly.')
     213                log.info(('Follow the instructions in it to '
     214                          'complete registration.'))
    213215        elif choice == '3':
    214216            data = {':action': 'password_reset'}
     
    217219                data['email'] = raw_input('Your email address: ')
    218220            code, result = self.post_to_server(data)
    219             print 'Server response (%s): %s'%(code, result)
     221            log.info('Server response (%s): %s' % (code, result))
    220222
    221223    def build_post_data(self, action):
     
    250252        ''' Post a query to the server, and return a string response.
    251253        '''
    252         self.announce('Registering %s to %s' % (data['name'],
    253                                                 self.repository), log.INFO)
     254        if 'name' in data:
     255            self.announce('Registering %s to %s' % (data['name'],
     256                                                   self.repository),
     257                                                   log.INFO)
    254258        # Build up the MIME payload for the urllib2 POST data
    255259        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
    256260        sep_boundary = '\n--' + boundary
    257261        end_boundary = sep_boundary + '--'
    258         body = StringIO.StringIO()
     262        chunks = []
    259263        for key, value in data.items():
    260264            # handle multiple entries for the same name
     
    262266                value = [value]
    263267            for value in value:
    264                 body.write(sep_boundary)
    265                 body.write('\nContent-Disposition: form-data; name="%s"'%key)
    266                 body.write("\n\n")
    267                 body.write(value)
     268                chunks.append(sep_boundary)
     269                chunks.append('\nContent-Disposition: form-data; name="%s"'%key)
     270                chunks.append("\n\n")
     271                chunks.append(value)
    268272                if value and value[-1] == '\r':
    269                     body.write('\n')  # write an extra newline (lurve Macs)
    270         body.write(end_boundary)
    271         body.write("\n")
    272         body = body.getvalue()
     273                    chunks.append('\n')  # write an extra newline (lurve Macs)
     274        chunks.append(end_boundary)
     275        chunks.append("\n")
     276
     277        # chunks may be bytes (str) or unicode objects that we need to encode
     278        body = []
     279        for chunk in chunks:
     280            if isinstance(chunk, unicode):
     281                body.append(chunk.encode('utf-8'))
     282            else:
     283                body.append(chunk)
     284
     285        body = ''.join(body)
    273286
    274287        # build the Request
     
    297310            result = 200, 'OK'
    298311        if self.show_response:
    299             print '-'*75, data, '-'*75
     312            dashes = '-' * 75
     313            self.announce('%s%s%s' % (dashes, data, dashes))
     314
    300315        return result
  • python/vendor/current/Lib/distutils/command/sdist.py

    r2 r388  
    33Implements the Distutils 'sdist' command (create a source distribution)."""
    44
    5 # This module should be kept compatible with Python 2.1.
    6 
    7 __revision__ = "$Id: sdist.py 68968 2009-01-26 17:20:15Z tarek.ziade $"
    8 
    9 import os, string
     5__revision__ = "$Id$"
     6
     7import os
     8import string
    109import sys
    11 from types import *
    1210from glob import glob
     11from warnings import warn
     12
    1313from distutils.core import Command
    1414from distutils import dir_util, dep_util, file_util, archive_util
    1515from distutils.text_file import TextFile
    16 from distutils.errors import *
     16from distutils.errors import (DistutilsPlatformError, DistutilsOptionError,
     17                              DistutilsTemplateError)
    1718from distutils.filelist import FileList
    1819from distutils import log
    19 
    20 
    21 def show_formats ():
     20from distutils.util import convert_path
     21
     22def show_formats():
    2223    """Print all possible values for the 'formats' option (used by
    2324    the "--help-formats" command-line option).
     
    2526    from distutils.fancy_getopt import FancyGetopt
    2627    from distutils.archive_util import ARCHIVE_FORMATS
    27     formats=[]
     28    formats = []
    2829    for format in ARCHIVE_FORMATS.keys():
    2930        formats.append(("formats=" + format, None,
    3031                        ARCHIVE_FORMATS[format][2]))
    3132    formats.sort()
    32     pretty_printer = FancyGetopt(formats)
    33     pretty_printer.print_help(
     33    FancyGetopt(formats).print_help(
    3434        "List of available source distribution formats:")
    3535
    36 class sdist (Command):
     36class sdist(Command):
    3737
    3838    description = "create a source distribution (tarball, zip file, etc.)"
     39
     40    def checking_metadata(self):
     41        """Callable used for the check sub-command.
     42
     43        Placed here so user_options can view it"""
     44        return self.metadata_check
    3945
    4046    user_options = [
     
    5864         "(implies --force-manifest)"),
    5965        ('force-manifest', 'f',
    60          "forcibly regenerate the manifest and carry on as usual"),
     66         "forcibly regenerate the manifest and carry on as usual. "
     67         "Deprecated: now the manifest is always regenerated."),
    6168        ('formats=', None,
    6269         "formats for source distribution (comma-separated list)"),
     
    6774         "directory to put the source distribution archive(s) in "
    6875         "[default: dist]"),
     76        ('metadata-check', None,
     77         "Ensure that all required elements of meta-data "
     78         "are supplied. Warn if any missing. [default]"),
     79        ('owner=', 'u',
     80         "Owner name used when creating a tar file [default: current user]"),
     81        ('group=', 'g',
     82         "Group name used when creating a tar file [default: current group]"),
    6983        ]
    7084
    7185    boolean_options = ['use-defaults', 'prune',
    7286                       'manifest-only', 'force-manifest',
    73                        'keep-temp']
     87                       'keep-temp', 'metadata-check']
    7488
    7589    help_options = [
     
    8195                    'no-prune': 'prune' }
    8296
    83     default_format = { 'posix': 'gztar',
    84                        'nt': 'zip' }
    85 
    86     def initialize_options (self):
     97    default_format = {'posix': 'gztar',
     98                      'nt': 'zip' }
     99
     100    sub_commands = [('check', checking_metadata)]
     101
     102    def initialize_options(self):
    87103        # 'template' and 'manifest' are, respectively, the names of
    88104        # the manifest template and manifest file.
     
    103119
    104120        self.archive_files = None
    105 
    106 
    107     def finalize_options (self):
     121        self.metadata_check = 1
     122        self.owner = None
     123        self.group = None
     124
     125    def finalize_options(self):
    108126        if self.manifest is None:
    109127            self.manifest = "MANIFEST"
     
    128146            self.dist_dir = "dist"
    129147
    130 
    131     def run (self):
    132 
     148    def run(self):
    133149        # 'filelist' contains the list of files that will make up the
    134150        # manifest
    135151        self.filelist = FileList()
    136152
    137         # Ensure that all required meta-data is given; warn if not (but
    138         # don't die, it's not *that* serious!)
    139         self.check_metadata()
     153        # Run sub commands
     154        for cmd_name in self.get_sub_commands():
     155            self.run_command(cmd_name)
    140156
    141157        # Do whatever it takes to get the list of files to process
     
    152168        self.make_distribution()
    153169
    154 
    155     def check_metadata (self):
    156         """Ensure that all required elements of meta-data (name, version,
    157         URL, (author and author_email) or (maintainer and
    158         maintainer_email)) are supplied by the Distribution object; warn if
    159         any are missing.
    160         """
    161         metadata = self.distribution.metadata
    162 
    163         missing = []
    164         for attr in ('name', 'version', 'url'):
    165             if not (hasattr(metadata, attr) and getattr(metadata, attr)):
    166                 missing.append(attr)
    167 
    168         if missing:
    169             self.warn("missing required meta-data: " +
    170                       string.join(missing, ", "))
    171 
    172         if metadata.author:
    173             if not metadata.author_email:
    174                 self.warn("missing meta-data: if 'author' supplied, " +
    175                           "'author_email' must be supplied too")
    176         elif metadata.maintainer:
    177             if not metadata.maintainer_email:
    178                 self.warn("missing meta-data: if 'maintainer' supplied, " +
    179                           "'maintainer_email' must be supplied too")
    180         else:
    181             self.warn("missing meta-data: either (author and author_email) " +
    182                       "or (maintainer and maintainer_email) " +
    183                       "must be supplied")
    184 
    185     # check_metadata ()
    186 
    187 
    188     def get_file_list (self):
     170    def check_metadata(self):
     171        """Deprecated API."""
     172        warn("distutils.command.sdist.check_metadata is deprecated, \
     173              use the check command instead", PendingDeprecationWarning)
     174        check = self.distribution.get_command_obj('check')
     175        check.ensure_finalized()
     176        check.run()
     177
     178    def get_file_list(self):
    189179        """Figure out the list of files to include in the source
    190180        distribution, and put it in 'self.filelist'.  This might involve
    191181        reading the manifest template (and writing the manifest), or just
    192182        reading the manifest, or just using the default file set -- it all
    193         depends on the user's options and the state of the filesystem.
    194         """
    195 
    196         # If we have a manifest template, see if it's newer than the
    197         # manifest; if so, we'll regenerate the manifest.
     183        depends on the user's options.
     184        """
     185        # new behavior when using a template:
     186        # the file list is recalculated every time because
     187        # even if MANIFEST.in or setup.py are not changed
     188        # the user might have added some files in the tree that
     189        # need to be included.
     190        #
     191        #  This makes --force the default and only behavior with templates.
    198192        template_exists = os.path.isfile(self.template)
    199         if template_exists:
    200             template_newer = dep_util.newer(self.template, self.manifest)
    201 
    202         # The contents of the manifest file almost certainly depend on the
    203         # setup script as well as the manifest template -- so if the setup
    204         # script is newer than the manifest, we'll regenerate the manifest
    205         # from the template.  (Well, not quite: if we already have a
    206         # manifest, but there's no template -- which will happen if the
    207         # developer elects to generate a manifest some other way -- then we
    208         # can't regenerate the manifest, so we don't.)
    209         self.debug_print("checking if %s newer than %s" %
    210                          (self.distribution.script_name, self.manifest))
    211         setup_newer = dep_util.newer(self.distribution.script_name,
    212                                      self.manifest)
    213 
    214         # cases:
    215         #   1) no manifest, template exists: generate manifest
    216         #      (covered by 2a: no manifest == template newer)
    217         #   2) manifest & template exist:
    218         #      2a) template or setup script newer than manifest:
    219         #          regenerate manifest
    220         #      2b) manifest newer than both:
    221         #          do nothing (unless --force or --manifest-only)
    222         #   3) manifest exists, no template:
    223         #      do nothing (unless --force or --manifest-only)
    224         #   4) no manifest, no template: generate w/ warning ("defaults only")
    225 
    226         manifest_outofdate = (template_exists and
    227                               (template_newer or setup_newer))
    228         force_regen = self.force_manifest or self.manifest_only
    229         manifest_exists = os.path.isfile(self.manifest)
    230         neither_exists = (not template_exists and not manifest_exists)
    231 
    232         # Regenerate the manifest if necessary (or if explicitly told to)
    233         if manifest_outofdate or neither_exists or force_regen:
    234             if not template_exists:
    235                 self.warn(("manifest template '%s' does not exist " +
    236                            "(using default file list)") %
    237                           self.template)
    238             self.filelist.findall()
    239 
    240             if self.use_defaults:
    241                 self.add_defaults()
    242             if template_exists:
    243                 self.read_template()
    244             if self.prune:
    245                 self.prune_file_list()
    246 
     193        if not template_exists and self._manifest_is_not_generated():
     194            self.read_manifest()
    247195            self.filelist.sort()
    248196            self.filelist.remove_duplicates()
    249             self.write_manifest()
    250 
    251         # Don't regenerate the manifest, just read it in.
    252         else:
    253             self.read_manifest()
    254 
    255     # get_file_list ()
    256 
    257 
    258     def add_defaults (self):
     197            return
     198
     199        if not template_exists:
     200            self.warn(("manifest template '%s' does not exist " +
     201                        "(using default file list)") %
     202                        self.template)
     203        self.filelist.findall()
     204
     205        if self.use_defaults:
     206            self.add_defaults()
     207
     208        if template_exists:
     209            self.read_template()
     210
     211        if self.prune:
     212            self.prune_file_list()
     213
     214        self.filelist.sort()
     215        self.filelist.remove_duplicates()
     216        self.write_manifest()
     217
     218    def add_defaults(self):
    259219        """Add all the default files to self.filelist:
    260220          - README or README.txt
     
    262222          - test/test*.py
    263223          - all pure Python modules mentioned in setup script
     224          - all files pointed by package_data (build_py)
     225          - all files defined in data_files.
     226          - all files defined as scripts.
    264227          - all C sources listed as part of extensions or C libraries
    265228            in the setup script (doesn't catch C headers!)
     
    270233        standards = [('README', 'README.txt'), self.distribution.script_name]
    271234        for fn in standards:
    272             if type(fn) is TupleType:
     235            if isinstance(fn, tuple):
    273236                alts = fn
    274237                got_it = 0
     
    294257                self.filelist.extend(files)
    295258
     259        # build_py is used to get:
     260        #  - python modules
     261        #  - files defined in package_data
     262        build_py = self.get_finalized_command('build_py')
     263
     264        # getting python files
    296265        if self.distribution.has_pure_modules():
    297             build_py = self.get_finalized_command('build_py')
    298266            self.filelist.extend(build_py.get_source_files())
     267
     268        # getting package_data files
     269        # (computed in build_py.data_files by build_py.finalize_options)
     270        for pkg, src_dir, build_dir, filenames in build_py.data_files:
     271            for filename in filenames:
     272                self.filelist.append(os.path.join(src_dir, filename))
     273
     274        # getting distribution.data_files
     275        if self.distribution.has_data_files():
     276            for item in self.distribution.data_files:
     277                if isinstance(item, str): # plain file
     278                    item = convert_path(item)
     279                    if os.path.isfile(item):
     280                        self.filelist.append(item)
     281                else:    # a (dirname, filenames) tuple
     282                    dirname, filenames = item
     283                    for f in filenames:
     284                        f = convert_path(f)
     285                        if os.path.isfile(f):
     286                            self.filelist.append(f)
    299287
    300288        if self.distribution.has_ext_modules():
     
    310298            self.filelist.extend(build_scripts.get_source_files())
    311299
    312     # add_defaults ()
    313 
    314 
    315     def read_template (self):
     300    def read_template(self):
    316301        """Read and parse manifest template file named by self.template.
    317302
     
    328313                            collapse_join=1)
    329314
    330         while 1:
    331             line = template.readline()
    332             if line is None:            # end of file
    333                 break
    334 
    335             try:
    336                 self.filelist.process_template_line(line)
    337             except DistutilsTemplateError, msg:
    338                 self.warn("%s, line %d: %s" % (template.filename,
    339                                                template.current_line,
    340                                                msg))
    341 
    342     # read_template ()
    343 
    344 
    345     def prune_file_list (self):
     315        try:
     316            while 1:
     317                line = template.readline()
     318                if line is None:            # end of file
     319                    break
     320
     321                try:
     322                    self.filelist.process_template_line(line)
     323                # the call above can raise a DistutilsTemplateError for
     324                # malformed lines, or a ValueError from the lower-level
     325                # convert_path function
     326                except (DistutilsTemplateError, ValueError) as msg:
     327                    self.warn("%s, line %d: %s" % (template.filename,
     328                                                   template.current_line,
     329                                                   msg))
     330        finally:
     331            template.close()
     332
     333    def prune_file_list(self):
    346334        """Prune off branches that might slip into the file list as created
    347335        by 'read_template()', but really don't belong there:
     
    369357        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
    370358
    371     def write_manifest (self):
     359    def write_manifest(self):
    372360        """Write the file list in 'self.filelist' (presumably as filled in
    373361        by 'add_defaults()' and 'read_template()') to the manifest file
    374362        named by 'self.manifest'.
    375363        """
    376         self.execute(file_util.write_file,
    377                      (self.manifest, self.filelist.files),
     364        if self._manifest_is_not_generated():
     365            log.info("not writing to manually maintained "
     366                     "manifest file '%s'" % self.manifest)
     367            return
     368
     369        content = self.filelist.files[:]
     370        content.insert(0, '# file GENERATED by distutils, do NOT edit')
     371        self.execute(file_util.write_file, (self.manifest, content),
    378372                     "writing manifest file '%s'" % self.manifest)
    379373
    380     # write_manifest ()
    381 
    382 
    383     def read_manifest (self):
     374    def _manifest_is_not_generated(self):
     375        # check for special comment used in 2.7.1 and higher
     376        if not os.path.isfile(self.manifest):
     377            return False
     378
     379        fp = open(self.manifest, 'rU')
     380        try:
     381            first_line = fp.readline()
     382        finally:
     383            fp.close()
     384        return first_line != '# file GENERATED by distutils, do NOT edit\n'
     385
     386    def read_manifest(self):
    384387        """Read the manifest file (named by 'self.manifest') and use it to
    385388        fill in 'self.filelist', the list of files to include in the source
     
    388391        log.info("reading manifest file '%s'", self.manifest)
    389392        manifest = open(self.manifest)
    390         while 1:
    391             line = manifest.readline()
    392             if line == '':              # end of file
    393                 break
    394             if line[-1] == '\n':
    395                 line = line[0:-1]
     393        for line in manifest:
     394            # ignore comments and blank lines
     395            line = line.strip()
     396            if line.startswith('#') or not line:
     397                continue
    396398            self.filelist.append(line)
    397399        manifest.close()
    398400
    399     # read_manifest ()
    400 
    401 
    402     def make_release_tree (self, base_dir, files):
     401    def make_release_tree(self, base_dir, files):
    403402        """Create the directory tree that will become the source
    404403        distribution archive.  All directories implied by the filenames in
     
    442441        self.distribution.metadata.write_pkg_info(base_dir)
    443442
    444     # make_release_tree ()
    445 
    446     def make_distribution (self):
     443    def make_distribution(self):
    447444        """Create the source distribution(s).  First, we create the release
    448445        tree with 'make_release_tree()'; then, we create all required
     
    464461
    465462        for fmt in self.formats:
    466             file = self.make_archive(base_name, fmt, base_dir=base_dir)
     463            file = self.make_archive(base_name, fmt, base_dir=base_dir,
     464                                     owner=self.owner, group=self.group)
    467465            archive_files.append(file)
    468466            self.distribution.dist_files.append(('sdist', '', file))
     
    473471            dir_util.remove_tree(base_dir, dry_run=self.dry_run)
    474472
    475     def get_archive_files (self):
     473    def get_archive_files(self):
    476474        """Return the list of archive files created when the command
    477475        was run, or None if the command hasn't run yet.
    478476        """
    479477        return self.archive_files
    480 
    481 # class sdist
  • python/vendor/current/Lib/distutils/command/upload.py

    r2 r388  
    22
    33Implements the Distutils 'upload' subcommand (upload package to PyPI)."""
     4import os
     5import socket
     6import platform
     7from urllib2 import urlopen, Request, HTTPError
     8from base64 import standard_b64encode
     9import urlparse
     10import cStringIO as StringIO
     11from hashlib import md5
    412
    5 from distutils.errors import *
     13from distutils.errors import DistutilsOptionError
    614from distutils.core import PyPIRCCommand
    715from distutils.spawn import spawn
    816from distutils import log
    9 from hashlib import md5
    10 import os
    11 import socket
    12 import platform
    13 import httplib
    14 from base64 import standard_b64encode
    15 import urlparse
    16 import cStringIO as StringIO
    17 from ConfigParser import ConfigParser
    18 
    1917
    2018class upload(PyPIRCCommand):
     
    5149            self.realm = config['realm']
    5250
     51        # getting the password from the distribution
     52        # if previously set by the register command
     53        if not self.password and self.distribution.password:
     54            self.password = self.distribution.password
     55
    5356    def run(self):
    5457        if not self.distribution.dist_files:
     
    5861
    5962    def upload_file(self, command, pyversion, filename):
     63        # Makes sure the repository URL is compliant
     64        schema, netloc, url, params, query, fragments = \
     65            urlparse.urlparse(self.repository)
     66        if params or query or fragments:
     67            raise AssertionError("Incompatible url %s" % self.repository)
     68
     69        if schema not in ('http', 'https'):
     70            raise AssertionError("unsupported schema " + schema)
     71
    6072        # Sign if requested
    6173        if self.sign:
     
    6880        # Fill in the data - send all the meta-data in case we need to
    6981        # register a new release
    70         content = open(filename,'rb').read()
     82        f = open(filename,'rb')
     83        try:
     84            content = f.read()
     85        finally:
     86            f.close()
    7187        meta = self.distribution.metadata
    7288        data = {
     
    126142        for key, value in data.items():
    127143            # handle multiple entries for the same name
    128             if type(value) != type([]):
     144            if not isinstance(value, list):
    129145                value = [value]
    130146            for value in value:
    131                 if type(value) is tuple:
     147                if isinstance(value, tuple):
    132148                    fn = ';filename="%s"' % value[0]
    133149                    value = value[1]
     
    149165
    150166        # build the Request
    151         # We can't use urllib2 since we need to send the Basic
    152         # auth right with the first request
    153         schema, netloc, url, params, query, fragments = \
    154             urlparse.urlparse(self.repository)
    155         assert not params and not query and not fragments
    156         if schema == 'http':
    157             http = httplib.HTTPConnection(netloc)
    158         elif schema == 'https':
    159             http = httplib.HTTPSConnection(netloc)
    160         else:
    161             raise AssertionError, "unsupported schema "+schema
     167        headers = {'Content-type':
     168                        'multipart/form-data; boundary=%s' % boundary,
     169                   'Content-length': str(len(body)),
     170                   'Authorization': auth}
    162171
    163         data = ''
    164         loglevel = log.INFO
     172        request = Request(self.repository, data=body,
     173                          headers=headers)
     174        # send the data
    165175        try:
    166             http.connect()
    167             http.putrequest("POST", url)
    168             http.putheader('Content-type',
    169                            'multipart/form-data; boundary=%s'%boundary)
    170             http.putheader('Content-length', str(len(body)))
    171             http.putheader('Authorization', auth)
    172             http.endheaders()
    173             http.send(body)
     176            result = urlopen(request)
     177            status = result.getcode()
     178            reason = result.msg
     179            if self.show_response:
     180                msg = '\n'.join(('-' * 75, r.read(), '-' * 75))
     181                self.announce(msg, log.INFO)
    174182        except socket.error, e:
    175183            self.announce(str(e), log.ERROR)
    176184            return
     185        except HTTPError, e:
     186            status = e.code
     187            reason = e.msg
    177188
    178         r = http.getresponse()
    179         if r.status == 200:
    180             self.announce('Server response (%s): %s' % (r.status, r.reason),
     189        if status == 200:
     190            self.announce('Server response (%s): %s' % (status, reason),
    181191                          log.INFO)
    182192        else:
    183             self.announce('Upload failed (%s): %s' % (r.status, r.reason),
     193            self.announce('Upload failed (%s): %s' % (status, reason),
    184194                          log.ERROR)
    185         if self.show_response:
    186             print '-'*75, r.read(), '-'*75
  • python/vendor/current/Lib/distutils/config.py

    r2 r388  
    55"""
    66import os
    7 import sys
    87from ConfigParser import ConfigParser
    98
     
    4443        """Creates a default .pypirc file."""
    4544        rc = self._get_rc_file()
    46         f = open(rc, 'w')
     45        f = os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0600), 'w')
    4746        try:
    4847            f.write(DEFAULT_PYPIRC % (username, password))
    4948        finally:
    5049            f.close()
    51         try:
    52             os.chmod(rc, 0600)
    53         except OSError:
    54             # should do something better here
    55             pass
    5650
    5751    def _read_pypirc(self):
     
    6155            self.announce('Using PyPI login from %s' % rc)
    6256            repository = self.repository or self.DEFAULT_REPOSITORY
    63             realm = self.realm or self.DEFAULT_REALM
    64 
    6557            config = ConfigParser()
    6658            config.read(rc)
     
    8375                    current = {'server': server}
    8476                    current['username'] = config.get(server, 'username')
    85                     current['password'] = config.get(server, 'password')
    8677
    8778                    # optional params
    8879                    for key, default in (('repository',
    8980                                          self.DEFAULT_REPOSITORY),
    90                                          ('realm', self.DEFAULT_REALM)):
     81                                         ('realm', self.DEFAULT_REALM),
     82                                         ('password', None)):
    9183                        if config.has_option(server, key):
    9284                            current[key] = config.get(server, key)
  • python/vendor/current/Lib/distutils/core.py

    r2 r388  
    77"""
    88
    9 # This module should be kept compatible with Python 2.1.
    10 
    11 __revision__ = "$Id: core.py 65806 2008-08-18 11:13:45Z marc-andre.lemburg $"
    12 
    13 import sys, os
    14 from types import *
     9__revision__ = "$Id$"
     10
     11import sys
     12import os
    1513
    1614from distutils.debug import DEBUG
    17 from distutils.errors import *
     15from distutils.errors import (DistutilsSetupError, DistutilsArgError,
     16                              DistutilsError, CCompilerError)
    1817from distutils.util import grok_environment_error
    1918
     
    3534"""
    3635
    37 def gen_usage (script_name):
     36def gen_usage(script_name):
    3837    script = os.path.basename(script_name)
    39     return USAGE % vars()
     38    return USAGE % {'script': script}
    4039
    4140
     
    6059                      'swig_opts', 'export_symbols', 'depends', 'language')
    6160
    62 def setup (**attrs):
     61def setup(**attrs):
    6362    """The gateway to the Distutils: do everything your setup script needs
    6463    to do, in a highly flexible and user-driven way.  Briefly: create a
     
    133132        return dist
    134133
    135     # Parse the command line; any command-line errors are the end user's
    136     # fault, so turn them into SystemExit to suppress tracebacks.
     134    # Parse the command line and override config files; any
     135    # command-line errors are the end user's fault, so turn them into
     136    # SystemExit to suppress tracebacks.
    137137    try:
    138138        ok = dist.parse_command_line()
     
    171171    return dist
    172172
    173 # setup ()
    174 
    175 
    176 def run_setup (script_name, script_args=None, stop_after="run"):
     173
     174def run_setup(script_name, script_args=None, stop_after="run"):
    177175    """Run a setup script in a somewhat controlled environment, and
    178176    return the Distribution instance that drives things.  This is useful
     
    219217            if script_args is not None:
    220218                sys.argv[1:] = script_args
    221             exec open(script_name, 'r').read() in g, l
     219            f = open(script_name)
     220            try:
     221                exec f.read() in g, l
     222            finally:
     223                f.close()
    222224        finally:
    223225            sys.argv = save_argv
     
    238240    # I wonder if the setup script's namespace -- g and l -- would be of
    239241    # any interest to callers?
    240     #print "_setup_distribution:", _setup_distribution
    241242    return _setup_distribution
    242 
    243 # run_setup ()
  • python/vendor/current/Lib/distutils/cygwinccompiler.py

    r2 r388  
    4848# This module should be kept compatible with Python 2.1.
    4949
    50 __revision__ = "$Id: cygwinccompiler.py 73349 2009-06-11 09:17:19Z tarek.ziade $"
     50__revision__ = "$Id$"
    5151
    5252import os,sys,copy
     
    320320            entry_point = ''
    321321
    322         self.set_executables(compiler='gcc -mno-cygwin -O -Wall',
    323                              compiler_so='gcc -mno-cygwin -mdll -O -Wall',
    324                              compiler_cxx='g++ -mno-cygwin -O -Wall',
    325                              linker_exe='gcc -mno-cygwin',
    326                              linker_so='%s -mno-cygwin %s %s'
    327                                         % (self.linker_dll, shared_option,
    328                                            entry_point))
     322        if self.gcc_version < '4' or is_cygwingcc():
     323            no_cygwin = ' -mno-cygwin'
     324        else:
     325            no_cygwin = ''
     326
     327        self.set_executables(compiler='gcc%s -O -Wall' % no_cygwin,
     328                             compiler_so='gcc%s -mdll -O -Wall' % no_cygwin,
     329                             compiler_cxx='g++%s -O -Wall' % no_cygwin,
     330                             linker_exe='gcc%s' % no_cygwin,
     331                             linker_so='%s%s %s %s'
     332                                    % (self.linker_dll, no_cygwin,
     333                                       shared_option, entry_point))
    329334        # Maybe we should also append -mthreads, but then the finished
    330335        # dlls need another dll (mingwm10.dll see Mingw32 docs)
     
    383388        # But we do this only once, and it is fast enough
    384389        f = open(fn)
    385         s = f.read()
    386         f.close()
     390        try:
     391            s = f.read()
     392        finally:
     393            f.close()
    387394
    388395    except IOError, exc:
     
    446453        dllwrap_version = None
    447454    return (gcc_version, ld_version, dllwrap_version)
     455
     456def is_cygwingcc():
     457    '''Try to determine if the gcc that would be used is from cygwin.'''
     458    out = os.popen('gcc -dumpmachine', 'r')
     459    out_string = out.read()
     460    out.close()
     461    # out_string is the target triplet cpu-vendor-os
     462    # Cygwin's gcc sets the os to 'cygwin'
     463    return out_string.strip().endswith('cygwin')
  • python/vendor/current/Lib/distutils/debug.py

    r2 r388  
    11import os
    22
    3 # This module should be kept compatible with Python 2.1.
    4 
    5 __revision__ = "$Id: debug.py 37828 2004-11-10 22:23:15Z loewis $"
     3__revision__ = "$Id$"
    64
    75# If DISTUTILS_DEBUG is anything other than the empty string, we run in
  • python/vendor/current/Lib/distutils/dep_util.py

    r2 r388  
    55timestamp dependency analysis."""
    66
    7 # This module should be kept compatible with Python 2.1.
    8 
    9 __revision__ = "$Id: dep_util.py 58049 2007-09-08 00:34:17Z skip.montanaro $"
     7__revision__ = "$Id$"
    108
    119import os
     10from stat import ST_MTIME
    1211from distutils.errors import DistutilsFileError
    1312
     13def newer(source, target):
     14    """Tells if the target is newer than the source.
    1415
    15 def newer (source, target):
    16     """Return true if 'source' exists and is more recently modified than
    17     'target', or if 'source' exists and 'target' doesn't.  Return false if
    18     both exist and 'target' is the same age or younger than 'source'.
    19     Raise DistutilsFileError if 'source' does not exist.
     16    Return true if 'source' exists and is more recently modified than
     17    'target', or if 'source' exists and 'target' doesn't.
     18
     19    Return false if both exist and 'target' is the same age or younger
     20    than 'source'. Raise DistutilsFileError if 'source' does not exist.
     21
     22    Note that this test is not very accurate: files created in the same second
     23    will have the same "age".
    2024    """
    2125    if not os.path.exists(source):
    22         raise DistutilsFileError, ("file '%s' does not exist" %
    23                                    os.path.abspath(source))
     26        raise DistutilsFileError("file '%s' does not exist" %
     27                                 os.path.abspath(source))
    2428    if not os.path.exists(target):
    25         return 1
     29        return True
    2630
    27     from stat import ST_MTIME
    28     mtime1 = os.stat(source)[ST_MTIME]
    29     mtime2 = os.stat(target)[ST_MTIME]
     31    return os.stat(source)[ST_MTIME] > os.stat(target)[ST_MTIME]
    3032
    31     return mtime1 > mtime2
    32 
    33 # newer ()
    34 
    35 
    36 def newer_pairwise (sources, targets):
     33def newer_pairwise(sources, targets):
    3734    """Walk two filename lists in parallel, testing if each source is newer
    3835    than its corresponding target.  Return a pair of lists (sources,
     
    4643    n_sources = []
    4744    n_targets = []
    48     for i in range(len(sources)):
    49         if newer(sources[i], targets[i]):
    50             n_sources.append(sources[i])
    51             n_targets.append(targets[i])
     45    for source, target in zip(sources, targets):
     46        if newer(source, target):
     47            n_sources.append(source)
     48            n_targets.append(target)
    5249
    53     return (n_sources, n_targets)
     50    return n_sources, n_targets
    5451
    55 # newer_pairwise ()
     52def newer_group(sources, target, missing='error'):
     53    """Return true if 'target' is out-of-date with respect to any file
     54    listed in 'sources'.
    5655
    57 
    58 def newer_group (sources, target, missing='error'):
    59     """Return true if 'target' is out-of-date with respect to any file
    60     listed in 'sources'.  In other words, if 'target' exists and is newer
     56    In other words, if 'target' exists and is newer
    6157    than every file in 'sources', return false; otherwise return true.
    6258    'missing' controls what we do when a source file is missing; the
     
    7167    # If the target doesn't even exist, then it's definitely out-of-date.
    7268    if not os.path.exists(target):
    73         return 1
     69        return True
    7470
    7571    # Otherwise we have to find out the hard way: if *any* source file
     
    7773    # we can immediately return true.  If we fall through to the end
    7874    # of the loop, then 'target' is up-to-date and we return false.
    79     from stat import ST_MTIME
    8075    target_mtime = os.stat(target)[ST_MTIME]
     76
    8177    for source in sources:
    8278        if not os.path.exists(source):
     
    8682                continue                #  target's dependency list
    8783            elif missing == 'newer':    # missing source means target is
    88                 return 1                #  out-of-date
     84                return True             #  out-of-date
    8985
    90         source_mtime = os.stat(source)[ST_MTIME]
    91         if source_mtime > target_mtime:
    92             return 1
    93     else:
    94         return 0
     86        if os.stat(source)[ST_MTIME] > target_mtime:
     87            return True
    9588
    96 # newer_group ()
     89    return False
  • python/vendor/current/Lib/distutils/dir_util.py

    r2 r388  
    33Utility functions for manipulating directories and directory trees."""
    44
    5 # This module should be kept compatible with Python 2.1.
    6 
    7 __revision__ = "$Id: dir_util.py 60923 2008-02-21 18:18:37Z guido.van.rossum $"
    8 
    9 import os, sys
    10 from types import *
     5__revision__ = "$Id$"
     6
     7import os
     8import errno
    119from distutils.errors import DistutilsFileError, DistutilsInternalError
    1210from distutils import log
     
    1917# b) it blows up if the directory already exists (I want to silently
    2018# succeed in that case).
    21 def mkpath (name, mode=0777, verbose=0, dry_run=0):
    22     """Create a directory and any missing ancestor directories.  If the
    23        directory already exists (or if 'name' is the empty string, which
    24        means the current directory, which of course exists), then do
    25        nothing.  Raise DistutilsFileError if unable to create some
    26        directory along the way (eg. some sub-path exists, but is a file
    27        rather than a directory).  If 'verbose' is true, print a one-line
    28        summary of each mkdir to stdout.  Return the list of directories
    29        actually created."""
     19def mkpath(name, mode=0777, verbose=1, dry_run=0):
     20    """Create a directory and any missing ancestor directories.
     21
     22    If the directory already exists (or if 'name' is the empty string, which
     23    means the current directory, which of course exists), then do nothing.
     24    Raise DistutilsFileError if unable to create some directory along the way
     25    (eg. some sub-path exists, but is a file rather than a directory).
     26    If 'verbose' is true, print a one-line summary of each mkdir to stdout.
     27    Return the list of directories actually created.
     28    """
    3029
    3130    global _path_created
    3231
    3332    # Detect a common bug -- name is None
    34     if not isinstance(name, StringTypes):
     33    if not isinstance(name, basestring):
    3534        raise DistutilsInternalError, \
    3635              "mkpath: 'name' must be a string (got %r)" % (name,)
     
    5251
    5352    while head and tail and not os.path.isdir(head):
    54         #print "splitting '%s': " % head,
    5553        (head, tail) = os.path.split(head)
    56         #print "to ('%s','%s')" % (head, tail)
    5754        tails.insert(0, tail)          # push next higher dir onto stack
    58 
    59     #print "stack of tails:", tails
    6055
    6156    # now 'head' contains the deepest directory that already exists
     
    7065            continue
    7166
    72         log.info("creating %s", head)
     67        if verbose >= 1:
     68            log.info("creating %s", head)
    7369
    7470        if not dry_run:
    7571            try:
    76                 os.mkdir(head)
    77                 created_dirs.append(head)
     72                os.mkdir(head, mode)
    7873            except OSError, exc:
    79                 raise DistutilsFileError, \
    80                       "could not create '%s': %s" % (head, exc[-1])
     74                if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
     75                    raise DistutilsFileError(
     76                          "could not create '%s': %s" % (head, exc.args[-1]))
     77            created_dirs.append(head)
    8178
    8279        _path_created[abs_head] = 1
    8380    return created_dirs
    8481
    85 # mkpath ()
    86 
    87 
    88 def create_tree (base_dir, files, mode=0777, verbose=0, dry_run=0):
    89 
    90     """Create all the empty directories under 'base_dir' needed to
    91        put 'files' there.  'base_dir' is just the a name of a directory
    92        which doesn't necessarily exist yet; 'files' is a list of filenames
    93        to be interpreted relative to 'base_dir'.  'base_dir' + the
    94        directory portion of every file in 'files' will be created if it
    95        doesn't already exist.  'mode', 'verbose' and 'dry_run' flags are as
    96        for 'mkpath()'."""
    97 
     82def create_tree(base_dir, files, mode=0777, verbose=1, dry_run=0):
     83    """Create all the empty directories under 'base_dir' needed to put 'files'
     84    there.
     85
     86    'base_dir' is just the a name of a directory which doesn't necessarily
     87    exist yet; 'files' is a list of filenames to be interpreted relative to
     88    'base_dir'.  'base_dir' + the directory portion of every file in 'files'
     89    will be created if it doesn't already exist.  'mode', 'verbose' and
     90    'dry_run' flags are as for 'mkpath()'.
     91    """
    9892    # First get the list of directories to create
    9993    need_dir = {}
     
    10599    # Now create them
    106100    for dir in need_dirs:
    107         mkpath(dir, mode, dry_run=dry_run)
    108 
    109 # create_tree ()
    110 
    111 
    112 def copy_tree (src, dst,
    113                preserve_mode=1,
    114                preserve_times=1,
    115                preserve_symlinks=0,
    116                update=0,
    117                verbose=0,
    118                dry_run=0):
    119 
    120     """Copy an entire directory tree 'src' to a new location 'dst'.  Both
    121        'src' and 'dst' must be directory names.  If 'src' is not a
    122        directory, raise DistutilsFileError.  If 'dst' does not exist, it is
    123        created with 'mkpath()'.  The end result of the copy is that every
    124        file in 'src' is copied to 'dst', and directories under 'src' are
    125        recursively copied to 'dst'.  Return the list of files that were
    126        copied or might have been copied, using their output name.  The
    127        return value is unaffected by 'update' or 'dry_run': it is simply
    128        the list of all files under 'src', with the names changed to be
    129        under 'dst'.
    130 
    131        'preserve_mode' and 'preserve_times' are the same as for
    132        'copy_file'; note that they only apply to regular files, not to
    133        directories.  If 'preserve_symlinks' is true, symlinks will be
    134        copied as symlinks (on platforms that support them!); otherwise
    135        (the default), the destination of the symlink will be copied.
    136        'update' and 'verbose' are the same as for 'copy_file'."""
    137 
     101        mkpath(dir, mode, verbose=verbose, dry_run=dry_run)
     102
     103def copy_tree(src, dst, preserve_mode=1, preserve_times=1,
     104              preserve_symlinks=0, update=0, verbose=1, dry_run=0):
     105    """Copy an entire directory tree 'src' to a new location 'dst'.
     106
     107    Both 'src' and 'dst' must be directory names.  If 'src' is not a
     108    directory, raise DistutilsFileError.  If 'dst' does not exist, it is
     109    created with 'mkpath()'.  The end result of the copy is that every
     110    file in 'src' is copied to 'dst', and directories under 'src' are
     111    recursively copied to 'dst'.  Return the list of files that were
     112    copied or might have been copied, using their output name.  The
     113    return value is unaffected by 'update' or 'dry_run': it is simply
     114    the list of all files under 'src', with the names changed to be
     115    under 'dst'.
     116
     117    'preserve_mode' and 'preserve_times' are the same as for
     118    'copy_file'; note that they only apply to regular files, not to
     119    directories.  If 'preserve_symlinks' is true, symlinks will be
     120    copied as symlinks (on platforms that support them!); otherwise
     121    (the default), the destination of the symlink will be copied.
     122    'update' and 'verbose' are the same as for 'copy_file'.
     123    """
    138124    from distutils.file_util import copy_file
    139125
     
    151137
    152138    if not dry_run:
    153         mkpath(dst)
     139        mkpath(dst, verbose=verbose)
    154140
    155141    outputs = []
     
    159145        dst_name = os.path.join(dst, n)
    160146
     147        if n.startswith('.nfs'):
     148            # skip NFS rename files
     149            continue
     150
    161151        if preserve_symlinks and os.path.islink(src_name):
    162152            link_dest = os.readlink(src_name)
    163             log.info("linking %s -> %s", dst_name, link_dest)
     153            if verbose >= 1:
     154                log.info("linking %s -> %s", dst_name, link_dest)
    164155            if not dry_run:
    165156                os.symlink(link_dest, dst_name)
     
    170161                copy_tree(src_name, dst_name, preserve_mode,
    171162                          preserve_times, preserve_symlinks, update,
    172                           dry_run=dry_run))
     163                          verbose=verbose, dry_run=dry_run))
    173164        else:
    174165            copy_file(src_name, dst_name, preserve_mode,
    175                       preserve_times, update, dry_run=dry_run)
     166                      preserve_times, update, verbose=verbose,
     167                      dry_run=dry_run)
    176168            outputs.append(dst_name)
    177169
    178170    return outputs
    179171
    180 # copy_tree ()
    181 
    182 # Helper for remove_tree()
    183172def _build_cmdtuple(path, cmdtuples):
     173    """Helper for remove_tree()."""
    184174    for f in os.listdir(path):
    185175        real_f = os.path.join(path,f)
     
    190180    cmdtuples.append((os.rmdir, path))
    191181
    192 
    193 def remove_tree (directory, verbose=0, dry_run=0):
    194     """Recursively remove an entire directory tree.  Any errors are ignored
    195     (apart from being reported to stdout if 'verbose' is true).
     182def remove_tree(directory, verbose=1, dry_run=0):
     183    """Recursively remove an entire directory tree.
     184
     185    Any errors are ignored (apart from being reported to stdout if 'verbose'
     186    is true).
    196187    """
    197188    from distutils.util import grok_environment_error
    198189    global _path_created
    199190
    200     log.info("removing '%s' (and everything under it)", directory)
     191    if verbose >= 1:
     192        log.info("removing '%s' (and everything under it)", directory)
    201193    if dry_run:
    202194        return
     
    205197    for cmd in cmdtuples:
    206198        try:
    207             apply(cmd[0], (cmd[1],))
     199            cmd[0](cmd[1])
    208200            # remove dir from cache if it's already there
    209201            abspath = os.path.abspath(cmd[1])
     
    214206                    exc, "error removing %s: " % directory))
    215207
    216 
    217 def ensure_relative (path):
    218     """Take the full path 'path', and make it a relative path so
    219     it can be the second argument to os.path.join().
     208def ensure_relative(path):
     209    """Take the full path 'path', and make it a relative path.
     210
     211    This is useful to make 'path' the second argument to os.path.join().
    220212    """
    221213    drive, path = os.path.splitdrive(path)
    222     if sys.platform == 'mac':
    223         return os.sep + path
    224     else:
    225         if path[0:1] == os.sep:
    226             path = drive + path[1:]
    227         return path
     214    if path[0:1] == os.sep:
     215        path = drive + path[1:]
     216    return path
  • python/vendor/current/Lib/distutils/dist.py

    r2 r388  
    55"""
    66
    7 # This module should be kept compatible with Python 2.1.
    8 
    9 __revision__ = "$Id: dist.py 77719 2010-01-24 00:57:20Z tarek.ziade $"
    10 
    11 import sys, os, string, re
    12 from types import *
    13 from copy import copy
     7__revision__ = "$Id$"
     8
     9import sys, os, re
     10from email import message_from_file
    1411
    1512try:
     
    1815    warnings = None
    1916
    20 from distutils.errors import *
     17from distutils.errors import (DistutilsOptionError, DistutilsArgError,
     18                              DistutilsModuleError, DistutilsClassError)
    2119from distutils.fancy_getopt import FancyGetopt, translate_longopt
    2220from distutils.util import check_environ, strtobool, rfc822_escape
     
    6159                      ('dry-run', 'n', "don't actually do anything"),
    6260                      ('help', 'h', "show detailed help message"),
    63                      ]
     61                      ('no-user-cfg', None,
     62                       'ignore pydistutils.cfg in your home directory'),
     63    ]
    6464
    6565    # 'common_usage' is a short (2-3 line) string describing the common
     
    207207        self.scripts = None
    208208        self.data_files = None
     209        self.password = ''
    209210
    210211        # And now initialize bookkeeping stuff that can't be supplied by
     
    254255            # Now work on the rest of the attributes.  Any attribute that's
    255256            # not already defined is invalid!
    256             for (key,val) in attrs.items():
     257            for (key, val) in attrs.items():
    257258                if hasattr(self.metadata, "set_" + key):
    258259                    getattr(self.metadata, "set_" + key)(val)
     
    268269                        sys.stderr.write(msg + "\n")
    269270
     271        # no-user-cfg is handled before other command line args
     272        # because other args override the config files, and this
     273        # one is needed before we can load the config files.
     274        # If attrs['script_args'] wasn't passed, assume false.
     275        #
     276        # This also make sure we just look at the global options
     277        self.want_user_cfg = True
     278
     279        if self.script_args is not None:
     280            for arg in self.script_args:
     281                if not arg.startswith('-'):
     282                    break
     283                if arg == '--no-user-cfg':
     284                    self.want_user_cfg = False
     285                    break
     286
    270287        self.finalize_options()
    271288
    272     # __init__ ()
    273 
    274 
    275     def get_option_dict (self, command):
     289    def get_option_dict(self, command):
    276290        """Get the option dictionary for a given command.  If that
    277291        command's option dictionary hasn't been created yet, then create it
     
    279293        option dictionary.
    280294        """
    281 
    282295        dict = self.command_options.get(command)
    283296        if dict is None:
     
    285298        return dict
    286299
    287 
    288     def dump_option_dicts (self, header=None, commands=None, indent=""):
     300    def dump_option_dicts(self, header=None, commands=None, indent=""):
    289301        from pprint import pformat
    290302
     
    294306
    295307        if header is not None:
    296             print indent + header
     308            self.announce(indent + header)
    297309            indent = indent + "  "
    298310
    299311        if not commands:
    300             print indent + "no commands known yet"
     312            self.announce(indent + "no commands known yet")
    301313            return
    302314
     
    304316            opt_dict = self.command_options.get(cmd_name)
    305317            if opt_dict is None:
    306                 print indent + "no option dict for '%s' command" % cmd_name
     318                self.announce(indent +
     319                              "no option dict for '%s' command" % cmd_name)
    307320            else:
    308                 print indent + "option dict for '%s' command:" % cmd_name
     321                self.announce(indent +
     322                              "option dict for '%s' command:" % cmd_name)
    309323                out = pformat(opt_dict)
    310                 for line in string.split(out, "\n"):
    311                     print indent + "  " + line
    312 
    313     # dump_option_dicts ()
    314 
    315 
     324                for line in out.split('\n'):
     325                    self.announce(indent + "  " + line)
    316326
    317327    # -- Config file finding/parsing methods ---------------------------
    318328
    319     def find_config_files (self):
     329    def find_config_files(self):
    320330        """Find as many configuration files as should be processed for this
    321331        platform, and return a list of filenames in the order in which they
     
    327337        Distutils __inst__.py file lives), a file in the user's home
    328338        directory named .pydistutils.cfg on Unix and pydistutils.cfg
    329         on Windows/Mac, and setup.cfg in the current directory.
     339        on Windows/Mac; and setup.cfg in the current directory.
     340
     341        The file in the user's home directory can be disabled with the
     342        --no-user-cfg option.
    330343        """
    331344        files = []
     
    347360
    348361        # And look for the user config file
    349         user_file = os.path.join(os.path.expanduser('~'), user_filename)
    350         if os.path.isfile(user_file):
    351             files.append(user_file)
     362        if self.want_user_cfg:
     363            user_file = os.path.join(os.path.expanduser('~'), user_filename)
     364            if os.path.isfile(user_file):
     365                files.append(user_file)
    352366
    353367        # All platforms support local setup.cfg
     
    356370            files.append(local_file)
    357371
     372        if DEBUG:
     373            self.announce("using config files: %s" % ', '.join(files))
     374
    358375        return files
    359376
    360     # find_config_files ()
    361 
    362 
    363     def parse_config_files (self, filenames=None):
     377    def parse_config_files(self, filenames=None):
    364378        from ConfigParser import ConfigParser
    365379
     
    367381            filenames = self.find_config_files()
    368382
    369         if DEBUG: print "Distribution.parse_config_files():"
     383        if DEBUG:
     384            self.announce("Distribution.parse_config_files():")
    370385
    371386        parser = ConfigParser()
    372387        for filename in filenames:
    373             if DEBUG: print "  reading", filename
     388            if DEBUG:
     389                self.announce("  reading %s" % filename)
    374390            parser.read(filename)
    375391            for section in parser.sections():
     
    380396                    if opt != '__name__':
    381397                        val = parser.get(section,opt)
    382                         opt = string.replace(opt, '-', '_')
     398                        opt = opt.replace('-', '_')
    383399                        opt_dict[opt] = (filename, val)
    384400
     
    403419                    raise DistutilsOptionError, msg
    404420
    405     # parse_config_files ()
    406 
    407 
    408421    # -- Command-line parsing methods ----------------------------------
    409422
    410     def parse_command_line (self):
     423    def parse_command_line(self):
    411424        """Parse the setup script's command line, taken from the
    412425        'script_args' instance attribute (which defaults to 'sys.argv[1:]'
     
    432445        #
    433446        toplevel_options = self._get_toplevel_options()
    434         if sys.platform == 'mac':
    435             import EasyDialogs
    436             cmdlist = self.get_command_list()
    437             self.script_args = EasyDialogs.GetArgv(
    438                 toplevel_options + self.display_options, cmdlist)
    439447
    440448        # We have to parse the command line a bit at a time -- global
     
    456464        if self.handle_display_options(option_order):
    457465            return
    458 
    459466        while args:
    460467            args = self._parse_command_opts(parser, args)
     
    481488        return 1
    482489
    483     # parse_command_line()
    484 
    485     def _get_toplevel_options (self):
     490    def _get_toplevel_options(self):
    486491        """Return the non-display options recognized at the top level.
    487492
     
    494499            ]
    495500
    496     def _parse_command_opts (self, parser, args):
     501    def _parse_command_opts(self, parser, args):
    497502        """Parse the command-line options for a single command.
    498503        'parser' must be a FancyGetopt instance; 'args' must be the list
     
    529534        # known options.
    530535        if not (hasattr(cmd_class, 'user_options') and
    531                 type(cmd_class.user_options) is ListType):
     536                isinstance(cmd_class.user_options, list)):
    532537            raise DistutilsClassError, \
    533538                  ("command class %s must provide " +
     
    539544        negative_opt = self.negative_opt
    540545        if hasattr(cmd_class, 'negative_opt'):
    541             negative_opt = copy(negative_opt)
     546            negative_opt = negative_opt.copy()
    542547            negative_opt.update(cmd_class.negative_opt)
    543548
     
    545550        # format (tuple of four) so we need to preprocess them here.
    546551        if (hasattr(cmd_class, 'help_options') and
    547             type(cmd_class.help_options) is ListType):
     552            isinstance(cmd_class.help_options, list)):
    548553            help_options = fix_help_options(cmd_class.help_options)
    549554        else:
     
    563568
    564569        if (hasattr(cmd_class, 'help_options') and
    565             type(cmd_class.help_options) is ListType):
     570            isinstance(cmd_class.help_options, list)):
    566571            help_option_found=0
    567572            for (help_option, short, desc, func) in cmd_class.help_options:
    568573                if hasattr(opts, parser.get_attr_name(help_option)):
    569574                    help_option_found=1
    570                     #print "showing help for option %s of command %s" % \
    571                     #      (help_option[0],cmd_class)
    572 
    573                     if callable(func):
     575                    if hasattr(func, '__call__'):
    574576                        func()
    575577                    else:
     
    590592        return args
    591593
    592     # _parse_command_opts ()
    593 
    594     def finalize_options (self):
     594    def finalize_options(self):
    595595        """Set final values for all the options on the Distribution
    596596        instance, analogous to the .finalize_options() method of Command
    597597        objects.
    598598        """
    599 
    600         keywords = self.metadata.keywords
    601         if keywords is not None:
    602             if type(keywords) is StringType:
    603                 keywordlist = string.split(keywords, ',')
    604                 self.metadata.keywords = map(string.strip, keywordlist)
    605 
    606         platforms = self.metadata.platforms
    607         if platforms is not None:
    608             if type(platforms) is StringType:
    609                 platformlist = string.split(platforms, ',')
    610                 self.metadata.platforms = map(string.strip, platformlist)
    611 
    612     def _show_help (self,
    613                     parser,
    614                     global_options=1,
    615                     display_options=1,
    616                     commands=[]):
     599        for attr in ('keywords', 'platforms'):
     600            value = getattr(self.metadata, attr)
     601            if value is None:
     602                continue
     603            if isinstance(value, str):
     604                value = [elm.strip() for elm in value.split(',')]
     605                setattr(self.metadata, attr, value)
     606
     607    def _show_help(self, parser, global_options=1, display_options=1,
     608                   commands=[]):
    617609        """Show help for the setup script command-line in the form of
    618610        several lists of command-line options.  'parser' should be a
     
    638630            parser.set_option_table(options)
    639631            parser.print_help(self.common_usage + "\nGlobal options:")
    640             print
     632            print('')
    641633
    642634        if display_options:
     
    645637                "Information display options (just display " +
    646638                "information, ignore any commands)")
    647             print
     639            print('')
    648640
    649641        for command in self.commands:
    650             if type(command) is ClassType and issubclass(command, Command):
     642            if isinstance(command, type) and issubclass(command, Command):
    651643                klass = command
    652644            else:
    653645                klass = self.get_command_class(command)
    654646            if (hasattr(klass, 'help_options') and
    655                 type(klass.help_options) is ListType):
     647                isinstance(klass.help_options, list)):
    656648                parser.set_option_table(klass.user_options +
    657649                                        fix_help_options(klass.help_options))
     
    659651                parser.set_option_table(klass.user_options)
    660652            parser.print_help("Options for '%s' command:" % klass.__name__)
    661             print
    662 
    663         print gen_usage(self.script_name)
    664         return
    665 
    666     # _show_help ()
    667 
    668 
    669     def handle_display_options (self, option_order):
     653            print('')
     654
     655        print(gen_usage(self.script_name))
     656
     657    def handle_display_options(self, option_order):
    670658        """If there were any non-global "display-only" options
    671659        (--help-commands or the metadata display options) on the command
     
    680668        if self.help_commands:
    681669            self.print_commands()
    682             print
    683             print gen_usage(self.script_name)
     670            print('')
     671            print(gen_usage(self.script_name))
    684672            return 1
    685673
     
    697685                value = getattr(self.metadata, "get_"+opt)()
    698686                if opt in ['keywords', 'platforms']:
    699                     print string.join(value, ',')
     687                    print(','.join(value))
    700688                elif opt in ('classifiers', 'provides', 'requires',
    701689                             'obsoletes'):
    702                     print string.join(value, '\n')
     690                    print('\n'.join(value))
    703691                else:
    704                     print value
     692                    print(value)
    705693                any_display_options = 1
    706694
    707695        return any_display_options
    708696
    709     # handle_display_options()
    710 
    711     def print_command_list (self, commands, header, max_length):
     697    def print_command_list(self, commands, header, max_length):
    712698        """Print a subset of the list of all commands -- used by
    713699        'print_commands()'.
    714700        """
    715 
    716         print header + ":"
     701        print(header + ":")
    717702
    718703        for cmd in commands:
     
    725710                description = "(no description available)"
    726711
    727             print "  %-*s  %s" % (max_length, cmd, description)
    728 
    729     # print_command_list ()
    730 
    731 
    732     def print_commands (self):
     712            print("  %-*s  %s" % (max_length, cmd, description))
     713
     714    def print_commands(self):
    733715        """Print out a help message listing all available commands with a
    734716        description of each.  The list is divided into "standard commands"
     
    738720        'description'.
    739721        """
    740 
    741722        import distutils.command
    742723        std_commands = distutils.command.__all__
     
    764745                                    max_length)
    765746
    766     # print_commands ()
    767 
    768     def get_command_list (self):
     747    def get_command_list(self):
    769748        """Get a list of (command, description) tuples.
    770749        The list is divided into "standard commands" (listed in
     
    801780    # -- Command class/object methods ----------------------------------
    802781
    803     def get_command_packages (self):
     782    def get_command_packages(self):
    804783        """Return a list of packages from which commands are loaded."""
    805784        pkgs = self.command_packages
    806         if not isinstance(pkgs, type([])):
    807             pkgs = string.split(pkgs or "", ",")
    808             for i in range(len(pkgs)):
    809                 pkgs[i] = string.strip(pkgs[i])
    810             pkgs = filter(None, pkgs)
     785        if not isinstance(pkgs, list):
     786            if pkgs is None:
     787                pkgs = ''
     788            pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']
    811789            if "distutils.command" not in pkgs:
    812790                pkgs.insert(0, "distutils.command")
     
    814792        return pkgs
    815793
    816     def get_command_class (self, command):
     794    def get_command_class(self, command):
    817795        """Return the class that implements the Distutils command named by
    818796        'command'.  First we check the 'cmdclass' dictionary; if the
     
    853831
    854832
    855     # get_command_class ()
    856 
    857     def get_command_obj (self, command, create=1):
     833    def get_command_obj(self, command, create=1):
    858834        """Return the command object for 'command'.  Normally this object
    859835        is cached on a previous call to 'get_command_obj()'; if no command
     
    864840        if not cmd_obj and create:
    865841            if DEBUG:
    866                 print "Distribution.get_command_obj(): " \
    867                       "creating '%s' command object" % command
     842                self.announce("Distribution.get_command_obj(): " \
     843                              "creating '%s' command object" % command)
    868844
    869845            klass = self.get_command_class(command)
     
    882858        return cmd_obj
    883859
    884     def _set_command_options (self, command_obj, option_dict=None):
     860    def _set_command_options(self, command_obj, option_dict=None):
    885861        """Set the options for 'command_obj' from 'option_dict'.  Basically
    886862        this means copying elements of a dictionary ('option_dict') to
     
    895871            option_dict = self.get_option_dict(command_name)
    896872
    897         if DEBUG: print "  setting options for '%s' command:" % command_name
     873        if DEBUG:
     874            self.announce("  setting options for '%s' command:" % command_name)
    898875        for (option, (source, value)) in option_dict.items():
    899             if DEBUG: print "    %s = %s (from %s)" % (option, value, source)
     876            if DEBUG:
     877                self.announce("    %s = %s (from %s)" % (option, value,
     878                                                         source))
    900879            try:
    901880                bool_opts = map(translate_longopt, command_obj.boolean_options)
     
    908887
    909888            try:
    910                 is_string = type(value) is StringType
     889                is_string = isinstance(value, str)
    911890                if option in neg_opt and is_string:
    912891                    setattr(command_obj, neg_opt[option], not strtobool(value))
     
    922901                raise DistutilsOptionError, msg
    923902
    924     def reinitialize_command (self, command, reinit_subcommands=0):
     903    def reinitialize_command(self, command, reinit_subcommands=0):
    925904        """Reinitializes a command to the state it was in when first
    926905        returned by 'get_command_obj()': ie., initialized but not yet
     
    961940        return command
    962941
    963 
    964942    # -- Methods that operate on the Distribution ----------------------
    965943
    966     def announce (self, msg, level=1):
    967         log.debug(msg)
    968 
    969     def run_commands (self):
     944    def announce(self, msg, level=log.INFO):
     945        log.log(level, msg)
     946
     947    def run_commands(self):
    970948        """Run each command that was seen on the setup script command line.
    971949        Uses the list of commands found and cache of command objects
     
    975953            self.run_command(cmd)
    976954
    977 
    978955    # -- Methods that operate on its Commands --------------------------
    979956
    980     def run_command (self, command):
     957    def run_command(self, command):
    981958        """Do whatever it takes to run a command (including nothing at all,
    982959        if the command has already been run).  Specifically: if we have
     
    999976    # -- Distribution query methods ------------------------------------
    1000977
    1001     def has_pure_modules (self):
     978    def has_pure_modules(self):
    1002979        return len(self.packages or self.py_modules or []) > 0
    1003980
    1004     def has_ext_modules (self):
     981    def has_ext_modules(self):
    1005982        return self.ext_modules and len(self.ext_modules) > 0
    1006983
    1007     def has_c_libraries (self):
     984    def has_c_libraries(self):
    1008985        return self.libraries and len(self.libraries) > 0
    1009986
    1010     def has_modules (self):
     987    def has_modules(self):
    1011988        return self.has_pure_modules() or self.has_ext_modules()
    1012989
    1013     def has_headers (self):
     990    def has_headers(self):
    1014991        return self.headers and len(self.headers) > 0
    1015992
    1016     def has_scripts (self):
     993    def has_scripts(self):
    1017994        return self.scripts and len(self.scripts) > 0
    1018995
    1019     def has_data_files (self):
     996    def has_data_files(self):
    1020997        return self.data_files and len(self.data_files) > 0
    1021998
    1022     def is_pure (self):
     999    def is_pure(self):
    10231000        return (self.has_pure_modules() and
    10241001                not self.has_ext_modules() and
     
    10311008    # to self.metadata.get_XXX.  The actual code is in the
    10321009    # DistributionMetadata class, below.
    1033 
    1034 # class Distribution
    1035 
    10361010
    10371011class DistributionMetadata:
     
    10501024                         )
    10511025
    1052     def __init__ (self):
    1053         self.name = None
    1054         self.version = None
    1055         self.author = None
    1056         self.author_email = None
     1026    def __init__(self, path=None):
     1027        if path is not None:
     1028            self.read_pkg_file(open(path))
     1029        else:
     1030            self.name = None
     1031            self.version = None
     1032            self.author = None
     1033            self.author_email = None
     1034            self.maintainer = None
     1035            self.maintainer_email = None
     1036            self.url = None
     1037            self.license = None
     1038            self.description = None
     1039            self.long_description = None
     1040            self.keywords = None
     1041            self.platforms = None
     1042            self.classifiers = None
     1043            self.download_url = None
     1044            # PEP 314
     1045            self.provides = None
     1046            self.requires = None
     1047            self.obsoletes = None
     1048
     1049    def read_pkg_file(self, file):
     1050        """Reads the metadata values from a file object."""
     1051        msg = message_from_file(file)
     1052
     1053        def _read_field(name):
     1054            value = msg[name]
     1055            if value == 'UNKNOWN':
     1056                return None
     1057            return value
     1058
     1059        def _read_list(name):
     1060            values = msg.get_all(name, None)
     1061            if values == []:
     1062                return None
     1063            return values
     1064
     1065        metadata_version = msg['metadata-version']
     1066        self.name = _read_field('name')
     1067        self.version = _read_field('version')
     1068        self.description = _read_field('summary')
     1069        # we are filling author only.
     1070        self.author = _read_field('author')
    10571071        self.maintainer = None
     1072        self.author_email = _read_field('author-email')
    10581073        self.maintainer_email = None
    1059         self.url = None
    1060         self.license = None
    1061         self.description = None
    1062         self.long_description = None
    1063         self.keywords = None
    1064         self.platforms = None
    1065         self.classifiers = None
    1066         self.download_url = None
    1067         # PEP 314
    1068         self.provides = None
    1069         self.requires = None
    1070         self.obsoletes = None
    1071 
    1072     def write_pkg_info (self, base_dir):
     1074        self.url = _read_field('home-page')
     1075        self.license = _read_field('license')
     1076
     1077        if 'download-url' in msg:
     1078            self.download_url = _read_field('download-url')
     1079        else:
     1080            self.download_url = None
     1081
     1082        self.long_description = _read_field('description')
     1083        self.description = _read_field('summary')
     1084
     1085        if 'keywords' in msg:
     1086            self.keywords = _read_field('keywords').split(',')
     1087
     1088        self.platforms = _read_list('platform')
     1089        self.classifiers = _read_list('classifier')
     1090
     1091        # PEP 314 - these fields only exist in 1.1
     1092        if metadata_version == '1.1':
     1093            self.requires = _read_list('requires')
     1094            self.provides = _read_list('provides')
     1095            self.obsoletes = _read_list('obsoletes')
     1096        else:
     1097            self.requires = None
     1098            self.provides = None
     1099            self.obsoletes = None
     1100
     1101    def write_pkg_info(self, base_dir):
    10731102        """Write the PKG-INFO file into the release tree.
    10741103        """
    1075         pkg_info = open( os.path.join(base_dir, 'PKG-INFO'), 'w')
    1076 
    1077         self.write_pkg_file(pkg_info)
    1078 
    1079         pkg_info.close()
    1080 
    1081     # write_pkg_info ()
    1082 
    1083     def write_pkg_file (self, file):
     1104        pkg_info = open(os.path.join(base_dir, 'PKG-INFO'), 'w')
     1105        try:
     1106            self.write_pkg_file(pkg_info)
     1107        finally:
     1108            pkg_info.close()
     1109
     1110    def write_pkg_file(self, file):
    10841111        """Write the PKG-INFO format data to a file object.
    10851112        """
    10861113        version = '1.0'
    1087         if self.provides or self.requires or self.obsoletes:
     1114        if (self.provides or self.requires or self.obsoletes or
     1115            self.classifiers or self.download_url):
    10881116            version = '1.1'
    10891117
     
    10991127            self._write_field(file, 'Download-URL', self.download_url)
    11001128
    1101         long_desc = rfc822_escape( self.get_long_description())
     1129        long_desc = rfc822_escape(self.get_long_description())
    11021130        self._write_field(file, 'Description', long_desc)
    11031131
    1104         keywords = string.join( self.get_keywords(), ',')
     1132        keywords = ','.join(self.get_keywords())
    11051133        if keywords:
    11061134            self._write_field(file, 'Keywords', keywords)
     
    11181146
    11191147    def _write_list (self, file, name, values):
    1120 
    11211148        for value in values:
    11221149            self._write_field(file, name, value)
     
    11311158    # -- Metadata query methods ----------------------------------------
    11321159
    1133     def get_name (self):
     1160    def get_name(self):
    11341161        return self.name or "UNKNOWN"
    11351162
     
    11371164        return self.version or "0.0.0"
    11381165
    1139     def get_fullname (self):
     1166    def get_fullname(self):
    11401167        return "%s-%s" % (self.get_name(), self.get_version())
    11411168
     
    11571184
    11581185    def get_contact_email(self):
    1159         return (self.maintainer_email or
    1160                 self.author_email or
    1161                 "UNKNOWN")
     1186        return self.maintainer_email or self.author_email or "UNKNOWN"
    11621187
    11631188    def get_url(self):
     
    11871212
    11881213    # PEP 314
    1189 
    11901214    def get_requires(self):
    11911215        return self.requires or []
     
    12161240        self.obsoletes = value
    12171241
    1218 # class DistributionMetadata
    1219 
    1220 
    1221 def fix_help_options (options):
     1242def fix_help_options(options):
    12221243    """Convert a 4-tuple 'help_options' list as found in various command
    12231244    classes to the 3-tuple form required by FancyGetopt.
     
    12271248        new_options.append(help_tuple[0:3])
    12281249    return new_options
    1229 
    1230 
    1231 if __name__ == "__main__":
    1232     dist = Distribution()
    1233     print "ok"
  • python/vendor/current/Lib/distutils/emxccompiler.py

    r2 r388  
    2020# * EMX gcc 2.81/EMX 0.9d fix03
    2121
    22 __revision__ = "$Id: emxccompiler.py 34786 2003-12-02 12:17:59Z aimacintyre $"
     22__revision__ = "$Id$"
    2323
    2424import os,sys,copy
     
    273273        # But we do this only once, and it is fast enough
    274274        f = open(fn)
    275         s = f.read()
    276         f.close()
     275        try:
     276            s = f.read()
     277        finally:
     278            f.close()
    277279
    278280    except IOError, exc:
     
    301303    if gcc_exe:
    302304        out = os.popen(gcc_exe + ' -dumpversion','r')
    303         out_string = out.read()
    304         out.close()
     305        try:
     306            out_string = out.read()
     307        finally:
     308            out.close()
    305309        result = re.search('(\d+\.\d+\.\d+)',out_string)
    306310        if result:
  • python/vendor/current/Lib/distutils/errors.py

    r2 r388  
    99symbols whose names start with "Distutils" and end with "Error"."""
    1010
    11 # This module should be kept compatible with Python 2.1.
     11__revision__ = "$Id$"
    1212
    13 __revision__ = "$Id: errors.py 77376 2010-01-08 23:27:23Z tarek.ziade $"
     13class DistutilsError(Exception):
     14    """The root of all Distutils evil."""
    1415
    15 class DistutilsError (Exception):
    16     """The root of all Distutils evil."""
    17     pass
    18 
    19 class DistutilsModuleError (DistutilsError):
     16class DistutilsModuleError(DistutilsError):
    2017    """Unable to load an expected module, or to find an expected class
    2118    within some module (in particular, command modules and classes)."""
    22     pass
    2319
    24 class DistutilsClassError (DistutilsError):
     20class DistutilsClassError(DistutilsError):
    2521    """Some command class (or possibly distribution class, if anyone
    2622    feels a need to subclass Distribution) is found not to be holding
    2723    up its end of the bargain, ie. implementing some part of the
    2824    "command "interface."""
    29     pass
    3025
    31 class DistutilsGetoptError (DistutilsError):
     26class DistutilsGetoptError(DistutilsError):
    3227    """The option table provided to 'fancy_getopt()' is bogus."""
    33     pass
    3428
    35 class DistutilsArgError (DistutilsError):
     29class DistutilsArgError(DistutilsError):
    3630    """Raised by fancy_getopt in response to getopt.error -- ie. an
    3731    error in the command line usage."""
    38     pass
    3932
    40 class DistutilsFileError (DistutilsError):
     33class DistutilsFileError(DistutilsError):
    4134    """Any problems in the filesystem: expected file not found, etc.
    4235    Typically this is for problems that we detect before IOError or
    4336    OSError could be raised."""
    44     pass
    4537
    46 class DistutilsOptionError (DistutilsError):
     38class DistutilsOptionError(DistutilsError):
    4739    """Syntactic/semantic errors in command options, such as use of
    4840    mutually conflicting options, or inconsistent options,
     
    5143    files, or what-have-you -- but if we *know* something originated in
    5244    the setup script, we'll raise DistutilsSetupError instead."""
    53     pass
    5445
    55 class DistutilsSetupError (DistutilsError):
     46class DistutilsSetupError(DistutilsError):
    5647    """For errors that can be definitely blamed on the setup script,
    5748    such as invalid keyword arguments to 'setup()'."""
    58     pass
    5949
    60 class DistutilsPlatformError (DistutilsError):
     50class DistutilsPlatformError(DistutilsError):
    6151    """We don't know how to do something on the current platform (but
    6252    we do know how to do it on some platform) -- eg. trying to compile
    6353    C files on a platform not supported by a CCompiler subclass."""
    64     pass
    6554
    66 class DistutilsExecError (DistutilsError):
     55class DistutilsExecError(DistutilsError):
    6756    """Any problems executing an external program (such as the C
    6857    compiler, when compiling C files)."""
    69     pass
    7058
    71 class DistutilsInternalError (DistutilsError):
     59class DistutilsInternalError(DistutilsError):
    7260    """Internal inconsistencies or impossibilities (obviously, this
    7361    should never be seen if the code is working!)."""
    74     pass
    7562
    76 class DistutilsTemplateError (DistutilsError):
     63class DistutilsTemplateError(DistutilsError):
    7764    """Syntax error in a file list template."""
    7865
     
    8168
    8269# Exception classes used by the CCompiler implementation classes
    83 class CCompilerError (Exception):
     70class CCompilerError(Exception):
    8471    """Some compile/link operation failed."""
    8572
    86 class PreprocessError (CCompilerError):
     73class PreprocessError(CCompilerError):
    8774    """Failure to preprocess one or more C/C++ files."""
    8875
    89 class CompileError (CCompilerError):
     76class CompileError(CCompilerError):
    9077    """Failure to compile one or more C/C++ source files."""
    9178
    92 class LibError (CCompilerError):
     79class LibError(CCompilerError):
    9380    """Failure to create a static library from one or more C/C++ object
    9481    files."""
    9582
    96 class LinkError (CCompilerError):
     83class LinkError(CCompilerError):
    9784    """Failure to link one or more C/C++ object files into an executable
    9885    or shared library file."""
    9986
    100 class UnknownFileError (CCompilerError):
     87class UnknownFileError(CCompilerError):
    10188    """Attempt to process an unknown file type."""
  • python/vendor/current/Lib/distutils/extension.py

    r2 r388  
    44modules in setup scripts."""
    55
    6 __revision__ = "$Id: extension.py 37623 2004-10-14 10:02:08Z anthonybaxter $"
     6__revision__ = "$Id$"
    77
    88import os, string, sys
     
    151151                    strip_comments=1, skip_blanks=1, join_lines=1,
    152152                    lstrip_ws=1, rstrip_ws=1)
    153     extensions = []
    154 
    155     while 1:
    156         line = file.readline()
    157         if line is None:                # eof
    158             break
    159         if _variable_rx.match(line):    # VAR=VALUE, handled in first pass
    160             continue
    161 
    162         if line[0] == line[-1] == "*":
    163             file.warn("'%s' lines not handled yet" % line)
    164             continue
    165 
    166         #print "original line: " + line
    167         line = expand_makefile_vars(line, vars)
    168         words = split_quoted(line)
    169         #print "expanded line: " + line
    170 
    171         # NB. this parses a slightly different syntax than the old
    172         # makesetup script: here, there must be exactly one extension per
    173         # line, and it must be the first word of the line.  I have no idea
    174         # why the old syntax supported multiple extensions per line, as
    175         # they all wind up being the same.
    176 
    177         module = words[0]
    178         ext = Extension(module, [])
    179         append_next_word = None
    180 
    181         for word in words[1:]:
    182             if append_next_word is not None:
    183                 append_next_word.append(word)
    184                 append_next_word = None
     153    try:
     154        extensions = []
     155
     156        while 1:
     157            line = file.readline()
     158            if line is None:                # eof
     159                break
     160            if _variable_rx.match(line):    # VAR=VALUE, handled in first pass
    185161                continue
    186162
    187             suffix = os.path.splitext(word)[1]
    188             switch = word[0:2] ; value = word[2:]
    189 
    190             if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
    191                 # hmm, should we do something about C vs. C++ sources?
    192                 # or leave it up to the CCompiler implementation to
    193                 # worry about?
    194                 ext.sources.append(word)
    195             elif switch == "-I":
    196                 ext.include_dirs.append(value)
    197             elif switch == "-D":
    198                 equals = string.find(value, "=")
    199                 if equals == -1:        # bare "-DFOO" -- no value
    200                     ext.define_macros.append((value, None))
    201                 else:                   # "-DFOO=blah"
    202                     ext.define_macros.append((value[0:equals],
    203                                               value[equals+2:]))
    204             elif switch == "-U":
    205                 ext.undef_macros.append(value)
    206             elif switch == "-C":        # only here 'cause makesetup has it!
    207                 ext.extra_compile_args.append(word)
    208             elif switch == "-l":
    209                 ext.libraries.append(value)
    210             elif switch == "-L":
    211                 ext.library_dirs.append(value)
    212             elif switch == "-R":
    213                 ext.runtime_library_dirs.append(value)
    214             elif word == "-rpath":
    215                 append_next_word = ext.runtime_library_dirs
    216             elif word == "-Xlinker":
    217                 append_next_word = ext.extra_link_args
    218             elif word == "-Xcompiler":
    219                 append_next_word = ext.extra_compile_args
    220             elif switch == "-u":
    221                 ext.extra_link_args.append(word)
    222                 if not value:
     163                if line[0] == line[-1] == "*":
     164                    file.warn("'%s' lines not handled yet" % line)
     165                    continue
     166
     167            #print "original line: " + line
     168            line = expand_makefile_vars(line, vars)
     169            words = split_quoted(line)
     170            #print "expanded line: " + line
     171
     172            # NB. this parses a slightly different syntax than the old
     173            # makesetup script: here, there must be exactly one extension per
     174            # line, and it must be the first word of the line.  I have no idea
     175            # why the old syntax supported multiple extensions per line, as
     176            # they all wind up being the same.
     177
     178            module = words[0]
     179            ext = Extension(module, [])
     180            append_next_word = None
     181
     182            for word in words[1:]:
     183                if append_next_word is not None:
     184                    append_next_word.append(word)
     185                    append_next_word = None
     186                    continue
     187
     188                suffix = os.path.splitext(word)[1]
     189                switch = word[0:2] ; value = word[2:]
     190
     191                if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
     192                    # hmm, should we do something about C vs. C++ sources?
     193                    # or leave it up to the CCompiler implementation to
     194                    # worry about?
     195                    ext.sources.append(word)
     196                elif switch == "-I":
     197                    ext.include_dirs.append(value)
     198                elif switch == "-D":
     199                    equals = string.find(value, "=")
     200                    if equals == -1:        # bare "-DFOO" -- no value
     201                        ext.define_macros.append((value, None))
     202                    else:                   # "-DFOO=blah"
     203                        ext.define_macros.append((value[0:equals],
     204                                                  value[equals+2:]))
     205                elif switch == "-U":
     206                    ext.undef_macros.append(value)
     207                elif switch == "-C":        # only here 'cause makesetup has it!
     208                    ext.extra_compile_args.append(word)
     209                elif switch == "-l":
     210                    ext.libraries.append(value)
     211                elif switch == "-L":
     212                    ext.library_dirs.append(value)
     213                elif switch == "-R":
     214                    ext.runtime_library_dirs.append(value)
     215                elif word == "-rpath":
     216                    append_next_word = ext.runtime_library_dirs
     217                elif word == "-Xlinker":
    223218                    append_next_word = ext.extra_link_args
    224             elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
    225                 # NB. a really faithful emulation of makesetup would
    226                 # append a .o file to extra_objects only if it
    227                 # had a slash in it; otherwise, it would s/.o/.c/
    228                 # and append it to sources.  Hmmmm.
    229                 ext.extra_objects.append(word)
    230             else:
    231                 file.warn("unrecognized argument '%s'" % word)
    232 
    233         extensions.append(ext)
     219                elif word == "-Xcompiler":
     220                    append_next_word = ext.extra_compile_args
     221                elif switch == "-u":
     222                    ext.extra_link_args.append(word)
     223                    if not value:
     224                        append_next_word = ext.extra_link_args
     225                elif word == "-Xcompiler":
     226                    append_next_word = ext.extra_compile_args
     227                elif switch == "-u":
     228                    ext.extra_link_args.append(word)
     229                    if not value:
     230                        append_next_word = ext.extra_link_args
     231                elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
     232                    # NB. a really faithful emulation of makesetup would
     233                    # append a .o file to extra_objects only if it
     234                    # had a slash in it; otherwise, it would s/.o/.c/
     235                    # and append it to sources.  Hmmmm.
     236                    ext.extra_objects.append(word)
     237                else:
     238                    file.warn("unrecognized argument '%s'" % word)
     239
     240            extensions.append(ext)
     241    finally:
     242        file.close()
    234243
    235244        #print "module:", module
  • python/vendor/current/Lib/distutils/fancy_getopt.py

    r2 r388  
    99"""
    1010
    11 # This module should be kept compatible with Python 2.1.
    12 
    13 __revision__ = "$Id: fancy_getopt.py 60923 2008-02-21 18:18:37Z guido.van.rossum $"
    14 
    15 import sys, string, re
    16 from types import *
     11__revision__ = "$Id$"
     12
     13import sys
     14import string
     15import re
    1716import getopt
    18 from distutils.errors import *
     17from distutils.errors import DistutilsGetoptError, DistutilsArgError
    1918
    2019# Much like command_re in distutils.core, this is close to but not quite
     
    120119
    121120    def _check_alias_dict (self, aliases, what):
    122         assert type(aliases) is DictionaryType
     121        assert isinstance(aliases, dict)
    123122        for (alias, opt) in aliases.items():
    124123            if alias not in self.option_index:
     
    167166
    168167            # Type- and value-check the option names
    169             if type(long) is not StringType or len(long) < 2:
     168            if not isinstance(long, str) or len(long) < 2:
    170169                raise DistutilsGetoptError, \
    171170                      ("invalid long option '%s': "
     
    173172
    174173            if (not ((short is None) or
    175                      (type(short) is StringType and len(short) == 1))):
     174                     (isinstance(short, str) and len(short) == 1))):
    176175                raise DistutilsGetoptError, \
    177176                      ("invalid short option '%s': "
     
    467466    return lines
    468467
    469 # wrap_text ()
    470 
    471 
    472 def translate_longopt (opt):
     468
     469def translate_longopt(opt):
    473470    """Convert a long option name to a valid Python identifier by
    474471    changing "-" to "_".
     
    486483        for opt in options:
    487484            setattr(self, opt, None)
    488 
    489 # class OptionDummy
    490 
    491 
    492 if __name__ == "__main__":
    493     text = """\
    494 Tra-la-la, supercalifragilisticexpialidocious.
    495 How *do* you spell that odd word, anyways?
    496 (Someone ask Mary -- she'll know [or she'll
    497 say, "How should I know?"].)"""
    498 
    499     for w in (10, 20, 30, 40):
    500         print "width: %d" % w
    501         print string.join(wrap_text(text, w), "\n")
    502         print
  • python/vendor/current/Lib/distutils/file_util.py

    r2 r388  
    44"""
    55
    6 # This module should be kept compatible with Python 2.1.
    7 
    8 __revision__ = "$Id: file_util.py 37828 2004-11-10 22:23:15Z loewis $"
     6__revision__ = "$Id$"
    97
    108import os
     
    1311
    1412# for generating verbose output in 'copy_file()'
    15 _copy_action = { None:   'copying',
    16                  'hard': 'hard linking',
    17                  'sym':  'symbolically linking' }
    18 
    19 
    20 def _copy_file_contents (src, dst, buffer_size=16*1024):
    21     """Copy the file 'src' to 'dst'; both must be filenames.  Any error
    22     opening either file, reading from 'src', or writing to 'dst', raises
    23     DistutilsFileError.  Data is read/written in chunks of 'buffer_size'
    24     bytes (default 16k).  No attempt is made to handle anything apart from
    25     regular files.
     13_copy_action = {None: 'copying',
     14                'hard': 'hard linking',
     15                'sym': 'symbolically linking'}
     16
     17
     18def _copy_file_contents(src, dst, buffer_size=16*1024):
     19    """Copy the file 'src' to 'dst'.
     20
     21    Both must be filenames. Any error opening either file, reading from
     22    'src', or writing to 'dst', raises DistutilsFileError.  Data is
     23    read/written in chunks of 'buffer_size' bytes (default 16k).  No attempt
     24    is made to handle anything apart from regular files.
    2625    """
    2726    # Stolen from shutil module in the standard library, but with
    2827    # custom error-handling added.
    29 
    3028    fsrc = None
    3129    fdst = None
     
    3432            fsrc = open(src, 'rb')
    3533        except os.error, (errno, errstr):
    36             raise DistutilsFileError, \
    37                   "could not open '%s': %s" % (src, errstr)
     34            raise DistutilsFileError("could not open '%s': %s" % (src, errstr))
    3835
    3936        if os.path.exists(dst):
     
    4138                os.unlink(dst)
    4239            except os.error, (errno, errstr):
    43                 raise DistutilsFileError, \
    44                       "could not delete '%s': %s" % (dst, errstr)
     40                raise DistutilsFileError(
     41                      "could not delete '%s': %s" % (dst, errstr))
    4542
    4643        try:
    4744            fdst = open(dst, 'wb')
    4845        except os.error, (errno, errstr):
    49             raise DistutilsFileError, \
    50                   "could not create '%s': %s" % (dst, errstr)
     46            raise DistutilsFileError(
     47                  "could not create '%s': %s" % (dst, errstr))
    5148
    5249        while 1:
     
    5451                buf = fsrc.read(buffer_size)
    5552            except os.error, (errno, errstr):
    56                 raise DistutilsFileError, \
    57                       "could not read from '%s': %s" % (src, errstr)
     53                raise DistutilsFileError(
     54                      "could not read from '%s': %s" % (src, errstr))
    5855
    5956            if not buf:
     
    6360                fdst.write(buf)
    6461            except os.error, (errno, errstr):
    65                 raise DistutilsFileError, \
    66                       "could not write to '%s': %s" % (dst, errstr)
     62                raise DistutilsFileError(
     63                      "could not write to '%s': %s" % (dst, errstr))
    6764
    6865    finally:
     
    7269            fsrc.close()
    7370
    74 # _copy_file_contents()
    75 
    76 def copy_file (src, dst,
    77                preserve_mode=1,
    78                preserve_times=1,
    79                update=0,
    80                link=None,
    81                verbose=0,
    82                dry_run=0):
    83 
    84     """Copy a file 'src' to 'dst'.  If 'dst' is a directory, then 'src' is
    85     copied there with the same name; otherwise, it must be a filename.  (If
    86     the file exists, it will be ruthlessly clobbered.)  If 'preserve_mode'
    87     is true (the default), the file's mode (type and permission bits, or
    88     whatever is analogous on the current platform) is copied.  If
    89     'preserve_times' is true (the default), the last-modified and
    90     last-access times are copied as well.  If 'update' is true, 'src' will
    91     only be copied if 'dst' does not exist, or if 'dst' does exist but is
    92     older than 'src'.
     71def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0,
     72              link=None, verbose=1, dry_run=0):
     73    """Copy a file 'src' to 'dst'.
     74
     75    If 'dst' is a directory, then 'src' is copied there with the same name;
     76    otherwise, it must be a filename.  (If the file exists, it will be
     77    ruthlessly clobbered.)  If 'preserve_mode' is true (the default),
     78    the file's mode (type and permission bits, or whatever is analogous on
     79    the current platform) is copied.  If 'preserve_times' is true (the
     80    default), the last-modified and last-access times are copied as well.
     81    If 'update' is true, 'src' will only be copied if 'dst' does not exist,
     82    or if 'dst' does exist but is older than 'src'.
    9383
    9484    'link' allows you to make hard links (os.link) or symbolic links
     
    116106
    117107    if not os.path.isfile(src):
    118         raise DistutilsFileError, \
    119               "can't copy '%s': doesn't exist or not a regular file" % src
     108        raise DistutilsFileError(
     109              "can't copy '%s': doesn't exist or not a regular file" % src)
    120110
    121111    if os.path.isdir(dst):
     
    126116
    127117    if update and not newer(src, dst):
    128         log.debug("not copying %s (output up-to-date)", src)
     118        if verbose >= 1:
     119            log.debug("not copying %s (output up-to-date)", src)
    129120        return dst, 0
    130121
     
    132123        action = _copy_action[link]
    133124    except KeyError:
    134         raise ValueError, \
    135               "invalid value '%s' for 'link' argument" % link
    136     if os.path.basename(dst) == os.path.basename(src):
    137         log.info("%s %s -> %s", action, src, dir)
    138     else:
    139         log.info("%s %s -> %s", action, src, dst)
     125        raise ValueError("invalid value '%s' for 'link' argument" % link)
     126
     127    if verbose >= 1:
     128        if os.path.basename(dst) == os.path.basename(src):
     129            log.info("%s %s -> %s", action, src, dir)
     130        else:
     131            log.info("%s %s -> %s", action, src, dst)
    140132
    141133    if dry_run:
    142134        return (dst, 1)
    143135
    144     # On Mac OS, use the native file copy routine
    145     if os.name == 'mac':
    146         import macostools
    147         try:
    148             macostools.copy(src, dst, 0, preserve_times)
    149         except os.error, exc:
    150             raise DistutilsFileError, \
    151                   "could not copy '%s' to '%s': %s" % (src, dst, exc[-1])
    152 
    153136    # If linking (hard or symbolic), use the appropriate system call
    154137    # (Unix only, of course, but that's the caller's responsibility)
    155     elif link == 'hard':
     138    if link == 'hard':
    156139        if not (os.path.exists(dst) and os.path.samefile(src, dst)):
    157140            os.link(src, dst)
     
    176159    return (dst, 1)
    177160
    178 # copy_file ()
    179 
    180 
    181161# XXX I suspect this is Unix-specific -- need porting help!
    182 def move_file (src, dst,
    183                verbose=0,
    184                dry_run=0):
    185 
    186     """Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
    187     be moved into it with the same name; otherwise, 'src' is just renamed
    188     to 'dst'.  Return the new full name of the file.
     162def move_file (src, dst, verbose=1, dry_run=0):
     163    """Move a file 'src' to 'dst'.
     164
     165    If 'dst' is a directory, the file will be moved into it with the same
     166    name; otherwise, 'src' is just renamed to 'dst'.  Return the new
     167    full name of the file.
    189168
    190169    Handles cross-device moves on Unix using 'copy_file()'.  What about
     
    194173    import errno
    195174
    196     log.info("moving %s -> %s", src, dst)
     175    if verbose >= 1:
     176        log.info("moving %s -> %s", src, dst)
    197177
    198178    if dry_run:
     
    200180
    201181    if not isfile(src):
    202         raise DistutilsFileError, \
    203               "can't move '%s': not a regular file" % src
     182        raise DistutilsFileError("can't move '%s': not a regular file" % src)
    204183
    205184    if isdir(dst):
    206185        dst = os.path.join(dst, basename(src))
    207186    elif exists(dst):
    208         raise DistutilsFileError, \
    209               "can't move '%s': destination '%s' already exists" % \
    210               (src, dst)
     187        raise DistutilsFileError(
     188              "can't move '%s': destination '%s' already exists" %
     189              (src, dst))
    211190
    212191    if not isdir(dirname(dst)):
    213         raise DistutilsFileError, \
     192        raise DistutilsFileError(
    214193              "can't move '%s': destination '%s' not a valid path" % \
    215               (src, dst)
     194              (src, dst))
    216195
    217196    copy_it = 0
     
    222201            copy_it = 1
    223202        else:
    224             raise DistutilsFileError, \
    225                   "couldn't move '%s' to '%s': %s" % (src, dst, msg)
     203            raise DistutilsFileError(
     204                  "couldn't move '%s' to '%s': %s" % (src, dst, msg))
    226205
    227206    if copy_it:
    228         copy_file(src, dst)
     207        copy_file(src, dst, verbose=verbose)
    229208        try:
    230209            os.unlink(src)
     
    234213            except os.error:
    235214                pass
    236             raise DistutilsFileError, \
     215            raise DistutilsFileError(
    237216                  ("couldn't move '%s' to '%s' by copy/delete: " +
    238                    "delete '%s' failed: %s") % \
    239                   (src, dst, src, msg)
    240 
     217                   "delete '%s' failed: %s") %
     218                  (src, dst, src, msg))
    241219    return dst
    242 
    243 # move_file ()
    244220
    245221
     
    249225    """
    250226    f = open(filename, "w")
    251     for line in contents:
    252         f.write(line + "\n")
    253     f.close()
     227    try:
     228        for line in contents:
     229            f.write(line + "\n")
     230    finally:
     231        f.close()
  • python/vendor/current/Lib/distutils/filelist.py

    r2 r388  
    55"""
    66
    7 # This module should be kept compatible with Python 2.1.
    8 
    9 __revision__ = "$Id: filelist.py 76044 2009-11-01 23:04:26Z tarek.ziade $"
    10 
    11 import os, string, re
     7__revision__ = "$Id$"
     8
     9import os, re
    1210import fnmatch
    13 from types import *
    1411from distutils.util import convert_path
    1512from distutils.errors import DistutilsTemplateError, DistutilsInternalError
     
    1714
    1815class FileList:
    19 
    2016    """A list of files built by on exploring the filesystem and filtered by
    2117    applying various patterns to what we find there.
     
    3228    """
    3329
    34     def __init__(self,
    35                  warn=None,
    36                  debug_print=None):
     30    def __init__(self, warn=None, debug_print=None):
    3731        # ignore argument to FileList, but keep them for backwards
    3832        # compatibility
    39 
    4033        self.allfiles = None
    4134        self.files = []
    4235
    43     def set_allfiles (self, allfiles):
     36    def set_allfiles(self, allfiles):
    4437        self.allfiles = allfiles
    4538
    46     def findall (self, dir=os.curdir):
     39    def findall(self, dir=os.curdir):
    4740        self.allfiles = findall(dir)
    4841
    49     def debug_print (self, msg):
     42    def debug_print(self, msg):
    5043        """Print 'msg' to stdout if the global DEBUG (taken from the
    5144        DISTUTILS_DEBUG environment variable) flag is true.
     
    5750    # -- List-like methods ---------------------------------------------
    5851
    59     def append (self, item):
     52    def append(self, item):
    6053        self.files.append(item)
    6154
    62     def extend (self, items):
     55    def extend(self, items):
    6356        self.files.extend(items)
    6457
    65     def sort (self):
     58    def sort(self):
    6659        # Not a strict lexical sort!
    6760        sortable_files = map(os.path.split, self.files)
     
    6962        self.files = []
    7063        for sort_tuple in sortable_files:
    71             self.files.append(apply(os.path.join, sort_tuple))
     64            self.files.append(os.path.join(*sort_tuple))
    7265
    7366
    7467    # -- Other miscellaneous utility methods ---------------------------
    7568
    76     def remove_duplicates (self):
     69    def remove_duplicates(self):
    7770        # Assumes list has been sorted!
    7871        for i in range(len(self.files) - 1, 0, -1):
     
    8376    # -- "File template" methods ---------------------------------------
    8477
    85     def _parse_template_line (self, line):
    86         words = string.split(line)
     78    def _parse_template_line(self, line):
     79        words = line.split()
    8780        action = words[0]
    8881
     
    117110        return (action, patterns, dir, dir_pattern)
    118111
    119     # _parse_template_line ()
    120 
    121 
    122     def process_template_line (self, line):
    123 
     112    def process_template_line(self, line):
    124113        # Parse the line: split it up, make sure the right number of words
    125114        # is there, and return the relevant words.  'action' is always
     
    127116        # three are defined depends on the action; it'll be either
    128117        # patterns, (dir and patterns), or (dir_pattern).
    129         (action, patterns, dir, dir_pattern) = self._parse_template_line(line)
     118        action, patterns, dir, dir_pattern = self._parse_template_line(line)
    130119
    131120        # OK, now we know that the action is valid and we have the
     
    133122        # can proceed with minimal error-checking.
    134123        if action == 'include':
    135             self.debug_print("include " + string.join(patterns))
     124            self.debug_print("include " + ' '.join(patterns))
    136125            for pattern in patterns:
    137126                if not self.include_pattern(pattern, anchor=1):
     
    140129
    141130        elif action == 'exclude':
    142             self.debug_print("exclude " + string.join(patterns))
     131            self.debug_print("exclude " + ' '.join(patterns))
    143132            for pattern in patterns:
    144133                if not self.exclude_pattern(pattern, anchor=1):
     
    147136
    148137        elif action == 'global-include':
    149             self.debug_print("global-include " + string.join(patterns))
     138            self.debug_print("global-include " + ' '.join(patterns))
    150139            for pattern in patterns:
    151140                if not self.include_pattern(pattern, anchor=0):
     
    154143
    155144        elif action == 'global-exclude':
    156             self.debug_print("global-exclude " + string.join(patterns))
     145            self.debug_print("global-exclude " + ' '.join(patterns))
    157146            for pattern in patterns:
    158147                if not self.exclude_pattern(pattern, anchor=0):
     
    163152        elif action == 'recursive-include':
    164153            self.debug_print("recursive-include %s %s" %
    165                              (dir, string.join(patterns)))
     154                             (dir, ' '.join(patterns)))
    166155            for pattern in patterns:
    167156                if not self.include_pattern(pattern, prefix=dir):
     
    172161        elif action == 'recursive-exclude':
    173162            self.debug_print("recursive-exclude %s %s" %
    174                              (dir, string.join(patterns)))
     163                             (dir, ' '.join(patterns)))
    175164            for pattern in patterns:
    176165                if not self.exclude_pattern(pattern, prefix=dir):
     
    194183                  "this cannot happen: invalid action '%s'" % action
    195184
    196     # process_template_line ()
    197 
    198 
    199185    # -- Filtering/selection methods -----------------------------------
    200186
    201     def include_pattern (self, pattern,
    202                          anchor=1, prefix=None, is_regex=0):
     187    def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
    203188        """Select strings (presumably filenames) from 'self.files' that
    204         match 'pattern', a Unix-style wildcard (glob) pattern.  Patterns
    205         are not quite the same as implemented by the 'fnmatch' module: '*'
    206         and '?'  match non-special characters, where "special" is platform-
    207         dependent: slash on Unix; colon, slash, and backslash on
     189        match 'pattern', a Unix-style wildcard (glob) pattern.
     190
     191        Patterns are not quite the same as implemented by the 'fnmatch'
     192        module: '*' and '?'  match non-special characters, where "special"
     193        is platform-dependent: slash on Unix; colon, slash, and backslash on
    208194        DOS/Windows; and colon on Mac OS.
    209195
     
    225211        Return 1 if files are found.
    226212        """
     213        # XXX docstring lying about what the special chars are?
    227214        files_found = 0
    228215        pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)
     
    242229        return files_found
    243230
    244     # include_pattern ()
    245 
    246 
    247     def exclude_pattern (self, pattern,
    248                          anchor=1, prefix=None, is_regex=0):
     231
     232    def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
    249233        """Remove strings (presumably filenames) from 'files' that match
    250         'pattern'.  Other parameters are the same as for
    251         'include_pattern()', above.
    252         The list 'self.files' is modified in place.
    253         Return 1 if files are found.
     234        'pattern'.
     235
     236        Other parameters are the same as for 'include_pattern()', above.
     237        The list 'self.files' is modified in place. Return 1 if files are
     238        found.
    254239        """
    255240        files_found = 0
     
    265250        return files_found
    266251
    267     # exclude_pattern ()
    268 
    269 # class FileList
    270 
    271252
    272253# ----------------------------------------------------------------------
    273254# Utility functions
    274255
    275 def findall (dir = os.curdir):
     256def findall(dir = os.curdir):
    276257    """Find all files under 'dir' and return the list of full filenames
    277258    (relative to 'dir').
     
    306287
    307288def glob_to_re(pattern):
    308     """Translate a shell-like glob pattern to a regular expression; return
    309     a string containing the regex.  Differs from 'fnmatch.translate()' in
    310     that '*' does not match "special characters" (which are
    311     platform-specific).
     289    """Translate a shell-like glob pattern to a regular expression.
     290
     291    Return a string containing the regex.  Differs from
     292    'fnmatch.translate()' in that '*' does not match "special characters"
     293    (which are platform-specific).
    312294    """
    313295    pattern_re = fnmatch.translate(pattern)
     
    317299    # and by extension they shouldn't match such "special characters" under
    318300    # any OS.  So change all non-escaped dots in the RE to match any
    319     # character except the special characters.
    320     # XXX currently the "special characters" are just slash -- i.e. this is
    321     # Unix-only.
    322     pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', r'\1[^/]', pattern_re)
    323 
     301    # character except the special characters (currently: just os.sep).
     302    sep = os.sep
     303    if os.sep == '\\':
     304        # we're using a regex to manipulate a regex, so we need
     305        # to escape the backslash twice
     306        sep = r'\\\\'
     307    escaped = r'\1[^%s]' % sep
     308    pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
    324309    return pattern_re
    325310
    326 # glob_to_re ()
    327 
    328 
    329 def translate_pattern (pattern, anchor=1, prefix=None, is_regex=0):
     311
     312def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
    330313    """Translate a shell-like wildcard pattern to a compiled regular
    331     expression.  Return the compiled regex.  If 'is_regex' true,
     314    expression.
     315
     316    Return the compiled regex.  If 'is_regex' true,
    332317    then 'pattern' is directly compiled to a regex (if it's a string)
    333318    or just returned as-is (assumes it's a regex object).
    334319    """
    335320    if is_regex:
    336         if type(pattern) is StringType:
     321        if isinstance(pattern, str):
    337322            return re.compile(pattern)
    338323        else:
     
    347332        # ditch end of pattern character
    348333        empty_pattern = glob_to_re('')
    349         prefix_re = (glob_to_re(prefix))[:-len(empty_pattern)]
    350         pattern_re = "^" + os.path.join(prefix_re, ".*" + pattern_re)
     334        prefix_re = glob_to_re(prefix)[:-len(empty_pattern)]
     335        sep = os.sep
     336        if os.sep == '\\':
     337            sep = r'\\'
     338        pattern_re = "^" + sep.join((prefix_re, ".*" + pattern_re))
    351339    else:                               # no prefix -- respect anchor flag
    352340        if anchor:
     
    354342
    355343    return re.compile(pattern_re)
    356 
    357 # translate_pattern ()
  • python/vendor/current/Lib/distutils/log.py

    r2 r388  
    11"""A simple log mechanism styled after PEP 282."""
    2 
    3 # This module should be kept compatible with Python 2.1.
    42
    53# The class here is styled after PEP 282 so that it could later be
     
    2018
    2119    def _log(self, level, msg, args):
     20        if level not in (DEBUG, INFO, WARN, ERROR, FATAL):
     21            raise ValueError('%s wrong log level' % str(level))
     22
    2223        if level >= self.threshold:
    23             if not args:
    24                 # msg may contain a '%'. If args is empty,
    25                 # don't even try to string-format
    26                 print msg
     24            if args:
     25                msg = msg % args
     26            if level in (WARN, ERROR, FATAL):
     27                stream = sys.stderr
    2728            else:
    28                 print msg % args
    29             sys.stdout.flush()
     29                stream = sys.stdout
     30            stream.write('%s\n' % msg)
     31            stream.flush()
    3032
    3133    def log(self, level, msg, *args):
  • python/vendor/current/Lib/distutils/msvc9compiler.py

    r2 r388  
    1313# ported to VS2005 and VS 2008 by Christian Heimes
    1414
    15 __revision__ = "$Id: msvc9compiler.py 76652 2009-12-03 20:56:15Z martin.v.loewis $"
     15__revision__ = "$Id$"
    1616
    1717import os
     
    1919import sys
    2020import re
     21
    2122from distutils.errors import (DistutilsExecError, DistutilsPlatformError,
    22     CompileError, LibError, LinkError)
    23 from distutils.ccompiler import (CCompiler, gen_preprocess_options,
    24     gen_lib_options)
     23                              CompileError, LibError, LinkError)
     24from distutils.ccompiler import CCompiler, gen_lib_options
    2525from distutils import log
    2626from distutils.util import get_platform
     
    3838         _winreg.HKEY_CLASSES_ROOT)
    3939
    40 VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f"
    41 WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows"
    42 NET_BASE = r"Software\Microsoft\.NETFramework"
     40NATIVE_WIN64 = (sys.platform == 'win32' and sys.maxsize > 2**32)
     41if NATIVE_WIN64:
     42    # Visual C++ is a 32-bit application, so we need to look in
     43    # the corresponding registry branch, if we're running a
     44    # 64-bit Python on Win64
     45    VS_BASE = r"Software\Wow6432Node\Microsoft\VisualStudio\%0.1f"
     46    VSEXPRESS_BASE = r"Software\Wow6432Node\Microsoft\VCExpress\%0.1f"
     47    WINSDK_BASE = r"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows"
     48    NET_BASE = r"Software\Wow6432Node\Microsoft\.NETFramework"
     49else:
     50    VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f"
     51    VSEXPRESS_BASE = r"Software\Microsoft\VCExpress\%0.1f"
     52    WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows"
     53    NET_BASE = r"Software\Microsoft\.NETFramework"
    4354
    4455# A map keyed by get_platform() return values to values accepted by
     
    5566    """
    5667
    57     @classmethod
    5868    def get_value(cls, path, key):
    5969        for base in HKEYS:
     
    6272                return d[key]
    6373        raise KeyError(key)
    64 
    65     @classmethod
     74    get_value = classmethod(get_value)
     75
    6676    def read_keys(cls, base, key):
    6777        """Return list of registry keys."""
     
    8090            i += 1
    8191        return L
    82 
    83     @classmethod
     92    read_keys = classmethod(read_keys)
     93
    8494    def read_values(cls, base, key):
    8595        """Return dict of registry keys and values.
     
    102112            i += 1
    103113        return d
    104 
    105     @staticmethod
     114    read_values = classmethod(read_values)
     115
    106116    def convert_mbcs(s):
    107117        dec = getattr(s, "decode", None)
     
    112122                pass
    113123        return s
     124    convert_mbcs = staticmethod(convert_mbcs)
    114125
    115126class MacroExpander:
     
    133144            else:
    134145                raise KeyError("sdkinstallrootv2.0")
    135         except KeyError as exc: #
     146        except KeyError:
    136147            raise DistutilsPlatformError(
    137148            """Python was built with Visual Studio 2008;
     
    217228                                   "productdir")
    218229    except KeyError:
    219         log.debug("Unable to find productdir in registry")
    220230        productdir = None
     231
     232    # trying Express edition
     233    if productdir is None:
     234        vsbase = VSEXPRESS_BASE % version
     235        try:
     236            productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
     237                                       "productdir")
     238        except KeyError:
     239            productdir = None
     240            log.debug("Unable to find productdir in registry")
    221241
    222242    if not productdir or not os.path.isdir(productdir):
     
    254274                             stdout=subprocess.PIPE,
    255275                             stderr=subprocess.PIPE)
    256 
    257     stdout, stderr = popen.communicate()
    258     if popen.wait() != 0:
    259         raise DistutilsPlatformError(stderr.decode("mbcs"))
    260 
    261     stdout = stdout.decode("mbcs")
    262     for line in stdout.split("\n"):
    263         line = Reg.convert_mbcs(line)
    264         if '=' not in line:
    265             continue
    266         line = line.strip()
    267         key, value = line.split('=', 1)
    268         key = key.lower()
    269         if key in interesting:
    270             if value.endswith(os.pathsep):
    271                 value = value[:-1]
    272             result[key] = removeDuplicates(value)
     276    try:
     277        stdout, stderr = popen.communicate()
     278        if popen.wait() != 0:
     279            raise DistutilsPlatformError(stderr.decode("mbcs"))
     280
     281        stdout = stdout.decode("mbcs")
     282        for line in stdout.split("\n"):
     283            line = Reg.convert_mbcs(line)
     284            if '=' not in line:
     285                continue
     286            line = line.strip()
     287            key, value = line.split('=', 1)
     288            key = key.lower()
     289            if key in interesting:
     290                if value.endswith(os.pathsep):
     291                    value = value[:-1]
     292                result[key] = removeDuplicates(value)
     293
     294    finally:
     295        popen.stdout.close()
     296        popen.stderr.close()
    273297
    274298    if len(result) != len(interesting):
     
    481505                    self.spawn([self.rc] + pp_opts +
    482506                               [output_opt] + [input_opt])
    483                 except DistutilsExecError as msg:
     507                except DistutilsExecError, msg:
    484508                    raise CompileError(msg)
    485509                continue
     
    508532                               ["/fo" + obj] + [rc_file])
    509533
    510                 except DistutilsExecError as msg:
     534                except DistutilsExecError, msg:
    511535                    raise CompileError(msg)
    512536                continue
     
    521545                           [input_opt, output_opt] +
    522546                           extra_postargs)
    523             except DistutilsExecError as msg:
     547            except DistutilsExecError, msg:
    524548                raise CompileError(msg)
    525549
     
    546570            try:
    547571                self.spawn([self.lib] + lib_args)
    548             except DistutilsExecError as msg:
     572            except DistutilsExecError, msg:
    549573                raise LibError(msg)
    550574        else:
     
    617641                ld_args.append ('/IMPLIB:' + implib_file)
    618642
    619             # Embedded manifests are recommended - see MSDN article titled
    620             # "How to: Embed a Manifest Inside a C/C++ Application"
    621             # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
    622             # Ask the linker to generate the manifest in the temp dir, so
    623             # we can embed it later.
    624             temp_manifest = os.path.join(
    625                     build_temp,
    626                     os.path.basename(output_filename) + ".manifest")
    627             ld_args.append('/MANIFESTFILE:' + temp_manifest)
     643            self.manifest_setup_ldargs(output_filename, build_temp, ld_args)
    628644
    629645            if extra_preargs:
     
    635651            try:
    636652                self.spawn([self.linker] + ld_args)
    637             except DistutilsExecError as msg:
     653            except DistutilsExecError, msg:
    638654                raise LinkError(msg)
    639655
     
    643659            # manifest.  Maybe we should link to a temp file?  OTOH, that
    644660            # implies a build environment error that shouldn't go undetected.
    645             if target_desc == CCompiler.EXECUTABLE:
    646                 mfid = 1
    647             else:
    648                 mfid = 2
     661            mfinfo = self.manifest_get_embed_info(target_desc, ld_args)
     662            if mfinfo is not None:
     663                mffilename, mfid = mfinfo
     664                out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
    649665                try:
    650                     # Remove references to the Visual C runtime, so they will
    651                     # fall through to the Visual C dependency of Python.exe.
    652                     # This way, when installed for a restricted user (e.g.
    653                     # runtimes are not in WinSxS folder, but in Python's own
    654                     # folder), the runtimes do not need to be in every folder
    655                     # with .pyd's.
    656                     manifest_f = open(temp_manifest, "rb")
    657                     manifest_buf = manifest_f.read()
    658                     manifest_f.close()
    659                     pattern = re.compile(
    660                         r"""<assemblyIdentity.*?name=("|')Microsoft\."""\
    661                         r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""",
    662                         re.DOTALL)
    663                     manifest_buf = re.sub(pattern, "", manifest_buf)
    664                     pattern = "<dependentAssembly>\s*</dependentAssembly>"
    665                     manifest_buf = re.sub(pattern, "", manifest_buf)
    666                     manifest_f = open(temp_manifest, "wb")
    667                     manifest_f.write(manifest_buf)
    668                     manifest_f.close()
    669                 except IOError:
    670                     pass
    671             out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
     666                    self.spawn(['mt.exe', '-nologo', '-manifest',
     667                                mffilename, out_arg])
     668                except DistutilsExecError, msg:
     669                    raise LinkError(msg)
     670        else:
     671            log.debug("skipping %s (up-to-date)", output_filename)
     672
     673    def manifest_setup_ldargs(self, output_filename, build_temp, ld_args):
     674        # If we need a manifest at all, an embedded manifest is recommended.
     675        # See MSDN article titled
     676        # "How to: Embed a Manifest Inside a C/C++ Application"
     677        # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
     678        # Ask the linker to generate the manifest in the temp dir, so
     679        # we can check it, and possibly embed it, later.
     680        temp_manifest = os.path.join(
     681                build_temp,
     682                os.path.basename(output_filename) + ".manifest")
     683        ld_args.append('/MANIFESTFILE:' + temp_manifest)
     684
     685    def manifest_get_embed_info(self, target_desc, ld_args):
     686        # If a manifest should be embedded, return a tuple of
     687        # (manifest_filename, resource_id).  Returns None if no manifest
     688        # should be embedded.  See http://bugs.python.org/issue7833 for why
     689        # we want to avoid any manifest for extension modules if we can)
     690        for arg in ld_args:
     691            if arg.startswith("/MANIFESTFILE:"):
     692                temp_manifest = arg.split(":", 1)[1]
     693                break
     694        else:
     695            # no /MANIFESTFILE so nothing to do.
     696            return None
     697        if target_desc == CCompiler.EXECUTABLE:
     698            # by default, executables always get the manifest with the
     699            # CRT referenced.
     700            mfid = 1
     701        else:
     702            # Extension modules try and avoid any manifest if possible.
     703            mfid = 2
     704            temp_manifest = self._remove_visual_c_ref(temp_manifest)
     705        if temp_manifest is None:
     706            return None
     707        return temp_manifest, mfid
     708
     709    def _remove_visual_c_ref(self, manifest_file):
     710        try:
     711            # Remove references to the Visual C runtime, so they will
     712            # fall through to the Visual C dependency of Python.exe.
     713            # This way, when installed for a restricted user (e.g.
     714            # runtimes are not in WinSxS folder, but in Python's own
     715            # folder), the runtimes do not need to be in every folder
     716            # with .pyd's.
     717            # Returns either the filename of the modified manifest or
     718            # None if no manifest should be embedded.
     719            manifest_f = open(manifest_file)
    672720            try:
    673                 self.spawn(['mt.exe', '-nologo', '-manifest',
    674                             temp_manifest, out_arg])
    675             except DistutilsExecError as msg:
    676                 raise LinkError(msg)
    677         else:
    678             log.debug("skipping %s (up-to-date)", output_filename)
    679 
     721                manifest_buf = manifest_f.read()
     722            finally:
     723                manifest_f.close()
     724            pattern = re.compile(
     725                r"""<assemblyIdentity.*?name=("|')Microsoft\."""\
     726                r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""",
     727                re.DOTALL)
     728            manifest_buf = re.sub(pattern, "", manifest_buf)
     729            pattern = "<dependentAssembly>\s*</dependentAssembly>"
     730            manifest_buf = re.sub(pattern, "", manifest_buf)
     731            # Now see if any other assemblies are referenced - if not, we
     732            # don't want a manifest embedded.
     733            pattern = re.compile(
     734                r"""<assemblyIdentity.*?name=(?:"|')(.+?)(?:"|')"""
     735                r""".*?(?:/>|</assemblyIdentity>)""", re.DOTALL)
     736            if re.search(pattern, manifest_buf) is None:
     737                return None
     738
     739            manifest_f = open(manifest_file, 'w')
     740            try:
     741                manifest_f.write(manifest_buf)
     742                return manifest_file
     743            finally:
     744                manifest_f.close()
     745        except IOError:
     746            pass
    680747
    681748    # -- Miscellaneous methods -----------------------------------------
  • python/vendor/current/Lib/distutils/msvccompiler.py

    r2 r388  
    99#   finding DevStudio (through the registry)
    1010
    11 # This module should be kept compatible with Python 2.1.
    12 
    13 __revision__ = "$Id: msvccompiler.py 62197 2008-04-07 01:53:39Z mark.hammond $"
    14 
    15 import sys, os, string
    16 from distutils.errors import \
    17      DistutilsExecError, DistutilsPlatformError, \
    18      CompileError, LibError, LinkError
    19 from distutils.ccompiler import \
    20      CCompiler, gen_preprocess_options, gen_lib_options
     11__revision__ = "$Id$"
     12
     13import sys
     14import os
     15import string
     16
     17from distutils.errors import (DistutilsExecError, DistutilsPlatformError,
     18                              CompileError, LibError, LinkError)
     19from distutils.ccompiler import CCompiler, gen_lib_options
    2120from distutils import log
    2221
     
    130129            else:
    131130                self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
    132         except KeyError, exc: #
     131        except KeyError:
    133132            raise DistutilsPlatformError, \
    134133                  ("""Python was built with Visual Studio 2003;
  • python/vendor/current/Lib/distutils/spawn.py

    r2 r388  
    77"""
    88
    9 # This module should be kept compatible with Python 2.1.
     9__revision__ = "$Id$"
    1010
    11 __revision__ = "$Id: spawn.py 37828 2004-11-10 22:23:15Z loewis $"
     11import sys
     12import os
    1213
    13 import sys, os, string
    14 from distutils.errors import *
     14from distutils.errors import DistutilsPlatformError, DistutilsExecError
    1515from distutils import log
    1616
    17 def spawn (cmd,
    18            search_path=1,
    19            verbose=0,
    20            dry_run=0):
     17def spawn(cmd, search_path=1, verbose=0, dry_run=0):
     18    """Run another program, specified as a command list 'cmd', in a new process.
    2119
    22     """Run another program, specified as a command list 'cmd', in a new
    23     process.  'cmd' is just the argument list for the new process, ie.
     20    'cmd' is just the argument list for the new process, ie.
    2421    cmd[0] is the program to run and cmd[1:] are the rest of its arguments.
    2522    There is no way to run a program with a name different from that of its
     
    4441              "don't know how to spawn programs on platform '%s'" % os.name
    4542
    46 # spawn ()
     43def _nt_quote_args(args):
     44    """Quote command-line arguments for DOS/Windows conventions.
    4745
    48 
    49 def _nt_quote_args (args):
    50     """Quote command-line arguments for DOS/Windows conventions: just
    51     wraps every argument which contains blanks in double quotes, and
     46    Just wraps every argument which contains blanks in double quotes, and
    5247    returns a new argument list.
    5348    """
    54 
    5549    # XXX this doesn't seem very robust to me -- but if the Windows guys
    5650    # say it'll work, I guess I'll have to accept it.  (What if an arg
     
    5852    # have to be escaped?  Is there an escaping mechanism other than
    5953    # quoting?)
    60 
    61     for i in range(len(args)):
    62         if string.find(args[i], ' ') != -1:
    63             args[i] = '"%s"' % args[i]
     54    for i, arg in enumerate(args):
     55        if ' ' in arg:
     56            args[i] = '"%s"' % arg
    6457    return args
    6558
    66 def _spawn_nt (cmd,
    67                search_path=1,
    68                verbose=0,
    69                dry_run=0):
    70 
     59def _spawn_nt(cmd, search_path=1, verbose=0, dry_run=0):
    7160    executable = cmd[0]
    7261    cmd = _nt_quote_args(cmd)
     
    7463        # either we find one or it stays the same
    7564        executable = find_executable(executable) or executable
    76     log.info(string.join([executable] + cmd[1:], ' '))
     65    log.info(' '.join([executable] + cmd[1:]))
    7766    if not dry_run:
    7867        # spawn for NT requires a full path to the .exe
     
    8877                  "command '%s' failed with exit status %d" % (cmd[0], rc)
    8978
    90 
    91 def _spawn_os2 (cmd,
    92                 search_path=1,
    93                 verbose=0,
    94                 dry_run=0):
    95 
     79def _spawn_os2(cmd, search_path=1, verbose=0, dry_run=0):
    9680    executable = cmd[0]
    97     #cmd = _nt_quote_args(cmd)
    9881    if search_path:
    9982        # either we find one or it stays the same
    10083        executable = find_executable(executable) or executable
    101     log.info(string.join([executable] + cmd[1:], ' '))
     84    log.info(' '.join([executable] + cmd[1:]))
    10285    if not dry_run:
    10386        # spawnv for OS/2 EMX requires a full path to the .exe
     
    11093        if rc != 0:
    11194            # and this reflects the command running but failing
    112             print "command '%s' failed with exit status %d" % (cmd[0], rc)
     95            log.debug("command '%s' failed with exit status %d" % (cmd[0], rc))
    11396            raise DistutilsExecError, \
    11497                  "command '%s' failed with exit status %d" % (cmd[0], rc)
    11598
     99if sys.platform == 'darwin':
     100    from distutils import sysconfig
     101    _cfg_target = None
     102    _cfg_target_split = None
    116103
    117 def _spawn_posix (cmd,
    118                   search_path=1,
    119                   verbose=0,
    120                   dry_run=0):
    121 
    122     log.info(string.join(cmd, ' '))
     104def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0):
     105    log.info(' '.join(cmd))
    123106    if dry_run:
    124107        return
    125108    exec_fn = search_path and os.execvp or os.execv
    126 
     109    exec_args = [cmd[0], cmd]
     110    if sys.platform == 'darwin':
     111        global _cfg_target, _cfg_target_split
     112        if _cfg_target is None:
     113            _cfg_target = sysconfig.get_config_var(
     114                                  'MACOSX_DEPLOYMENT_TARGET') or ''
     115            if _cfg_target:
     116                _cfg_target_split = [int(x) for x in _cfg_target.split('.')]
     117        if _cfg_target:
     118            # ensure that the deployment target of build process is not less
     119            # than that used when the interpreter was built. This ensures
     120            # extension modules are built with correct compatibility values
     121            cur_target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', _cfg_target)
     122            if _cfg_target_split > [int(x) for x in cur_target.split('.')]:
     123                my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: '
     124                          'now "%s" but "%s" during configure'
     125                                % (cur_target, _cfg_target))
     126                raise DistutilsPlatformError(my_msg)
     127            env = dict(os.environ,
     128                       MACOSX_DEPLOYMENT_TARGET=cur_target)
     129            exec_fn = search_path and os.execvpe or os.execve
     130            exec_args.append(env)
    127131    pid = os.fork()
    128132
    129     if pid == 0:                        # in the child
     133    if pid == 0:  # in the child
    130134        try:
    131             #print "cmd[0] =", cmd[0]
    132             #print "cmd =", cmd
    133             exec_fn(cmd[0], cmd)
     135            exec_fn(*exec_args)
    134136        except OSError, e:
    135137            sys.stderr.write("unable to execute %s: %s\n" %
     
    139141        sys.stderr.write("unable to execute %s for unknown reasons" % cmd[0])
    140142        os._exit(1)
    141 
    142 
    143     else:                               # in the parent
     143    else:   # in the parent
    144144        # Loop until the child either exits or is terminated by a signal
    145145        # (ie. keep waiting if it's merely stopped)
    146146        while 1:
    147147            try:
    148                 (pid, status) = os.waitpid(pid, 0)
     148                pid, status = os.waitpid(pid, 0)
    149149            except OSError, exc:
    150150                import errno
     
    161161                exit_status = os.WEXITSTATUS(status)
    162162                if exit_status == 0:
    163                     return              # hey, it succeeded!
     163                    return   # hey, it succeeded!
    164164                else:
    165165                    raise DistutilsExecError, \
     
    174174                      "unknown error executing '%s': termination status %d" % \
    175175                      (cmd[0], status)
    176 # _spawn_posix ()
    177 
    178176
    179177def find_executable(executable, path=None):
    180     """Try to find 'executable' in the directories listed in 'path' (a
    181     string listing directories separated by 'os.pathsep'; defaults to
    182     os.environ['PATH']).  Returns the complete filename or None if not
    183     found.
     178    """Tries to find 'executable' in the directories listed in 'path'.
     179
     180    A string listing directories separated by 'os.pathsep'; defaults to
     181    os.environ['PATH'].  Returns the complete filename or None if not found.
    184182    """
    185183    if path is None:
    186184        path = os.environ['PATH']
    187     paths = string.split(path, os.pathsep)
    188     (base, ext) = os.path.splitext(executable)
     185    paths = path.split(os.pathsep)
     186    base, ext = os.path.splitext(executable)
     187
    189188    if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'):
    190189        executable = executable + '.exe'
     190
    191191    if not os.path.isfile(executable):
    192192        for p in paths:
     
    198198    else:
    199199        return executable
    200 
    201 # find_executable()
  • python/vendor/current/Lib/distutils/sysconfig.py

    r2 r388  
    1010"""
    1111
    12 __revision__ = "$Id: sysconfig.py 76739 2009-12-10 10:29:05Z ronald.oussoren $"
     12__revision__ = "$Id$"
    1313
    1414import os
     
    3838                                                os.path.pardir))
    3939
     40# set for cross builds
     41if "_PYTHON_PROJECT_BASE" in os.environ:
     42    # this is the build directory, at least for posix
     43    project_base = os.path.normpath(os.environ["_PYTHON_PROJECT_BASE"])
     44
    4045# python_build: (Boolean) if true, we're either building Python or
    4146# building an extension with an un-installed Python, so we use
     
    7277    if prefix is None:
    7378        prefix = plat_specific and EXEC_PREFIX or PREFIX
     79
    7480    if os.name == "posix":
    7581        if python_build:
    76             base = os.path.dirname(os.path.abspath(sys.executable))
     82            buildir = os.path.dirname(sys.executable)
    7783            if plat_specific:
    78                 inc_dir = base
     84                # python.h is located in the buildir
     85                inc_dir = buildir
    7986            else:
    80                 inc_dir = os.path.join(base, "Include")
    81                 if not os.path.exists(inc_dir):
    82                     inc_dir = os.path.join(os.path.dirname(base), "Include")
     87                # the source dir is relative to the buildir
     88                srcdir = os.path.abspath(os.path.join(buildir,
     89                                         get_config_var('srcdir')))
     90                # Include is located in the srcdir
     91                inc_dir = os.path.join(srcdir, "Include")
    8392            return inc_dir
    8493        return os.path.join(prefix, "include", "python" + get_python_version())
    8594    elif os.name == "nt":
    8695        return os.path.join(prefix, "include")
    87     elif os.name == "mac":
    88         if plat_specific:
    89             return os.path.join(prefix, "Mac", "Include")
    90         else:
    91             return os.path.join(prefix, "Include")
    9296    elif os.name == "os2":
    9397        return os.path.join(prefix, "Include")
     
    132136                return os.path.join(prefix, "Lib", "site-packages")
    133137
    134     elif os.name == "mac":
    135         if plat_specific:
    136             if standard_lib:
    137                 return os.path.join(prefix, "Lib", "lib-dynload")
    138             else:
    139                 return os.path.join(prefix, "Lib", "site-packages")
    140         else:
    141             if standard_lib:
    142                 return os.path.join(prefix, "Lib")
    143             else:
    144                 return os.path.join(prefix, "Lib", "site-packages")
    145 
    146138    elif os.name == "os2":
    147139        if standard_lib:
     
    156148
    157149
     150
    158151def customize_compiler(compiler):
    159152    """Do any platform-specific customization of a CCompiler instance.
     
    163156    """
    164157    if compiler.compiler_type == "unix":
    165         (cc, cxx, opt, cflags, ccshared, ldshared, so_ext) = \
     158        if sys.platform == "darwin":
     159            # Perform first-time customization of compiler-related
     160            # config vars on OS X now that we know we need a compiler.
     161            # This is primarily to support Pythons from binary
     162            # installers.  The kind and paths to build tools on
     163            # the user system may vary significantly from the system
     164            # that Python itself was built on.  Also the user OS
     165            # version and build tools may not support the same set
     166            # of CPU architectures for universal builds.
     167            global _config_vars
     168            if not _config_vars.get('CUSTOMIZED_OSX_COMPILER', ''):
     169                import _osx_support
     170                _osx_support.customize_compiler(_config_vars)
     171                _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
     172
     173        (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \
    166174            get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
    167                             'CCSHARED', 'LDSHARED', 'SO')
     175                            'CCSHARED', 'LDSHARED', 'SO', 'AR',
     176                            'ARFLAGS')
    168177
    169178        if 'CC' in os.environ:
    170             cc = os.environ['CC']
     179            newcc = os.environ['CC']
     180            if (sys.platform == 'darwin'
     181                    and 'LDSHARED' not in os.environ
     182                    and ldshared.startswith(cc)):
     183                # On OS X, if CC is overridden, use that as the default
     184                #       command for LDSHARED as well
     185                ldshared = newcc + ldshared[len(cc):]
     186            cc = newcc
    171187        if 'CXX' in os.environ:
    172188            cxx = os.environ['CXX']
     
    186202            cflags = cflags + ' ' + os.environ['CPPFLAGS']
    187203            ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
     204        if 'AR' in os.environ:
     205            ar = os.environ['AR']
     206        if 'ARFLAGS' in os.environ:
     207            archiver = ar + ' ' + os.environ['ARFLAGS']
     208        else:
     209            archiver = ar + ' ' + ar_flags
    188210
    189211        cc_cmd = cc + ' ' + cflags
     
    194216            compiler_cxx=cxx,
    195217            linker_so=ldshared,
    196             linker_exe=cc)
     218            linker_exe=cc,
     219            archiver=archiver)
    197220
    198221        compiler.shared_lib_extension = so_ext
     
    219242    """Return full pathname of installed Makefile from the Python build."""
    220243    if python_build:
    221         return os.path.join(os.path.dirname(sys.executable), "Makefile")
     244        return os.path.join(project_base, "Makefile")
    222245    lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
    223246    return os.path.join(lib_dir, "config", "Makefile")
     
    332355    fp.close()
    333356
     357    # strip spurious spaces
     358    for k, v in done.items():
     359        if isinstance(v, str):
     360            done[k] = v.strip()
     361
    334362    # save the results in the global dictionary
    335363    g.update(done)
     
    366394def _init_posix():
    367395    """Initialize the module as appropriate for POSIX systems."""
    368     g = {}
    369     # load the installed Makefile:
    370     try:
    371         filename = get_makefile_filename()
    372         parse_makefile(filename, g)
    373     except IOError, msg:
    374         my_msg = "invalid Python installation: unable to open %s" % filename
    375         if hasattr(msg, "strerror"):
    376             my_msg = my_msg + " (%s)" % msg.strerror
    377 
    378         raise DistutilsPlatformError(my_msg)
    379 
    380     # load the installed pyconfig.h:
    381     try:
    382         filename = get_config_h_filename()
    383         parse_config_h(file(filename), g)
    384     except IOError, msg:
    385         my_msg = "invalid Python installation: unable to open %s" % filename
    386         if hasattr(msg, "strerror"):
    387             my_msg = my_msg + " (%s)" % msg.strerror
    388 
    389         raise DistutilsPlatformError(my_msg)
    390 
    391     # On MacOSX we need to check the setting of the environment variable
    392     # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so
    393     # it needs to be compatible.
    394     # If it isn't set we set it to the configure-time value
    395     if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g:
    396         cfg_target = g['MACOSX_DEPLOYMENT_TARGET']
    397         cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '')
    398         if cur_target == '':
    399             cur_target = cfg_target
    400             os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target)
    401         elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')):
    402             my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'
    403                 % (cur_target, cfg_target))
    404             raise DistutilsPlatformError(my_msg)
    405 
    406     # On AIX, there are wrong paths to the linker scripts in the Makefile
    407     # -- these paths are relative to the Python source, but when installed
    408     # the scripts are in another directory.
    409     if python_build:
    410         g['LDSHARED'] = g['BLDSHARED']
    411 
    412     elif get_python_version() < '2.1':
    413         # The following two branches are for 1.5.2 compatibility.
    414         if sys.platform == 'aix4':          # what about AIX 3.x ?
    415             # Linker script is in the config directory, not in Modules as the
    416             # Makefile says.
    417             python_lib = get_python_lib(standard_lib=1)
    418             ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
    419             python_exp = os.path.join(python_lib, 'config', 'python.exp')
    420 
    421             g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp)
    422 
    423         elif sys.platform == 'beos':
    424             # Linker script is in the config directory.  In the Makefile it is
    425             # relative to the srcdir, which after installation no longer makes
    426             # sense.
    427             python_lib = get_python_lib(standard_lib=1)
    428             linkerscript_path = string.split(g['LDSHARED'])[0]
    429             linkerscript_name = os.path.basename(linkerscript_path)
    430             linkerscript = os.path.join(python_lib, 'config',
    431                                         linkerscript_name)
    432 
    433             # XXX this isn't the right place to do this: adding the Python
    434             # library to the link, if needed, should be in the "build_ext"
    435             # command.  (It's also needed for non-MS compilers on Windows, and
    436             # it's taken care of for them by the 'build_ext.get_libraries()'
    437             # method.)
    438             g['LDSHARED'] = ("%s -L%s/lib -lpython%s" %
    439                              (linkerscript, PREFIX, get_python_version()))
    440 
     396    # _sysconfigdata is generated at build time, see the sysconfig module
     397    from _sysconfigdata import build_time_vars
    441398    global _config_vars
    442     _config_vars = g
     399    _config_vars = {}
     400    _config_vars.update(build_time_vars)
    443401
    444402
     
    462420
    463421
    464 def _init_mac():
    465     """Initialize the module as appropriate for Macintosh systems"""
    466     g = {}
    467     # set basic install directories
    468     g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
    469     g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
    470 
    471     # XXX hmmm.. a normal install puts include files here
    472     g['INCLUDEPY'] = get_python_inc(plat_specific=0)
    473 
    474     import MacOS
    475     if not hasattr(MacOS, 'runtimemodel'):
    476         g['SO'] = '.ppc.slb'
    477     else:
    478         g['SO'] = '.%s.slb' % MacOS.runtimemodel
    479 
    480     # XXX are these used anywhere?
    481     g['install_lib'] = os.path.join(EXEC_PREFIX, "Lib")
    482     g['install_platlib'] = os.path.join(EXEC_PREFIX, "Mac", "Lib")
    483 
    484     # These are used by the extension module build
    485     g['srcdir'] = ':'
    486     global _config_vars
    487     _config_vars = g
    488 
    489 
    490422def _init_os2():
    491423    """Initialize the module as appropriate for OS/2"""
     
    529461        _config_vars['exec_prefix'] = EXEC_PREFIX
    530462
     463        # OS X platforms require special customization to handle
     464        # multi-architecture, multi-os-version installers
    531465        if sys.platform == 'darwin':
    532             kernel_version = os.uname()[2] # Kernel version (8.4.3)
    533             major_version = int(kernel_version.split('.')[0])
    534 
    535             if major_version < 8:
    536                 # On Mac OS X before 10.4, check if -arch and -isysroot
    537                 # are in CFLAGS or LDFLAGS and remove them if they are.
    538                 # This is needed when building extensions on a 10.3 system
    539                 # using a universal build of python.
    540                 for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
    541                         # a number of derived variables. These need to be
    542                         # patched up as well.
    543                         'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
    544                     flags = _config_vars[key]
    545                     flags = re.sub('-arch\s+\w+\s', ' ', flags)
    546                     flags = re.sub('-isysroot [^ \t]*', ' ', flags)
    547                     _config_vars[key] = flags
    548 
    549             else:
    550 
    551                 # Allow the user to override the architecture flags using
    552                 # an environment variable.
    553                 # NOTE: This name was introduced by Apple in OSX 10.5 and
    554                 # is used by several scripting languages distributed with
    555                 # that OS release.
    556 
    557                 if 'ARCHFLAGS' in os.environ:
    558                     arch = os.environ['ARCHFLAGS']
    559                     for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
    560                         # a number of derived variables. These need to be
    561                         # patched up as well.
    562                         'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
    563 
    564                         flags = _config_vars[key]
    565                         flags = re.sub('-arch\s+\w+\s', ' ', flags)
    566                         flags = flags + ' ' + arch
    567                         _config_vars[key] = flags
    568 
    569                 # If we're on OSX 10.5 or later and the user tries to
    570                 # compiles an extension using an SDK that is not present
    571                 # on the current machine it is better to not use an SDK
    572                 # than to fail.
    573                 #
    574                 # The major usecase for this is users using a Python.org
    575                 # binary installer  on OSX 10.6: that installer uses
    576                 # the 10.4u SDK, but that SDK is not installed by default
    577                 # when you install Xcode.
    578                 #
    579                 m = re.search('-isysroot\s+(\S+)', _config_vars['CFLAGS'])
    580                 if m is not None:
    581                     sdk = m.group(1)
    582                     if not os.path.exists(sdk):
    583                         for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
    584                              # a number of derived variables. These need to be
    585                              # patched up as well.
    586                             'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
    587 
    588                             flags = _config_vars[key]
    589                             flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
    590                             _config_vars[key] = flags
     466            import _osx_support
     467            _osx_support.customize_config_vars(_config_vars)
    591468
    592469    if args:
  • python/vendor/current/Lib/distutils/tests/__init__.py

    r2 r388  
    1616import sys
    1717import unittest
     18from test.test_support import run_unittest
    1819
    1920
    20 here = os.path.dirname(__file__)
     21here = os.path.dirname(__file__) or os.curdir
    2122
    2223
     
    3334
    3435if __name__ == "__main__":
    35     unittest.main(defaultTest="test_suite")
     36    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/support.py

    r2 r388  
    11"""Support code for distutils test cases."""
    22import os
     3import sys
    34import shutil
    45import tempfile
    5 
     6import unittest
     7import sysconfig
     8from copy import deepcopy
     9import warnings
     10
     11from distutils import log
    612from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL
    7 from distutils import log
    8 from distutils.dist import Distribution
    9 from distutils.cmd import Command
     13from distutils.core import Distribution
     14
     15
     16def capture_warnings(func):
     17    def _capture_warnings(*args, **kw):
     18        with warnings.catch_warnings():
     19            warnings.simplefilter("ignore")
     20            return func(*args, **kw)
     21    return _capture_warnings
     22
    1023
    1124class LoggingSilencer(object):
     
    2033        log.Log._log = self._log
    2134        self.logs = []
    22         self._old_warn = Command.warn
    23         Command.warn = self._warn
    2435
    2536    def tearDown(self):
    2637        log.set_threshold(self.threshold)
    2738        log.Log._log = self._old_log
    28         Command.warn = self._old_warn
    2939        super(LoggingSilencer, self).tearDown()
    30 
    31     def _warn(self, msg):
    32         self.logs.append(('', msg, ''))
    3340
    3441    def _log(self, level, msg, args):
     
    5764    def setUp(self):
    5865        super(TempdirManager, self).setUp()
     66        self.old_cwd = os.getcwd()
    5967        self.tempdirs = []
    6068
    6169    def tearDown(self):
     70        # Restore working dir, for Solaris and derivatives, where rmdir()
     71        # on the current directory fails.
     72        os.chdir(self.old_cwd)
    6273        super(TempdirManager, self).tearDown()
    6374        while self.tempdirs:
    6475            d = self.tempdirs.pop()
    65             shutil.rmtree(d)
     76            shutil.rmtree(d, os.name in ('nt', 'cygwin'))
    6677
    6778    def mkdtemp(self):
     
    7687    def write_file(self, path, content='xxx'):
    7788        """Writes a file in the given path.
     89
    7890
    7991        path can be a string or a sequence.
     
    104116        return pkg_dir, dist
    105117
     118
    106119class DummyCommand:
    107120    """Class to store options for retrieval via set_undefined_options()."""
     
    113126    def ensure_finalized(self):
    114127        pass
     128
     129
     130class EnvironGuard(object):
     131
     132    def setUp(self):
     133        super(EnvironGuard, self).setUp()
     134        self.old_environ = deepcopy(os.environ)
     135
     136    def tearDown(self):
     137        for key, value in self.old_environ.items():
     138            if os.environ.get(key) != value:
     139                os.environ[key] = value
     140
     141        for key in os.environ.keys():
     142            if key not in self.old_environ:
     143                del os.environ[key]
     144
     145        super(EnvironGuard, self).tearDown()
     146
     147
     148def copy_xxmodule_c(directory):
     149    """Helper for tests that need the xxmodule.c source file.
     150
     151    Example use:
     152
     153        def test_compile(self):
     154            copy_xxmodule_c(self.tmpdir)
     155            self.assertIn('xxmodule.c', os.listdir(self.tmpdir))
     156
     157    If the source file can be found, it will be copied to *directory*.  If not,
     158    the test will be skipped.  Errors during copy are not caught.
     159    """
     160    filename = _get_xxmodule_path()
     161    if filename is None:
     162        raise unittest.SkipTest('cannot find xxmodule.c (test must run in '
     163                                'the python build dir)')
     164    shutil.copy(filename, directory)
     165
     166
     167def _get_xxmodule_path():
     168    # FIXME when run from regrtest, srcdir seems to be '.', which does not help
     169    # us find the xxmodule.c file
     170    srcdir = sysconfig.get_config_var('srcdir')
     171    candidates = [
     172        # use installed copy if available
     173        os.path.join(os.path.dirname(__file__), 'xxmodule.c'),
     174        # otherwise try using copy from build directory
     175        os.path.join(srcdir, 'Modules', 'xxmodule.c'),
     176        # srcdir mysteriously can be $srcdir/Lib/distutils/tests when
     177        # this file is run from its parent directory, so walk up the
     178        # tree to find the real srcdir
     179        os.path.join(srcdir, '..', '..', '..', 'Modules', 'xxmodule.c'),
     180    ]
     181    for path in candidates:
     182        if os.path.exists(path):
     183            return path
     184
     185
     186def fixup_build_ext(cmd):
     187    """Function needed to make build_ext tests pass.
     188
     189    When Python was build with --enable-shared on Unix, -L. is not good
     190    enough to find the libpython<blah>.so.  This is because regrtest runs
     191    it under a tempdir, not in the top level where the .so lives.  By the
     192    time we've gotten here, Python's already been chdir'd to the tempdir.
     193
     194    When Python was built with in debug mode on Windows, build_ext commands
     195    need their debug attribute set, and it is not done automatically for
     196    some reason.
     197
     198    This function handles both of these things.  Example use:
     199
     200        cmd = build_ext(dist)
     201        support.fixup_build_ext(cmd)
     202        cmd.ensure_finalized()
     203
     204    Unlike most other Unix platforms, Mac OS X embeds absolute paths
     205    to shared libraries into executables, so the fixup is not needed there.
     206    """
     207    if os.name == 'nt':
     208        cmd.debug = sys.executable.endswith('_d.exe')
     209    elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
     210        # To further add to the shared builds fun on Unix, we can't just add
     211        # library_dirs to the Extension() instance because that doesn't get
     212        # plumbed through to the final compiler command.
     213        runshared = sysconfig.get_config_var('RUNSHARED')
     214        if runshared is None:
     215            cmd.library_dirs = ['.']
     216        else:
     217            if sys.platform == 'darwin':
     218                cmd.library_dirs = []
     219            else:
     220                name, equals, value = runshared.partition('=')
     221                cmd.library_dirs = value.split(os.pathsep)
  • python/vendor/current/Lib/distutils/tests/test_bdist_wininst.py

    r2 r388  
    11"""Tests for distutils.command.bdist_wininst."""
    22import unittest
    3 import os
    43
    5 from distutils.dist import Distribution
     4from test.test_support import run_unittest
     5
    66from distutils.command.bdist_wininst import bdist_wininst
    77from distutils.tests import support
     
    1616        # this test makes sure it works now for every platform
    1717        # let's create a command
    18         tmp_dir = self.mkdtemp()
    19         pkg_dir = os.path.join(tmp_dir, 'foo')
    20         os.mkdir(pkg_dir)
    21         dist = Distribution()
     18        pkg_pth, dist = self.create_dist()
    2219        cmd = bdist_wininst(dist)
    2320        cmd.ensure_finalized()
     
    2724        # no matter what platform we have
    2825        exe_file = cmd.get_exe_bytes()
    29         self.assert_(len(exe_file) > 10)
     26        self.assertTrue(len(exe_file) > 10)
    3027
    3128def test_suite():
     
    3330
    3431if __name__ == '__main__':
    35     test_support.run_unittest(test_suite())
     32    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_build_ext.py

    r2 r388  
    11import sys
    22import os
    3 import tempfile
    4 import shutil
    53from StringIO import StringIO
     4import textwrap
    65
    76from distutils.core import Extension, Distribution
     
    98from distutils import sysconfig
    109from distutils.tests import support
    11 from distutils.errors import DistutilsSetupError
     10from distutils.errors import (DistutilsSetupError, CompileError,
     11                              DistutilsPlatformError)
    1212
    1313import unittest
     
    1818ALREADY_TESTED = False
    1919
    20 def _get_source_filename():
    21     srcdir = sysconfig.get_config_var('srcdir')
    22     if srcdir is None:
    23         return os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c')
    24     return os.path.join(srcdir, 'Modules', 'xxmodule.c')
    2520
    2621class BuildExtTestCase(support.TempdirManager,
     
    2823                       unittest.TestCase):
    2924    def setUp(self):
    30         # Create a simple test environment
    31         # Note that we're making changes to sys.path
    3225        super(BuildExtTestCase, self).setUp()
    33         self.tmp_dir = tempfile.mkdtemp(prefix="pythontest_")
    34         self.sys_path = sys.path[:]
     26        self.tmp_dir = self.mkdtemp()
     27        self.xx_created = False
    3528        sys.path.append(self.tmp_dir)
    36         shutil.copy(_get_source_filename(), self.tmp_dir)
     29        self.addCleanup(sys.path.remove, self.tmp_dir)
     30        if sys.version > "2.6":
     31            import site
     32            self.old_user_base = site.USER_BASE
     33            site.USER_BASE = self.mkdtemp()
     34            from distutils.command import build_ext
     35            build_ext.USER_BASE = site.USER_BASE
     36
     37    def tearDown(self):
     38        if self.xx_created:
     39            test_support.unload('xx')
     40            # XXX on Windows the test leaves a directory
     41            # with xx module in TEMP
     42        super(BuildExtTestCase, self).tearDown()
    3743
    3844    def test_build_ext(self):
    3945        global ALREADY_TESTED
     46        support.copy_xxmodule_c(self.tmp_dir)
     47        self.xx_created = True
    4048        xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
    4149        xx_ext = Extension('xx', [xx_c])
     
    4351        dist.package_dir = self.tmp_dir
    4452        cmd = build_ext(dist)
    45         if os.name == "nt":
    46             # On Windows, we must build a debug version iff running
    47             # a debug build of Python
    48             cmd.debug = sys.executable.endswith("_d.exe")
     53        support.fixup_build_ext(cmd)
    4954        cmd.build_lib = self.tmp_dir
    5055        cmd.build_temp = self.tmp_dir
     
    6873
    6974        for attr in ('error', 'foo', 'new', 'roj'):
    70             self.assert_(hasattr(xx, attr))
    71 
    72         self.assertEquals(xx.foo(2, 5), 7)
    73         self.assertEquals(xx.foo(13,15), 28)
    74         self.assertEquals(xx.new().demo(), None)
    75         doc = 'This is a template module just for instruction.'
    76         self.assertEquals(xx.__doc__, doc)
    77         self.assert_(isinstance(xx.Null(), xx.Null))
    78         self.assert_(isinstance(xx.Str(), xx.Str))
    79 
    80     def tearDown(self):
    81         # Get everything back to normal
    82         test_support.unload('xx')
    83         sys.path = self.sys_path
    84         # XXX on Windows the test leaves a directory with xx module in TEMP
    85         shutil.rmtree(self.tmp_dir, os.name == 'nt' or sys.platform == 'cygwin')
    86         super(BuildExtTestCase, self).tearDown()
     75            self.assertTrue(hasattr(xx, attr))
     76
     77        self.assertEqual(xx.foo(2, 5), 7)
     78        self.assertEqual(xx.foo(13,15), 28)
     79        self.assertEqual(xx.new().demo(), None)
     80        if test_support.HAVE_DOCSTRINGS:
     81            doc = 'This is a template module just for instruction.'
     82            self.assertEqual(xx.__doc__, doc)
     83        self.assertTrue(isinstance(xx.Null(), xx.Null))
     84        self.assertTrue(isinstance(xx.Str(), xx.Str))
    8785
    8886    def test_solaris_enable_shared(self):
     
    105103
    106104        # make sure we get some library dirs under solaris
    107         self.assert_(len(cmd.library_dirs) > 0)
     105        self.assertTrue(len(cmd.library_dirs) > 0)
     106
     107    def test_user_site(self):
     108        # site.USER_SITE was introduced in 2.6
     109        if sys.version < '2.6':
     110            return
     111
     112        import site
     113        dist = Distribution({'name': 'xx'})
     114        cmd = build_ext(dist)
     115
     116        # making sure the user option is there
     117        options = [name for name, short, label in
     118                   cmd.user_options]
     119        self.assertIn('user', options)
     120
     121        # setting a value
     122        cmd.user = 1
     123
     124        # setting user based lib and include
     125        lib = os.path.join(site.USER_BASE, 'lib')
     126        incl = os.path.join(site.USER_BASE, 'include')
     127        os.mkdir(lib)
     128        os.mkdir(incl)
     129
     130        cmd.ensure_finalized()
     131
     132        # see if include_dirs and library_dirs were set
     133        self.assertIn(lib, cmd.library_dirs)
     134        self.assertIn(lib, cmd.rpath)
     135        self.assertIn(incl, cmd.include_dirs)
    108136
    109137    def test_finalize_options(self):
     
    115143        cmd.finalize_options()
    116144
    117         from distutils import sysconfig
    118145        py_include = sysconfig.get_python_inc()
    119         self.assert_(py_include in cmd.include_dirs)
     146        self.assertTrue(py_include in cmd.include_dirs)
    120147
    121148        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
    122         self.assert_(plat_py_include in cmd.include_dirs)
     149        self.assertTrue(plat_py_include in cmd.include_dirs)
    123150
    124151        # make sure cmd.libraries is turned into a list
    125152        # if it's a string
    126153        cmd = build_ext(dist)
    127         cmd.libraries = 'my_lib'
    128         cmd.finalize_options()
    129         self.assertEquals(cmd.libraries, ['my_lib'])
     154        cmd.libraries = 'my_lib, other_lib lastlib'
     155        cmd.finalize_options()
     156        self.assertEqual(cmd.libraries, ['my_lib', 'other_lib', 'lastlib'])
    130157
    131158        # make sure cmd.library_dirs is turned into a list
    132159        # if it's a string
    133160        cmd = build_ext(dist)
    134         cmd.library_dirs = 'my_lib_dir'
    135         cmd.finalize_options()
    136         self.assert_('my_lib_dir' in cmd.library_dirs)
     161        cmd.library_dirs = 'my_lib_dir%sother_lib_dir' % os.pathsep
     162        cmd.finalize_options()
     163        self.assertIn('my_lib_dir', cmd.library_dirs)
     164        self.assertIn('other_lib_dir', cmd.library_dirs)
    137165
    138166        # make sure rpath is turned into a list
    139         # if it's a list of os.pathsep's paths
    140         cmd = build_ext(dist)
    141         cmd.rpath = os.pathsep.join(['one', 'two'])
    142         cmd.finalize_options()
    143         self.assertEquals(cmd.rpath, ['one', 'two'])
     167        # if it's a string
     168        cmd = build_ext(dist)
     169        cmd.rpath = 'one%stwo' % os.pathsep
     170        cmd.finalize_options()
     171        self.assertEqual(cmd.rpath, ['one', 'two'])
    144172
    145173        # XXX more tests to perform for win32
     
    150178        cmd.define = 'one,two'
    151179        cmd.finalize_options()
    152         self.assertEquals(cmd.define, [('one', '1'), ('two', '1')])
     180        self.assertEqual(cmd.define, [('one', '1'), ('two', '1')])
    153181
    154182        # make sure undef is turned into a list of
     
    157185        cmd.undef = 'one,two'
    158186        cmd.finalize_options()
    159         self.assertEquals(cmd.undef, ['one', 'two'])
     187        self.assertEqual(cmd.undef, ['one', 'two'])
    160188
    161189        # make sure swig_opts is turned into a list
     
    163191        cmd.swig_opts = None
    164192        cmd.finalize_options()
    165         self.assertEquals(cmd.swig_opts, [])
     193        self.assertEqual(cmd.swig_opts, [])
    166194
    167195        cmd = build_ext(dist)
    168196        cmd.swig_opts = '1 2'
    169197        cmd.finalize_options()
    170         self.assertEquals(cmd.swig_opts, ['1', '2'])
     198        self.assertEqual(cmd.swig_opts, ['1', '2'])
    171199
    172200    def test_check_extensions_list(self):
     
    199227        cmd.check_extensions_list(exts)
    200228        ext = exts[0]
    201         self.assert_(isinstance(ext, Extension))
     229        self.assertTrue(isinstance(ext, Extension))
    202230
    203231        # check_extensions_list adds in ext the values passed
    204232        # when they are in ('include_dirs', 'library_dirs', 'libraries'
    205233        # 'extra_objects', 'extra_compile_args', 'extra_link_args')
    206         self.assertEquals(ext.libraries, 'foo')
    207         self.assert_(not hasattr(ext, 'some'))
     234        self.assertEqual(ext.libraries, 'foo')
     235        self.assertTrue(not hasattr(ext, 'some'))
    208236
    209237        # 'macros' element of build info dict must be 1- or 2-tuple
     
    214242        exts[0][1]['macros'] = [('1', '2'), ('3',)]
    215243        cmd.check_extensions_list(exts)
    216         self.assertEquals(exts[0].undef_macros, ['3'])
    217         self.assertEquals(exts[0].define_macros, [('1', '2')])
     244        self.assertEqual(exts[0].undef_macros, ['3'])
     245        self.assertEqual(exts[0].define_macros, [('1', '2')])
    218246
    219247    def test_get_source_files(self):
     
    222250        cmd = build_ext(dist)
    223251        cmd.ensure_finalized()
    224         self.assertEquals(cmd.get_source_files(), ['xxx'])
     252        self.assertEqual(cmd.get_source_files(), ['xxx'])
    225253
    226254    def test_compiler_option(self):
     
    233261        cmd.ensure_finalized()
    234262        cmd.run()
    235         self.assertEquals(cmd.compiler, 'unix')
     263        self.assertEqual(cmd.compiler, 'unix')
    236264
    237265    def test_get_outputs(self):
     
    243271                             'ext_modules': [ext]})
    244272        cmd = build_ext(dist)
    245         cmd.ensure_finalized()
    246         self.assertEquals(len(cmd.get_outputs()), 1)
    247 
    248         if os.name == "nt":
    249             cmd.debug = sys.executable.endswith("_d.exe")
     273        support.fixup_build_ext(cmd)
     274        cmd.ensure_finalized()
     275        self.assertEqual(len(cmd.get_outputs()), 1)
    250276
    251277        cmd.build_lib = os.path.join(self.tmp_dir, 'build')
     
    263289        finally:
    264290            os.chdir(old_wd)
    265         self.assert_(os.path.exists(so_file))
    266         self.assertEquals(os.path.splitext(so_file)[-1],
    267                           sysconfig.get_config_var('SO'))
     291        self.assertTrue(os.path.exists(so_file))
     292        self.assertEqual(os.path.splitext(so_file)[-1],
     293                         sysconfig.get_config_var('SO'))
    268294        so_dir = os.path.dirname(so_file)
    269         self.assertEquals(so_dir, other_tmp_dir)
     295        self.assertEqual(so_dir, other_tmp_dir)
    270296        cmd.compiler = None
    271297        cmd.inplace = 0
    272298        cmd.run()
    273299        so_file = cmd.get_outputs()[0]
    274         self.assert_(os.path.exists(so_file))
    275         self.assertEquals(os.path.splitext(so_file)[-1],
    276                           sysconfig.get_config_var('SO'))
     300        self.assertTrue(os.path.exists(so_file))
     301        self.assertEqual(os.path.splitext(so_file)[-1],
     302                         sysconfig.get_config_var('SO'))
    277303        so_dir = os.path.dirname(so_file)
    278         self.assertEquals(so_dir, cmd.build_lib)
     304        self.assertEqual(so_dir, cmd.build_lib)
    279305
    280306        # inplace = 0, cmd.package = 'bar'
     
    284310        # checking that the last directory is the build_dir
    285311        path = os.path.split(path)[0]
    286         self.assertEquals(path, cmd.build_lib)
     312        self.assertEqual(path, cmd.build_lib)
    287313
    288314        # inplace = 1, cmd.package = 'bar'
     
    298324        path = os.path.split(path)[0]
    299325        lastdir = os.path.split(path)[-1]
    300         self.assertEquals(lastdir, 'bar')
     326        self.assertEqual(lastdir, 'bar')
    301327
    302328    def test_ext_fullpath(self):
     
    310336        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
    311337        path = cmd.get_ext_fullpath('lxml.etree')
    312         self.assertEquals(wanted, path)
     338        self.assertEqual(wanted, path)
    313339
    314340        # building lxml.etree not inplace
     
    317343        wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
    318344        path = cmd.get_ext_fullpath('lxml.etree')
    319         self.assertEquals(wanted, path)
     345        self.assertEqual(wanted, path)
    320346
    321347        # building twisted.runner.portmap not inplace
     
    326352        wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner',
    327353                              'portmap' + ext)
    328         self.assertEquals(wanted, path)
     354        self.assertEqual(wanted, path)
    329355
    330356        # building twisted.runner.portmap inplace
     
    332358        path = cmd.get_ext_fullpath('twisted.runner.portmap')
    333359        wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
    334         self.assertEquals(wanted, path)
     360        self.assertEqual(wanted, path)
    335361
    336362    def test_build_ext_inplace(self):
     
    347373        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
    348374        path = cmd.get_ext_fullpath('lxml.etree')
    349         self.assertEquals(wanted, path)
     375        self.assertEqual(wanted, path)
    350376
    351377    def test_setuptools_compat(self):
    352         from setuptools_build_ext import build_ext as setuptools_build_ext
    353         from setuptools_extension import Extension
    354 
    355         etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
    356         etree_ext = Extension('lxml.etree', [etree_c])
    357         dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
    358         cmd = setuptools_build_ext(dist)
    359         cmd.ensure_finalized()
    360         cmd.inplace = 1
    361         cmd.distribution.package_dir = {'': 'src'}
    362         cmd.distribution.packages = ['lxml', 'lxml.html']
    363         curdir = os.getcwd()
    364         ext = sysconfig.get_config_var("SO")
    365         wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
    366         path = cmd.get_ext_fullpath('lxml.etree')
    367         self.assertEquals(wanted, path)
     378        import distutils.core, distutils.extension, distutils.command.build_ext
     379        saved_ext = distutils.extension.Extension
     380        try:
     381            # on some platforms, it loads the deprecated "dl" module
     382            test_support.import_module('setuptools_build_ext', deprecated=True)
     383
     384            # theses import patch Distutils' Extension class
     385            from setuptools_build_ext import build_ext as setuptools_build_ext
     386            from setuptools_extension import Extension
     387
     388            etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
     389            etree_ext = Extension('lxml.etree', [etree_c])
     390            dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
     391            cmd = setuptools_build_ext(dist)
     392            cmd.ensure_finalized()
     393            cmd.inplace = 1
     394            cmd.distribution.package_dir = {'': 'src'}
     395            cmd.distribution.packages = ['lxml', 'lxml.html']
     396            curdir = os.getcwd()
     397            ext = sysconfig.get_config_var("SO")
     398            wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
     399            path = cmd.get_ext_fullpath('lxml.etree')
     400            self.assertEqual(wanted, path)
     401        finally:
     402            # restoring Distutils' Extension class otherwise its broken
     403            distutils.extension.Extension = saved_ext
     404            distutils.core.Extension = saved_ext
     405            distutils.command.build_ext.Extension = saved_ext
    368406
    369407    def test_build_ext_path_with_os_sep(self):
     
    375413        ext_path = cmd.get_ext_fullpath(ext_name)
    376414        wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext)
    377         self.assertEquals(ext_path, wanted)
     415        self.assertEqual(ext_path, wanted)
    378416
    379417    def test_build_ext_path_cross_platform(self):
     
    388426        ext_path = cmd.get_ext_fullpath(ext_name)
    389427        wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext)
    390         self.assertEquals(ext_path, wanted)
     428        self.assertEqual(ext_path, wanted)
     429
     430    @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
     431    def test_deployment_target_default(self):
     432        # Issue 9516: Test that, in the absence of the environment variable,
     433        # an extension module is compiled with the same deployment target as
     434        #  the interpreter.
     435        self._try_compile_deployment_target('==', None)
     436
     437    @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
     438    def test_deployment_target_too_low(self):
     439        # Issue 9516: Test that an extension module is not allowed to be
     440        # compiled with a deployment target less than that of the interpreter.
     441        self.assertRaises(DistutilsPlatformError,
     442            self._try_compile_deployment_target, '>', '10.1')
     443
     444    @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
     445    def test_deployment_target_higher_ok(self):
     446        # Issue 9516: Test that an extension module can be compiled with a
     447        # deployment target higher than that of the interpreter: the ext
     448        # module may depend on some newer OS feature.
     449        deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
     450        if deptarget:
     451            # increment the minor version number (i.e. 10.6 -> 10.7)
     452            deptarget = [int(x) for x in deptarget.split('.')]
     453            deptarget[-1] += 1
     454            deptarget = '.'.join(str(i) for i in deptarget)
     455            self._try_compile_deployment_target('<', deptarget)
     456
     457    def _try_compile_deployment_target(self, operator, target):
     458        orig_environ = os.environ
     459        os.environ = orig_environ.copy()
     460        self.addCleanup(setattr, os, 'environ', orig_environ)
     461
     462        if target is None:
     463            if os.environ.get('MACOSX_DEPLOYMENT_TARGET'):
     464                del os.environ['MACOSX_DEPLOYMENT_TARGET']
     465        else:
     466            os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
     467
     468        deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c')
     469
     470        with open(deptarget_c, 'w') as fp:
     471            fp.write(textwrap.dedent('''\
     472                #include <AvailabilityMacros.h>
     473
     474                int dummy;
     475
     476                #if TARGET %s MAC_OS_X_VERSION_MIN_REQUIRED
     477                #else
     478                #error "Unexpected target"
     479                #endif
     480
     481            ''' % operator))
     482
     483        # get the deployment target that the interpreter was built with
     484        target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
     485        target = tuple(map(int, target.split('.')))
     486        target = '%02d%01d0' % target
     487        deptarget_ext = Extension(
     488            'deptarget',
     489            [deptarget_c],
     490            extra_compile_args=['-DTARGET=%s'%(target,)],
     491        )
     492        dist = Distribution({
     493            'name': 'deptarget',
     494            'ext_modules': [deptarget_ext]
     495        })
     496        dist.package_dir = self.tmp_dir
     497        cmd = build_ext(dist)
     498        cmd.build_lib = self.tmp_dir
     499        cmd.build_temp = self.tmp_dir
     500
     501        try:
     502            cmd.ensure_finalized()
     503            cmd.run()
     504        except CompileError:
     505            self.fail("Wrong deployment target during compilation")
    391506
    392507def test_suite():
    393     src = _get_source_filename()
    394     if not os.path.exists(src):
    395         if test_support.verbose:
    396             print ('test_build_ext: Cannot find source code (test'
    397                    ' must run in python build dir)')
    398         return unittest.TestSuite()
    399     else: return unittest.makeSuite(BuildExtTestCase)
     508    return unittest.makeSuite(BuildExtTestCase)
    400509
    401510if __name__ == '__main__':
  • python/vendor/current/Lib/distutils/tests/test_build_py.py

    r2 r388  
    1111
    1212from distutils.tests import support
     13from test.test_support import run_unittest
    1314
    1415
     
    2021        sources = self.mkdtemp()
    2122        f = open(os.path.join(sources, "__init__.py"), "w")
    22         f.write("# Pretend this is a package.")
    23         f.close()
     23        try:
     24            f.write("# Pretend this is a package.")
     25        finally:
     26            f.close()
    2427        f = open(os.path.join(sources, "README.txt"), "w")
    25         f.write("Info about this package")
    26         f.close()
     28        try:
     29            f.write("Info about this package")
     30        finally:
     31            f.close()
    2732
    2833        destination = self.mkdtemp()
     
    5358        pkgdest = os.path.join(destination, "pkg")
    5459        files = os.listdir(pkgdest)
    55         self.assert_("__init__.py" in files)
    56         self.assert_("__init__.pyc" in files)
    57         self.assert_("README.txt" in files)
     60        self.assertIn("__init__.py", files)
     61        self.assertIn("README.txt", files)
     62        # XXX even with -O, distutils writes pyc, not pyo; bug?
     63        if sys.dont_write_bytecode:
     64            self.assertNotIn("__init__.pyc", files)
     65        else:
     66            self.assertIn("__init__.pyc", files)
    5867
    59     def test_empty_package_dir (self):
     68    def test_empty_package_dir(self):
    6069        # See SF 1668596/1720897.
    6170        cwd = os.getcwd()
     
    105114            sys.dont_write_bytecode = old_dont_write_bytecode
    106115
    107         self.assertTrue('byte-compiling is disabled' in self.logs[0][1])
     116        self.assertIn('byte-compiling is disabled', self.logs[0][1])
    108117
    109118def test_suite():
     
    111120
    112121if __name__ == "__main__":
    113     unittest.main(defaultTest="test_suite")
     122    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_build_scripts.py

    r2 r388  
    66from distutils.command.build_scripts import build_scripts
    77from distutils.core import Distribution
    8 from distutils import sysconfig
     8import sysconfig
    99
    1010from distutils.tests import support
     11from test.test_support import run_unittest
    1112
    1213
     
    1718    def test_default_settings(self):
    1819        cmd = self.get_build_scripts_cmd("/foo/bar", [])
    19         self.assert_(not cmd.force)
    20         self.assert_(cmd.build_dir is None)
     20        self.assertTrue(not cmd.force)
     21        self.assertTrue(cmd.build_dir is None)
    2122
    2223        cmd.finalize_options()
    2324
    24         self.assert_(cmd.force)
     25        self.assertTrue(cmd.force)
    2526        self.assertEqual(cmd.build_dir, "/foo/bar")
    2627
     
    3839        built = os.listdir(target)
    3940        for name in expected:
    40             self.assert_(name in built)
     41            self.assertTrue(name in built)
    4142
    4243    def get_build_scripts_cmd(self, target, scripts):
     
    7273    def write_script(self, dir, name, text):
    7374        f = open(os.path.join(dir, name), "w")
    74         f.write(text)
    75         f.close()
     75        try:
     76            f.write(text)
     77        finally:
     78            f.close()
    7679
    7780    def test_version_int(self):
     
    9295        # failed when writing the name of the executable
    9396        old = sysconfig.get_config_vars().get('VERSION')
    94         sysconfig._config_vars['VERSION'] = 4
     97        sysconfig._CONFIG_VARS['VERSION'] = 4
    9598        try:
    9699            cmd.run()
    97100        finally:
    98101            if old is not None:
    99                 sysconfig._config_vars['VERSION'] = old
     102                sysconfig._CONFIG_VARS['VERSION'] = old
    100103
    101104        built = os.listdir(target)
    102105        for name in expected:
    103             self.assert_(name in built)
     106            self.assertTrue(name in built)
    104107
    105108def test_suite():
     
    107110
    108111if __name__ == "__main__":
    109     unittest.main(defaultTest="test_suite")
     112    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_config.py

    r2 r388  
    33import os
    44import unittest
     5import tempfile
     6import shutil
    57
    68from distutils.core import PyPIRCCommand
     
    1012
    1113from distutils.tests import support
     14from test.test_support import run_unittest
    1215
    1316PYPIRC = """\
     
    4649
    4750
    48 class PyPIRCCommandTestCase(support.TempdirManager, unittest.TestCase):
     51class PyPIRCCommandTestCase(support.TempdirManager,
     52                            support.LoggingSilencer,
     53                            support.EnvironGuard,
     54                            unittest.TestCase):
    4955
    5056    def setUp(self):
    5157        """Patches the environment."""
    5258        super(PyPIRCCommandTestCase, self).setUp()
    53         if os.environ.has_key('HOME'):
    54             self._old_home = os.environ['HOME']
    55         else:
    56             self._old_home = None
    57         tempdir = self.mkdtemp()
    58         os.environ['HOME'] = tempdir
    59         self.rc = os.path.join(tempdir, '.pypirc')
     59        self.tmp_dir = self.mkdtemp()
     60        os.environ['HOME'] = self.tmp_dir
     61        self.rc = os.path.join(self.tmp_dir, '.pypirc')
    6062        self.dist = Distribution()
    6163
     
    7274    def tearDown(self):
    7375        """Removes the patch."""
    74         if self._old_home is None:
    75             del os.environ['HOME']
    76         else:
    77             os.environ['HOME'] = self._old_home
    7876        set_threshold(self.old_threshold)
    7977        super(PyPIRCCommandTestCase, self).tearDown()
     
    8583
    8684        # new format
    87         f = open(self.rc, 'w')
    88         try:
    89             f.write(PYPIRC)
    90         finally:
    91             f.close()
    92 
     85        self.write_file(self.rc, PYPIRC)
    9386        cmd = self._cmd(self.dist)
    9487        config = cmd._read_pypirc()
     
    9992                  ('repository', 'http://pypi.python.org/pypi'),
    10093                  ('server', 'server1'), ('username', 'me')]
    101         self.assertEquals(config, waited)
     94        self.assertEqual(config, waited)
    10295
    10396        # old format
    104         f = open(self.rc, 'w')
    105         f.write(PYPIRC_OLD)
    106         f.close()
    107 
     97        self.write_file(self.rc, PYPIRC_OLD)
    10898        config = cmd._read_pypirc()
    10999        config = config.items()
     
    112102                  ('repository', 'http://pypi.python.org/pypi'),
    113103                  ('server', 'server-login'), ('username', 'tarek')]
    114         self.assertEquals(config, waited)
     104        self.assertEqual(config, waited)
    115105
    116106    def test_server_empty_registration(self):
    117 
    118107        cmd = self._cmd(self.dist)
    119108        rc = cmd._get_rc_file()
    120         self.assert_(not os.path.exists(rc))
    121 
     109        self.assertTrue(not os.path.exists(rc))
    122110        cmd._store_pypirc('tarek', 'xxx')
    123 
    124         self.assert_(os.path.exists(rc))
    125         content = open(rc).read()
    126 
    127         self.assertEquals(content, WANTED)
    128 
     111        self.assertTrue(os.path.exists(rc))
     112        f = open(rc)
     113        try:
     114            content = f.read()
     115            self.assertEqual(content, WANTED)
     116        finally:
     117            f.close()
    129118
    130119def test_suite():
     
    132121
    133122if __name__ == "__main__":
    134     unittest.main(defaultTest="test_suite")
     123    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_core.py

    r2 r388  
    77import sys
    88import test.test_support
     9from test.test_support import captured_stdout, run_unittest
    910import unittest
    10 
     11from distutils.tests import support
    1112
    1213# setup script that uses __file__
     
    2930
    3031
    31 class CoreTestCase(unittest.TestCase):
     32class CoreTestCase(support.EnvironGuard, unittest.TestCase):
    3233
    3334    def setUp(self):
     35        super(CoreTestCase, self).setUp()
    3436        self.old_stdout = sys.stdout
    3537        self.cleanup_testfn()
     38        self.old_argv = sys.argv, sys.argv[:]
    3639
    3740    def tearDown(self):
    3841        sys.stdout = self.old_stdout
    3942        self.cleanup_testfn()
     43        sys.argv = self.old_argv[0]
     44        sys.argv[:] = self.old_argv[1]
     45        super(CoreTestCase, self).tearDown()
    4046
    4147    def cleanup_testfn(self):
     
    4753
    4854    def write_setup(self, text, path=test.test_support.TESTFN):
    49         open(path, "w").write(text)
     55        f = open(path, "w")
     56        try:
     57            f.write(text)
     58        finally:
     59            f.close()
    5060        return path
    5161
     
    7484        self.assertEqual(cwd, output)
    7585
     86    def test_debug_mode(self):
     87        # this covers the code called when DEBUG is set
     88        sys.argv = ['setup.py', '--name']
     89        with captured_stdout() as stdout:
     90            distutils.core.setup(name='bar')
     91        stdout.seek(0)
     92        self.assertEqual(stdout.read(), 'bar\n')
     93
     94        distutils.core.DEBUG = True
     95        try:
     96            with captured_stdout() as stdout:
     97                distutils.core.setup(name='bar')
     98        finally:
     99            distutils.core.DEBUG = False
     100        stdout.seek(0)
     101        wanted = "options (after parsing config files):\n"
     102        self.assertEqual(stdout.readlines()[0], wanted)
    76103
    77104def test_suite():
     
    79106
    80107if __name__ == "__main__":
    81     unittest.main(defaultTest="test_suite")
     108    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_dist.py

    r2 r388  
    1 # -*- coding: latin-1 -*-
     1# -*- coding: utf8 -*-
    22
    33"""Tests for distutils.dist."""
    4 
    5 import distutils.cmd
    6 import distutils.dist
    74import os
    85import StringIO
     
    129import textwrap
    1310
    14 from test.test_support import TESTFN
    15 
    16 
    17 class test_dist(distutils.cmd.Command):
     11from distutils.dist import Distribution, fix_help_options
     12from distutils.cmd import Command
     13import distutils.dist
     14from test.test_support import TESTFN, captured_stdout, run_unittest
     15from distutils.tests import support
     16
     17
     18class test_dist(Command):
    1819    """Sample distutils extension command."""
    1920
     
    2627
    2728
    28 class TestDistribution(distutils.dist.Distribution):
     29class TestDistribution(Distribution):
    2930    """Distribution subclasses that avoids the default search for
    3031    configuration files.
     
    3839
    3940
    40 class DistributionTestCase(unittest.TestCase):
     41class DistributionTestCase(support.TempdirManager,
     42                           support.LoggingSilencer,
     43                           support.EnvironGuard,
     44                           unittest.TestCase):
    4145
    4246    def setUp(self):
    43         self.argv = sys.argv[:]
     47        super(DistributionTestCase, self).setUp()
     48        self.argv = sys.argv, sys.argv[:]
    4449        del sys.argv[1:]
    4550
    4651    def tearDown(self):
    47         sys.argv[:] = self.argv
     52        sys.argv = self.argv[0]
     53        sys.argv[:] = self.argv[1]
     54        super(DistributionTestCase, self).tearDown()
    4855
    4956    def create_distribution(self, configfiles=()):
     
    5360        d.parse_command_line()
    5461        return d
     62
     63    def test_debug_mode(self):
     64        with open(TESTFN, "w") as f:
     65            f.write("[global]\n")
     66            f.write("command_packages = foo.bar, splat")
     67
     68        files = [TESTFN]
     69        sys.argv.append("build")
     70
     71        with captured_stdout() as stdout:
     72            self.create_distribution(files)
     73        stdout.seek(0)
     74        self.assertEqual(stdout.read(), '')
     75        distutils.dist.DEBUG = True
     76        try:
     77            with captured_stdout() as stdout:
     78                self.create_distribution(files)
     79            stdout.seek(0)
     80            self.assertEqual(stdout.read(), '')
     81        finally:
     82            distutils.dist.DEBUG = False
    5583
    5684    def test_command_packages_unspecified(self):
     
    7199                         ["distutils.command", "foo.bar", "distutils.tests"])
    72100        cmd = d.get_command_obj("test_dist")
    73         self.assert_(isinstance(cmd, test_dist))
     101        self.assertIsInstance(cmd, test_dist)
    74102        self.assertEqual(cmd.sample_option, "sometext")
    75103
    76104    def test_command_packages_configfile(self):
    77105        sys.argv.append("build")
     106        self.addCleanup(os.unlink, TESTFN)
    78107        f = open(TESTFN, "w")
    79108        try:
    80             print >>f, "[global]"
    81             print >>f, "command_packages = foo.bar, splat"
     109            print >> f, "[global]"
     110            print >> f, "command_packages = foo.bar, splat"
     111        finally:
    82112            f.close()
    83             d = self.create_distribution([TESTFN])
    84             self.assertEqual(d.get_command_packages(),
    85                              ["distutils.command", "foo.bar", "splat"])
    86 
    87             # ensure command line overrides config:
    88             sys.argv[1:] = ["--command-packages", "spork", "build"]
    89             d = self.create_distribution([TESTFN])
    90             self.assertEqual(d.get_command_packages(),
    91                              ["distutils.command", "spork"])
    92 
    93             # Setting --command-packages to '' should cause the default to
    94             # be used even if a config file specified something else:
    95             sys.argv[1:] = ["--command-packages", "", "build"]
    96             d = self.create_distribution([TESTFN])
    97             self.assertEqual(d.get_command_packages(), ["distutils.command"])
    98 
    99         finally:
    100             os.unlink(TESTFN)
     113
     114        d = self.create_distribution([TESTFN])
     115        self.assertEqual(d.get_command_packages(),
     116                         ["distutils.command", "foo.bar", "splat"])
     117
     118        # ensure command line overrides config:
     119        sys.argv[1:] = ["--command-packages", "spork", "build"]
     120        d = self.create_distribution([TESTFN])
     121        self.assertEqual(d.get_command_packages(),
     122                         ["distutils.command", "spork"])
     123
     124        # Setting --command-packages to '' should cause the default to
     125        # be used even if a config file specified something else:
     126        sys.argv[1:] = ["--command-packages", "", "build"]
     127        d = self.create_distribution([TESTFN])
     128        self.assertEqual(d.get_command_packages(), ["distutils.command"])
    101129
    102130    def test_write_pkg_file(self):
    103131        # Check DistributionMetadata handling of Unicode fields
    104         my_file = os.path.join(os.path.dirname(__file__), 'f')
    105         klass = distutils.dist.Distribution
    106 
    107         dist = klass(attrs={'author': u'Mister Café',
     132        tmp_dir = self.mkdtemp()
     133        my_file = os.path.join(tmp_dir, 'f')
     134        klass = Distribution
     135
     136        dist = klass(attrs={'author': u'Mister Café',
    108137                            'name': 'my.package',
    109                             'maintainer': u'Café Junior',
    110                             'description': u'Café torréfié',
    111                             'long_description': u'Héhéhé'})
    112 
     138                            'maintainer': u'Café Junior',
     139                            'description': u'Café torréfié',
     140                            'long_description': u'Héhéhé'})
    113141
    114142        # let's make sure the file can be written
    115143        # with Unicode fields. they are encoded with
    116144        # PKG_INFO_ENCODING
    117         try:
    118             dist.metadata.write_pkg_file(open(my_file, 'w'))
    119         finally:
    120             if os.path.exists(my_file):
    121                 os.remove(my_file)
     145        dist.metadata.write_pkg_file(open(my_file, 'w'))
    122146
    123147        # regular ascii is of course always usable
     
    128152                            'long_description': 'Hehehe'})
    129153
    130         try:
    131             dist.metadata.write_pkg_file(open(my_file, 'w'))
    132         finally:
    133             if os.path.exists(my_file):
    134                 os.remove(my_file)
     154        my_file2 = os.path.join(tmp_dir, 'f2')
     155        dist.metadata.write_pkg_file(open(my_file2, 'w'))
    135156
    136157    def test_empty_options(self):
    137158        # an empty options dictionary should not stay in the
    138159        # list of attributes
    139         klass = distutils.dist.Distribution
    140160
    141161        # catching warnings
    142162        warns = []
     163
    143164        def _warn(msg):
    144165            warns.append(msg)
    145166
    146         old_warn = warnings.warn
     167        self.addCleanup(setattr, warnings, 'warn', warnings.warn)
    147168        warnings.warn = _warn
     169        dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx',
     170                                   'version': 'xxx', 'url': 'xxxx',
     171                                   'options': {}})
     172
     173        self.assertEqual(len(warns), 0)
     174        self.assertNotIn('options', dir(dist))
     175
     176    def test_finalize_options(self):
     177        attrs = {'keywords': 'one,two',
     178                 'platforms': 'one,two'}
     179
     180        dist = Distribution(attrs=attrs)
     181        dist.finalize_options()
     182
     183        # finalize_option splits platforms and keywords
     184        self.assertEqual(dist.metadata.platforms, ['one', 'two'])
     185        self.assertEqual(dist.metadata.keywords, ['one', 'two'])
     186
     187    def test_get_command_packages(self):
     188        dist = Distribution()
     189        self.assertEqual(dist.command_packages, None)
     190        cmds = dist.get_command_packages()
     191        self.assertEqual(cmds, ['distutils.command'])
     192        self.assertEqual(dist.command_packages,
     193                         ['distutils.command'])
     194
     195        dist.command_packages = 'one,two'
     196        cmds = dist.get_command_packages()
     197        self.assertEqual(cmds, ['distutils.command', 'one', 'two'])
     198
     199    def test_announce(self):
     200        # make sure the level is known
     201        dist = Distribution()
     202        args = ('ok',)
     203        kwargs = {'level': 'ok2'}
     204        self.assertRaises(ValueError, dist.announce, args, kwargs)
     205
     206    def test_find_config_files_disable(self):
     207        # Ticket #1180: Allow user to disable their home config file.
     208        temp_home = self.mkdtemp()
     209        if os.name == 'posix':
     210            user_filename = os.path.join(temp_home, ".pydistutils.cfg")
     211        else:
     212            user_filename = os.path.join(temp_home, "pydistutils.cfg")
     213
     214        with open(user_filename, 'w') as f:
     215            f.write('[distutils]\n')
     216
     217        def _expander(path):
     218            return temp_home
     219
     220        old_expander = os.path.expanduser
     221        os.path.expanduser = _expander
    148222        try:
    149             dist = klass(attrs={'author': 'xxx',
    150                                 'name': 'xxx',
    151                                 'version': 'xxx',
    152                                 'url': 'xxxx',
    153                                 'options': {}})
     223            d = distutils.dist.Distribution()
     224            all_files = d.find_config_files()
     225
     226            d = distutils.dist.Distribution(attrs={'script_args':
     227                                            ['--no-user-cfg']})
     228            files = d.find_config_files()
    154229        finally:
    155             warnings.warn = old_warn
    156 
    157         self.assertEquals(len(warns), 0)
    158 
    159 class MetadataTestCase(unittest.TestCase):
    160 
    161     def test_simple_metadata(self):
    162         attrs = {"name": "package",
    163                  "version": "1.0"}
    164         dist = distutils.dist.Distribution(attrs)
    165         meta = self.format_metadata(dist)
    166         self.assert_("Metadata-Version: 1.0" in meta)
    167         self.assert_("provides:" not in meta.lower())
    168         self.assert_("requires:" not in meta.lower())
    169         self.assert_("obsoletes:" not in meta.lower())
    170 
    171     def test_provides(self):
    172         attrs = {"name": "package",
    173                  "version": "1.0",
    174                  "provides": ["package", "package.sub"]}
    175         dist = distutils.dist.Distribution(attrs)
    176         self.assertEqual(dist.metadata.get_provides(),
    177                          ["package", "package.sub"])
    178         self.assertEqual(dist.get_provides(),
    179                          ["package", "package.sub"])
    180         meta = self.format_metadata(dist)
    181         self.assert_("Metadata-Version: 1.1" in meta)
    182         self.assert_("requires:" not in meta.lower())
    183         self.assert_("obsoletes:" not in meta.lower())
    184 
    185     def test_provides_illegal(self):
    186         self.assertRaises(ValueError,
    187                           distutils.dist.Distribution,
    188                           {"name": "package",
    189                            "version": "1.0",
    190                            "provides": ["my.pkg (splat)"]})
    191 
    192     def test_requires(self):
    193         attrs = {"name": "package",
    194                  "version": "1.0",
    195                  "requires": ["other", "another (==1.0)"]}
    196         dist = distutils.dist.Distribution(attrs)
    197         self.assertEqual(dist.metadata.get_requires(),
    198                          ["other", "another (==1.0)"])
    199         self.assertEqual(dist.get_requires(),
    200                          ["other", "another (==1.0)"])
    201         meta = self.format_metadata(dist)
    202         self.assert_("Metadata-Version: 1.1" in meta)
    203         self.assert_("provides:" not in meta.lower())
    204         self.assert_("Requires: other" in meta)
    205         self.assert_("Requires: another (==1.0)" in meta)
    206         self.assert_("obsoletes:" not in meta.lower())
    207 
    208     def test_requires_illegal(self):
    209         self.assertRaises(ValueError,
    210                           distutils.dist.Distribution,
    211                           {"name": "package",
    212                            "version": "1.0",
    213                            "requires": ["my.pkg (splat)"]})
    214 
    215     def test_obsoletes(self):
    216         attrs = {"name": "package",
    217                  "version": "1.0",
    218                  "obsoletes": ["other", "another (<1.0)"]}
    219         dist = distutils.dist.Distribution(attrs)
    220         self.assertEqual(dist.metadata.get_obsoletes(),
    221                          ["other", "another (<1.0)"])
    222         self.assertEqual(dist.get_obsoletes(),
    223                          ["other", "another (<1.0)"])
    224         meta = self.format_metadata(dist)
    225         self.assert_("Metadata-Version: 1.1" in meta)
    226         self.assert_("provides:" not in meta.lower())
    227         self.assert_("requires:" not in meta.lower())
    228         self.assert_("Obsoletes: other" in meta)
    229         self.assert_("Obsoletes: another (<1.0)" in meta)
    230 
    231     def test_obsoletes_illegal(self):
    232         self.assertRaises(ValueError,
    233                           distutils.dist.Distribution,
    234                           {"name": "package",
    235                            "version": "1.0",
    236                            "obsoletes": ["my.pkg (splat)"]})
    237 
    238     def format_metadata(self, dist):
    239         sio = StringIO.StringIO()
    240         dist.metadata.write_pkg_file(sio)
    241         return sio.getvalue()
    242 
    243     def test_custom_pydistutils(self):
    244         # fixes #2166
    245         # make sure pydistutils.cfg is found
    246         old = {}
    247         for env in ('HOME', 'HOMEPATH', 'HOMEDRIVE'):
    248             value = os.environ.get(env)
    249             old[env] = value
    250             if value is not None:
    251                 del os.environ[env]
    252 
    253         if os.name == 'posix':
    254             user_filename = ".pydistutils.cfg"
    255         else:
    256             user_filename = "pydistutils.cfg"
    257 
    258         curdir = os.path.dirname(__file__)
    259         user_filename = os.path.join(curdir, user_filename)
    260         f = open(user_filename, 'w')
    261         f.write('.')
    262         f.close()
    263 
    264         try:
    265             dist = distutils.dist.Distribution()
    266 
    267             # linux-style
    268             if sys.platform in ('linux', 'darwin'):
    269                 os.environ['HOME'] = curdir
    270                 files = dist.find_config_files()
    271                 self.assert_(user_filename in files)
    272 
    273             # win32-style
    274             if sys.platform == 'win32':
    275                 # home drive should be found
    276                 os.environ['HOME'] = curdir
    277                 files = dist.find_config_files()
    278                 self.assert_(user_filename in files,
    279                              '%r not found in %r' % (user_filename, files))
    280         finally:
    281             for key, value in old.items():
    282                 if value is None:
    283                     continue
    284                 os.environ[key] = value
    285             os.remove(user_filename)
     230            os.path.expanduser = old_expander
     231
     232        # make sure --no-user-cfg disables the user cfg file
     233        self.assertEqual(len(all_files)-1, len(files))
     234
     235
     236class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
     237                       unittest.TestCase):
     238
     239    def setUp(self):
     240        super(MetadataTestCase, self).setUp()
     241        self.argv = sys.argv, sys.argv[:]
     242
     243    def tearDown(self):
     244        sys.argv = self.argv[0]
     245        sys.argv[:] = self.argv[1]
     246        super(MetadataTestCase, self).tearDown()
     247
     248    def test_classifier(self):
     249        attrs = {'name': 'Boa', 'version': '3.0',
     250                 'classifiers': ['Programming Language :: Python :: 3']}
     251        dist = Distribution(attrs)
     252        meta = self.format_metadata(dist)
     253        self.assertIn('Metadata-Version: 1.1', meta)
     254
     255    def test_download_url(self):
     256        attrs = {'name': 'Boa', 'version': '3.0',
     257                 'download_url': 'http://example.org/boa'}
     258        dist = Distribution(attrs)
     259        meta = self.format_metadata(dist)
     260        self.assertIn('Metadata-Version: 1.1', meta)
    286261
    287262    def test_long_description(self):
     
    295270                 "long_description": long_desc}
    296271
    297         dist = distutils.dist.Distribution(attrs)
     272        dist = Distribution(attrs)
    298273        meta = self.format_metadata(dist)
    299274        meta = meta.replace('\n' + 8 * ' ', '\n')
    300         self.assertTrue(long_desc in meta)
     275        self.assertIn(long_desc, meta)
     276
     277    def test_simple_metadata(self):
     278        attrs = {"name": "package",
     279                 "version": "1.0"}
     280        dist = Distribution(attrs)
     281        meta = self.format_metadata(dist)
     282        self.assertIn("Metadata-Version: 1.0", meta)
     283        self.assertNotIn("provides:", meta.lower())
     284        self.assertNotIn("requires:", meta.lower())
     285        self.assertNotIn("obsoletes:", meta.lower())
     286
     287    def test_provides(self):
     288        attrs = {"name": "package",
     289                 "version": "1.0",
     290                 "provides": ["package", "package.sub"]}
     291        dist = Distribution(attrs)
     292        self.assertEqual(dist.metadata.get_provides(),
     293                         ["package", "package.sub"])
     294        self.assertEqual(dist.get_provides(),
     295                         ["package", "package.sub"])
     296        meta = self.format_metadata(dist)
     297        self.assertIn("Metadata-Version: 1.1", meta)
     298        self.assertNotIn("requires:", meta.lower())
     299        self.assertNotIn("obsoletes:", meta.lower())
     300
     301    def test_provides_illegal(self):
     302        self.assertRaises(ValueError, Distribution,
     303                          {"name": "package",
     304                           "version": "1.0",
     305                           "provides": ["my.pkg (splat)"]})
     306
     307    def test_requires(self):
     308        attrs = {"name": "package",
     309                 "version": "1.0",
     310                 "requires": ["other", "another (==1.0)"]}
     311        dist = Distribution(attrs)
     312        self.assertEqual(dist.metadata.get_requires(),
     313                         ["other", "another (==1.0)"])
     314        self.assertEqual(dist.get_requires(),
     315                         ["other", "another (==1.0)"])
     316        meta = self.format_metadata(dist)
     317        self.assertIn("Metadata-Version: 1.1", meta)
     318        self.assertNotIn("provides:", meta.lower())
     319        self.assertIn("Requires: other", meta)
     320        self.assertIn("Requires: another (==1.0)", meta)
     321        self.assertNotIn("obsoletes:", meta.lower())
     322
     323    def test_requires_illegal(self):
     324        self.assertRaises(ValueError, Distribution,
     325                          {"name": "package",
     326                           "version": "1.0",
     327                           "requires": ["my.pkg (splat)"]})
     328
     329    def test_obsoletes(self):
     330        attrs = {"name": "package",
     331                 "version": "1.0",
     332                 "obsoletes": ["other", "another (<1.0)"]}
     333        dist = Distribution(attrs)
     334        self.assertEqual(dist.metadata.get_obsoletes(),
     335                         ["other", "another (<1.0)"])
     336        self.assertEqual(dist.get_obsoletes(),
     337                         ["other", "another (<1.0)"])
     338        meta = self.format_metadata(dist)
     339        self.assertIn("Metadata-Version: 1.1", meta)
     340        self.assertNotIn("provides:", meta.lower())
     341        self.assertNotIn("requires:", meta.lower())
     342        self.assertIn("Obsoletes: other", meta)
     343        self.assertIn("Obsoletes: another (<1.0)", meta)
     344
     345    def test_obsoletes_illegal(self):
     346        self.assertRaises(ValueError, Distribution,
     347                          {"name": "package",
     348                           "version": "1.0",
     349                           "obsoletes": ["my.pkg (splat)"]})
     350
     351    def format_metadata(self, dist):
     352        sio = StringIO.StringIO()
     353        dist.metadata.write_pkg_file(sio)
     354        return sio.getvalue()
     355
     356    def test_custom_pydistutils(self):
     357        # fixes #2166
     358        # make sure pydistutils.cfg is found
     359        if os.name == 'posix':
     360            user_filename = ".pydistutils.cfg"
     361        else:
     362            user_filename = "pydistutils.cfg"
     363
     364        temp_dir = self.mkdtemp()
     365        user_filename = os.path.join(temp_dir, user_filename)
     366        f = open(user_filename, 'w')
     367        try:
     368            f.write('.')
     369        finally:
     370            f.close()
     371
     372        try:
     373            dist = Distribution()
     374
     375            # linux-style
     376            if sys.platform in ('linux', 'darwin'):
     377                os.environ['HOME'] = temp_dir
     378                files = dist.find_config_files()
     379                self.assertIn(user_filename, files)
     380
     381            # win32-style
     382            if sys.platform == 'win32':
     383                # home drive should be found
     384                os.environ['HOME'] = temp_dir
     385                files = dist.find_config_files()
     386                self.assertIn(user_filename, files,
     387                             '%r not found in %r' % (user_filename, files))
     388        finally:
     389            os.remove(user_filename)
     390
     391    def test_fix_help_options(self):
     392        help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
     393        fancy_options = fix_help_options(help_tuples)
     394        self.assertEqual(fancy_options[0], ('a', 'b', 'c'))
     395        self.assertEqual(fancy_options[1], (1, 2, 3))
     396
     397    def test_show_help(self):
     398        # smoke test, just makes sure some help is displayed
     399        dist = Distribution()
     400        sys.argv = []
     401        dist.help = 1
     402        dist.script_name = 'setup.py'
     403        with captured_stdout() as s:
     404            dist.parse_command_line()
     405
     406        output = [line for line in s.getvalue().split('\n')
     407                  if line.strip() != '']
     408        self.assertTrue(output)
     409
     410    def test_read_metadata(self):
     411        attrs = {"name": "package",
     412                 "version": "1.0",
     413                 "long_description": "desc",
     414                 "description": "xxx",
     415                 "download_url": "http://example.com",
     416                 "keywords": ['one', 'two'],
     417                 "requires": ['foo']}
     418
     419        dist = Distribution(attrs)
     420        metadata = dist.metadata
     421
     422        # write it then reloads it
     423        PKG_INFO = StringIO.StringIO()
     424        metadata.write_pkg_file(PKG_INFO)
     425        PKG_INFO.seek(0)
     426        metadata.read_pkg_file(PKG_INFO)
     427
     428        self.assertEqual(metadata.name, "package")
     429        self.assertEqual(metadata.version, "1.0")
     430        self.assertEqual(metadata.description, "xxx")
     431        self.assertEqual(metadata.download_url, 'http://example.com')
     432        self.assertEqual(metadata.keywords, ['one', 'two'])
     433        self.assertEqual(metadata.platforms, ['UNKNOWN'])
     434        self.assertEqual(metadata.obsoletes, None)
     435        self.assertEqual(metadata.requires, ['foo'])
     436
    301437
    302438def test_suite():
     
    307443
    308444if __name__ == "__main__":
    309     unittest.main(defaultTest="test_suite")
     445    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_filelist.py

    r2 r388  
    11"""Tests for distutils.filelist."""
     2import os
     3import re
    24import unittest
    3 from distutils.filelist import glob_to_re
    4 
    5 class FileListTestCase(unittest.TestCase):
     5from distutils import debug
     6from distutils.log import WARN
     7from distutils.errors import DistutilsTemplateError
     8from distutils.filelist import glob_to_re, translate_pattern, FileList
     9
     10from test.test_support import captured_stdout, run_unittest
     11from distutils.tests import support
     12
     13MANIFEST_IN = """\
     14include ok
     15include xo
     16exclude xo
     17include foo.tmp
     18include buildout.cfg
     19global-include *.x
     20global-include *.txt
     21global-exclude *.tmp
     22recursive-include f *.oo
     23recursive-exclude global *.x
     24graft dir
     25prune dir3
     26"""
     27
     28
     29def make_local_path(s):
     30    """Converts '/' in a string to os.sep"""
     31    return s.replace('/', os.sep)
     32
     33
     34class FileListTestCase(support.LoggingSilencer,
     35                       unittest.TestCase):
     36
     37    def assertNoWarnings(self):
     38        self.assertEqual(self.get_logs(WARN), [])
     39        self.clear_logs()
     40
     41    def assertWarnings(self):
     42        self.assertGreater(len(self.get_logs(WARN)), 0)
     43        self.clear_logs()
    644
    745    def test_glob_to_re(self):
    8         # simple cases
    9         self.assertEquals(glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)')
    10         self.assertEquals(glob_to_re('foo?'), 'foo[^/]\\Z(?ms)')
    11         self.assertEquals(glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)')
    12 
    13         # special cases
    14         self.assertEquals(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)')
    15         self.assertEquals(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)')
    16         self.assertEquals(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)')
    17         self.assertEquals(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)')
     46        sep = os.sep
     47        if os.sep == '\\':
     48            sep = re.escape(os.sep)
     49
     50        for glob, regex in (
     51            # simple cases
     52            ('foo*', r'foo[^%(sep)s]*\Z(?ms)'),
     53            ('foo?', r'foo[^%(sep)s]\Z(?ms)'),
     54            ('foo??', r'foo[^%(sep)s][^%(sep)s]\Z(?ms)'),
     55            # special cases
     56            (r'foo\\*', r'foo\\\\[^%(sep)s]*\Z(?ms)'),
     57            (r'foo\\\*', r'foo\\\\\\[^%(sep)s]*\Z(?ms)'),
     58            ('foo????', r'foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s]\Z(?ms)'),
     59            (r'foo\\??', r'foo\\\\[^%(sep)s][^%(sep)s]\Z(?ms)')):
     60            regex = regex % {'sep': sep}
     61            self.assertEqual(glob_to_re(glob), regex)
     62
     63    def test_process_template_line(self):
     64        # testing  all MANIFEST.in template patterns
     65        file_list = FileList()
     66        l = make_local_path
     67
     68        # simulated file list
     69        file_list.allfiles = ['foo.tmp', 'ok', 'xo', 'four.txt',
     70                              'buildout.cfg',
     71                              # filelist does not filter out VCS directories,
     72                              # it's sdist that does
     73                              l('.hg/last-message.txt'),
     74                              l('global/one.txt'),
     75                              l('global/two.txt'),
     76                              l('global/files.x'),
     77                              l('global/here.tmp'),
     78                              l('f/o/f.oo'),
     79                              l('dir/graft-one'),
     80                              l('dir/dir2/graft2'),
     81                              l('dir3/ok'),
     82                              l('dir3/sub/ok.txt'),
     83                             ]
     84
     85        for line in MANIFEST_IN.split('\n'):
     86            if line.strip() == '':
     87                continue
     88            file_list.process_template_line(line)
     89
     90        wanted = ['ok',
     91                  'buildout.cfg',
     92                  'four.txt',
     93                  l('.hg/last-message.txt'),
     94                  l('global/one.txt'),
     95                  l('global/two.txt'),
     96                  l('f/o/f.oo'),
     97                  l('dir/graft-one'),
     98                  l('dir/dir2/graft2'),
     99                 ]
     100
     101        self.assertEqual(file_list.files, wanted)
     102
     103    def test_debug_print(self):
     104        file_list = FileList()
     105        with captured_stdout() as stdout:
     106            file_list.debug_print('xxx')
     107        self.assertEqual(stdout.getvalue(), '')
     108
     109        debug.DEBUG = True
     110        try:
     111            with captured_stdout() as stdout:
     112                file_list.debug_print('xxx')
     113            self.assertEqual(stdout.getvalue(), 'xxx\n')
     114        finally:
     115            debug.DEBUG = False
     116
     117    def test_set_allfiles(self):
     118        file_list = FileList()
     119        files = ['a', 'b', 'c']
     120        file_list.set_allfiles(files)
     121        self.assertEqual(file_list.allfiles, files)
     122
     123    def test_remove_duplicates(self):
     124        file_list = FileList()
     125        file_list.files = ['a', 'b', 'a', 'g', 'c', 'g']
     126        # files must be sorted beforehand (sdist does it)
     127        file_list.sort()
     128        file_list.remove_duplicates()
     129        self.assertEqual(file_list.files, ['a', 'b', 'c', 'g'])
     130
     131    def test_translate_pattern(self):
     132        # not regex
     133        self.assertTrue(hasattr(
     134            translate_pattern('a', anchor=True, is_regex=False),
     135            'search'))
     136
     137        # is a regex
     138        regex = re.compile('a')
     139        self.assertEqual(
     140            translate_pattern(regex, anchor=True, is_regex=True),
     141            regex)
     142
     143        # plain string flagged as regex
     144        self.assertTrue(hasattr(
     145            translate_pattern('a', anchor=True, is_regex=True),
     146            'search'))
     147
     148        # glob support
     149        self.assertTrue(translate_pattern(
     150            '*.py', anchor=True, is_regex=False).search('filelist.py'))
     151
     152    def test_exclude_pattern(self):
     153        # return False if no match
     154        file_list = FileList()
     155        self.assertFalse(file_list.exclude_pattern('*.py'))
     156
     157        # return True if files match
     158        file_list = FileList()
     159        file_list.files = ['a.py', 'b.py']
     160        self.assertTrue(file_list.exclude_pattern('*.py'))
     161
     162        # test excludes
     163        file_list = FileList()
     164        file_list.files = ['a.py', 'a.txt']
     165        file_list.exclude_pattern('*.py')
     166        self.assertEqual(file_list.files, ['a.txt'])
     167
     168    def test_include_pattern(self):
     169        # return False if no match
     170        file_list = FileList()
     171        file_list.set_allfiles([])
     172        self.assertFalse(file_list.include_pattern('*.py'))
     173
     174        # return True if files match
     175        file_list = FileList()
     176        file_list.set_allfiles(['a.py', 'b.txt'])
     177        self.assertTrue(file_list.include_pattern('*.py'))
     178
     179        # test * matches all files
     180        file_list = FileList()
     181        self.assertIsNone(file_list.allfiles)
     182        file_list.set_allfiles(['a.py', 'b.txt'])
     183        file_list.include_pattern('*')
     184        self.assertEqual(file_list.allfiles, ['a.py', 'b.txt'])
     185
     186    def test_process_template(self):
     187        l = make_local_path
     188        # invalid lines
     189        file_list = FileList()
     190        for action in ('include', 'exclude', 'global-include',
     191                       'global-exclude', 'recursive-include',
     192                       'recursive-exclude', 'graft', 'prune', 'blarg'):
     193            self.assertRaises(DistutilsTemplateError,
     194                              file_list.process_template_line, action)
     195
     196        # include
     197        file_list = FileList()
     198        file_list.set_allfiles(['a.py', 'b.txt', l('d/c.py')])
     199
     200        file_list.process_template_line('include *.py')
     201        self.assertEqual(file_list.files, ['a.py'])
     202        self.assertNoWarnings()
     203
     204        file_list.process_template_line('include *.rb')
     205        self.assertEqual(file_list.files, ['a.py'])
     206        self.assertWarnings()
     207
     208        # exclude
     209        file_list = FileList()
     210        file_list.files = ['a.py', 'b.txt', l('d/c.py')]
     211
     212        file_list.process_template_line('exclude *.py')
     213        self.assertEqual(file_list.files, ['b.txt', l('d/c.py')])
     214        self.assertNoWarnings()
     215
     216        file_list.process_template_line('exclude *.rb')
     217        self.assertEqual(file_list.files, ['b.txt', l('d/c.py')])
     218        self.assertWarnings()
     219
     220        # global-include
     221        file_list = FileList()
     222        file_list.set_allfiles(['a.py', 'b.txt', l('d/c.py')])
     223
     224        file_list.process_template_line('global-include *.py')
     225        self.assertEqual(file_list.files, ['a.py', l('d/c.py')])
     226        self.assertNoWarnings()
     227
     228        file_list.process_template_line('global-include *.rb')
     229        self.assertEqual(file_list.files, ['a.py', l('d/c.py')])
     230        self.assertWarnings()
     231
     232        # global-exclude
     233        file_list = FileList()
     234        file_list.files = ['a.py', 'b.txt', l('d/c.py')]
     235
     236        file_list.process_template_line('global-exclude *.py')
     237        self.assertEqual(file_list.files, ['b.txt'])
     238        self.assertNoWarnings()
     239
     240        file_list.process_template_line('global-exclude *.rb')
     241        self.assertEqual(file_list.files, ['b.txt'])
     242        self.assertWarnings()
     243
     244        # recursive-include
     245        file_list = FileList()
     246        file_list.set_allfiles(['a.py', l('d/b.py'), l('d/c.txt'),
     247                                l('d/d/e.py')])
     248
     249        file_list.process_template_line('recursive-include d *.py')
     250        self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')])
     251        self.assertNoWarnings()
     252
     253        file_list.process_template_line('recursive-include e *.py')
     254        self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')])
     255        self.assertWarnings()
     256
     257        # recursive-exclude
     258        file_list = FileList()
     259        file_list.files = ['a.py', l('d/b.py'), l('d/c.txt'), l('d/d/e.py')]
     260
     261        file_list.process_template_line('recursive-exclude d *.py')
     262        self.assertEqual(file_list.files, ['a.py', l('d/c.txt')])
     263        self.assertNoWarnings()
     264
     265        file_list.process_template_line('recursive-exclude e *.py')
     266        self.assertEqual(file_list.files, ['a.py', l('d/c.txt')])
     267        self.assertWarnings()
     268
     269        # graft
     270        file_list = FileList()
     271        file_list.set_allfiles(['a.py', l('d/b.py'), l('d/d/e.py'),
     272                                l('f/f.py')])
     273
     274        file_list.process_template_line('graft d')
     275        self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')])
     276        self.assertNoWarnings()
     277
     278        file_list.process_template_line('graft e')
     279        self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')])
     280        self.assertWarnings()
     281
     282        # prune
     283        file_list = FileList()
     284        file_list.files = ['a.py', l('d/b.py'), l('d/d/e.py'), l('f/f.py')]
     285
     286        file_list.process_template_line('prune d')
     287        self.assertEqual(file_list.files, ['a.py', l('f/f.py')])
     288        self.assertNoWarnings()
     289
     290        file_list.process_template_line('prune e')
     291        self.assertEqual(file_list.files, ['a.py', l('f/f.py')])
     292        self.assertWarnings()
     293
    18294
    19295def test_suite():
     
    21297
    22298if __name__ == "__main__":
    23     unittest.main(defaultTest="test_suite")
     299    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_install.py

    r2 r388  
    22
    33import os
     4import sys
    45import unittest
    5 
     6import site
     7
     8from test.test_support import captured_stdout, run_unittest
     9
     10from distutils import sysconfig
    611from distutils.command.install import install
     12from distutils.command import install as install_module
     13from distutils.command.build_ext import build_ext
     14from distutils.command.install import INSTALL_SCHEMES
    715from distutils.core import Distribution
     16from distutils.errors import DistutilsOptionError
     17from distutils.extension import Extension
    818
    919from distutils.tests import support
    1020
    1121
    12 class InstallTestCase(support.TempdirManager, unittest.TestCase):
     22def _make_ext_name(modname):
     23    if os.name == 'nt' and sys.executable.endswith('_d.exe'):
     24        modname += '_d'
     25    return modname + sysconfig.get_config_var('SO')
     26
     27
     28class InstallTestCase(support.TempdirManager,
     29                      support.LoggingSilencer,
     30                      unittest.TestCase):
    1331
    1432    def test_home_installation_scheme(self):
     
    4866        check_path(cmd.install_data, destination)
    4967
     68    def test_user_site(self):
     69        # site.USER_SITE was introduced in 2.6
     70        if sys.version < '2.6':
     71            return
     72
     73        # preparing the environment for the test
     74        self.old_user_base = site.USER_BASE
     75        self.old_user_site = site.USER_SITE
     76        self.tmpdir = self.mkdtemp()
     77        self.user_base = os.path.join(self.tmpdir, 'B')
     78        self.user_site = os.path.join(self.tmpdir, 'S')
     79        site.USER_BASE = self.user_base
     80        site.USER_SITE = self.user_site
     81        install_module.USER_BASE = self.user_base
     82        install_module.USER_SITE = self.user_site
     83
     84        def _expanduser(path):
     85            return self.tmpdir
     86        self.old_expand = os.path.expanduser
     87        os.path.expanduser = _expanduser
     88
     89        def cleanup():
     90            site.USER_BASE = self.old_user_base
     91            site.USER_SITE = self.old_user_site
     92            install_module.USER_BASE = self.old_user_base
     93            install_module.USER_SITE = self.old_user_site
     94            os.path.expanduser = self.old_expand
     95
     96        self.addCleanup(cleanup)
     97
     98        for key in ('nt_user', 'unix_user', 'os2_home'):
     99            self.assertIn(key, INSTALL_SCHEMES)
     100
     101        dist = Distribution({'name': 'xx'})
     102        cmd = install(dist)
     103
     104        # making sure the user option is there
     105        options = [name for name, short, lable in
     106                   cmd.user_options]
     107        self.assertIn('user', options)
     108
     109        # setting a value
     110        cmd.user = 1
     111
     112        # user base and site shouldn't be created yet
     113        self.assertFalse(os.path.exists(self.user_base))
     114        self.assertFalse(os.path.exists(self.user_site))
     115
     116        # let's run finalize
     117        cmd.ensure_finalized()
     118
     119        # now they should
     120        self.assertTrue(os.path.exists(self.user_base))
     121        self.assertTrue(os.path.exists(self.user_site))
     122
     123        self.assertIn('userbase', cmd.config_vars)
     124        self.assertIn('usersite', cmd.config_vars)
     125
     126    def test_handle_extra_path(self):
     127        dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'})
     128        cmd = install(dist)
     129
     130        # two elements
     131        cmd.handle_extra_path()
     132        self.assertEqual(cmd.extra_path, ['path', 'dirs'])
     133        self.assertEqual(cmd.extra_dirs, 'dirs')
     134        self.assertEqual(cmd.path_file, 'path')
     135
     136        # one element
     137        cmd.extra_path = ['path']
     138        cmd.handle_extra_path()
     139        self.assertEqual(cmd.extra_path, ['path'])
     140        self.assertEqual(cmd.extra_dirs, 'path')
     141        self.assertEqual(cmd.path_file, 'path')
     142
     143        # none
     144        dist.extra_path = cmd.extra_path = None
     145        cmd.handle_extra_path()
     146        self.assertEqual(cmd.extra_path, None)
     147        self.assertEqual(cmd.extra_dirs, '')
     148        self.assertEqual(cmd.path_file, None)
     149
     150        # three elements (no way !)
     151        cmd.extra_path = 'path,dirs,again'
     152        self.assertRaises(DistutilsOptionError, cmd.handle_extra_path)
     153
     154    def test_finalize_options(self):
     155        dist = Distribution({'name': 'xx'})
     156        cmd = install(dist)
     157
     158        # must supply either prefix/exec-prefix/home or
     159        # install-base/install-platbase -- not both
     160        cmd.prefix = 'prefix'
     161        cmd.install_base = 'base'
     162        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
     163
     164        # must supply either home or prefix/exec-prefix -- not both
     165        cmd.install_base = None
     166        cmd.home = 'home'
     167        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
     168
     169        # can't combine user with prefix/exec_prefix/home or
     170        # install_(plat)base
     171        cmd.prefix = None
     172        cmd.user = 'user'
     173        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
     174
     175    def test_record(self):
     176        install_dir = self.mkdtemp()
     177        project_dir, dist = self.create_dist(py_modules=['hello'],
     178                                             scripts=['sayhi'])
     179        os.chdir(project_dir)
     180        self.write_file('hello.py', "def main(): print 'o hai'")
     181        self.write_file('sayhi', 'from hello import main; main()')
     182
     183        cmd = install(dist)
     184        dist.command_obj['install'] = cmd
     185        cmd.root = install_dir
     186        cmd.record = os.path.join(project_dir, 'filelist')
     187        cmd.ensure_finalized()
     188        cmd.run()
     189
     190        f = open(cmd.record)
     191        try:
     192            content = f.read()
     193        finally:
     194            f.close()
     195
     196        found = [os.path.basename(line) for line in content.splitlines()]
     197        expected = ['hello.py', 'hello.pyc', 'sayhi',
     198                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
     199        self.assertEqual(found, expected)
     200
     201    def test_record_extensions(self):
     202        install_dir = self.mkdtemp()
     203        project_dir, dist = self.create_dist(ext_modules=[
     204            Extension('xx', ['xxmodule.c'])])
     205        os.chdir(project_dir)
     206        support.copy_xxmodule_c(project_dir)
     207
     208        buildextcmd = build_ext(dist)
     209        support.fixup_build_ext(buildextcmd)
     210        buildextcmd.ensure_finalized()
     211
     212        cmd = install(dist)
     213        dist.command_obj['install'] = cmd
     214        dist.command_obj['build_ext'] = buildextcmd
     215        cmd.root = install_dir
     216        cmd.record = os.path.join(project_dir, 'filelist')
     217        cmd.ensure_finalized()
     218        cmd.run()
     219
     220        f = open(cmd.record)
     221        try:
     222            content = f.read()
     223        finally:
     224            f.close()
     225
     226        found = [os.path.basename(line) for line in content.splitlines()]
     227        expected = [_make_ext_name('xx'),
     228                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
     229        self.assertEqual(found, expected)
     230
     231    def test_debug_mode(self):
     232        # this covers the code called when DEBUG is set
     233        old_logs_len = len(self.logs)
     234        install_module.DEBUG = True
     235        try:
     236            with captured_stdout():
     237                self.test_record()
     238        finally:
     239            install_module.DEBUG = False
     240        self.assertTrue(len(self.logs) > old_logs_len)
     241
    50242
    51243def test_suite():
     
    53245
    54246if __name__ == "__main__":
    55     unittest.main(defaultTest="test_suite")
     247    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_install_lib.py

    r2 r388  
    11"""Tests for distutils.command.install_data."""
     2import os
    23import sys
    3 import os
    44import unittest
    55
     
    88from distutils.tests import support
    99from distutils.errors import DistutilsOptionError
     10from test.test_support import run_unittest
    1011
    1112class InstallLibTestCase(support.TempdirManager,
    1213                         support.LoggingSilencer,
     14                         support.EnvironGuard,
    1315                         unittest.TestCase):
     16
     17    def test_finalize_options(self):
     18        pkg_dir, dist = self.create_dist()
     19        cmd = install_lib(dist)
     20
     21        cmd.finalize_options()
     22        self.assertEqual(cmd.compile, 1)
     23        self.assertEqual(cmd.optimize, 0)
     24
     25        # optimize must be 0, 1, or 2
     26        cmd.optimize = 'foo'
     27        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
     28        cmd.optimize = '4'
     29        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
     30
     31        cmd.optimize = '2'
     32        cmd.finalize_options()
     33        self.assertEqual(cmd.optimize, 2)
     34
     35    def _setup_byte_compile(self):
     36        pkg_dir, dist = self.create_dist()
     37        cmd = install_lib(dist)
     38        cmd.compile = cmd.optimize = 1
     39
     40        f = os.path.join(pkg_dir, 'foo.py')
     41        self.write_file(f, '# python file')
     42        cmd.byte_compile([f])
     43        return pkg_dir
     44
     45    @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile not enabled')
     46    def test_byte_compile(self):
     47        pkg_dir = self._setup_byte_compile()
     48        if sys.flags.optimize < 1:
     49            self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyc')))
     50        else:
     51            self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyo')))
     52
     53    def test_get_outputs(self):
     54        pkg_dir, dist = self.create_dist()
     55        cmd = install_lib(dist)
     56
     57        # setting up a dist environment
     58        cmd.compile = cmd.optimize = 1
     59        cmd.install_dir = pkg_dir
     60        f = os.path.join(pkg_dir, 'foo.py')
     61        self.write_file(f, '# python file')
     62        cmd.distribution.py_modules = [pkg_dir]
     63        cmd.distribution.ext_modules = [Extension('foo', ['xxx'])]
     64        cmd.distribution.packages = [pkg_dir]
     65        cmd.distribution.script_name = 'setup.py'
     66
     67        # get_output should return 4 elements
     68        self.assertTrue(len(cmd.get_outputs()) >= 2)
     69
     70    def test_get_inputs(self):
     71        pkg_dir, dist = self.create_dist()
     72        cmd = install_lib(dist)
     73
     74        # setting up a dist environment
     75        cmd.compile = cmd.optimize = 1
     76        cmd.install_dir = pkg_dir
     77        f = os.path.join(pkg_dir, 'foo.py')
     78        self.write_file(f, '# python file')
     79        cmd.distribution.py_modules = [pkg_dir]
     80        cmd.distribution.ext_modules = [Extension('foo', ['xxx'])]
     81        cmd.distribution.packages = [pkg_dir]
     82        cmd.distribution.script_name = 'setup.py'
     83
     84        # get_input should return 2 elements
     85        self.assertEqual(len(cmd.get_inputs()), 2)
    1486
    1587    def test_dont_write_bytecode(self):
     
    33105
    34106if __name__ == "__main__":
    35     unittest.main(defaultTest="test_suite")
     107    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_install_scripts.py

    r2 r388  
    88
    99from distutils.tests import support
     10from test.test_support import run_unittest
    1011
    1112
     
    2425            )
    2526        cmd = install_scripts(dist)
    26         self.assert_(not cmd.force)
    27         self.assert_(not cmd.skip_build)
    28         self.assert_(cmd.build_dir is None)
    29         self.assert_(cmd.install_dir is None)
     27        self.assertTrue(not cmd.force)
     28        self.assertTrue(not cmd.skip_build)
     29        self.assertTrue(cmd.build_dir is None)
     30        self.assertTrue(cmd.install_dir is None)
    3031
    3132        cmd.finalize_options()
    3233
    33         self.assert_(cmd.force)
    34         self.assert_(cmd.skip_build)
     34        self.assertTrue(cmd.force)
     35        self.assertTrue(cmd.skip_build)
    3536        self.assertEqual(cmd.build_dir, "/foo/bar")
    3637        self.assertEqual(cmd.install_dir, "/splat/funk")
     
    4344            expected.append(name)
    4445            f = open(os.path.join(source, name), "w")
    45             f.write(text)
    46             f.close()
     46            try:
     47                f.write(text)
     48            finally:
     49                f.close()
    4750
    4851        write_script("script1.py", ("#! /usr/bin/env python2.3\n"
     
    7073        installed = os.listdir(target)
    7174        for name in expected:
    72             self.assert_(name in installed)
     75            self.assertTrue(name in installed)
    7376
    7477
     
    7780
    7881if __name__ == "__main__":
    79     unittest.main(defaultTest="test_suite")
     82    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_msvc9compiler.py

    r2 r388  
    22import sys
    33import unittest
     4import os
    45
    56from distutils.errors import DistutilsPlatformError
     7from distutils.tests import support
     8from test.test_support import run_unittest
    69
    7 class msvc9compilerTestCase(unittest.TestCase):
     10# A manifest with the only assembly reference being the msvcrt assembly, so
     11# should have the assembly completely stripped.  Note that although the
     12# assembly has a <security> reference the assembly is removed - that is
     13# currently a "feature", not a bug :)
     14_MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\
     15<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     16<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
     17          manifestVersion="1.0">
     18  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
     19    <security>
     20      <requestedPrivileges>
     21        <requestedExecutionLevel level="asInvoker" uiAccess="false">
     22        </requestedExecutionLevel>
     23      </requestedPrivileges>
     24    </security>
     25  </trustInfo>
     26  <dependency>
     27    <dependentAssembly>
     28      <assemblyIdentity type="win32" name="Microsoft.VC90.CRT"
     29         version="9.0.21022.8" processorArchitecture="x86"
     30         publicKeyToken="XXXX">
     31      </assemblyIdentity>
     32    </dependentAssembly>
     33  </dependency>
     34</assembly>
     35"""
     36
     37# A manifest with references to assemblies other than msvcrt.  When processed,
     38# this assembly should be returned with just the msvcrt part removed.
     39_MANIFEST_WITH_MULTIPLE_REFERENCES = """\
     40<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     41<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
     42          manifestVersion="1.0">
     43  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
     44    <security>
     45      <requestedPrivileges>
     46        <requestedExecutionLevel level="asInvoker" uiAccess="false">
     47        </requestedExecutionLevel>
     48      </requestedPrivileges>
     49    </security>
     50  </trustInfo>
     51  <dependency>
     52    <dependentAssembly>
     53      <assemblyIdentity type="win32" name="Microsoft.VC90.CRT"
     54         version="9.0.21022.8" processorArchitecture="x86"
     55         publicKeyToken="XXXX">
     56      </assemblyIdentity>
     57    </dependentAssembly>
     58  </dependency>
     59  <dependency>
     60    <dependentAssembly>
     61      <assemblyIdentity type="win32" name="Microsoft.VC90.MFC"
     62        version="9.0.21022.8" processorArchitecture="x86"
     63        publicKeyToken="XXXX"></assemblyIdentity>
     64    </dependentAssembly>
     65  </dependency>
     66</assembly>
     67"""
     68
     69_CLEANED_MANIFEST = """\
     70<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     71<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
     72          manifestVersion="1.0">
     73  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
     74    <security>
     75      <requestedPrivileges>
     76        <requestedExecutionLevel level="asInvoker" uiAccess="false">
     77        </requestedExecutionLevel>
     78      </requestedPrivileges>
     79    </security>
     80  </trustInfo>
     81  <dependency>
     82
     83  </dependency>
     84  <dependency>
     85    <dependentAssembly>
     86      <assemblyIdentity type="win32" name="Microsoft.VC90.MFC"
     87        version="9.0.21022.8" processorArchitecture="x86"
     88        publicKeyToken="XXXX"></assemblyIdentity>
     89    </dependentAssembly>
     90  </dependency>
     91</assembly>"""
     92
     93if sys.platform=="win32":
     94    from distutils.msvccompiler import get_build_version
     95    if get_build_version()>=8.0:
     96        SKIP_MESSAGE = None
     97    else:
     98        SKIP_MESSAGE = "These tests are only for MSVC8.0 or above"
     99else:
     100    SKIP_MESSAGE = "These tests are only for win32"
     101
     102@unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE)
     103class msvc9compilerTestCase(support.TempdirManager,
     104                            unittest.TestCase):
    8105
    9106    def test_no_compiler(self):
    10         # makes sure query_vcvarsall throws
     107        # makes sure query_vcvarsall raises
    11108        # a DistutilsPlatformError if the compiler
    12109        # is not found
    13         if sys.platform != 'win32':
    14             # this test is only for win32
    15             return
    16         from distutils.msvccompiler import get_build_version
    17         if get_build_version() < 8.0:
    18             # this test is only for MSVC8.0 or above
    19             return
    20110        from distutils.msvc9compiler import query_vcvarsall
    21111        def _find_vcvarsall(version):
     
    31121            msvc9compiler.find_vcvarsall = old_find_vcvarsall
    32122
     123    def test_reg_class(self):
     124        from distutils.msvc9compiler import Reg
     125        self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx')
     126
     127        # looking for values that should exist on all
     128        # windows registeries versions.
     129        path = r'Control Panel\Desktop'
     130        v = Reg.get_value(path, u'dragfullwindows')
     131        self.assertTrue(v in (u'0', u'1', u'2'))
     132
     133        import _winreg
     134        HKCU = _winreg.HKEY_CURRENT_USER
     135        keys = Reg.read_keys(HKCU, 'xxxx')
     136        self.assertEqual(keys, None)
     137
     138        keys = Reg.read_keys(HKCU, r'Control Panel')
     139        self.assertTrue('Desktop' in keys)
     140
     141    def test_remove_visual_c_ref(self):
     142        from distutils.msvc9compiler import MSVCCompiler
     143        tempdir = self.mkdtemp()
     144        manifest = os.path.join(tempdir, 'manifest')
     145        f = open(manifest, 'w')
     146        try:
     147            f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES)
     148        finally:
     149            f.close()
     150
     151        compiler = MSVCCompiler()
     152        compiler._remove_visual_c_ref(manifest)
     153
     154        # see what we got
     155        f = open(manifest)
     156        try:
     157            # removing trailing spaces
     158            content = '\n'.join([line.rstrip() for line in f.readlines()])
     159        finally:
     160            f.close()
     161
     162        # makes sure the manifest was properly cleaned
     163        self.assertEqual(content, _CLEANED_MANIFEST)
     164
     165    def test_remove_entire_manifest(self):
     166        from distutils.msvc9compiler import MSVCCompiler
     167        tempdir = self.mkdtemp()
     168        manifest = os.path.join(tempdir, 'manifest')
     169        f = open(manifest, 'w')
     170        try:
     171            f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE)
     172        finally:
     173            f.close()
     174
     175        compiler = MSVCCompiler()
     176        got = compiler._remove_visual_c_ref(manifest)
     177        self.assertIs(got, None)
     178
     179
    33180def test_suite():
    34181    return unittest.makeSuite(msvc9compilerTestCase)
    35182
    36183if __name__ == "__main__":
    37     unittest.main(defaultTest="test_suite")
     184    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_register.py

    r2 r388  
     1# -*- encoding: utf8 -*-
    12"""Tests for distutils.command.register."""
    2 import sys
    33import os
    44import unittest
    5 
     5import getpass
     6import urllib2
     7import warnings
     8
     9from test.test_support import check_warnings, run_unittest
     10
     11from distutils.command import register as register_module
    612from distutils.command.register import register
    7 from distutils.core import Distribution
    8 
    9 from distutils.tests import support
    10 from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase
     13from distutils.errors import DistutilsSetupError
     14
     15from distutils.tests.test_config import PyPIRCCommandTestCase
     16
     17try:
     18    import docutils
     19except ImportError:
     20    docutils = None
     21
     22PYPIRC_NOPASSWORD = """\
     23[distutils]
     24
     25index-servers =
     26    server1
     27
     28[server1]
     29username:me
     30"""
     31
     32WANTED_PYPIRC = """\
     33[distutils]
     34index-servers =
     35    pypi
     36
     37[pypi]
     38username:tarek
     39password:password
     40"""
    1141
    1242class RawInputs(object):
     
    2252            self.index += 1
    2353
    24 WANTED_PYPIRC = """\
    25 [distutils]
    26 index-servers =
    27     pypi
    28 
    29 [pypi]
    30 username:tarek
    31 password:xxx
    32 """
    33 
    34 class registerTestCase(PyPIRCCommandTestCase):
     54class FakeOpener(object):
     55    """Fakes a PyPI server"""
     56    def __init__(self):
     57        self.reqs = []
     58
     59    def __call__(self, *args):
     60        return self
     61
     62    def open(self, req):
     63        self.reqs.append(req)
     64        return self
     65
     66    def read(self):
     67        return 'xxx'
     68
     69class RegisterTestCase(PyPIRCCommandTestCase):
     70
     71    def setUp(self):
     72        super(RegisterTestCase, self).setUp()
     73        # patching the password prompt
     74        self._old_getpass = getpass.getpass
     75        def _getpass(prompt):
     76            return 'password'
     77        getpass.getpass = _getpass
     78        self.old_opener = urllib2.build_opener
     79        self.conn = urllib2.build_opener = FakeOpener()
     80
     81    def tearDown(self):
     82        getpass.getpass = self._old_getpass
     83        urllib2.build_opener = self.old_opener
     84        super(RegisterTestCase, self).tearDown()
     85
     86    def _get_cmd(self, metadata=None):
     87        if metadata is None:
     88            metadata = {'url': 'xxx', 'author': 'xxx',
     89                        'author_email': 'xxx',
     90                        'name': 'xxx', 'version': 'xxx'}
     91        pkg_info, dist = self.create_dist(**metadata)
     92        return register(dist)
    3593
    3694    def test_create_pypirc(self):
     
    3896        # is created when requested.
    3997
    40         # let's create a fake distribution
    41         # and a register instance
    42         dist = Distribution()
    43         dist.metadata.url = 'xxx'
    44         dist.metadata.author = 'xxx'
    45         dist.metadata.author_email = 'xxx'
    46         dist.metadata.name = 'xxx'
    47         dist.metadata.version =  'xxx'
    48         cmd = register(dist)
     98        # let's create a register instance
     99        cmd = self._get_cmd()
    49100
    50101        # we shouldn't have a .pypirc file yet
    51         self.assert_(not os.path.exists(self.rc))
     102        self.assertTrue(not os.path.exists(self.rc))
    52103
    53104        # patching raw_input and getpass.getpass
     
    57108        # use your existing login (choice 1.)
    58109        # Username : 'tarek'
    59         # Password : 'xxx'
     110        # Password : 'password'
    60111        # Save your login (y/N)? : 'y'
    61112        inputs = RawInputs('1', 'tarek', 'y')
    62         from distutils.command import register as register_module
    63         register_module.raw_input = inputs.__call__
    64         def _getpass(prompt):
    65             return 'xxx'
    66         register_module.getpass.getpass = _getpass
    67         class FakeServer(object):
    68             def __init__(self):
    69                 self.calls = []
    70 
    71             def __call__(self, *args):
    72                 # we want to compare them, so let's store
    73                 # something comparable
    74                 els = args[0].items()
    75                 els.sort()
    76                 self.calls.append(tuple(els))
    77                 return 200, 'OK'
    78 
    79         cmd.post_to_server = pypi_server = FakeServer()
    80 
    81         # let's run the command
    82         cmd.run()
     113        register_module.raw_input = inputs.__call__
     114        # let's run the command
     115        try:
     116            cmd.run()
     117        finally:
     118            del register_module.raw_input
    83119
    84120        # we should have a brand new .pypirc file
    85         self.assert_(os.path.exists(self.rc))
     121        self.assertTrue(os.path.exists(self.rc))
    86122
    87123        # with the content similar to WANTED_PYPIRC
    88         content = open(self.rc).read()
    89         self.assertEquals(content, WANTED_PYPIRC)
     124        f = open(self.rc)
     125        try:
     126            content = f.read()
     127            self.assertEqual(content, WANTED_PYPIRC)
     128        finally:
     129            f.close()
    90130
    91131        # now let's make sure the .pypirc file generated
     
    96136        register_module.raw_input = _no_way
    97137
     138        cmd.show_response = 1
    98139        cmd.run()
    99140
    100141        # let's see what the server received : we should
    101142        # have 2 similar requests
    102         self.assert_(len(pypi_server.calls), 2)
    103         self.assert_(pypi_server.calls[0], pypi_server.calls[1])
     143        self.assertEqual(len(self.conn.reqs), 2)
     144        req1 = dict(self.conn.reqs[0].headers)
     145        req2 = dict(self.conn.reqs[1].headers)
     146        self.assertEqual(req2['Content-length'], req1['Content-length'])
     147        self.assertTrue('xxx' in self.conn.reqs[1].data)
     148
     149    def test_password_not_in_file(self):
     150
     151        self.write_file(self.rc, PYPIRC_NOPASSWORD)
     152        cmd = self._get_cmd()
     153        cmd._set_config()
     154        cmd.finalize_options()
     155        cmd.send_metadata()
     156
     157        # dist.password should be set
     158        # therefore used afterwards by other commands
     159        self.assertEqual(cmd.distribution.password, 'password')
     160
     161    def test_registering(self):
     162        # this test runs choice 2
     163        cmd = self._get_cmd()
     164        inputs = RawInputs('2', 'tarek', 'tarek@ziade.org')
     165        register_module.raw_input = inputs.__call__
     166        try:
     167            # let's run the command
     168            cmd.run()
     169        finally:
     170            del register_module.raw_input
     171
     172        # we should have send a request
     173        self.assertEqual(len(self.conn.reqs), 1)
     174        req = self.conn.reqs[0]
     175        headers = dict(req.headers)
     176        self.assertEqual(headers['Content-length'], '608')
     177        self.assertTrue('tarek' in req.data)
     178
     179    def test_password_reset(self):
     180        # this test runs choice 3
     181        cmd = self._get_cmd()
     182        inputs = RawInputs('3', 'tarek@ziade.org')
     183        register_module.raw_input = inputs.__call__
     184        try:
     185            # let's run the command
     186            cmd.run()
     187        finally:
     188            del register_module.raw_input
     189
     190        # we should have send a request
     191        self.assertEqual(len(self.conn.reqs), 1)
     192        req = self.conn.reqs[0]
     193        headers = dict(req.headers)
     194        self.assertEqual(headers['Content-length'], '290')
     195        self.assertTrue('tarek' in req.data)
     196
     197    @unittest.skipUnless(docutils is not None, 'needs docutils')
     198    def test_strict(self):
     199        # testing the script option
     200        # when on, the register command stops if
     201        # the metadata is incomplete or if
     202        # long_description is not reSt compliant
     203
     204        # empty metadata
     205        cmd = self._get_cmd({})
     206        cmd.ensure_finalized()
     207        cmd.strict = 1
     208        self.assertRaises(DistutilsSetupError, cmd.run)
     209
     210        # metadata are OK but long_description is broken
     211        metadata = {'url': 'xxx', 'author': 'xxx',
     212                    'author_email': u'éxéxé',
     213                    'name': 'xxx', 'version': 'xxx',
     214                    'long_description': 'title\n==\n\ntext'}
     215
     216        cmd = self._get_cmd(metadata)
     217        cmd.ensure_finalized()
     218        cmd.strict = 1
     219        self.assertRaises(DistutilsSetupError, cmd.run)
     220
     221        # now something that works
     222        metadata['long_description'] = 'title\n=====\n\ntext'
     223        cmd = self._get_cmd(metadata)
     224        cmd.ensure_finalized()
     225        cmd.strict = 1
     226        inputs = RawInputs('1', 'tarek', 'y')
     227        register_module.raw_input = inputs.__call__
     228        # let's run the command
     229        try:
     230            cmd.run()
     231        finally:
     232            del register_module.raw_input
     233
     234        # strict is not by default
     235        cmd = self._get_cmd()
     236        cmd.ensure_finalized()
     237        inputs = RawInputs('1', 'tarek', 'y')
     238        register_module.raw_input = inputs.__call__
     239        # let's run the command
     240        try:
     241            cmd.run()
     242        finally:
     243            del register_module.raw_input
     244
     245        # and finally a Unicode test (bug #12114)
     246        metadata = {'url': u'xxx', 'author': u'\u00c9ric',
     247                    'author_email': u'xxx', u'name': 'xxx',
     248                    'version': u'xxx',
     249                    'description': u'Something about esszet \u00df',
     250                    'long_description': u'More things about esszet \u00df'}
     251
     252        cmd = self._get_cmd(metadata)
     253        cmd.ensure_finalized()
     254        cmd.strict = 1
     255        inputs = RawInputs('1', 'tarek', 'y')
     256        register_module.raw_input = inputs.__call__
     257        # let's run the command
     258        try:
     259            cmd.run()
     260        finally:
     261            del register_module.raw_input
     262
     263    @unittest.skipUnless(docutils is not None, 'needs docutils')
     264    def test_register_invalid_long_description(self):
     265        description = ':funkie:`str`'  # mimic Sphinx-specific markup
     266        metadata = {'url': 'xxx', 'author': 'xxx',
     267                    'author_email': 'xxx',
     268                    'name': 'xxx', 'version': 'xxx',
     269                    'long_description': description}
     270        cmd = self._get_cmd(metadata)
     271        cmd.ensure_finalized()
     272        cmd.strict = True
     273        inputs = RawInputs('2', 'tarek', 'tarek@ziade.org')
     274        register_module.raw_input = inputs
     275        self.addCleanup(delattr, register_module, 'raw_input')
     276        self.assertRaises(DistutilsSetupError, cmd.run)
     277
     278    def test_check_metadata_deprecated(self):
     279        # makes sure make_metadata is deprecated
     280        cmd = self._get_cmd()
     281        with check_warnings() as w:
     282            warnings.simplefilter("always")
     283            cmd.check_metadata()
     284            self.assertEqual(len(w.warnings), 1)
    104285
    105286def test_suite():
    106     return unittest.makeSuite(registerTestCase)
     287    return unittest.makeSuite(RegisterTestCase)
    107288
    108289if __name__ == "__main__":
    109     unittest.main(defaultTest="test_suite")
     290    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_sdist.py

    r2 r388  
    11"""Tests for distutils.command.sdist."""
    22import os
     3import tarfile
    34import unittest
    4 import shutil
     5import warnings
    56import zipfile
    67from os.path import join
    7 import sys
    8 
    9 from distutils.command.sdist import sdist
     8from textwrap import dedent
     9from test.test_support import captured_stdout, check_warnings, run_unittest
     10
     11# zlib is not used here, but if it's not available
     12# the tests that use zipfile may fail
     13try:
     14    import zlib
     15except ImportError:
     16    zlib = None
     17
     18try:
     19    import grp
     20    import pwd
     21    UID_GID_SUPPORT = True
     22except ImportError:
     23    UID_GID_SUPPORT = False
     24
     25
     26from distutils.command.sdist import sdist, show_formats
    1027from distutils.core import Distribution
    1128from distutils.tests.test_config import PyPIRCCommandTestCase
    12 from distutils.errors import DistutilsExecError
     29from distutils.errors import DistutilsOptionError
    1330from distutils.spawn import find_executable
     31from distutils.log import WARN
     32from distutils.filelist import FileList
     33from distutils.archive_util import ARCHIVE_FORMATS
    1434
    1535SETUP_PY = """
     
    2040"""
    2141
    22 MANIFEST_IN = """
    23 recursive-include somecode *
     42MANIFEST = """\
     43# file GENERATED by distutils, do NOT edit
     44README
     45buildout.cfg
     46inroot.txt
     47setup.py
     48data%(sep)sdata.dt
     49scripts%(sep)sscript.py
     50some%(sep)sfile.txt
     51some%(sep)sother_file.txt
     52somecode%(sep)s__init__.py
     53somecode%(sep)sdoc.dat
     54somecode%(sep)sdoc.txt
    2455"""
    2556
    26 class sdistTestCase(PyPIRCCommandTestCase):
     57class SDistTestCase(PyPIRCCommandTestCase):
    2758
    2859    def setUp(self):
    29         super(sdistTestCase, self).setUp()
     60        # PyPIRCCommandTestCase creates a temp dir already
     61        # and put it in self.tmp_dir
     62        super(SDistTestCase, self).setUp()
     63        # setting up an environment
    3064        self.old_path = os.getcwd()
    31         self.temp_pkg = os.path.join(self.mkdtemp(), 'temppkg')
     65        os.mkdir(join(self.tmp_dir, 'somecode'))
     66        os.mkdir(join(self.tmp_dir, 'dist'))
     67        # a package, and a README
     68        self.write_file((self.tmp_dir, 'README'), 'xxx')
     69        self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#')
     70        self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY)
     71        os.chdir(self.tmp_dir)
    3272
    3373    def tearDown(self):
     74        # back to normal
    3475        os.chdir(self.old_path)
    35         super(sdistTestCase, self).tearDown()
    36 
    37     def _init_tmp_pkg(self):
    38         if os.path.exists(self.temp_pkg):
    39             shutil.rmtree(self.temp_pkg)
    40         os.mkdir(self.temp_pkg)
    41         os.mkdir(join(self.temp_pkg, 'somecode'))
    42         os.mkdir(join(self.temp_pkg, 'dist'))
    43         # creating a MANIFEST, a package, and a README
    44         self._write(join(self.temp_pkg, 'MANIFEST.in'), MANIFEST_IN)
    45         self._write(join(self.temp_pkg, 'README'), 'xxx')
    46         self._write(join(self.temp_pkg, 'somecode', '__init__.py'), '#')
    47         self._write(join(self.temp_pkg, 'setup.py'), SETUP_PY)
    48         os.chdir(self.temp_pkg)
    49 
    50     def _write(self, path, content):
    51         f = open(path, 'w')
    52         try:
    53             f.write(content)
    54         finally:
    55             f.close()
    56 
    57     def test_prune_file_list(self):
    58         # this test creates a package with some vcs dirs in it
    59         # and launch sdist to make sure they get pruned
    60         # on all systems
    61         self._init_tmp_pkg()
    62 
    63         # creating VCS directories with some files in them
    64         os.mkdir(join(self.temp_pkg, 'somecode', '.svn'))
    65         self._write(join(self.temp_pkg, 'somecode', '.svn', 'ok.py'), 'xxx')
    66 
    67         os.mkdir(join(self.temp_pkg, 'somecode', '.hg'))
    68         self._write(join(self.temp_pkg, 'somecode', '.hg',
    69                          'ok'), 'xxx')
    70 
    71         os.mkdir(join(self.temp_pkg, 'somecode', '.git'))
    72         self._write(join(self.temp_pkg, 'somecode', '.git',
    73                          'ok'), 'xxx')
    74 
    75         # now building a sdist
    76         dist = Distribution()
     76        super(SDistTestCase, self).tearDown()
     77
     78    def get_cmd(self, metadata=None):
     79        """Returns a cmd"""
     80        if metadata is None:
     81            metadata = {'name': 'fake', 'version': '1.0',
     82                        'url': 'xxx', 'author': 'xxx',
     83                        'author_email': 'xxx'}
     84        dist = Distribution(metadata)
    7785        dist.script_name = 'setup.py'
    78         dist.metadata.name = 'fake'
    79         dist.metadata.version = '1.0'
    80         dist.metadata.url = 'http://xxx'
    81         dist.metadata.author = dist.metadata.author_email = 'xxx'
    8286        dist.packages = ['somecode']
    8387        dist.include_package_data = True
    8488        cmd = sdist(dist)
    85         cmd.manifest = 'MANIFEST'
    86         cmd.template = 'MANIFEST.in'
    8789        cmd.dist_dir = 'dist'
     90        return dist, cmd
     91
     92    @unittest.skipUnless(zlib, "requires zlib")
     93    def test_prune_file_list(self):
     94        # this test creates a project with some VCS dirs and an NFS rename
     95        # file, then launches sdist to check they get pruned on all systems
     96
     97        # creating VCS directories with some files in them
     98        os.mkdir(join(self.tmp_dir, 'somecode', '.svn'))
     99        self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx')
     100
     101        os.mkdir(join(self.tmp_dir, 'somecode', '.hg'))
     102        self.write_file((self.tmp_dir, 'somecode', '.hg',
     103                         'ok'), 'xxx')
     104
     105        os.mkdir(join(self.tmp_dir, 'somecode', '.git'))
     106        self.write_file((self.tmp_dir, 'somecode', '.git',
     107                         'ok'), 'xxx')
     108
     109        self.write_file((self.tmp_dir, 'somecode', '.nfs0001'), 'xxx')
     110
     111        # now building a sdist
     112        dist, cmd = self.get_cmd()
    88113
    89114        # zip is available universally
    90115        # (tar might not be installed under win32)
    91116        cmd.formats = ['zip']
     117
     118        cmd.ensure_finalized()
    92119        cmd.run()
    93120
    94121        # now let's check what we have
    95         dist_folder = join(self.temp_pkg, 'dist')
     122        dist_folder = join(self.tmp_dir, 'dist')
    96123        files = os.listdir(dist_folder)
    97         self.assertEquals(files, ['fake-1.0.zip'])
     124        self.assertEqual(files, ['fake-1.0.zip'])
    98125
    99126        zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
     
    104131
    105132        # making sure everything has been pruned correctly
    106         self.assertEquals(len(content), 4)
    107 
     133        self.assertEqual(len(content), 4)
     134
     135    @unittest.skipUnless(zlib, "requires zlib")
    108136    def test_make_distribution(self):
    109137
     
    113141            return
    114142
    115         self._init_tmp_pkg()
    116 
    117143        # now building a sdist
    118         dist = Distribution()
    119         dist.script_name = 'setup.py'
    120         dist.metadata.name = 'fake'
    121         dist.metadata.version = '1.0'
    122         dist.metadata.url = 'http://xxx'
    123         dist.metadata.author = dist.metadata.author_email = 'xxx'
    124         dist.packages = ['somecode']
    125         dist.include_package_data = True
    126         cmd = sdist(dist)
    127         cmd.manifest = 'MANIFEST'
    128         cmd.template = 'MANIFEST.in'
    129         cmd.dist_dir = 'dist'
     144        dist, cmd = self.get_cmd()
    130145
    131146        # creating a gztar then a tar
    132147        cmd.formats = ['gztar', 'tar']
     148        cmd.ensure_finalized()
    133149        cmd.run()
    134150
    135151        # making sure we have two files
    136         dist_folder = join(self.temp_pkg, 'dist')
     152        dist_folder = join(self.tmp_dir, 'dist')
    137153        result = os.listdir(dist_folder)
    138154        result.sort()
    139         self.assertEquals(result,
    140                           ['fake-1.0.tar', 'fake-1.0.tar.gz'] )
     155        self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])
    141156
    142157        os.remove(join(dist_folder, 'fake-1.0.tar'))
     
    145160        # now trying a tar then a gztar
    146161        cmd.formats = ['tar', 'gztar']
     162
     163        cmd.ensure_finalized()
    147164        cmd.run()
    148165
    149166        result = os.listdir(dist_folder)
    150167        result.sort()
    151         self.assertEquals(result,
    152                 ['fake-1.0.tar', 'fake-1.0.tar.gz'])
     168        self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])
     169
     170    @unittest.skipUnless(zlib, "requires zlib")
     171    def test_unicode_metadata_tgz(self):
     172        """
     173        Unicode name or version should not break building to tar.gz format.
     174        Reference issue #11638.
     175        """
     176
     177        # create the sdist command with unicode parameters
     178        dist, cmd = self.get_cmd({'name': u'fake', 'version': u'1.0'})
     179
     180        # create the sdist as gztar and run the command
     181        cmd.formats = ['gztar']
     182        cmd.ensure_finalized()
     183        cmd.run()
     184
     185        # The command should have created the .tar.gz file
     186        dist_folder = join(self.tmp_dir, 'dist')
     187        result = os.listdir(dist_folder)
     188        self.assertEqual(result, ['fake-1.0.tar.gz'])
     189
     190        os.remove(join(dist_folder, 'fake-1.0.tar.gz'))
     191
     192    @unittest.skipUnless(zlib, "requires zlib")
     193    def test_add_defaults(self):
     194
     195        # http://bugs.python.org/issue2279
     196
     197        # add_default should also include
     198        # data_files and package_data
     199        dist, cmd = self.get_cmd()
     200
     201        # filling data_files by pointing files
     202        # in package_data
     203        dist.package_data = {'': ['*.cfg', '*.dat'],
     204                             'somecode': ['*.txt']}
     205        self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
     206        self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#')
     207
     208        # adding some data in data_files
     209        data_dir = join(self.tmp_dir, 'data')
     210        os.mkdir(data_dir)
     211        self.write_file((data_dir, 'data.dt'), '#')
     212        some_dir = join(self.tmp_dir, 'some')
     213        os.mkdir(some_dir)
     214        # make sure VCS directories are pruned (#14004)
     215        hg_dir = join(self.tmp_dir, '.hg')
     216        os.mkdir(hg_dir)
     217        self.write_file((hg_dir, 'last-message.txt'), '#')
     218        # a buggy regex used to prevent this from working on windows (#6884)
     219        self.write_file((self.tmp_dir, 'buildout.cfg'), '#')
     220        self.write_file((self.tmp_dir, 'inroot.txt'), '#')
     221        self.write_file((some_dir, 'file.txt'), '#')
     222        self.write_file((some_dir, 'other_file.txt'), '#')
     223
     224        dist.data_files = [('data', ['data/data.dt',
     225                                     'buildout.cfg',
     226                                     'inroot.txt',
     227                                     'notexisting']),
     228                           'some/file.txt',
     229                           'some/other_file.txt']
     230
     231        # adding a script
     232        script_dir = join(self.tmp_dir, 'scripts')
     233        os.mkdir(script_dir)
     234        self.write_file((script_dir, 'script.py'), '#')
     235        dist.scripts = [join('scripts', 'script.py')]
     236
     237        cmd.formats = ['zip']
     238        cmd.use_defaults = True
     239
     240        cmd.ensure_finalized()
     241        cmd.run()
     242
     243        # now let's check what we have
     244        dist_folder = join(self.tmp_dir, 'dist')
     245        files = os.listdir(dist_folder)
     246        self.assertEqual(files, ['fake-1.0.zip'])
     247
     248        zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
     249        try:
     250            content = zip_file.namelist()
     251        finally:
     252            zip_file.close()
     253
     254        # making sure everything was added
     255        self.assertEqual(len(content), 12)
     256
     257        # checking the MANIFEST
     258        f = open(join(self.tmp_dir, 'MANIFEST'))
     259        try:
     260            manifest = f.read()
     261        finally:
     262            f.close()
     263        self.assertEqual(manifest, MANIFEST % {'sep': os.sep})
     264
     265    @unittest.skipUnless(zlib, "requires zlib")
     266    def test_metadata_check_option(self):
     267        # testing the `medata-check` option
     268        dist, cmd = self.get_cmd(metadata={})
     269
     270        # this should raise some warnings !
     271        # with the `check` subcommand
     272        cmd.ensure_finalized()
     273        cmd.run()
     274        warnings = [msg for msg in self.get_logs(WARN) if
     275                    msg.startswith('warning: check:')]
     276        self.assertEqual(len(warnings), 2)
     277
     278        # trying with a complete set of metadata
     279        self.clear_logs()
     280        dist, cmd = self.get_cmd()
     281        cmd.ensure_finalized()
     282        cmd.metadata_check = 0
     283        cmd.run()
     284        warnings = [msg for msg in self.get_logs(WARN) if
     285                    msg.startswith('warning: check:')]
     286        self.assertEqual(len(warnings), 0)
     287
     288    def test_check_metadata_deprecated(self):
     289        # makes sure make_metadata is deprecated
     290        dist, cmd = self.get_cmd()
     291        with check_warnings() as w:
     292            warnings.simplefilter("always")
     293            cmd.check_metadata()
     294            self.assertEqual(len(w.warnings), 1)
     295
     296    def test_show_formats(self):
     297        with captured_stdout() as stdout:
     298            show_formats()
     299
     300        # the output should be a header line + one line per format
     301        num_formats = len(ARCHIVE_FORMATS.keys())
     302        output = [line for line in stdout.getvalue().split('\n')
     303                  if line.strip().startswith('--formats=')]
     304        self.assertEqual(len(output), num_formats)
     305
     306    def test_finalize_options(self):
     307        dist, cmd = self.get_cmd()
     308        cmd.finalize_options()
     309
     310        # default options set by finalize
     311        self.assertEqual(cmd.manifest, 'MANIFEST')
     312        self.assertEqual(cmd.template, 'MANIFEST.in')
     313        self.assertEqual(cmd.dist_dir, 'dist')
     314
     315        # formats has to be a string splitable on (' ', ',') or
     316        # a stringlist
     317        cmd.formats = 1
     318        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
     319        cmd.formats = ['zip']
     320        cmd.finalize_options()
     321
     322        # formats has to be known
     323        cmd.formats = 'supazipa'
     324        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
     325
     326    @unittest.skipUnless(zlib, "requires zlib")
     327    @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
     328    def test_make_distribution_owner_group(self):
     329
     330        # check if tar and gzip are installed
     331        if (find_executable('tar') is None or
     332            find_executable('gzip') is None):
     333            return
     334
     335        # now building a sdist
     336        dist, cmd = self.get_cmd()
     337
     338        # creating a gztar and specifying the owner+group
     339        cmd.formats = ['gztar']
     340        cmd.owner = pwd.getpwuid(0)[0]
     341        cmd.group = grp.getgrgid(0)[0]
     342        cmd.ensure_finalized()
     343        cmd.run()
     344
     345        # making sure we have the good rights
     346        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
     347        archive = tarfile.open(archive_name)
     348        try:
     349            for member in archive.getmembers():
     350                self.assertEqual(member.uid, 0)
     351                self.assertEqual(member.gid, 0)
     352        finally:
     353            archive.close()
     354
     355        # building a sdist again
     356        dist, cmd = self.get_cmd()
     357
     358        # creating a gztar
     359        cmd.formats = ['gztar']
     360        cmd.ensure_finalized()
     361        cmd.run()
     362
     363        # making sure we have the good rights
     364        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
     365        archive = tarfile.open(archive_name)
     366
     367        # note that we are not testing the group ownership here
     368        # because, depending on the platforms and the container
     369        # rights (see #7408)
     370        try:
     371            for member in archive.getmembers():
     372                self.assertEqual(member.uid, os.getuid())
     373        finally:
     374            archive.close()
     375
     376    # the following tests make sure there is a nice error message instead
     377    # of a traceback when parsing an invalid manifest template
     378
     379    def _check_template(self, content):
     380        dist, cmd = self.get_cmd()
     381        os.chdir(self.tmp_dir)
     382        self.write_file('MANIFEST.in', content)
     383        cmd.ensure_finalized()
     384        cmd.filelist = FileList()
     385        cmd.read_template()
     386        warnings = self.get_logs(WARN)
     387        self.assertEqual(len(warnings), 1)
     388
     389    def test_invalid_template_unknown_command(self):
     390        self._check_template('taunt knights *')
     391
     392    def test_invalid_template_wrong_arguments(self):
     393        # this manifest command takes one argument
     394        self._check_template('prune')
     395
     396    @unittest.skipIf(os.name != 'nt', 'test relevant for Windows only')
     397    def test_invalid_template_wrong_path(self):
     398        # on Windows, trailing slashes are not allowed
     399        # this used to crash instead of raising a warning: #8286
     400        self._check_template('include examples/')
     401
     402    @unittest.skipUnless(zlib, "requires zlib")
     403    def test_get_file_list(self):
     404        # make sure MANIFEST is recalculated
     405        dist, cmd = self.get_cmd()
     406
     407        # filling data_files by pointing files in package_data
     408        dist.package_data = {'somecode': ['*.txt']}
     409        self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
     410        cmd.formats = ['gztar']
     411        cmd.ensure_finalized()
     412        cmd.run()
     413
     414        f = open(cmd.manifest)
     415        try:
     416            manifest = [line.strip() for line in f.read().split('\n')
     417                        if line.strip() != '']
     418        finally:
     419            f.close()
     420
     421        self.assertEqual(len(manifest), 5)
     422
     423        # adding a file
     424        self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#')
     425
     426        # make sure build_py is reinitialized, like a fresh run
     427        build_py = dist.get_command_obj('build_py')
     428        build_py.finalized = False
     429        build_py.ensure_finalized()
     430
     431        cmd.run()
     432
     433        f = open(cmd.manifest)
     434        try:
     435            manifest2 = [line.strip() for line in f.read().split('\n')
     436                         if line.strip() != '']
     437        finally:
     438            f.close()
     439
     440        # do we have the new file in MANIFEST ?
     441        self.assertEqual(len(manifest2), 6)
     442        self.assertIn('doc2.txt', manifest2[-1])
     443
     444    @unittest.skipUnless(zlib, "requires zlib")
     445    def test_manifest_marker(self):
     446        # check that autogenerated MANIFESTs have a marker
     447        dist, cmd = self.get_cmd()
     448        cmd.ensure_finalized()
     449        cmd.run()
     450
     451        f = open(cmd.manifest)
     452        try:
     453            manifest = [line.strip() for line in f.read().split('\n')
     454                        if line.strip() != '']
     455        finally:
     456            f.close()
     457
     458        self.assertEqual(manifest[0],
     459                         '# file GENERATED by distutils, do NOT edit')
     460
     461    @unittest.skipUnless(zlib, 'requires zlib')
     462    def test_manifest_comments(self):
     463        # make sure comments don't cause exceptions or wrong includes
     464        contents = dedent("""\
     465            # bad.py
     466            #bad.py
     467            good.py
     468            """)
     469        dist, cmd = self.get_cmd()
     470        cmd.ensure_finalized()
     471        self.write_file((self.tmp_dir, cmd.manifest), contents)
     472        self.write_file((self.tmp_dir, 'good.py'), '# pick me!')
     473        self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!")
     474        self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!")
     475        cmd.run()
     476        self.assertEqual(cmd.filelist.files, ['good.py'])
     477
     478    @unittest.skipUnless(zlib, "requires zlib")
     479    def test_manual_manifest(self):
     480        # check that a MANIFEST without a marker is left alone
     481        dist, cmd = self.get_cmd()
     482        cmd.formats = ['gztar']
     483        cmd.ensure_finalized()
     484        self.write_file((self.tmp_dir, cmd.manifest), 'README.manual')
     485        self.write_file((self.tmp_dir, 'README.manual'),
     486                         'This project maintains its MANIFEST file itself.')
     487        cmd.run()
     488        self.assertEqual(cmd.filelist.files, ['README.manual'])
     489
     490        f = open(cmd.manifest)
     491        try:
     492            manifest = [line.strip() for line in f.read().split('\n')
     493                        if line.strip() != '']
     494        finally:
     495            f.close()
     496
     497        self.assertEqual(manifest, ['README.manual'])
     498
     499        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
     500        archive = tarfile.open(archive_name)
     501        try:
     502            filenames = [tarinfo.name for tarinfo in archive]
     503        finally:
     504            archive.close()
     505        self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO',
     506                                             'fake-1.0/README.manual'])
    153507
    154508def test_suite():
    155     return unittest.makeSuite(sdistTestCase)
     509    return unittest.makeSuite(SDistTestCase)
    156510
    157511if __name__ == "__main__":
    158     unittest.main(defaultTest="test_suite")
     512    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_sysconfig.py

    r2 r388  
    1 """Tests for distutils.dist."""
    2 
    3 from distutils import sysconfig
     1"""Tests for distutils.sysconfig."""
    42import os
    53import test
    64import unittest
     5import shutil
    76
     7from distutils import sysconfig
     8from distutils.tests import support
    89from test.test_support import TESTFN
    910
    10 class SysconfigTestCase(unittest.TestCase):
     11class SysconfigTestCase(support.EnvironGuard,
     12                        unittest.TestCase):
    1113    def setUp(self):
    1214        super(SysconfigTestCase, self).setUp()
     
    1618        if self.makefile is not None:
    1719            os.unlink(self.makefile)
     20        self.cleanup_testfn()
    1821        super(SysconfigTestCase, self).tearDown()
    1922
    20     def test_get_config_h_filename(self):
    21         config_h = sysconfig.get_config_h_filename()
    22         self.assert_(os.path.isfile(config_h), config_h)
     23    def cleanup_testfn(self):
     24        path = test.test_support.TESTFN
     25        if os.path.isfile(path):
     26            os.remove(path)
     27        elif os.path.isdir(path):
     28            shutil.rmtree(path)
    2329
    2430    def test_get_python_lib(self):
    2531        lib_dir = sysconfig.get_python_lib()
    2632        # XXX doesn't work on Linux when Python was never installed before
    27         #self.assert_(os.path.isdir(lib_dir), lib_dir)
     33        #self.assertTrue(os.path.isdir(lib_dir), lib_dir)
    2834        # test for pythonxx.lib?
    2935        self.assertNotEqual(sysconfig.get_python_lib(),
    3036                            sysconfig.get_python_lib(prefix=TESTFN))
     37        _sysconfig = __import__('sysconfig')
     38        res = sysconfig.get_python_lib(True, True)
     39        self.assertEqual(_sysconfig.get_path('platstdlib'), res)
    3140
    3241    def test_get_python_inc(self):
     
    3948        self.assertTrue(os.path.isfile(python_h), python_h)
    4049
    41     def test_get_config_vars(self):
    42         cvars = sysconfig.get_config_vars()
    43         self.assert_(isinstance(cvars, dict))
    44         self.assert_(cvars)
     50    def test_parse_makefile_base(self):
     51        self.makefile = test.test_support.TESTFN
     52        fd = open(self.makefile, 'w')
     53        try:
     54            fd.write(r"CONFIG_ARGS=  '--arg1=optarg1' 'ENV=LIB'" '\n')
     55            fd.write('VAR=$OTHER\nOTHER=foo')
     56        finally:
     57            fd.close()
     58        d = sysconfig.parse_makefile(self.makefile)
     59        self.assertEqual(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'",
     60                             'OTHER': 'foo'})
    4561
    4662    def test_parse_makefile_literal_dollar(self):
    4763        self.makefile = test.test_support.TESTFN
    4864        fd = open(self.makefile, 'w')
    49         fd.write(r"CONFIG_ARGS=  '--arg1=optarg1' 'ENV=\$$LIB'" '\n')
    50         fd.write('VAR=$OTHER\nOTHER=foo')
    51         fd.close()
     65        try:
     66            fd.write(r"CONFIG_ARGS=  '--arg1=optarg1' 'ENV=\$$LIB'" '\n')
     67            fd.write('VAR=$OTHER\nOTHER=foo')
     68        finally:
     69            fd.close()
    5270        d = sysconfig.parse_makefile(self.makefile)
    53         self.assertEquals(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'",
    54                               'OTHER': 'foo'})
     71        self.assertEqual(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'",
     72                             'OTHER': 'foo'})
     73
     74
     75    def test_sysconfig_module(self):
     76        import sysconfig as global_sysconfig
     77        self.assertEqual(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS'))
     78        self.assertEqual(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS'))
     79
     80    @unittest.skipIf(sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'),'compiler flags customized')
     81    def test_sysconfig_compiler_vars(self):
     82        # On OS X, binary installers support extension module building on
     83        # various levels of the operating system with differing Xcode
     84        # configurations.  This requires customization of some of the
     85        # compiler configuration directives to suit the environment on
     86        # the installed machine.  Some of these customizations may require
     87        # running external programs and, so, are deferred until needed by
     88        # the first extension module build.  With Python 3.3, only
     89        # the Distutils version of sysconfig is used for extension module
     90        # builds, which happens earlier in the Distutils tests.  This may
     91        # cause the following tests to fail since no tests have caused
     92        # the global version of sysconfig to call the customization yet.
     93        # The solution for now is to simply skip this test in this case.
     94        # The longer-term solution is to only have one version of sysconfig.
     95
     96        import sysconfig as global_sysconfig
     97        if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'):
     98            return
     99        self.assertEqual(global_sysconfig.get_config_var('LDSHARED'), sysconfig.get_config_var('LDSHARED'))
     100        self.assertEqual(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC'))
     101
    55102
    56103
  • python/vendor/current/Lib/distutils/tests/test_unixccompiler.py

    r2 r388  
    11"""Tests for distutils.unixccompiler."""
     2import os
    23import sys
    34import unittest
     5from test.test_support import EnvironmentVarGuard, run_unittest
    46
    57from distutils import sysconfig
     
    122124        self.assertEqual(self.cc.rpath_foo(), '-R/foo')
    123125
     126    @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for OS X')
     127    def test_osx_cc_overrides_ldshared(self):
     128        # Issue #18080:
     129        # ensure that setting CC env variable also changes default linker
     130        def gcv(v):
     131            if v == 'LDSHARED':
     132                return 'gcc-4.2 -bundle -undefined dynamic_lookup '
     133            return 'gcc-4.2'
     134        sysconfig.get_config_var = gcv
     135        with EnvironmentVarGuard() as env:
     136            env['CC'] = 'my_cc'
     137            del env['LDSHARED']
     138            sysconfig.customize_compiler(self.cc)
     139        self.assertEqual(self.cc.linker_so[0], 'my_cc')
     140
     141    @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for OS X')
     142    def test_osx_explict_ldshared(self):
     143        # Issue #18080:
     144        # ensure that setting CC env variable does not change
     145        #   explicit LDSHARED setting for linker
     146        def gcv(v):
     147            if v == 'LDSHARED':
     148                return 'gcc-4.2 -bundle -undefined dynamic_lookup '
     149            return 'gcc-4.2'
     150        sysconfig.get_config_var = gcv
     151        with EnvironmentVarGuard() as env:
     152            env['CC'] = 'my_cc'
     153            env['LDSHARED'] = 'my_ld -bundle -dynamic'
     154            sysconfig.customize_compiler(self.cc)
     155        self.assertEqual(self.cc.linker_so[0], 'my_ld')
     156
    124157
    125158def test_suite():
     
    127160
    128161if __name__ == "__main__":
    129     unittest.main(defaultTest="test_suite")
     162    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_upload.py

    r2 r388  
     1# -*- encoding: utf8 -*-
    12"""Tests for distutils.command.upload."""
    2 # -*- encoding: utf8 -*-
    3 import sys
    43import os
    54import unittest
    6 import httplib
     5from test.test_support import run_unittest
    76
     7from distutils.command import upload as upload_mod
    88from distutils.command.upload import upload
    99from distutils.core import Distribution
    1010
    11 from distutils.tests import support
    1211from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase
    1312
     
    3029"""
    3130
    32 class _Resp(object):
    33     def __init__(self, status):
    34         self.status = status
    35         self.reason = 'OK'
    3631
    37 _CONNECTIONS = []
     32PYPIRC_NOPASSWORD = """\
     33[distutils]
    3834
    39 class _FakeHTTPConnection(object):
    40     def __init__(self, netloc):
    41         self.requests = []
    42         self.headers = {}
    43         self.body = None
    44         self.netloc = netloc
    45         _CONNECTIONS.append(self)
     35index-servers =
     36    server1
    4637
    47     def connect(self):
    48         pass
    49     endheaders = connect
     38[server1]
     39username:me
     40"""
    5041
    51     def send(self, body):
    52         self.body = body
     42class FakeOpen(object):
    5343
    54     def putrequest(self, type_, data):
    55         self.requests.append((type_, data))
     44    def __init__(self, url):
     45        self.url = url
     46        if not isinstance(url, str):
     47            self.req = url
     48        else:
     49            self.req = None
     50        self.msg = 'OK'
    5651
    57     def putheader(self, name, value):
    58         self.headers[name] = value
     52    def getcode(self):
     53        return 200
    5954
    60     def getresponse(self):
    61         return _Resp(200)
    6255
    6356class uploadTestCase(PyPIRCCommandTestCase):
     
    6558    def setUp(self):
    6659        super(uploadTestCase, self).setUp()
    67         self.old_klass = httplib.HTTPConnection
    68         httplib.HTTPConnection = _FakeHTTPConnection
     60        self.old_open = upload_mod.urlopen
     61        upload_mod.urlopen = self._urlopen
     62        self.last_open = None
    6963
    7064    def tearDown(self):
    71         httplib.HTTPConnection = self.old_klass
     65        upload_mod.urlopen = self.old_open
    7266        super(uploadTestCase, self).tearDown()
     67
     68    def _urlopen(self, url):
     69        self.last_open = FakeOpen(url)
     70        return self.last_open
    7371
    7472    def test_finalize_options(self):
    7573
    7674        # new format
    77         f = open(self.rc, 'w')
    78         f.write(PYPIRC)
    79         f.close()
    80 
     75        self.write_file(self.rc, PYPIRC)
    8176        dist = Distribution()
    8277        cmd = upload(dist)
     
    8580                             ('realm', 'pypi'),
    8681                             ('repository', 'http://pypi.python.org/pypi')):
    87             self.assertEquals(getattr(cmd, attr), waited)
     82            self.assertEqual(getattr(cmd, attr), waited)
    8883
     84    def test_saved_password(self):
     85        # file with no password
     86        self.write_file(self.rc, PYPIRC_NOPASSWORD)
     87
     88        # make sure it passes
     89        dist = Distribution()
     90        cmd = upload(dist)
     91        cmd.finalize_options()
     92        self.assertEqual(cmd.password, None)
     93
     94        # make sure we get it as well, if another command
     95        # initialized it at the dist level
     96        dist.password = 'xxx'
     97        cmd = upload(dist)
     98        cmd.finalize_options()
     99        self.assertEqual(cmd.password, 'xxx')
    89100
    90101    def test_upload(self):
     
    103114
    104115        # what did we send ?
    105         res = _CONNECTIONS[-1]
    106 
    107         headers = res.headers
    108         self.assert_('dédé' in res.body)
    109         self.assertEquals(headers['Content-length'], '2085')
     116        self.assertIn('dédé', self.last_open.req.data)
     117        headers = dict(self.last_open.req.headers)
     118        self.assertEqual(headers['Content-length'], '2085')
    110119        self.assertTrue(headers['Content-type'].startswith('multipart/form-data'))
    111 
    112         method, request = res.requests[-1]
    113         self.assertEquals(method, 'POST')
    114         self.assertEquals(res.netloc, 'pypi.python.org')
    115         self.assertTrue('xxx' in res.body)
    116         self.assertFalse('\n' in headers['Authorization'])
     120        self.assertEqual(self.last_open.req.get_method(), 'POST')
     121        self.assertEqual(self.last_open.req.get_full_url(),
     122                         'http://pypi.python.org/pypi')
     123        self.assertTrue('xxx' in self.last_open.req.data)
     124        auth = self.last_open.req.headers['Authorization']
     125        self.assertFalse('\n' in auth)
    117126
    118127def test_suite():
     
    120129
    121130if __name__ == "__main__":
    122     unittest.main(defaultTest="test_suite")
     131    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_util.py

    r2 r388  
    22import sys
    33import unittest
     4from test.test_support import run_unittest
    45
    56from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError
     
    2223
    2324if __name__ == "__main__":
    24     unittest.main(defaultTest="test_suite")
     25    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/tests/test_versionpredicate.py

    r2 r388  
    55import distutils.versionpredicate
    66import doctest
     7from test.test_support import run_unittest
    78
    89def test_suite():
    910    return doctest.DocTestSuite(distutils.versionpredicate)
     11
     12if __name__ == '__main__':
     13    run_unittest(test_suite())
  • python/vendor/current/Lib/distutils/text_file.py

    r2 r388  
    55lines, and joining lines with backslashes."""
    66
    7 __revision__ = "$Id: text_file.py 60923 2008-02-21 18:18:37Z guido.van.rossum $"
    8 
    9 from types import *
    10 import sys, os, string
     7__revision__ = "$Id$"
     8
     9import sys
    1110
    1211
     
    138137            line = self.current_line
    139138        outmsg.append(self.filename + ", ")
    140         if type (line) in (ListType, TupleType):
     139        if isinstance(line, (list, tuple)):
    141140            outmsg.append("lines %d-%d: " % tuple (line))
    142141        else:
    143142            outmsg.append("line %d: " % line)
    144143        outmsg.append(str(msg))
    145         return string.join(outmsg, "")
     144        return ''.join(outmsg)
    146145
    147146
     
    197196                # lurking in there) and otherwise leave the line alone.
    198197
    199                 pos = string.find (line, "#")
     198                pos = line.find("#")
    200199                if pos == -1:           # no "#" -- no comments
    201200                    pass
     
    220219                    #   there
    221220                    # result in "hello there".
    222                     if string.strip(line) == "":
     221                    if line.strip() == "":
    223222                        continue
    224223
    225224                else:                   # it's an escaped "#"
    226                     line = string.replace (line, "\\#", "#")
     225                    line = line.replace("\\#", "#")
    227226
    228227
     
    236235
    237236                if self.collapse_join:
    238                     line = string.lstrip (line)
     237                    line = line.lstrip()
    239238                line = buildup_line + line
    240239
    241240                # careful: pay attention to line number when incrementing it
    242                 if type (self.current_line) is ListType:
     241                if isinstance(self.current_line, list):
    243242                    self.current_line[1] = self.current_line[1] + 1
    244243                else:
     
    251250
    252251                # still have to be careful about incrementing the line number!
    253                 if type (self.current_line) is ListType:
     252                if isinstance(self.current_line, list):
    254253                    self.current_line = self.current_line[1] + 1
    255254                else:
     
    260259            # trailing, or one or the other, or neither)
    261260            if self.lstrip_ws and self.rstrip_ws:
    262                 line = string.strip (line)
     261                line = line.strip()
    263262            elif self.lstrip_ws:
    264                 line = string.lstrip (line)
     263                line = line.lstrip()
    265264            elif self.rstrip_ws:
    266                 line = string.rstrip (line)
     265                line = line.rstrip()
    267266
    268267            # blank line (whether we rstrip'ed or not)? skip to next line
     
    304303
    305304        self.linebuf.append (line)
    306 
    307 
    308 if __name__ == "__main__":
    309     test_data = """# test file
    310 
    311 line 3 \\
    312 # intervening comment
    313   continues on next line
    314 """
    315     # result 1: no fancy options
    316     result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1])
    317 
    318     # result 2: just strip comments
    319     result2 = ["\n",
    320                "line 3 \\\n",
    321                "  continues on next line\n"]
    322 
    323     # result 3: just strip blank lines
    324     result3 = ["# test file\n",
    325                "line 3 \\\n",
    326                "# intervening comment\n",
    327                "  continues on next line\n"]
    328 
    329     # result 4: default, strip comments, blank lines, and trailing whitespace
    330     result4 = ["line 3 \\",
    331                "  continues on next line"]
    332 
    333     # result 5: strip comments and blanks, plus join lines (but don't
    334     # "collapse" joined lines
    335     result5 = ["line 3   continues on next line"]
    336 
    337     # result 6: strip comments and blanks, plus join lines (and
    338     # "collapse" joined lines
    339     result6 = ["line 3 continues on next line"]
    340 
    341     def test_input (count, description, file, expected_result):
    342         result = file.readlines ()
    343         # result = string.join (result, '')
    344         if result == expected_result:
    345             print "ok %d (%s)" % (count, description)
    346         else:
    347             print "not ok %d (%s):" % (count, description)
    348             print "** expected:"
    349             print expected_result
    350             print "** received:"
    351             print result
    352 
    353 
    354     filename = "test.txt"
    355     out_file = open (filename, "w")
    356     out_file.write (test_data)
    357     out_file.close ()
    358 
    359     in_file = TextFile (filename, strip_comments=0, skip_blanks=0,
    360                         lstrip_ws=0, rstrip_ws=0)
    361     test_input (1, "no processing", in_file, result1)
    362 
    363     in_file = TextFile (filename, strip_comments=1, skip_blanks=0,
    364                         lstrip_ws=0, rstrip_ws=0)
    365     test_input (2, "strip comments", in_file, result2)
    366 
    367     in_file = TextFile (filename, strip_comments=0, skip_blanks=1,
    368                         lstrip_ws=0, rstrip_ws=0)
    369     test_input (3, "strip blanks", in_file, result3)
    370 
    371     in_file = TextFile (filename)
    372     test_input (4, "default processing", in_file, result4)
    373 
    374     in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
    375                         join_lines=1, rstrip_ws=1)
    376     test_input (5, "join lines without collapsing", in_file, result5)
    377 
    378     in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
    379                         join_lines=1, rstrip_ws=1, collapse_join=1)
    380     test_input (6, "join lines with collapsing", in_file, result6)
    381 
    382     os.remove (filename)
  • python/vendor/current/Lib/distutils/unixccompiler.py

    r2 r388  
    1414"""
    1515
    16 __revision__ = "$Id: unixccompiler.py 77378 2010-01-08 23:48:37Z tarek.ziade $"
    17 
    18 import os, sys
     16__revision__ = "$Id$"
     17
     18import os, sys, re
    1919from types import StringType, NoneType
    2020
     
    2626     DistutilsExecError, CompileError, LibError, LinkError
    2727from distutils import log
     28
     29if sys.platform == 'darwin':
     30    import _osx_support
    2831
    2932# XXX Things not currently handled:
     
    4245#     options and carry on.
    4346
    44 def _darwin_compiler_fixup(compiler_so, cc_args):
    45     """
    46     This function will strip '-isysroot PATH' and '-arch ARCH' from the
    47     compile flags if the user has specified one them in extra_compile_flags.
    48 
    49     This is needed because '-arch ARCH' adds another architecture to the
    50     build, without a way to remove an architecture. Furthermore GCC will
    51     barf if multiple '-isysroot' arguments are present.
    52     """
    53     stripArch = stripSysroot = 0
    54 
    55     compiler_so = list(compiler_so)
    56     kernel_version = os.uname()[2] # 8.4.3
    57     major_version = int(kernel_version.split('.')[0])
    58 
    59     if major_version < 8:
    60         # OSX before 10.4.0, these don't support -arch and -isysroot at
    61         # all.
    62         stripArch = stripSysroot = True
    63     else:
    64         stripArch = '-arch' in cc_args
    65         stripSysroot = '-isysroot' in cc_args
    66 
    67     if stripArch or 'ARCHFLAGS' in os.environ:
    68         while 1:
    69             try:
    70                 index = compiler_so.index('-arch')
    71                 # Strip this argument and the next one:
    72                 del compiler_so[index:index+2]
    73             except ValueError:
    74                 break
    75 
    76     if 'ARCHFLAGS' in os.environ and not stripArch:
    77         # User specified different -arch flags in the environ,
    78         # see also distutils.sysconfig
    79         compiler_so = compiler_so + os.environ['ARCHFLAGS'].split()
    80 
    81     if stripSysroot:
    82         try:
    83             index = compiler_so.index('-isysroot')
    84             # Strip this argument and the next one:
    85             del compiler_so[index:index+2]
    86         except ValueError:
    87             pass
    88 
    89     # Check if the SDK that is used during compilation actually exists,
    90     # the universal build requires the usage of a universal SDK and not all
    91     # users have that installed by default.
    92     sysroot = None
    93     if '-isysroot' in cc_args:
    94         idx = cc_args.index('-isysroot')
    95         sysroot = cc_args[idx+1]
    96     elif '-isysroot' in compiler_so:
    97         idx = compiler_so.index('-isysroot')
    98         sysroot = compiler_so[idx+1]
    99 
    100     if sysroot and not os.path.isdir(sysroot):
    101         log.warn("Compiling with an SDK that doesn't seem to exist: %s",
    102                 sysroot)
    103         log.warn("Please check your Xcode installation")
    104 
    105     return compiler_so
    10647
    10748class UnixCCompiler(CCompiler):
     
    173114        compiler_so = self.compiler_so
    174115        if sys.platform == 'darwin':
    175             compiler_so = _darwin_compiler_fixup(compiler_so, cc_args + extra_postargs)
     116            compiler_so = _osx_support.compiler_fixup(compiler_so,
     117                                                    cc_args + extra_postargs)
    176118        try:
    177119            self.spawn(compiler_so + cc_args + [src, '-o', obj] +
     
    252194
    253195                if sys.platform == 'darwin':
    254                     linker = _darwin_compiler_fixup(linker, ld_args)
     196                    linker = _osx_support.compiler_fixup(linker, ld_args)
    255197
    256198                self.spawn(linker + ld_args)
     
    306248        static_f = self.library_filename(lib, lib_type='static')
    307249
     250        if sys.platform == 'darwin':
     251            # On OSX users can specify an alternate SDK using
     252            # '-isysroot', calculate the SDK root if it is specified
     253            # (and use it further on)
     254            cflags = sysconfig.get_config_var('CFLAGS')
     255            m = re.search(r'-isysroot\s+(\S+)', cflags)
     256            if m is None:
     257                sysroot = '/'
     258            else:
     259                sysroot = m.group(1)
     260
     261
     262
    308263        for dir in dirs:
    309264            shared = os.path.join(dir, shared_f)
    310265            dylib = os.path.join(dir, dylib_f)
    311266            static = os.path.join(dir, static_f)
     267
     268            if sys.platform == 'darwin' and (
     269                dir.startswith('/System/') or (
     270                dir.startswith('/usr/') and not dir.startswith('/usr/local/'))):
     271
     272                shared = os.path.join(sysroot, dir[1:], shared_f)
     273                dylib = os.path.join(sysroot, dir[1:], dylib_f)
     274                static = os.path.join(sysroot, dir[1:], static_f)
     275
    312276            # We're second-guessing the linker here, with not much hard
    313277            # data to go on: GCC seems to prefer the shared library, so I'm
  • python/vendor/current/Lib/distutils/util.py

    r2 r388  
    55"""
    66
    7 __revision__ = "$Id: util.py 77376 2010-01-08 23:27:23Z tarek.ziade $"
     7__revision__ = "$Id$"
    88
    99import sys, os, string, re
     
    5252        return sys.platform
    5353
     54    # Set for cross builds explicitly
     55    if "_PYTHON_HOST_PLATFORM" in os.environ:
     56        return os.environ["_PYTHON_HOST_PLATFORM"]
     57
    5458    if os.name != "posix" or not hasattr(os, 'uname'):
    5559        # XXX what about the architecture? NT is Intel or Alpha,
     
    7781            osname = "solaris"
    7882            release = "%d.%s" % (int(release[0]) - 3, release[2:])
     83            # We can't use "platform.architecture()[0]" because a
     84            # bootstrap problem. We use a dict to get an error
     85            # if some suspicious happens.
     86            bitness = {2147483647:"32bit", 9223372036854775807:"64bit"}
     87            machine += ".%s" % bitness[sys.maxint]
    7988        # fall through to standard osname-release-machine representation
    8089    elif osname[:4] == "irix":              # could be "irix64"!
     
    8998            release = m.group()
    9099    elif osname[:6] == "darwin":
    91         #
    92         # For our purposes, we'll assume that the system version from
    93         # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set
    94         # to. This makes the compatibility story a bit more sane because the
    95         # machine is going to compile and link as if it were
    96         # MACOSX_DEPLOYMENT_TARGET.
    97         from distutils.sysconfig import get_config_vars
    98         cfgvars = get_config_vars()
    99 
    100         macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
    101         if not macver:
    102             macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
    103 
    104         if 1:
    105             # Always calculate the release of the running machine,
    106             # needed to determine if we can build fat binaries or not.
    107 
    108             macrelease = macver
    109             # Get the system version. Reading this plist is a documented
    110             # way to get the system version (see the documentation for
    111             # the Gestalt Manager)
    112             try:
    113                 f = open('/System/Library/CoreServices/SystemVersion.plist')
    114             except IOError:
    115                 # We're on a plain darwin box, fall back to the default
    116                 # behaviour.
    117                 pass
    118             else:
    119                 m = re.search(
    120                         r'<key>ProductUserVisibleVersion</key>\s*' +
    121                         r'<string>(.*?)</string>', f.read())
    122                 f.close()
    123                 if m is not None:
    124                     macrelease = '.'.join(m.group(1).split('.')[:2])
    125                 # else: fall back to the default behaviour
    126 
    127         if not macver:
    128             macver = macrelease
    129 
    130         if macver:
    131             from distutils.sysconfig import get_config_vars
    132             release = macver
    133             osname = "macosx"
    134 
    135             if (macrelease + '.') >= '10.4.' and \
    136                     '-arch' in get_config_vars().get('CFLAGS', '').strip():
    137                 # The universal build will build fat binaries, but not on
    138                 # systems before 10.4
    139                 #
    140                 # Try to detect 4-way universal builds, those have machine-type
    141                 # 'universal' instead of 'fat'.
    142 
    143                 machine = 'fat'
    144                 cflags = get_config_vars().get('CFLAGS')
    145 
    146                 archs = re.findall('-arch\s+(\S+)', cflags)
    147                 archs.sort()
    148                 archs = tuple(archs)
    149 
    150                 if len(archs) == 1:
    151                     machine = archs[0]
    152                 elif archs == ('i386', 'ppc'):
    153                     machine = 'fat'
    154                 elif archs == ('i386', 'x86_64'):
    155                     machine = 'intel'
    156                 elif archs == ('i386', 'ppc', 'x86_64'):
    157                     machine = 'fat3'
    158                 elif archs == ('ppc64', 'x86_64'):
    159                     machine = 'fat64'
    160                 elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
    161                     machine = 'universal'
    162                 else:
    163                     raise ValueError(
    164                        "Don't know machine value for archs=%r"%(archs,))
    165 
    166             elif machine == 'i386':
    167                 # On OSX the machine type returned by uname is always the
    168                 # 32-bit variant, even if the executable architecture is
    169                 # the 64-bit variant
    170                 if sys.maxint >= 2**32:
    171                     machine = 'x86_64'
    172 
    173             elif machine in ('PowerPC', 'Power_Macintosh'):
    174                 # Pick a sane name for the PPC architecture.
    175                 machine = 'ppc'
    176 
    177                 # See 'i386' case
    178                 if sys.maxint >= 2**32:
    179                     machine = 'ppc64'
     100        import _osx_support, distutils.sysconfig
     101        osname, release, machine = _osx_support.get_platform_osx(
     102                                        distutils.sysconfig.get_config_vars(),
     103                                        osname, release, machine)
    180104
    181105    return "%s-%s-%s" % (osname, release, machine)
     
    207131    if not paths:
    208132        return os.curdir
    209     return apply(os.path.join, paths)
     133    return os.path.join(*paths)
    210134
    211135# convert_path ()
     
    235159            path = path[1:]
    236160        return os.path.join(new_root, path)
    237 
    238     elif os.name == 'mac':
    239         if not os.path.isabs(pathname):
    240             return os.path.join(new_root, pathname)
    241         else:
    242             # Chop off volume name from start of path
    243             elements = string.split(pathname, ":", 1)
    244             pathname = ":" + elements[1]
    245             return os.path.join(new_root, pathname)
    246161
    247162    else:
     
    407322    log.info(msg)
    408323    if not dry_run:
    409         apply(func, args)
     324        func(*args)
    410325
    411326
  • python/vendor/current/Lib/distutils/version.py

    r2 r388  
    55# Python Module Distribution Utilities.
    66#
    7 # $Id: version.py 71270 2009-04-05 21:11:43Z georg.brandl $
     7# $Id$
    88#
    99
Note: See TracChangeset for help on using the changeset viewer.