Package tdi :: Package tools :: Module rcssmin
[frames] | no frames]

Source Code for Module tdi.tools.rcssmin

  1  #!/usr/bin/env python 
  2  # -*- coding: ascii -*- 
  3  r""" 
  4  ============== 
  5   CSS Minifier 
  6  ============== 
  7   
  8  CSS Minifier. 
  9   
 10  The minifier is based on the semantics of the `YUI compressor`_\\, which 
 11  itself is based on `the rule list by Isaac Schlueter`_\\. 
 12   
 13  :Copyright: 
 14   
 15   Copyright 2011 - 2015 
 16   Andr\xe9 Malo or his licensors, as applicable 
 17   
 18  :License: 
 19   
 20   Licensed under the Apache License, Version 2.0 (the "License"); 
 21   you may not use this file except in compliance with the License. 
 22   You may obtain a copy of the License at 
 23   
 24       http://www.apache.org/licenses/LICENSE-2.0 
 25   
 26   Unless required by applicable law or agreed to in writing, software 
 27   distributed under the License is distributed on an "AS IS" BASIS, 
 28   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 29   See the License for the specific language governing permissions and 
 30   limitations under the License. 
 31   
 32  This module is a re-implementation aiming for speed instead of maximum 
 33  compression, so it can be used at runtime (rather than during a preprocessing 
 34  step). RCSSmin does syntactical compression only (removing spaces, comments 
 35  and possibly semicolons). It does not provide semantic compression (like 
 36  removing empty blocks, collapsing redundant properties etc). It does, however, 
 37  support various CSS hacks (by keeping them working as intended). 
 38   
 39  Here's a feature list: 
 40   
 41  - Strings are kept, except that escaped newlines are stripped 
 42  - Space/Comments before the very end or before various characters are 
 43    stripped: ``:{});=>],!`` (The colon (``:``) is a special case, a single 
 44    space is kept if it's outside a ruleset.) 
 45  - Space/Comments at the very beginning or after various characters are 
 46    stripped: ``{}(=:>[,!`` 
 47  - Optional space after unicode escapes is kept, resp. replaced by a simple 
 48    space 
 49  - whitespaces inside ``url()`` definitions are stripped 
 50  - Comments starting with an exclamation mark (``!``) can be kept optionally. 
 51  - All other comments and/or whitespace characters are replaced by a single 
 52    space. 
 53  - Multiple consecutive semicolons are reduced to one 
 54  - The last semicolon within a ruleset is stripped 
 55  - CSS Hacks supported: 
 56   
 57    - IE7 hack (``>/**/``) 
 58    - Mac-IE5 hack (``/*\\*/.../**/``) 
 59    - The boxmodelhack is supported naturally because it relies on valid CSS2 
 60      strings 
 61    - Between ``:first-line`` and the following comma or curly brace a space is 
 62      inserted. (apparently it's needed for IE6) 
 63    - Same for ``:first-letter`` 
 64   
 65  rcssmin.c is a reimplementation of rcssmin.py in C and improves runtime up to 
 66  factor 100 or so (depending on the input). docs/BENCHMARKS in the source 
 67  distribution contains the details. 
 68   
 69  Both python 2 (>= 2.4) and python 3 are supported. 
 70   
 71  .. _YUI compressor: https://github.com/yui/yuicompressor/ 
 72   
 73  .. _the rule list by Isaac Schlueter: https://github.com/isaacs/cssmin/ 
 74  """ 
 75  if __doc__: 
 76      # pylint: disable = W0622 
 77      __doc__ = __doc__.encode('ascii').decode('unicode_escape') 
 78  __author__ = r"Andr\xe9 Malo".encode('ascii').decode('unicode_escape') 
 79  __docformat__ = "restructuredtext en" 
 80  __license__ = "Apache License, Version 2.0" 
 81  __version__ = '1.0.6' 
 82  __all__ = ['cssmin'] 
 83   
 84  import re as _re 
 85   
 86   
87 -def _make_cssmin(python_only=False):
88 """ 89 Generate CSS minifier. 90 91 :Parameters: 92 `python_only` : ``bool`` 93 Use only the python variant. If true, the c extension is not even 94 tried to be loaded. (tdi.c._tdi_rcssmin) 95 96 :Return: Minifier 97 :Rtype: ``callable`` 98 """ 99 # pylint: disable = R0912, R0914, W0612 100 101 if not python_only: 102 from .. import c 103 rcssmin = c.load('rcssmin') 104 if rcssmin is not None: 105 return rcssmin.cssmin 106 107 nl = r'(?:[\n\f]|\r\n?)' # pylint: disable = C0103 108 spacechar = r'[\r\n\f\040\t]' 109 110 unicoded = r'[0-9a-fA-F]{1,6}(?:[\040\n\t\f]|\r\n?)?' 111 escaped = r'[^\n\r\f0-9a-fA-F]' 112 escape = r'(?:\\(?:%(unicoded)s|%(escaped)s))' % locals() 113 114 nmchar = r'[^\000-\054\056\057\072-\100\133-\136\140\173-\177]' 115 # nmstart = r'[^\000-\100\133-\136\140\173-\177]' 116 # ident = (r'(?:' 117 # r'-?(?:%(nmstart)s|%(escape)s)%(nmchar)s*(?:%(escape)s%(nmchar)s*)*' 118 # r')') % locals() 119 120 comment = r'(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)' 121 122 # only for specific purposes. The bang is grouped: 123 _bang_comment = r'(?:/\*(!?)[^*]*\*+(?:[^/*][^*]*\*+)*/)' 124 125 string1 = \ 126 r'(?:\047[^\047\\\r\n\f]*(?:\\[^\r\n\f][^\047\\\r\n\f]*)*\047)' 127 string2 = r'(?:"[^"\\\r\n\f]*(?:\\[^\r\n\f][^"\\\r\n\f]*)*")' 128 strings = r'(?:%s|%s)' % (string1, string2) 129 130 nl_string1 = \ 131 r'(?:\047[^\047\\\r\n\f]*(?:\\(?:[^\r]|\r\n?)[^\047\\\r\n\f]*)*\047)' 132 nl_string2 = r'(?:"[^"\\\r\n\f]*(?:\\(?:[^\r]|\r\n?)[^"\\\r\n\f]*)*")' 133 nl_strings = r'(?:%s|%s)' % (nl_string1, nl_string2) 134 135 uri_nl_string1 = r'(?:\047[^\047\\]*(?:\\(?:[^\r]|\r\n?)[^\047\\]*)*\047)' 136 uri_nl_string2 = r'(?:"[^"\\]*(?:\\(?:[^\r]|\r\n?)[^"\\]*)*")' 137 uri_nl_strings = r'(?:%s|%s)' % (uri_nl_string1, uri_nl_string2) 138 139 nl_escaped = r'(?:\\%(nl)s)' % locals() 140 141 space = r'(?:%(spacechar)s|%(comment)s)' % locals() 142 143 ie7hack = r'(?:>/\*\*/)' 144 145 uri = (r'(?:' 146 # noqa pylint: disable = C0330 147 r'(?:[^\000-\040"\047()\\\177]*' 148 r'(?:%(escape)s[^\000-\040"\047()\\\177]*)*)' 149 r'(?:' 150 r'(?:%(spacechar)s+|%(nl_escaped)s+)' 151 r'(?:' 152 r'(?:[^\000-\040"\047()\\\177]|%(escape)s|%(nl_escaped)s)' 153 r'[^\000-\040"\047()\\\177]*' 154 r'(?:%(escape)s[^\000-\040"\047()\\\177]*)*' 155 r')+' 156 r')*' 157 r')') % locals() 158 159 nl_unesc_sub = _re.compile(nl_escaped).sub 160 161 uri_space_sub = _re.compile(( 162 r'(%(escape)s+)|%(spacechar)s+|%(nl_escaped)s+' 163 ) % locals()).sub 164 uri_space_subber = lambda m: m.groups()[0] or '' 165 166 space_sub_simple = _re.compile(( 167 r'[\r\n\f\040\t;]+|(%(comment)s+)' 168 ) % locals()).sub 169 space_sub_banged = _re.compile(( 170 r'[\r\n\f\040\t;]+|(%(_bang_comment)s+)' 171 ) % locals()).sub 172 173 post_esc_sub = _re.compile(r'[\r\n\f\t]+').sub 174 175 main_sub = _re.compile(( 176 # noqa pylint: disable = C0330 177 r'([^\\"\047u>@\r\n\f\040\t/;:{}+]+)' # 1 178 r'|(?<=[{}(=:>[,!])(%(space)s+)' # 2 179 r'|^(%(space)s+)' # 3 180 r'|(%(space)s+)(?=(([:{});=>\],!])|$)?)' # 4, 5, 6 181 r'|;(%(space)s*(?:;%(space)s*)*)(?=(\})?)' # 7, 8 182 r'|(\{)' # 9 183 r'|(\})' # 10 184 r'|(%(strings)s)' # 11 185 r'|(?<!%(nmchar)s)url\(%(spacechar)s*(' # 12 186 r'%(uri_nl_strings)s' 187 r'|%(uri)s' 188 r')%(spacechar)s*\)' 189 r'|(@(?:' # 13 190 r'[mM][eE][dD][iI][aA]' 191 r'|[sS][uU][pP][pP][oO][rR][tT][sS]' 192 r'|[dD][oO][cC][uU][mM][eE][nN][tT]' 193 r'|(?:-(?:' 194 r'[wW][eE][bB][kK][iI][tT]|[mM][oO][zZ]|[oO]|[mM][sS]' 195 r')-)?' 196 r'[kK][eE][yY][fF][rR][aA][mM][eE][sS]' 197 r'))(?!%(nmchar)s)' 198 r'|(%(ie7hack)s)(%(space)s*)' # 14, 15 199 r'|(:[fF][iI][rR][sS][tT]-[lL]' # 16 200 r'(?:[iI][nN][eE]|[eE][tT][tT][eE][rR]))' 201 r'(%(space)s*)(?=[{,])' # 17 202 r'|(%(nl_strings)s)' # 18 203 r'|(%(escape)s[^\\"\047u>@\r\n\f\040\t/;:{}+]*)' # 19 204 ) % locals()).sub 205 206 # print main_sub.__self__.pattern 207 208 def main_subber(keep_bang_comments): 209 """ Make main subber """ 210 in_macie5, in_rule, at_group = [0], [0], [0] 211 212 if keep_bang_comments: 213 space_sub = space_sub_banged 214 215 def space_subber(match): 216 """ Space|Comment subber """ 217 if match.lastindex: 218 group1, group2 = match.group(1, 2) 219 if group2: 220 if group1.endswith(r'\*/'): 221 in_macie5[0] = 1 222 else: 223 in_macie5[0] = 0 224 return group1 225 elif group1: 226 if group1.endswith(r'\*/'): 227 if in_macie5[0]: 228 return '' 229 in_macie5[0] = 1 230 return r'/*\*/' 231 elif in_macie5[0]: 232 in_macie5[0] = 0 233 return '/**/' 234 return ''
235 else: 236 space_sub = space_sub_simple 237 238 def space_subber(match): 239 """ Space|Comment subber """ 240 if match.lastindex: 241 if match.group(1).endswith(r'\*/'): 242 if in_macie5[0]: 243 return '' 244 in_macie5[0] = 1 245 return r'/*\*/' 246 elif in_macie5[0]: 247 in_macie5[0] = 0 248 return '/**/' 249 return '' 250 251 def fn_space_post(group): 252 """ space with token after """ 253 if group(5) is None or ( 254 group(6) == ':' and not in_rule[0] and not at_group[0]): 255 return ' ' + space_sub(space_subber, group(4)) 256 return space_sub(space_subber, group(4)) 257 258 def fn_semicolon(group): 259 """ ; handler """ 260 return ';' + space_sub(space_subber, group(7)) 261 262 def fn_semicolon2(group): 263 """ ; handler """ 264 if in_rule[0]: 265 return space_sub(space_subber, group(7)) 266 return ';' + space_sub(space_subber, group(7)) 267 268 def fn_open(_): 269 """ { handler """ 270 if at_group[0]: 271 at_group[0] -= 1 272 else: 273 in_rule[0] = 1 274 return '{' 275 276 def fn_close(_): 277 """ } handler """ 278 in_rule[0] = 0 279 return '}' 280 281 def fn_at_group(group): 282 """ @xxx group handler """ 283 at_group[0] += 1 284 return group(13) 285 286 def fn_ie7hack(group): 287 """ IE7 Hack handler """ 288 if not in_rule[0] and not at_group[0]: 289 in_macie5[0] = 0 290 return group(14) + space_sub(space_subber, group(15)) 291 return '>' + space_sub(space_subber, group(15)) 292 293 table = ( 294 # noqa pylint: disable = C0330 295 None, 296 None, 297 None, 298 None, 299 fn_space_post, # space with token after 300 fn_space_post, # space with token after 301 fn_space_post, # space with token after 302 fn_semicolon, # semicolon 303 fn_semicolon2, # semicolon 304 fn_open, # { 305 fn_close, # } 306 lambda g: g(11), # string 307 lambda g: 'url(%s)' % uri_space_sub(uri_space_subber, g(12)), 308 # url(...) 309 fn_at_group, # @xxx expecting {...} 310 None, 311 fn_ie7hack, # ie7hack 312 None, 313 lambda g: g(16) + ' ' + space_sub(space_subber, g(17)), 314 # :first-line|letter followed 315 # by [{,] (apparently space 316 # needed for IE6) 317 lambda g: nl_unesc_sub('', g(18)), # nl_string 318 lambda g: post_esc_sub(' ', g(19)), # escape 319 ) 320 321 def func(match): 322 """ Main subber """ 323 idx, group = match.lastindex, match.group 324 if idx > 3: 325 return table[idx](group) 326 327 # shortcuts for frequent operations below: 328 elif idx == 1: # not interesting 329 return group(1) 330 # else: # space with token before or at the beginning 331 return space_sub(space_subber, group(idx)) 332 333 return func 334 335 def cssmin(style, keep_bang_comments=False): # pylint: disable = W0621 336 """ 337 Minify CSS. 338 339 :Parameters: 340 `style` : ``str`` 341 CSS to minify 342 343 `keep_bang_comments` : ``bool`` 344 Keep comments starting with an exclamation mark? (``/*!...*/``) 345 346 :Return: Minified style 347 :Rtype: ``str`` 348 """ 349 return main_sub(main_subber(keep_bang_comments), style) 350 351 return cssmin 352 353 cssmin = _make_cssmin() 354 355 356 if __name__ == '__main__':
357 - def main():
358 """ Main """ 359 import sys as _sys 360 keep_bang_comments = ( 361 '-b' in _sys.argv[1:] 362 or '-bp' in _sys.argv[1:] 363 or '-pb' in _sys.argv[1:] 364 ) 365 if '-p' in _sys.argv[1:] or '-bp' in _sys.argv[1:] \ 366 or '-pb' in _sys.argv[1:]: 367 global cssmin # pylint: disable = W0603 368 cssmin = _make_cssmin(python_only=True) 369 _sys.stdout.write(cssmin( 370 _sys.stdin.read(), keep_bang_comments=keep_bang_comments 371 ))
372 main() 373