"""quixote.imphooks

Import hooks; when installed, these hooks allow importing .ptl files
as if they were Python modules.
"""

__revision__ = "$Id: imphooks.py,v 1.6 2000/05/31 22:13:40 akuchlin Exp $"


import imp, ihooks, new
import cgi, urllib

import template

# Constant used to signal a PTL file
PTL_FILE = 128

class PTLHooks (ihooks.Hooks):

    def get_suffixes (self):
        # Return the list of supported file suffixes, adding .ptl
        L = imp.get_suffixes()
        return L + [('.ptl', 'r', PTL_FILE)]

class PTLLoader (ihooks.ModuleLoader):
    
    def load_module (self, name, stuff):
        file, filename, info = stuff
        (suff, mode, type) = info

        # If it's a PTL file, load it specially.
        if type == PTL_FILE:
            input = file.read()
            template_list = template.compile_template( input )
            new_mod = new.module(name)
            new_mod.__file__ = filename
            new_mod.__name__ = name

            # Add an empty __exports__ attribute to the module object;
            # we'll have to fill it in with the names of the templates
            # in the .file source file.
            new_mod.__exports__ = []

            # Set up initial contents of the module
            new_mod.html_quote = cgi.escape
            new_mod.url_quote = urllib.quote

            if (len(template_list) == 1 and
                (t.name is None or t.signature is None) ):
                raise ImportError, ('Attempting to import PTL file ' +
                                    repr(filename) +
                                    ' without template directive' )
            
            for t in template_list:
                setattr(new_mod, t.name, t)
                t.set_file(filename)
                text = t.output_code()
                exec text in new_mod.__dict__
                new_mod.__exports__.append( t.name )

            return new_mod

        else:
            # Otherwise, use the default handler for loading
            return ihooks.ModuleLoader.load_module( self, name, stuff)

def install ():
    hooks = PTLHooks()
    loader = PTLLoader( hooks )
    ihooks.install( ihooks.ModuleImporter(loader) )

if __name__ == '__main__':
    import foo
    print repr(foo.f1(1,2,3))
