Back to index

plone3  3.1.7
compress.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 """Remove comments, newlines and redundant whitespace from JavaScript code
00004 
00005     This reads all paths that were passed in as arguments on the command-line
00006     and removes everything that is ignored by JavaScript. This makes that
00007     the source isn't readable anymore (which I personally consider bad),
00008     but also that less bytes have to be served by the server, scripts are
00009     loaded faster and also that they're executed faster.
00010     
00011     WARNING: This script converts files in place! Original files will be
00012     overwritten. Do *not* run this on a development version of your code,
00013     since you won't be able to get them back into the original state. This
00014     should be ran only by system administrators if they want to speed up
00015     their setups.
00016 """
00017 
00018 import sys, re
00019 
00020 one_line_comment = re.compile(r'^\s*//.*$', re.M)
00021 trailing_comment = re.compile(r'//(\w|\s)*$', re.M)
00022 multi_line_comment = re.compile(r'^\s*/\*.*?\*/', re.M | re.S)
00023 whitespace_after_separator = re.compile(r';\s*', re.M | re.S)
00024 whitespace_after_opening_bracket = re.compile(r'{\s*', re.M | re.S)
00025 starting_whitespace = re.compile(r'^\s*', re.M | re.S)
00026 
00027 def strip(data):
00028     """Processes the data, removing comments and unecessary whitespace."""
00029     data = one_line_comment.sub('', data)
00030     data = trailing_comment.sub('', data)
00031     data = multi_line_comment.sub('', data)
00032     data = whitespace_after_separator.sub(';', data)
00033     data = whitespace_after_opening_bracket.sub('{', data)
00034     data = starting_whitespace.sub('', data)
00035     return data.strip()
00036 
00037 for file in sys.argv[1:]:
00038     data = open(file).read()
00039     data = strip(data)
00040     open(file, 'w').write(data)