Source

JSBrowser.html / build.py

Full commit
#!/usr/bin/env python

import sys
import os

from lxml import etree, html

from jsmin import jsmin


parser = etree.HTMLParser()

methods = {
          "minified": jsmin,
          "plain": lambda input: input,
}



def main():

    try:
        (_,
         method_type,
         input_filename,
         output_filename) = sys.argv
    except ValueError:
        sys.stderr.write("Usage: %s <minified/plain> <input.html> <output.html>\n" 
                         % os.path.basename(__file__))
        return 1


    try:
        method = methods[method_type]
    except KeyError:
        sys.stderr.write("Bad method type " + method_type + "\n")
        return 1


    f = open(input_filename)
    tree = etree.parse(f, parser)
    for script in tree.xpath("/html/head/script[@type='text/javascript']"):
        src_filename = script.get("src") 
        print "loading", src_filename
        src = open(src_filename, "r")
        script.text = "\n/* From %s */\n\n" % src_filename 
        script.text += unicode(method(src.read()))
        src.close()
        
        del script.attrib['src']
        
    f.close()
    
    print
    print "writing output file", output_filename
    out = open(output_filename, "w")
    out.write(html.tostring(tree, 
                            pretty_print=(True if method_type == "plain" 
                                               else False), 
                            encoding=unicode))
    out.close()

    return 0
    

if __name__ == "__main__":
    sys.exit(main())