Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/distutils/archive_util.py

    r2 r391  
    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 ()
Note: See TracChangeset for help on using the changeset viewer.