#
# Gordon McMillan (as inspired and influenced by Greg Stein)
#

# subclasses may not need marshal or struct, but since they're
# builtin, importing is safe.
#
# While an Archive is really an abstraction for any "filesystem
# within a file", it is tuned for use with imputil.FuncImporter.
# This assumes it contains python code objects, indexed by the
# the internal name (ie, no '.py').
# See carchive.py for a more general archive (contains anything)
# that can be understood by a C program.
import marshal, struct, imp, sys
_listdir = None
#_verbose = None
#_log=sys.stderr

_c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes())

for nm in ('nt', 'posix', 'dos', 'os2', 'mac'):
    if nm in sys.builtin_module_names:
        mod = __import__(nm)
        _listdir = mod.listdir

if hasattr(sys, 'version_info'):
    versuffix = '%d%d'%(sys.version_info[0],sys.version_info[1])
else:
    vers = sys.version
    dot1 = dot2 = 0
    for i in range(len(vers)):
        if vers[i] == '.':
            if dot1:
                dot2 = i
                break
            else:
                dot1 = i
    else:
        dot2 = len(vers)
    versuffix = '%s%s' % (vers[:dot1], vers[dot1+1:dot2])

class Archive:
    """ A base class for a repository of python code objects.
        The extract method is used by imputil.ArchiveImporter
        to get code objects by name (fully qualified name), so
        an enduser "import a.b" would become
          extract('a.__init__')
          extract('a.b')
    """
    MAGIC = 'PYL\0'
    HDRLEN = 12        # default is MAGIC followed by python's magic, int pos of toc
    TOCPOS = 8
    TRLLEN = 0        # default - no trailer
    TOCTMPLT = {}     #
    os = None
    _bincache = None
    def __init__(self, path=None, start=0):
        "Initialize an Archive. If path is omitted, it will be an empty Archive."
        self.toc = None
        self.path = path
        self.start = start
        import imp
        self.pymagic = imp.get_magic()
        if path is not None:
            self.lib = open(self.path, 'rb')
            self.checkmagic()
            self.loadtoc()

            ####### Sub-methods of __init__ - override as needed #############
    def checkmagic(self):
        """ Overridable.
            Check to see if the file object self.lib actually has a file
            we understand.
        """
        self.lib.seek(self.start)   #default - magic is at start of file
        if self.lib.read(len(self.MAGIC)) != self.MAGIC:
            raise RuntimeError, "%s is not a valid %s archive file" \
              % (self.path, self.__class__.__name__)
        if self.lib.read(len(self.pymagic)) != self.pymagic:
            raise RuntimeError, "%s has version mismatch to dll" % (self.path)
        self.lib.read(4)

    def loadtoc(self):
        """ Overridable.
            Default: After magic comes an int (4 byte native) giving the
            position of the TOC within self.lib.
            Default: The TOC is a marshal-able string.
        """
        self.lib.seek(self.start + self.TOCPOS)
        (offset,) = struct.unpack('<i', self.lib.read(4))
        self.lib.seek(self.start + offset)
        self.toc = marshal.load(self.lib)

    ####### Core method - Override as needed  #########
    def extract(self, name):
        """ Get the object corresponding to name, or None.
            For use with imputil ArchiveImporter, object is a python code object.
            'name' is the name as specified in an 'import name'.
            'import a.b' will become:
            extract('a') (return None because 'a' is not a code object)
            extract('a.__init__') (return a code object)
            extract('a.b') (return a code object)
            Default implementation:
              self.toc is a dict
              self.toc[name] is pos
              self.lib has the code object marshal-ed at pos
        """
        ispkg, pos = self.toc.get(name, (0,None))
        if pos is None:
            return None
        self.lib.seek(self.start + pos)
        return ispkg, marshal.load(self.lib)

        ########################################################################
        # Informational methods

    def contents(self):
        """Return a list of the contents
           Default implementation assumes self.toc is a dict like object.
           Not required by ArchiveImporter.
        """
        return self.toc.keys()

        ########################################################################
        # Building

        ####### Top level method - shouldn't need overriding #######
    def build(self, path, lTOC):
        """Create an archive file of name 'path'.
           lTOC is a 'logical TOC' - a list of (name, path, ...)
           where name is the internal name, eg 'a'
           and path is a file to get the object from, eg './a.pyc'.
        """
        self.path = path
        self.lib = open(path, 'wb')
        #reserve space for the header
        if self.HDRLEN:
            self.lib.write('\0'*self.HDRLEN)

            #create an empty toc

        if type(self.TOCTMPLT) == type({}):
            self.toc = {}
        else:       # assume callable
            self.toc = self.TOCTMPLT()

        for tocentry in lTOC:
            self.add(tocentry)   # the guts of the archive

        tocpos = self.lib.tell()
        self.save_toc(tocpos)
        if self.TRLLEN:
            self.save_trailer(tocpos)
        if self.HDRLEN:
            self.update_headers(tocpos)
        self.lib.close()

    def _get_os(self):
        if self.os is None:
            import os
            self.os = os
        return self.os 

        ####### manages keeping the internal TOC and the guts in sync #######
    def add(self, entry):
        """Override this to influence the mechanics of the Archive.
           Assumes entry is a seq beginning with (nm, pth, ...) where
           nm is the key by which we'll be asked for the object.
           pth is the name of where we find the object. Overrides of
           get_obj_from can make use of further elements in entry.
        """
        nm = entry[0]
        pth = entry[1]
        os = self._get_os()
        pynm, ext = os.path.splitext(os.path.basename(pth))
        ispkg = pynm == '__init__'
        assert ext in ('.pyc', '.pyo')
        self.toc[nm] = (ispkg, self.lib.tell())
        f = open(entry[1], 'rb')
        f.seek(8)   #skip magic and timestamp
        self.lib.write(f.read())

    def save_toc(self, tocpos):
        """Default - toc is a dict
           Gets marshaled to self.lib
        """
        marshal.dump(self.toc, self.lib)

    def save_trailer(self, tocpos):
        """Default - not used"""
        pass

    def update_headers(self, tocpos):
        """Default - MAGIC + Python's magic + tocpos"""
        self.lib.seek(self.start)
        self.lib.write(self.MAGIC)
        self.lib.write(self.pymagic)
        self.lib.write(struct.pack('<i', tocpos))

class DummyZlib:
    def decompress(self, data):
        return data
    def compress(self, data, lvl):
        return data

from _rl_iu import Owner, _os_path_dirname, _os_path_join, PathImportDirector, DirOwner, _os_getcwd, _os_sep
##############################################################
#
# ZlibArchive - an archive with compressed entries
#
class ZlibArchive(Archive):
    MAGIC = 'PYZ\0'
    TOCPOS = 8
    HDRLEN = 16
    TRLLEN = 0
    TOCTMPLT = {}
    LEVEL = 9

    def __init__(self, path=None, offset=None, level=9):
        if path is None:
            offset = 0
        elif offset is None:
            for i in range(len(path)-1, -1, -1):
                if path[i] == '?':
                    offset = int(path[i+1:])
                    path = path[:i]
                    break
            else:
                offset = 0
        self.LEVEL = level
        Archive.__init__(self, path, offset)
        # dynamic import so not imported if not needed
        global zlib
        if self.LEVEL:
            try:
                import zlib
            except ImportError:
                zlib = DummyZlib()
        else:
            zlib = DummyZlib()


    def extract(self, name):
        (ispkg, pos, lngth) = self.toc.get(name, (0, None, 0))
        if pos is None:
            return None
        self.lib.seek(self.start + pos)
        try:
            co = marshal.loads(zlib.decompress(self.lib.read(lngth)))
        except EOFError:
            raise ImportError, "PYZ entry '%s' failed to unmarshal" % name
        return ispkg, co

    def add(self, entry):
        os = self._get_os()
        nm = entry[0]
        pth = entry[1]
        base, ext = os.path.splitext(os.path.basename(pth))
        ispkg = base == '__init__'
        try:
            f = open(pth, 'rb')
            f.seek(8)   #skip magic and timestamp
            bytecode = f.read()
            marshal.loads(bytecode).co_filename # to make sure it's valid
            obj = zlib.compress(bytecode, self.LEVEL)
        except (IOError, ValueError, EOFError, AttributeError), e:
            #print >>_log, e, "in loading '%s' (%s) - recompiling" % (nm, pth)
            try:
                co = compile(open(pth[:-1], 'r').read()+'\n', pth, 'exec')
            except SyntaxError, e:
                #print >>_log, "Syntax error in", pth[:-1]
                #print >>_log, e.args
                raise
            obj = zlib.compress(marshal.dumps(co), self.LEVEL)
        self.toc[nm] = (ispkg, self.lib.tell(), len(obj))
        self.lib.write(obj)
    def update_headers(self, tocpos):
        """add level"""
        Archive.update_headers(self, tocpos)
        self.lib.write(struct.pack('<i', self.LEVEL))
    def checkmagic(self):
        Archive.checkmagic(self)
        self.LEVEL = struct.unpack('<i', self.lib.read(4))[0]

class PYZOwner(Owner):
    def __init__(self, path, depth=1, overlay=1):
        '''
        create a ZArchive importer
        path    where the ZArchive is
        depth   how deep the archive is wrt the assumed path.
        overlay how we deal with FS 0 means no overlaying
                + means try FS before PYZ, - means after.
        '''
        self.pyz = ZlibArchive(path)
        self.fs_depth = max(0,depth)
        self.fs_overlay = overlay
        Owner.__init__(self, path)

    def _exp_fs_pfx(self,name):
        if name[:3]=='_p:':
            _p = self.pyz.path
            if _p:
                _p = _os_path_dirname(_p)
                for x in xrange(self.fs_depth):
                    _p = _os_path_dirname(_p)
                if not _p: _p = _os_getcwd()
            else:
                _p = sys.exec_prefix
            return _os_path_join(_p,name[3:])
        _fs_pfx = getattr(self,'_fs_pfx',None)
        if _fs_pfx is None:
            try:
                r = self.pyz.extract(nm)
                exec r[1].__co__ in locals()
                self._fs_pfx = _fs_pfx
            except:
                r = None
            if not r:
                self._fs_pfx = {}
                return name
        if sys.platform=='win32':
            r = name.find(':')
            if r>=0:
                pfx = _fs_pfx.get(name[:r-1],None)
                if pfx: name = pfx+_os_sep+name[r:]
        return name

    def getmod(self, nm, newmod=imp.new_module):
        #if _verbose: print >>_log,"PYZOwner.getmod %s" % nm
        rslt = self.pyz.extract(nm)
        if rslt is None:
            return None
        ispkg, co = rslt
        mod = newmod(nm)
        try:
            mod.__file__ = self._exp_fs_pfx(co.co_filename.replace('\\',_os_sep))
        except AttributeError:
            raise ImportError, "PYZ entry '%s' (%s) is not a valid code object" % (nm, repr(co))
        if ispkg:
            overlay, path = self.fs_overlay, self.path
            lpath = _os_path_dirname(path)
            dname = _os_path_dirname(mod.__file__)
            if overlay>0:
                P = [lpath,path]
            elif overlay<0:
                P = [path,lpath]
            else:
                P = [path]
            if dname not in P: P += [dname]
            mod.__path__ = P
            #if _verbose: print >>_log,"PYZOwner setting %s's __path__: %s" % (nm, P)
            pfx = '.'.join(nm.split('.')[self.fs_depth:])
            pkgI = pfx and ExtInPkgImporter(lpath, pfx,allowPkg=0) or DirOwner(lpath,allowPkg=0)
            mod.__importsub__ = PathImportDirector(P, {path:PkgInPYZImporter(nm,self),lpath:pkgI},
                                        [DirOwner]).getmod
        mod.__co__ = co
        return mod

class PkgInPYZImporter:
    def __init__(self, name, owner):
        self.name = name
        self.owner = owner
    def getmod(self, nm):
        nnm = self.name+'.'+nm
        #if _verbose: print >>_log,"PkgInPYZImporter.getmod %s -> %s" % (nm, nnm)
        return self.owner.getmod(nnm)
class ExtInPkgImporter(DirOwner):
    def __init__(self, path, prefix,allowPkg=0):
        DirOwner.__init__(self, path,allowPkg=allowPkg)
        self.prefix = prefix
    def getmod(self, nm):
        prefix = self.prefix
        pnm = prefix+'.'+nm
        #if _verbose: print >>_log,"ExtInPYZImporter.getmod %s -> %s" % (nm, pnm)
        return DirOwner.getmod(self, pnm)
