Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes
MoinMoin.support.tarfile.TarFile Class Reference

List of all members.

Public Member Functions

def __init__
def open
def taropen
def gzopen
def bz2open
def close
def getmember
def getmembers
def getnames
def gettarinfo
def list
def add
def addfile
def extractall
def extract
def extractfile
def makedir
def makefile
def makeunknown
def makefifo
def makedev
def makelink
def chown
def chmod
def utime
def next
def proc_member
def proc_builtin
def proc_gnulong
def proc_sparse
def __iter__

Public Attributes

 mode
 name
 fileobj
 closed
 members
 offset
 inodes
 firstmember

Static Public Attributes

int debug = 0
 dereference = False
 ignore_zeros = False
int errorlevel = 0
 posix = False
 fileobject = ExFileObject
tuple open = classmethod(open)
tuple taropen = classmethod(taropen)
tuple gzopen = classmethod(gzopen)
tuple bz2open = classmethod(bz2open)
dictionary OPEN_METH

Private Member Functions

def _extract_member
def _block
def _getmember
def _load
def _check
def _dbg

Private Attributes

 _mode
 _extfileobj
 _loaded

Detailed Description

The TarFile Class provides an interface to tar archives.

Definition at line 1036 of file tarfile.py.


Constructor & Destructor Documentation

def MoinMoin.support.tarfile.TarFile.__init__ (   self,
  name = None,
  mode = "r",
  fileobj = None 
)
Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
   read from an existing archive, 'a' to append data to an existing
   file or 'w' to create a new file overwriting an existing one. `mode'
   defaults to 'r'.
   If `fileobj' is given, it is used for reading or writing data. If it
   can be determined, `mode' is overridden by `fileobj's mode.
   `fileobj' is not closed, when TarFile is closed.

Definition at line 1057 of file tarfile.py.

01057 
01058     def __init__(self, name=None, mode="r", fileobj=None):
01059         """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
01060            read from an existing archive, 'a' to append data to an existing
01061            file or 'w' to create a new file overwriting an existing one. `mode'
01062            defaults to 'r'.
01063            If `fileobj' is given, it is used for reading or writing data. If it
01064            can be determined, `mode' is overridden by `fileobj's mode.
01065            `fileobj' is not closed, when TarFile is closed.
01066         """
01067         if len(mode) > 1 or mode not in "raw":
01068             raise ValueError("mode must be 'r', 'a' or 'w'")
01069         self._mode = mode
01070         self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode]
01071 
01072         if not fileobj:
01073             if self._mode == "a" and not os.path.exists(name):
01074                 # Create nonexistent files in append mode.
01075                 self._mode = "w"
01076                 self.mode = "wb"
01077             fileobj = file(name, self.mode)
01078             self._extfileobj = False
01079         else:
01080             if name is None and hasattr(fileobj, "name"):
01081                 name = fileobj.name
01082             if hasattr(fileobj, "mode"):
01083                 self.mode = fileobj.mode
01084             self._extfileobj = True
01085         self.name = name and os.path.abspath(name) or None
01086         self.fileobj = fileobj
01087 
01088         # Init datastructures
01089         self.closed = False
01090         self.members = []       # list of members as TarInfo objects
01091         self._loaded = False    # flag if all members have been read
01092         self.offset = self.fileobj.tell()
01093                                 # current position in the archive file
01094         self.inodes = {}        # dictionary caching the inodes of
01095                                 # archive members already added
01096 
01097         if self._mode == "r":
01098             self.firstmember = None
01099             self.firstmember = self.next()
01100 
01101         if self._mode == "a":
01102             # Move to the end of the archive,
01103             # before the first empty block.
01104             self.firstmember = None
01105             while True:
01106                 try:
01107                     tarinfo = self.next()
01108                 except ReadError:
01109                     self.fileobj.seek(0)
01110                     break
01111                 if tarinfo is None:
01112                     if self.offset > 0:
01113                         self.fileobj.seek(- BLOCKSIZE, 1)
01114                     break
01115 
01116         if self._mode in "aw":
01117             self._loaded = True


Member Function Documentation

Provide an iterator object.

Definition at line 2029 of file tarfile.py.

02029 
02030     def __iter__(self):
02031         """Provide an iterator object.
02032         """
02033         if self._loaded:
02034             return iter(self.members)
02035         else:
02036             return TarIter(self)

def MoinMoin.support.tarfile.TarFile._block (   self,
  count 
) [private]
Round up a byte count by BLOCKSIZE and return it,
   e.g. _block(834) => 1024.

Definition at line 1985 of file tarfile.py.

01985 
01986     def _block(self, count):
01987         """Round up a byte count by BLOCKSIZE and return it,
01988            e.g. _block(834) => 1024.
01989         """
01990         blocks, remainder = divmod(count, BLOCKSIZE)
01991         if remainder:
01992             blocks += 1
01993         return blocks * BLOCKSIZE

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile._check (   self,
  mode = None 
) [private]
Check if TarFile is still open, and if the operation's mode
   corresponds to TarFile's mode.

Definition at line 2020 of file tarfile.py.

02020 
02021     def _check(self, mode=None):
02022         """Check if TarFile is still open, and if the operation's mode
02023            corresponds to TarFile's mode.
02024         """
02025         if self.closed:
02026             raise IOError("%s is closed" % self.__class__.__name__)
02027         if mode is not None and self._mode not in mode:
02028             raise IOError("bad operation for mode %r" % self._mode)

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile._dbg (   self,
  level,
  msg 
) [private]
Write debugging output to sys.stderr.

Definition at line 2037 of file tarfile.py.

02037 
02038     def _dbg(self, level, msg):
02039         """Write debugging output to sys.stderr.
02040         """
02041         if level <= self.debug:
02042             print >> sys.stderr, msg
02043 # class TarFile

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile._extract_member (   self,
  tarinfo,
  targetpath 
) [private]
Extract the TarInfo object tarinfo to a physical
   file called targetpath.

Definition at line 1631 of file tarfile.py.

01631 
01632     def _extract_member(self, tarinfo, targetpath):
01633         """Extract the TarInfo object tarinfo to a physical
01634            file called targetpath.
01635         """
01636         # Fetch the TarInfo object for the given name
01637         # and build the destination pathname, replacing
01638         # forward slashes to platform specific separators.
01639         if targetpath[-1:] == "/":
01640             targetpath = targetpath[:-1]
01641         targetpath = os.path.normpath(targetpath)
01642 
01643         # Create all upper directories.
01644         upperdirs = os.path.dirname(targetpath)
01645         if upperdirs and not os.path.exists(upperdirs):
01646             # Create directories that are not part of the archive with
01647             # default permissions.
01648             os.makedirs(upperdirs)
01649 
01650         if tarinfo.islnk() or tarinfo.issym():
01651             self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
01652         else:
01653             self._dbg(1, tarinfo.name)
01654 
01655         if tarinfo.isreg():
01656             self.makefile(tarinfo, targetpath)
01657         elif tarinfo.isdir():
01658             self.makedir(tarinfo, targetpath)
01659         elif tarinfo.isfifo():
01660             self.makefifo(tarinfo, targetpath)
01661         elif tarinfo.ischr() or tarinfo.isblk():
01662             self.makedev(tarinfo, targetpath)
01663         elif tarinfo.islnk() or tarinfo.issym():
01664             self.makelink(tarinfo, targetpath)
01665         elif tarinfo.type not in SUPPORTED_TYPES:
01666             self.makeunknown(tarinfo, targetpath)
01667         else:
01668             self.makefile(tarinfo, targetpath)
01669 
01670         self.chown(tarinfo, targetpath)
01671         if not tarinfo.issym():
01672             self.chmod(tarinfo, targetpath)
01673             self.utime(tarinfo, targetpath)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile._getmember (   self,
  name,
  tarinfo = None 
) [private]
Find an archive member by name from bottom to top.
   If tarinfo is given, it is used as the starting point.

Definition at line 1994 of file tarfile.py.

01994 
01995     def _getmember(self, name, tarinfo=None):
01996         """Find an archive member by name from bottom to top.
01997            If tarinfo is given, it is used as the starting point.
01998         """
01999         # Ensure that all members have been loaded.
02000         members = self.getmembers()
02001 
02002         if tarinfo is None:
02003             end = len(members)
02004         else:
02005             end = members.index(tarinfo)
02006 
02007         for i in xrange(end - 1, -1, -1):
02008             if name == members[i].name:
02009                 return members[i]

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile._load (   self) [private]
Read through the entire archive file and look for readable
   members.

Definition at line 2010 of file tarfile.py.

02010 
02011     def _load(self):
02012         """Read through the entire archive file and look for readable
02013            members.
02014         """
02015         while True:
02016             tarinfo = self.next()
02017             if tarinfo is None:
02018                 break
02019         self._loaded = True

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.add (   self,
  name,
  arcname = None,
  recursive = True 
)
Add the file `name' to the archive. `name' may be any type of file
   (directory, fifo, symbolic link, etc.). If given, `arcname'
   specifies an alternative name for the file in the archive.
   Directories are added recursively by default. This can be avoided by
   setting `recursive' to False.

Definition at line 1445 of file tarfile.py.

01445 
01446     def add(self, name, arcname=None, recursive=True):
01447         """Add the file `name' to the archive. `name' may be any type of file
01448            (directory, fifo, symbolic link, etc.). If given, `arcname'
01449            specifies an alternative name for the file in the archive.
01450            Directories are added recursively by default. This can be avoided by
01451            setting `recursive' to False.
01452         """
01453         self._check("aw")
01454 
01455         if arcname is None:
01456             arcname = name
01457 
01458         # Skip if somebody tries to archive the archive...
01459         if self.name is not None and os.path.abspath(name) == self.name:
01460             self._dbg(2, "tarfile: Skipped %r" % name)
01461             return
01462 
01463         # Special case: The user wants to add the current
01464         # working directory.
01465         if name == ".":
01466             if recursive:
01467                 if arcname == ".":
01468                     arcname = ""
01469                 for f in os.listdir("."):
01470                     self.add(f, os.path.join(arcname, f))
01471             return
01472 
01473         self._dbg(1, name)
01474 
01475         # Create a TarInfo object from the file.
01476         tarinfo = self.gettarinfo(name, arcname)
01477 
01478         if tarinfo is None:
01479             self._dbg(1, "tarfile: Unsupported type %r" % name)
01480             return
01481 
01482         # Append the tar header and data to the archive.
01483         if tarinfo.isreg():
01484             f = file(name, "rb")
01485             self.addfile(tarinfo, f)
01486             f.close()
01487 
01488         elif tarinfo.isdir():
01489             self.addfile(tarinfo)
01490             if recursive:
01491                 for f in os.listdir(name):
01492                     self.add(os.path.join(name, f), os.path.join(arcname, f))
01493 
01494         else:
01495             self.addfile(tarinfo)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.addfile (   self,
  tarinfo,
  fileobj = None 
)
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
   given, tarinfo.size bytes are read from it and added to the archive.
   You can create TarInfo objects using gettarinfo().
   On Windows platforms, `fileobj' should always be opened with mode
   'rb' to avoid irritation about the file size.

Definition at line 1496 of file tarfile.py.

01496 
01497     def addfile(self, tarinfo, fileobj=None):
01498         """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
01499            given, tarinfo.size bytes are read from it and added to the archive.
01500            You can create TarInfo objects using gettarinfo().
01501            On Windows platforms, `fileobj' should always be opened with mode
01502            'rb' to avoid irritation about the file size.
01503         """
01504         self._check("aw")
01505 
01506         tarinfo = copy.copy(tarinfo)
01507 
01508         buf = tarinfo.tobuf(self.posix)
01509         self.fileobj.write(buf)
01510         self.offset += len(buf)
01511 
01512         # If there's data to follow, append it.
01513         if fileobj is not None:
01514             copyfileobj(fileobj, self.fileobj, tarinfo.size)
01515             blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
01516             if remainder > 0:
01517                 self.fileobj.write(NUL * (BLOCKSIZE - remainder))
01518                 blocks += 1
01519             self.offset += blocks * BLOCKSIZE
01520 
01521         self.members.append(tarinfo)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.bz2open (   cls,
  name,
  mode = "r",
  fileobj = None,
  compresslevel = 9 
)
Open bzip2 compressed tar archive name for reading or writing.
   Appending is not allowed.

Definition at line 1234 of file tarfile.py.

01234 
01235     def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9):
01236         """Open bzip2 compressed tar archive name for reading or writing.
01237            Appending is not allowed.
01238         """
01239         if len(mode) > 1 or mode not in "rw":
01240             raise ValueError("mode must be 'r' or 'w'.")
01241 
01242         try:
01243             import bz2
01244         except ImportError:
01245             raise CompressionError("bz2 module is not available")
01246 
01247         if fileobj is not None:
01248             fileobj = _BZ2Proxy(fileobj, mode)
01249         else:
01250             fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)
01251 
01252         try:
01253             t = cls.taropen(name, mode, fileobj)
01254         except IOError:
01255             raise ReadError("not a bzip2 file")
01256         t._extfileobj = False
        return t
def MoinMoin.support.tarfile.TarFile.chmod (   self,
  tarinfo,
  targetpath 
)
Set file permissions of targetpath according to tarinfo.

Definition at line 1785 of file tarfile.py.

01785 
01786     def chmod(self, tarinfo, targetpath):
01787         """Set file permissions of targetpath according to tarinfo.
01788         """
01789         if hasattr(os, 'chmod'):
01790             try:
01791                 os.chmod(targetpath, tarinfo.mode)
01792             except EnvironmentError, e:
01793                 raise ExtractError("could not change mode")

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.chown (   self,
  tarinfo,
  targetpath 
)
Set owner of targetpath according to tarinfo.

Definition at line 1757 of file tarfile.py.

01757 
01758     def chown(self, tarinfo, targetpath):
01759         """Set owner of targetpath according to tarinfo.
01760         """
01761         if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
01762             # We have to be root to do so.
01763             try:
01764                 g = grp.getgrnam(tarinfo.gname)[2]
01765             except KeyError:
01766                 try:
01767                     g = grp.getgrgid(tarinfo.gid)[2]
01768                 except KeyError:
01769                     g = os.getgid()
01770             try:
01771                 u = pwd.getpwnam(tarinfo.uname)[2]
01772             except KeyError:
01773                 try:
01774                     u = pwd.getpwuid(tarinfo.uid)[2]
01775                 except KeyError:
01776                     u = os.getuid()
01777             try:
01778                 if tarinfo.issym() and hasattr(os, "lchown"):
01779                     os.lchown(targetpath, u, g)
01780                 else:
01781                     if sys.platform != "os2emx":
01782                         os.chown(targetpath, u, g)
01783             except EnvironmentError, e:
01784                 raise ExtractError("could not change owner")

Here is the caller graph for this function:

Close the TarFile. In write-mode, two finishing zero blocks are
   appended to the archive.

Definition at line 1269 of file tarfile.py.

01269 
01270     def close(self):
01271         """Close the TarFile. In write-mode, two finishing zero blocks are
01272            appended to the archive.
01273         """
01274         if self.closed:
01275             return
01276 
01277         if self._mode in "aw":
01278             self.fileobj.write(NUL * (BLOCKSIZE * 2))
01279             self.offset += (BLOCKSIZE * 2)
01280             # fill up the end with zero-blocks
01281             # (like option -b20 for tar does)
01282             blocks, remainder = divmod(self.offset, RECORDSIZE)
01283             if remainder > 0:
01284                 self.fileobj.write(NUL * (RECORDSIZE - remainder))
01285 
01286         if not self._extfileobj:
01287             self.fileobj.close()
01288         self.closed = True

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.extract (   self,
  member,
  path = "" 
)
Extract a member from the archive to the current working directory,
   using its full name. Its file information is extracted as accurately
   as possible. `member' may be a filename or a TarInfo object. You can
   specify a different directory using `path'.

Definition at line 1559 of file tarfile.py.

01559 
01560     def extract(self, member, path=""):
01561         """Extract a member from the archive to the current working directory,
01562            using its full name. Its file information is extracted as accurately
01563            as possible. `member' may be a filename or a TarInfo object. You can
01564            specify a different directory using `path'.
01565         """
01566         self._check("r")
01567 
01568         if isinstance(member, TarInfo):
01569             tarinfo = member
01570         else:
01571             tarinfo = self.getmember(member)
01572 
01573         # Prepare the link target for makelink().
01574         if tarinfo.islnk():
01575             tarinfo._link_target = os.path.join(path, tarinfo.linkname)
01576 
01577         try:
01578             self._extract_member(tarinfo, os.path.join(path, tarinfo.name))
01579         except EnvironmentError, e:
01580             if self.errorlevel > 0:
01581                 raise
01582             else:
01583                 if e.filename is None:
01584                     self._dbg(1, "tarfile: %s" % e.strerror)
01585                 else:
01586                     self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
01587         except ExtractError, e:
01588             if self.errorlevel > 1:
01589                 raise
01590             else:
01591                 self._dbg(1, "tarfile: %s" % e)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.extractall (   self,
  path = ".",
  members = None 
)
Extract all members from the archive to the current working
   directory and set owner, modification time and permissions on
   directories afterwards. `path' specifies a different directory
   to extract to. `members' is optional and must be a subset of the
   list returned by getmembers().

Definition at line 1522 of file tarfile.py.

01522 
01523     def extractall(self, path=".", members=None):
01524         """Extract all members from the archive to the current working
01525            directory and set owner, modification time and permissions on
01526            directories afterwards. `path' specifies a different directory
01527            to extract to. `members' is optional and must be a subset of the
01528            list returned by getmembers().
01529         """
01530         directories = []
01531 
01532         if members is None:
01533             members = self
01534 
01535         for tarinfo in members:
01536             if tarinfo.isdir():
01537                 # Extract directories with a safe mode.
01538                 directories.append(tarinfo)
01539                 tarinfo = copy.copy(tarinfo)
01540                 tarinfo.mode = 0700
01541             self.extract(tarinfo, path)
01542 
01543         # Reverse sort directories.
01544         directories.sort(lambda a, b: cmp(a.name, b.name))
01545         directories.reverse()
01546 
01547         # Set correct owner, mtime and filemode on directories.
01548         for tarinfo in directories:
01549             dirpath = os.path.join(path, tarinfo.name)
01550             try:
01551                 self.chown(tarinfo, dirpath)
01552                 self.utime(tarinfo, dirpath)
01553                 self.chmod(tarinfo, dirpath)
01554             except ExtractError, e:
01555                 if self.errorlevel > 1:
01556                     raise
01557                 else:
01558                     self._dbg(1, "tarfile: %s" % e)

Here is the call graph for this function:

def MoinMoin.support.tarfile.TarFile.extractfile (   self,
  member 
)
Extract a member from the archive as a file object. `member' may be
   a filename or a TarInfo object. If `member' is a regular file, a
   file-like object is returned. If `member' is a link, a file-like
   object is constructed from the link's target. If `member' is none of
   the above, None is returned.
   The file-like object is read-only and provides the following
   methods: read(), readline(), readlines(), seek() and tell()

Definition at line 1592 of file tarfile.py.

01592 
01593     def extractfile(self, member):
01594         """Extract a member from the archive as a file object. `member' may be
01595            a filename or a TarInfo object. If `member' is a regular file, a
01596            file-like object is returned. If `member' is a link, a file-like
01597            object is constructed from the link's target. If `member' is none of
01598            the above, None is returned.
01599            The file-like object is read-only and provides the following
01600            methods: read(), readline(), readlines(), seek() and tell()
01601         """
01602         self._check("r")
01603 
01604         if isinstance(member, TarInfo):
01605             tarinfo = member
01606         else:
01607             tarinfo = self.getmember(member)
01608 
01609         if tarinfo.isreg():
01610             return self.fileobject(self, tarinfo)
01611 
01612         elif tarinfo.type not in SUPPORTED_TYPES:
01613             # If a member's type is unknown, it is treated as a
01614             # regular file.
01615             return self.fileobject(self, tarinfo)
01616 
01617         elif tarinfo.islnk() or tarinfo.issym():
01618             if isinstance(self.fileobj, _Stream):
01619                 # A small but ugly workaround for the case that someone tries
01620                 # to extract a (sym)link as a file-object from a non-seekable
01621                 # stream of tar blocks.
01622                 raise StreamError("cannot extract (sym)link as file object")
01623             else:
01624                 # A (sym)link's file object is its target's file object.
01625                 return self.extractfile(self._getmember(tarinfo.linkname,
01626                                                         tarinfo))
01627         else:
01628             # If there's no data associated with the member (directory, chrdev,
01629             # blkdev, etc.), return None instead of a file object.
01630             return None

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.getmember (   self,
  name 
)
Return a TarInfo object for member `name'. If `name' can not be
   found in the archive, KeyError is raised. If a member occurs more
   than once in the archive, its last occurence is assumed to be the
   most up-to-date version.

Definition at line 1289 of file tarfile.py.

01289 
01290     def getmember(self, name):
01291         """Return a TarInfo object for member `name'. If `name' can not be
01292            found in the archive, KeyError is raised. If a member occurs more
01293            than once in the archive, its last occurence is assumed to be the
01294            most up-to-date version.
01295         """
01296         tarinfo = self._getmember(name)
01297         if tarinfo is None:
01298             raise KeyError("filename %r not found" % name)
01299         return tarinfo

Here is the call graph for this function:

Here is the caller graph for this function:

Return the members of the archive as a list of TarInfo objects. The
   list has the same order as the members in the archive.

Definition at line 1300 of file tarfile.py.

01300 
01301     def getmembers(self):
01302         """Return the members of the archive as a list of TarInfo objects. The
01303            list has the same order as the members in the archive.
01304         """
01305         self._check()
01306         if not self._loaded:    # if we want to obtain a list of
01307             self._load()        # all members, we first have to
01308                                 # scan the whole archive.
01309         return self.members

Here is the call graph for this function:

Here is the caller graph for this function:

Return the members of the archive as a list of their names. It has
   the same order as the list returned by getmembers().

Definition at line 1310 of file tarfile.py.

01310 
01311     def getnames(self):
01312         """Return the members of the archive as a list of their names. It has
01313            the same order as the list returned by getmembers().
01314         """
01315         return [tarinfo.name for tarinfo in self.getmembers()]

Here is the call graph for this function:

def MoinMoin.support.tarfile.TarFile.gettarinfo (   self,
  name = None,
  arcname = None,
  fileobj = None 
)
Create a TarInfo object for either the file `name' or the file
   object `fileobj' (using os.fstat on its file descriptor). You can
   modify some of the TarInfo's attributes before you add it using
   addfile(). If given, `arcname' specifies an alternative name for the
   file in the archive.

Definition at line 1316 of file tarfile.py.

01316 
01317     def gettarinfo(self, name=None, arcname=None, fileobj=None):
01318         """Create a TarInfo object for either the file `name' or the file
01319            object `fileobj' (using os.fstat on its file descriptor). You can
01320            modify some of the TarInfo's attributes before you add it using
01321            addfile(). If given, `arcname' specifies an alternative name for the
01322            file in the archive.
01323         """
01324         self._check("aw")
01325 
01326         # When fileobj is given, replace name by
01327         # fileobj's real name.
01328         if fileobj is not None:
01329             name = fileobj.name
01330 
01331         # Building the name of the member in the archive.
01332         # Backward slashes are converted to forward slashes,
01333         # Absolute paths are turned to relative paths.
01334         if arcname is None:
01335             arcname = name
01336         arcname = normpath(arcname)
01337         drv, arcname = os.path.splitdrive(arcname)
01338         while arcname[0:1] == "/":
01339             arcname = arcname[1:]
01340 
01341         # Now, fill the TarInfo object with
01342         # information specific for the file.
01343         tarinfo = TarInfo()
01344 
01345         # Use os.stat or os.lstat, depending on platform
01346         # and if symlinks shall be resolved.
01347         if fileobj is None:
01348             if hasattr(os, "lstat") and not self.dereference:
01349                 statres = os.lstat(name)
01350             else:
01351                 statres = os.stat(name)
01352         else:
01353             statres = os.fstat(fileobj.fileno())
01354         linkname = ""
01355 
01356         stmd = statres.st_mode
01357         if stat.S_ISREG(stmd):
01358             inode = (statres.st_ino, statres.st_dev)
01359             if not self.dereference and \
01360                     statres.st_nlink > 1 and inode in self.inodes:
01361                 # Is it a hardlink to an already
01362                 # archived file?
01363                 type = LNKTYPE
01364                 linkname = self.inodes[inode]
01365             else:
01366                 # The inode is added only if its valid.
01367                 # For win32 it is always 0.
01368                 type = REGTYPE
01369                 if inode[0]:
01370                     self.inodes[inode] = arcname
01371         elif stat.S_ISDIR(stmd):
01372             type = DIRTYPE
01373             if arcname[-1:] != "/":
01374                 arcname += "/"
01375         elif stat.S_ISFIFO(stmd):
01376             type = FIFOTYPE
01377         elif stat.S_ISLNK(stmd):
01378             type = SYMTYPE
01379             linkname = os.readlink(name)
01380         elif stat.S_ISCHR(stmd):
01381             type = CHRTYPE
01382         elif stat.S_ISBLK(stmd):
01383             type = BLKTYPE
01384         else:
01385             return None
01386 
01387         # Fill the TarInfo object with all
01388         # information we can get.
01389         tarinfo.name = arcname
01390         tarinfo.mode = stmd
01391         tarinfo.uid = statres.st_uid
01392         tarinfo.gid = statres.st_gid
01393         if stat.S_ISREG(stmd):
01394             tarinfo.size = statres.st_size
01395         else:
01396             tarinfo.size = 0L
01397         tarinfo.mtime = statres.st_mtime
01398         tarinfo.type = type
01399         tarinfo.linkname = linkname
01400         if pwd:
01401             try:
01402                 tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
01403             except KeyError:
01404                 pass
01405         if grp:
01406             try:
01407                 tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
01408             except KeyError:
01409                 pass
01410 
01411         if type in (CHRTYPE, BLKTYPE):
01412             if hasattr(os, "major") and hasattr(os, "minor"):
01413                 tarinfo.devmajor = os.major(statres.st_rdev)
01414                 tarinfo.devminor = os.minor(statres.st_rdev)
01415         return tarinfo

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.gzopen (   cls,
  name,
  mode = "r",
  fileobj = None,
  compresslevel = 9 
)
Open gzip compressed tar archive name for reading or writing.
   Appending is not allowed.

Definition at line 1209 of file tarfile.py.

01209 
01210     def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9):
01211         """Open gzip compressed tar archive name for reading or writing.
01212            Appending is not allowed.
01213         """
01214         if len(mode) > 1 or mode not in "rw":
01215             raise ValueError("mode must be 'r' or 'w'")
01216 
01217         try:
01218             import gzip
01219             gzip.GzipFile
01220         except (ImportError, AttributeError):
01221             raise CompressionError("gzip module is not available")
01222 
01223         if fileobj is None:
01224             fileobj = file(name, mode + "b")
01225 
01226         try:
01227             t = cls.taropen(name, mode,
01228                 gzip.GzipFile(name, mode, compresslevel, fileobj))
01229         except IOError:
01230             raise ReadError("not a gzip file")
01231         t._extfileobj = False
        return t
def MoinMoin.support.tarfile.TarFile.list (   self,
  verbose = True 
)
Print a table of contents to sys.stdout. If `verbose' is False, only
   the names of the members are printed. If it is True, an `ls -l'-like
   output is produced.

Definition at line 1416 of file tarfile.py.

01416 
01417     def list(self, verbose=True):
01418         """Print a table of contents to sys.stdout. If `verbose' is False, only
01419            the names of the members are printed. If it is True, an `ls -l'-like
01420            output is produced.
01421         """
01422         self._check()
01423 
01424         for tarinfo in self:
01425             if verbose:
01426                 print filemode(tarinfo.mode),
01427                 print "%s/%s" % (tarinfo.uname or tarinfo.uid,
01428                                  tarinfo.gname or tarinfo.gid),
01429                 if tarinfo.ischr() or tarinfo.isblk():
01430                     print "%10s" % ("%d,%d" \
01431                                     % (tarinfo.devmajor, tarinfo.devminor)),
01432                 else:
01433                     print "%10d" % tarinfo.size,
01434                 print "%d-%02d-%02d %02d:%02d:%02d" \
01435                       % time.localtime(tarinfo.mtime)[:6],
01436 
01437             print tarinfo.name,
01438 
01439             if verbose:
01440                 if tarinfo.issym():
01441                     print "->", tarinfo.linkname,
01442                 if tarinfo.islnk():
01443                     print "link to", tarinfo.linkname,
01444             print

Here is the call graph for this function:

def MoinMoin.support.tarfile.TarFile.makedev (   self,
  tarinfo,
  targetpath 
)
Make a character or block device called targetpath.

Definition at line 1715 of file tarfile.py.

01715 
01716     def makedev(self, tarinfo, targetpath):
01717         """Make a character or block device called targetpath.
01718         """
01719         if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
01720             raise ExtractError("special devices not supported by system")
01721 
01722         mode = tarinfo.mode
01723         if tarinfo.isblk():
01724             mode |= stat.S_IFBLK
01725         else:
01726             mode |= stat.S_IFCHR
01727 
01728         os.mknod(targetpath, mode,
01729                  os.makedev(tarinfo.devmajor, tarinfo.devminor))

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.makedir (   self,
  tarinfo,
  targetpath 
)
Make a directory called targetpath.

Definition at line 1679 of file tarfile.py.

01679 
01680     def makedir(self, tarinfo, targetpath):
01681         """Make a directory called targetpath.
01682         """
01683         try:
01684             # Use a safe mode for the directory, the real mode is set
01685             # later in _extract_member().
01686             os.mkdir(targetpath, 0700)
01687         except EnvironmentError, e:
01688             if e.errno != errno.EEXIST:
01689                 raise

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.makefifo (   self,
  tarinfo,
  targetpath 
)
Make a fifo called targetpath.

Definition at line 1707 of file tarfile.py.

01707 
01708     def makefifo(self, tarinfo, targetpath):
01709         """Make a fifo called targetpath.
01710         """
01711         if hasattr(os, "mkfifo"):
01712             os.mkfifo(targetpath)
01713         else:
01714             raise ExtractError("fifo not supported by system")

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.makefile (   self,
  tarinfo,
  targetpath 
)
Make a file called targetpath.

Definition at line 1690 of file tarfile.py.

01690 
01691     def makefile(self, tarinfo, targetpath):
01692         """Make a file called targetpath.
01693         """
01694         source = self.extractfile(tarinfo)
01695         target = file(targetpath, "wb")
01696         copyfileobj(source, target)
01697         source.close()
01698         target.close()

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.makelink (   self,
  tarinfo,
  targetpath 
)
Make a (symbolic) link called targetpath. If it cannot be created
  (platform limitation), we try to make a copy of the referenced file
  instead of a link.

Definition at line 1730 of file tarfile.py.

01730 
01731     def makelink(self, tarinfo, targetpath):
01732         """Make a (symbolic) link called targetpath. If it cannot be created
01733           (platform limitation), we try to make a copy of the referenced file
01734           instead of a link.
01735         """
01736         linkpath = tarinfo.linkname
01737         try:
01738             if tarinfo.issym():
01739                 os.symlink(linkpath, targetpath)
01740             else:
01741                 # See extract().
01742                 os.link(tarinfo._link_target, targetpath)
01743         except AttributeError:
01744             if tarinfo.issym():
01745                 linkpath = os.path.join(os.path.dirname(tarinfo.name),
01746                                         linkpath)
01747                 linkpath = normpath(linkpath)
01748 
01749             try:
01750                 self._extract_member(self.getmember(linkpath), targetpath)
01751             except (EnvironmentError, KeyError), e:
01752                 linkpath = os.path.normpath(linkpath)
01753                 try:
01754                     shutil.copy2(linkpath, targetpath)
01755                 except EnvironmentError, e:
01756                     raise IOError("link could not be created")

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.makeunknown (   self,
  tarinfo,
  targetpath 
)
Make a file from a TarInfo object with an unknown type
   at targetpath.

Definition at line 1699 of file tarfile.py.

01699 
01700     def makeunknown(self, tarinfo, targetpath):
01701         """Make a file from a TarInfo object with an unknown type
01702            at targetpath.
01703         """
01704         self.makefile(tarinfo, targetpath)
01705         self._dbg(1, "tarfile: Unknown file type %r, " \
01706                      "extracted as regular file." % tarinfo.type)

Here is the call graph for this function:

Here is the caller graph for this function:

Return the next member of the archive as a TarInfo object, when
   TarFile is opened for reading. Return None if there is no more
   available.

Definition at line 1809 of file tarfile.py.

01809 
01810     def next(self):
01811         """Return the next member of the archive as a TarInfo object, when
01812            TarFile is opened for reading. Return None if there is no more
01813            available.
01814         """
01815         self._check("ra")
01816         if self.firstmember is not None:
01817             m = self.firstmember
01818             self.firstmember = None
01819             return m
01820 
01821         # Read the next block.
01822         self.fileobj.seek(self.offset)
01823         while True:
01824             buf = self.fileobj.read(BLOCKSIZE)
01825             if not buf:
01826                 return None
01827 
01828             try:
01829                 tarinfo = TarInfo.frombuf(buf)
01830 
01831                 # Set the TarInfo object's offset to the current position of the
01832                 # TarFile and set self.offset to the position where the data blocks
01833                 # should begin.
01834                 tarinfo.offset = self.offset
01835                 self.offset += BLOCKSIZE
01836 
01837                 tarinfo = self.proc_member(tarinfo)
01838 
01839             except ValueError, e:
01840                 if self.ignore_zeros:
01841                     self._dbg(2, "0x%X: empty or invalid block: %s" %
01842                               (self.offset, e))
01843                     self.offset += BLOCKSIZE
01844                     continue
01845                 else:
01846                     if self.offset == 0:
01847                         raise ReadError("empty, unreadable or compressed "
01848                                         "file: %s" % e)
01849                     return None
01850             break
01851 
01852         # Some old tar programs represent a directory as a regular
01853         # file with a trailing slash.
01854         if tarinfo.isreg() and tarinfo.name.endswith("/"):
01855             tarinfo.type = DIRTYPE
01856 
01857         # Directory names should have a '/' at the end.
01858         if tarinfo.isdir() and not tarinfo.name.endswith("/"):
01859             tarinfo.name += "/"
01860 
01861         self.members.append(tarinfo)
01862         return tarinfo

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.open (   cls,
  name = None,
  mode = "r",
  fileobj = None,
  bufsize = 20*512 
)
Open a tar archive for reading, writing or appending. Return
   an appropriate TarFile class.

   mode:
   'r' or 'r:*' open for reading with transparent compression
   'r:'         open for reading exclusively uncompressed
   'r:gz'       open for reading with gzip compression
   'r:bz2'      open for reading with bzip2 compression
   'a' or 'a:'  open for appending, creating the file if necessary
   'w' or 'w:'  open for writing without compression
   'w:gz'       open for writing with gzip compression
   'w:bz2'      open for writing with bzip2 compression

   'r|*'        open a stream of tar blocks with transparent compression
   'r|'         open an uncompressed stream of tar blocks for reading
   'r|gz'       open a gzip compressed stream of tar blocks
   'r|bz2'      open a bzip2 compressed stream of tar blocks
   'w|'         open an uncompressed stream for writing
   'w|gz'       open a gzip compressed stream for writing
   'w|bz2'      open a bzip2 compressed stream for writing

Definition at line 1129 of file tarfile.py.

01129 
01130     def open(cls, name=None, mode="r", fileobj=None, bufsize=20*512):
01131         """Open a tar archive for reading, writing or appending. Return
01132            an appropriate TarFile class.
01133 
01134            mode:
01135            'r' or 'r:*' open for reading with transparent compression
01136            'r:'         open for reading exclusively uncompressed
01137            'r:gz'       open for reading with gzip compression
01138            'r:bz2'      open for reading with bzip2 compression
01139            'a' or 'a:'  open for appending, creating the file if necessary
01140            'w' or 'w:'  open for writing without compression
01141            'w:gz'       open for writing with gzip compression
01142            'w:bz2'      open for writing with bzip2 compression
01143 
01144            'r|*'        open a stream of tar blocks with transparent compression
01145            'r|'         open an uncompressed stream of tar blocks for reading
01146            'r|gz'       open a gzip compressed stream of tar blocks
01147            'r|bz2'      open a bzip2 compressed stream of tar blocks
01148            'w|'         open an uncompressed stream for writing
01149            'w|gz'       open a gzip compressed stream for writing
01150            'w|bz2'      open a bzip2 compressed stream for writing
01151         """
01152 
01153         if not name and not fileobj:
01154             raise ValueError("nothing to open")
01155 
01156         if mode in ("r", "r:*"):
01157             # Find out which *open() is appropriate for opening the file.
01158             for comptype in cls.OPEN_METH:
01159                 func = getattr(cls, cls.OPEN_METH[comptype])
01160                 if fileobj is not None:
01161                     saved_pos = fileobj.tell()
01162                 try:
01163                     return func(name, "r", fileobj)
01164                 except (ReadError, CompressionError):
01165                     if fileobj is not None:
01166                         fileobj.seek(saved_pos)
01167                     continue
01168             raise ReadError("file could not be opened successfully")
01169 
01170         elif ":" in mode:
01171             filemode, comptype = mode.split(":", 1)
01172             filemode = filemode or "r"
01173             comptype = comptype or "tar"
01174 
01175             # Select the *open() function according to
01176             # given compression.
01177             if comptype in cls.OPEN_METH:
01178                 func = getattr(cls, cls.OPEN_METH[comptype])
01179             else:
01180                 raise CompressionError("unknown compression type %r" % comptype)
01181             return func(name, filemode, fileobj)
01182 
01183         elif "|" in mode:
01184             filemode, comptype = mode.split("|", 1)
01185             filemode = filemode or "r"
01186             comptype = comptype or "tar"
01187 
01188             if filemode not in "rw":
01189                 raise ValueError("mode must be 'r' or 'w'")
01190 
01191             t = cls(name, filemode,
01192                     _Stream(name, filemode, comptype, fileobj, bufsize))
01193             t._extfileobj = False
01194             return t
01195 
01196         elif mode in "aw":
01197             return cls.taropen(name, mode, fileobj)
01198 
        raise ValueError("undiscernible mode")

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.proc_builtin (   self,
  tarinfo 
)
Process a builtin type member or an unknown member
   which will be treated as a regular file.

Definition at line 1886 of file tarfile.py.

01886 
01887     def proc_builtin(self, tarinfo):
01888         """Process a builtin type member or an unknown member
01889            which will be treated as a regular file.
01890         """
01891         tarinfo.offset_data = self.offset
01892         if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
01893             # Skip the following data blocks.
01894             self.offset += self._block(tarinfo.size)
01895         return tarinfo

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.proc_gnulong (   self,
  tarinfo 
)
Process the blocks that hold a GNU longname
   or longlink member.

Definition at line 1896 of file tarfile.py.

01896 
01897     def proc_gnulong(self, tarinfo):
01898         """Process the blocks that hold a GNU longname
01899            or longlink member.
01900         """
01901         buf = ""
01902         count = tarinfo.size
01903         while count > 0:
01904             block = self.fileobj.read(BLOCKSIZE)
01905             buf += block
01906             self.offset += BLOCKSIZE
01907             count -= BLOCKSIZE
01908 
01909         # Fetch the next header and process it.
01910         b = self.fileobj.read(BLOCKSIZE)
01911         t = TarInfo.frombuf(b)
01912         t.offset = self.offset
01913         self.offset += BLOCKSIZE
01914         next = self.proc_member(t)
01915 
01916         # Patch the TarInfo object from the next header with
01917         # the longname information.
01918         next.offset = tarinfo.offset
01919         if tarinfo.type == GNUTYPE_LONGNAME:
01920             next.name = nts(buf)
01921         elif tarinfo.type == GNUTYPE_LONGLINK:
01922             next.linkname = nts(buf)
01923 
01924         return next

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.proc_member (   self,
  tarinfo 
)
Choose the right processing method for tarinfo depending
   on its type and call it.

Definition at line 1875 of file tarfile.py.

01875 
01876     def proc_member(self, tarinfo):
01877         """Choose the right processing method for tarinfo depending
01878            on its type and call it.
01879         """
01880         if tarinfo.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
01881             return self.proc_gnulong(tarinfo)
01882         elif tarinfo.type == GNUTYPE_SPARSE:
01883             return self.proc_sparse(tarinfo)
01884         else:
01885             return self.proc_builtin(tarinfo)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.proc_sparse (   self,
  tarinfo 
)
Process a GNU sparse header plus extra headers.

Definition at line 1925 of file tarfile.py.

01925 
01926     def proc_sparse(self, tarinfo):
01927         """Process a GNU sparse header plus extra headers.
01928         """
01929         buf = tarinfo.buf
01930         sp = _ringbuffer()
01931         pos = 386
01932         lastpos = 0L
01933         realpos = 0L
01934         # There are 4 possible sparse structs in the
01935         # first header.
01936         for i in xrange(4):
01937             try:
01938                 offset = nti(buf[pos:pos + 12])
01939                 numbytes = nti(buf[pos + 12:pos + 24])
01940             except ValueError:
01941                 break
01942             if offset > lastpos:
01943                 sp.append(_hole(lastpos, offset - lastpos))
01944             sp.append(_data(offset, numbytes, realpos))
01945             realpos += numbytes
01946             lastpos = offset + numbytes
01947             pos += 24
01948 
01949         isextended = ord(buf[482])
01950         origsize = nti(buf[483:495])
01951 
01952         # If the isextended flag is given,
01953         # there are extra headers to process.
01954         while isextended == 1:
01955             buf = self.fileobj.read(BLOCKSIZE)
01956             self.offset += BLOCKSIZE
01957             pos = 0
01958             for i in xrange(21):
01959                 try:
01960                     offset = nti(buf[pos:pos + 12])
01961                     numbytes = nti(buf[pos + 12:pos + 24])
01962                 except ValueError:
01963                     break
01964                 if offset > lastpos:
01965                     sp.append(_hole(lastpos, offset - lastpos))
01966                 sp.append(_data(offset, numbytes, realpos))
01967                 realpos += numbytes
01968                 lastpos = offset + numbytes
01969                 pos += 24
01970             isextended = ord(buf[504])
01971 
01972         if lastpos < origsize:
01973             sp.append(_hole(lastpos, origsize - lastpos))
01974 
01975         tarinfo.sparse = sp
01976 
01977         tarinfo.offset_data = self.offset
01978         self.offset += self._block(tarinfo.size)
01979         tarinfo.size = origsize
01980 
01981         return tarinfo

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.tarfile.TarFile.taropen (   cls,
  name,
  mode = "r",
  fileobj = None 
)
Open uncompressed tar archive name for reading or writing.

Definition at line 1201 of file tarfile.py.

01201 
01202     def taropen(cls, name, mode="r", fileobj=None):
01203         """Open uncompressed tar archive name for reading or writing.
01204         """
01205         if len(mode) > 1 or mode not in "raw":
01206             raise ValueError("mode must be 'r', 'a' or 'w'")
        return cls(name, mode, fileobj)
def MoinMoin.support.tarfile.TarFile.utime (   self,
  tarinfo,
  targetpath 
)
Set modification time of targetpath according to tarinfo.

Definition at line 1794 of file tarfile.py.

01794 
01795     def utime(self, tarinfo, targetpath):
01796         """Set modification time of targetpath according to tarinfo.
01797         """
01798         if not hasattr(os, 'utime'):
01799             return
01800         if sys.platform == "win32" and tarinfo.isdir():
01801             # According to msdn.microsoft.com, it is an error (EACCES)
01802             # to use utime() on directories.
01803             return
01804         try:
01805             os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
01806         except EnvironmentError, e:
01807             raise ExtractError("could not change modification time")

Here is the caller graph for this function:


Member Data Documentation

Definition at line 1077 of file tarfile.py.

Definition at line 1090 of file tarfile.py.

Definition at line 1068 of file tarfile.py.

tuple MoinMoin.support.tarfile.TarFile.bz2open = classmethod(bz2open) [static]

Definition at line 1257 of file tarfile.py.

Definition at line 1088 of file tarfile.py.

Definition at line 1040 of file tarfile.py.

Definition at line 1042 of file tarfile.py.

Definition at line 1048 of file tarfile.py.

Definition at line 1085 of file tarfile.py.

Definition at line 1055 of file tarfile.py.

Definition at line 1097 of file tarfile.py.

tuple MoinMoin.support.tarfile.TarFile.gzopen = classmethod(gzopen) [static]

Definition at line 1232 of file tarfile.py.

Definition at line 1045 of file tarfile.py.

Definition at line 1093 of file tarfile.py.

Definition at line 1089 of file tarfile.py.

Definition at line 1069 of file tarfile.py.

Definition at line 1084 of file tarfile.py.

Definition at line 1091 of file tarfile.py.

tuple MoinMoin.support.tarfile.TarFile.open = classmethod(open) [static]

Definition at line 1199 of file tarfile.py.

Initial value:
{
        "tar": "taropen",   # uncompressed tar
        "gz":  "gzopen",    # gzip compressed tar
        "bz2": "bz2open"    # bzip2 compressed tar
    }

Definition at line 1260 of file tarfile.py.

Definition at line 1052 of file tarfile.py.

tuple MoinMoin.support.tarfile.TarFile.taropen = classmethod(taropen) [static]

Definition at line 1207 of file tarfile.py.


The documentation for this class was generated from the following file: