code_junkie

Python script for minifying CSS?

Nov 11th, 2011
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. import sys, re
  2.  
  3. css = open( sys.argv[1] , 'r' ).read()
  4.  
  5. # remove comments - this will break a lot of hacks :-P
  6. css = re.sub( r's*/*s**/', "$$HACK1$$", css ) # preserve IE<6 comment hack
  7. css = re.sub( r'/*[sS]*?*/', "", css )
  8. css = css.replace( "$$HACK1$$", '/**/' ) # preserve IE<6 comment hack
  9.  
  10. # url() doesn't need quotes
  11. css = re.sub( r'url((["'])([^)]*)1)', r'url(2)', css )
  12.  
  13. # spaces may be safely collapsed as generated content will collapse them anyway
  14. css = re.sub( r's+', ' ', css )
  15.  
  16. # shorten collapsable colors: #aabbcc to #abc
  17. css = re.sub( r'#([0-9a-f])1([0-9a-f])2([0-9a-f])3(s|;)', r'#1234', css )
  18.  
  19. # fragment values can loose zeros
  20. css = re.sub( r':s*0(.d+([cm]m|e[mx]|in|p[ctx]))s*;', r':1;', css )
  21.  
  22. for rule in re.findall( r'([^{]+){([^}]*)}', css ):
  23.  
  24. # we don't need spaces around operators
  25. selectors = [re.sub( r'(?<=[[(>+=])s+|s+(?=[=~^$*|>+])])', r'', selector.strip() ) for selector in rule[0].split( ',' )]
  26.  
  27. # order is important, but we still want to discard repetitions
  28. properties = {}
  29. porder = []
  30. for prop in re.findall( '(.*?):(.*?)(;|$)', rule[1] ):
  31. key = prop[0].strip().lower()
  32. if key not in porder: porder.append( key )
  33. properties[ key ] = prop[1].strip()
  34.  
  35. # output rule if it contains any declarations
  36. if properties:
  37. print "%s{%s}" % ( ','.join( selectors ), ''.join(['%s:%s;' % (key, properties[key]) for key in porder])[:-1] )
Add Comment
Please, Sign In to add comment