Created
July 27, 2011 04:14
-
-
Save PaulGuo/1108658 to your computer and use it in GitHub Desktop.
Auto-Compress *.css or *.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Author: Guokai | |
# CreateDate: 2011-07-26 | |
# Description: This script executed to auto-compress *.css or *.js files. | |
# Rely: YUI-compressor-x.y.z | |
# Usage (anyone below): | |
# --- compressor.py *.js | |
# --- compressor.py demo.css | |
# --- compressor.py *.js *.css | |
# --- compressor.py in.js style.css | |
# for example,if you use compressor.py style.css motools.js in-min.js,these files will be changed: | |
# style.css -----> style-compressor-source.css (un-compressed) && style.css (compressed) | |
# mootools.js -----> mootools-compressor-source.js (un-compressed) && mootools.js (compressed) | |
# in-min.js -----> in-min.js (will skip and not compress it) | |
import os,sys,fnmatch,re | |
compressor_path='E:\\Tools\\yuicompressor-2.4.6\\build\\yuicompressor-2.4.6.jar' | |
compressor_charset='utf-8' | |
arg=sys.argv[1:] | |
def compressor(file): | |
return '-min'.join([os.path.splitext(file)[0],os.path.splitext(file)[1]]) | |
def walk(path,pattern): | |
arr=[] | |
for i in pattern: | |
for root,dirs,files in os.walk(path): | |
for filename in fnmatch.filter(files,i): | |
# skip the files which have already been minified | |
if(not re.match(r'(.*(-min|\.min|-compressor-source)\..*)',filename)): | |
arr.append(os.path.join(root,filename)) | |
return arr; | |
def compress(files): | |
for file in files: | |
print(file+'\t-> [OK]') | |
os.system('java -jar %s %s -o %s --charset %s --preserve-semi' % (compressor_path,file,compressor(file),compressor_charset)) | |
try: | |
os.rename(file,re.sub(r'\.(?P<ext>css|js)$','-compressor-source.\g<ext>',file)) | |
os.rename(compressor(file),re.sub(r'-min\.(?P<ext>css|js)$','.\g<ext>',compressor(file))) | |
except: | |
print('There\'s some errors happened!') | |
# can't excuted without parameters | |
if(len(arg)<2): | |
print('>>> Usage:\t compressor.py directory_name file1 file2 ... file{n}') | |
print('>>> Example:\t compressor.py document *.js *.css demo.css') | |
sys.exit(0) | |
else: | |
path=arg.pop(0) | |
pattern=arg | |
files=walk(path,pattern) | |
compress(files) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment