import os from optparse import make_option from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-m','--method', action='store', dest='method', type='choice', choices=['jsmin', 'jspacker'], help='Packing or minimization method (jsmin/jspacker)'), make_option('-f','--file', action='append', dest='build_file', default=[], help='Build only this output file'), ) help = "Builds minimized/compacted javascript files" def handle(self, *args, **options): from django.conf import settings try: method = getattr(settings, 'JSC_METHOD') except AttributeError: method = None method = options.get('method') or method or 'jsmin' build_files = options.get('build_file', []) try: path = getattr(settings, 'JSC_PATH') except AttributeError: raise CommandError("Missing JSC_PATH in settings") try: filesdef = getattr(settings, 'JSC_FILES') except AttributeError: raise CommandError("Missing JSC_FILES in settings") all_outfiles = [ outfilename for (outfilename, other) in filesdef ] for build_file in build_files: if not build_file in all_outfiles: raise CommandError("Output file %s not included in JSC_FILES settings" % build_file) #by default build all files if build_files == []: build_files = all_outfiles for outfilename, inputfilenames in filesdef: if outfilename in build_files: print "Building minimized %s" % outfilename build_minimized_file(path, outfilename, inputfilenames, method) # Minimizes javascript using jsmin.py from http://javascript.crockford.com/jsmin.py.txt # Packs using http://www.crowproductions.de/repos/main/public/packer/jspacker.py def build_minimized_file(path, outfilename, inputfilenames, method): import jsmin import jspacker from StringIO import StringIO data = StringIO() for name in inputfilenames: try: f = file(os.path.join(path,name)) except IOError: raise CommandError("Error reading %s" % os.path.join(path,name)) data.write(f.read()) data.write('\n') outfile = file(os.path.join(path,outfilename),'w') if method == 'jsmin': outfile.write(jsmin.jsmin(data.getvalue())) else: p = jspacker.JavaScriptPacker() outfile.write(p.pack(data.getvalue(), compaction=False, encoding=62, fastDecode=True)) outfile.close()