I know there are many similar tools, but not all of them are written in Python. Hmm... I should say most of them are not.
This is not a real compressor, because it just try to get rid of comments, unnecessary characters, empty lines etc. On the Net there are more advanced solutions trying to join similar rules, use the shortest version of them if possible. Joining those two types of minification can give very good results, especially when connected with GZip compression as on this site.
Code is very simple. I'm using four types of compression:
-
NONE-- nothing is really done except of removing Windows line endings -
SIMPLE-- this method also remove longer comments and empty lines -
NORMAL-- as above but also converts rules to one line versions and removes all unnecessary characters -
FULL-- as above but also removes short comments and creates all CSS compressed to one line of text
Below code:
#test a {
/* Dummy comment */
text-align: left;
color: #222;
background-color: #fff;
}
#test a:hover {
color: #000;
}
will be transformed to something like this, using NORMAL compression level:
#test a{text-align:left;color:#222;background-color:#fff}
#test a:hover{color:#000}
Regular expression rules for compressing the CSS are separated from main code, so you can easily add your own. The code:
"""
Simple CSS Minifier.
Code were created by Rafał Jońca.
The code is available on double license: GPL and MIT.
"""
import re
# Constants for use in compression level setting.
NONE = 0
SIMPLE = 1
NORMAL = 2
FULL = 3
_REPLACERS = {
NONE: (None), # dummy
SIMPLE: ((r'\/\*.{4,}?\*\/', ''), # comment
(r'\n\s*\n', r"\n"), # empty new lines
(r'(^\s*\n)|(\s*\n$)', "")), # new lines at start or end
NORMAL: ((r'/\*.{4,}?\*/', ''), # comments
(r"\n", ""), # delete new lines
('[\t ]+', " "), # change spaces and tabs to one space
(r'\s?([;:{},+>])\s?', r"\1"), # delete space where it is not needed, change ;} to }
(r';}', "}"), # because semicolon is not needed there
(r'}', r"}\n")), # add new line after each rule
FULL: ((r'\/\*.*?\*\/', ''), # comments
(r"\n", ""), # delete new lines
(r'[\t ]+', " "), # change spaces and tabs to one space
(r'\s?([;:{},+>])\s?', r"\1"), # delete space where it is not needed, change ;} to }
(r';}', "}")), # because semicolon is not needed there
}
class CssMin:
def __init__(self, level=NORMAL):
self.level = level
def compress(self, css):
"""Tries to minimize the length of CSS code passed as parameter. Returns string."""
css = css.replace("\r\n", "\n") # get rid of Windows line endings, if they exist
for rule in _REPLACERS[self.level]:
css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rule[1], css)
return css
def minimalize(css, level=NORMAL):
"""Compress css using level method and return new css as a string."""
return CssMin(level).compress(css)
if __name__ == '__main__':
import sys
if len(sys.argv) <> 3:
print "Usage: %s% sys.argv[0] "
sys.exit(1)
f = open(sys.argv[1])
inputcss = f.read()
f.close()
open(sys.argv[2], 'w').write(minimalize(inputcss))
To compress code use minimalize() function. From command line, just use cssmin.py input output.
If you are looking for similar thing but for JavaScript, don't reinvent the wheel, use this code. It is based on original C version of JS minifier and work as a function or from command line.
0 komentarze:
Post a Comment