Skip to main content

Python script to compile JavaScript code using the Closure compiler web service.

#!/usr/bin/env python

from __future__ import print_function

try:
    # python 3
    import http.client as httplib
except ImportError:
    # python 2
    import httplib

import errno
import os.path
import sys
import urllib


#
# API Docs: https://developers.google.com/closure/compiler/
# Web-based: http://closure-compiler.appspot.com/
#

PROG_NAME = None


def usage():
    print('')
    print('Compiles JavaScript using the Closure Compiler Service API.')
    print('')
    print('Usage:')
    print('')
    print('   %s <code,file,url>' % PROG_NAME)
    print('')


def compile_code(js_code):
    params = urllib.urlencode((
        ('js_code', js_code),
        ('compilation_level', 'SIMPLE_OPTIMIZATIONS'),
        ('output_format', 'text'),
        ('output_info', 'compiled_code'),
    ))
    headers = {'Content-type': 'application/x-www-form-urlencoded'}
    conn = httplib.HTTPSConnection('closure-compiler.appspot.com')
    conn.request('POST', '/compile', params, headers)
    response = conn.getresponse()
    response_data = response.read()
    conn.close()
    return response_data


def compile_url(js_url):
    params = urllib.urlencode([
        ('code_url', js_url),
        ('compilation_level', 'SIMPLE_OPTIMIZATIONS'),
        ('output_format', 'text'),
        ('output_info', 'compiled_code'),
    ])
    headers = {'Content-type': 'application/x-www-form-urlencoded'}
    conn = httplib.HTTPSConnection('closure-compiler.appspot.com')
    conn.request('POST', '/compile', params, headers)
    response = conn.getresponse()
    response_data = response.read()
    conn.close()
    return response_data

if __name__ == '__main__':
    PROG_NAME = os.path.basename(str(sys.argv[0]))
    if len(sys.argv) < 2:
        usage()
        sys.exit(errno.EINVAL)
    else:
        arg = sys.argv[1]
        if arg == '-h' or arg == '--help':
            usage()
            sys.exit(2)

        if arg.startswith('http'):
            data = compile_url(arg)
            print(data)
        elif os.path.isfile(arg):
            fo = open(arg, 'r')
            str_in = fo.read()
            fo.close()
            data = compile_code(str_in)
            print(data)
        else:
            print("{0} error : no such file '{1}'".format(PROG_NAME, arg))
            sys.exit(errno.ENOENT)