jsmin.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #!/usr/bin/python
  2. # This code is original from jsmin by Douglas Crockford, it was translated to
  3. # Python by Baruch Even. The original code had the following copyright and
  4. # license.
  5. #
  6. # /* jsmin.c
  7. # 2007-05-22
  8. #
  9. # Copyright (c) 2002 Douglas Crockford (www.crockford.com)
  10. #
  11. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  12. # this software and associated documentation files (the "Software"), to deal in
  13. # the Software without restriction, including without limitation the rights to
  14. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  15. # of the Software, and to permit persons to whom the Software is furnished to do
  16. # so, subject to the following conditions:
  17. #
  18. # The above copyright notice and this permission notice shall be included in all
  19. # copies or substantial portions of the Software.
  20. #
  21. # The Software shall be used for Good, not Evil.
  22. #
  23. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  29. # SOFTWARE.
  30. # */
  31. from StringIO import StringIO
  32. def jsmin(js):
  33. ins = StringIO(js)
  34. outs = StringIO()
  35. JavascriptMinify().minify(ins, outs)
  36. str = outs.getvalue()
  37. if len(str) > 0 and str[0] == '\n':
  38. str = str[1:]
  39. return str
  40. def isAlphanum(c):
  41. """return true if the character is a letter, digit, underscore,
  42. dollar sign, or non-ASCII character.
  43. """
  44. return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or
  45. (c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126));
  46. class UnterminatedComment(Exception):
  47. pass
  48. class UnterminatedStringLiteral(Exception):
  49. pass
  50. class UnterminatedRegularExpression(Exception):
  51. pass
  52. class JavascriptMinify(object):
  53. def _outA(self):
  54. self.outstream.write(self.theA)
  55. def _outB(self):
  56. self.outstream.write(self.theB)
  57. def _get(self):
  58. """return the next character from stdin. Watch out for lookahead. If
  59. the character is a control character, translate it to a space or
  60. linefeed.
  61. """
  62. c = self.theLookahead
  63. self.theLookahead = None
  64. if c == None:
  65. c = self.instream.read(1)
  66. if c >= ' ' or c == '\n':
  67. return c
  68. if c == '': # EOF
  69. return '\000'
  70. if c == '\r':
  71. return '\n'
  72. return ' '
  73. def _peek(self):
  74. self.theLookahead = self._get()
  75. return self.theLookahead
  76. def _next(self):
  77. """get the next character, excluding comments. peek() is used to see
  78. if an unescaped '/' is followed by a '/' or '*'.
  79. """
  80. c = self._get()
  81. if c == '/' and self.theA != '\\':
  82. p = self._peek()
  83. if p == '/':
  84. c = self._get()
  85. while c > '\n':
  86. c = self._get()
  87. return c
  88. if p == '*':
  89. c = self._get()
  90. while 1:
  91. c = self._get()
  92. if c == '*':
  93. if self._peek() == '/':
  94. self._get()
  95. return ' '
  96. if c == '\000':
  97. raise UnterminatedComment()
  98. return c
  99. def _action(self, action):
  100. """do something! What you do is determined by the argument:
  101. 1 Output A. Copy B to A. Get the next B.
  102. 2 Copy B to A. Get the next B. (Delete A).
  103. 3 Get the next B. (Delete B).
  104. action treats a string as a single character. Wow!
  105. action recognizes a regular expression if it is preceded by ( or , or =.
  106. """
  107. if action <= 1:
  108. self._outA()
  109. if action <= 2:
  110. self.theA = self.theB
  111. if self.theA == "'" or self.theA == '"':
  112. while 1:
  113. self._outA()
  114. self.theA = self._get()
  115. if self.theA == self.theB:
  116. break
  117. if self.theA <= '\n':
  118. raise UnterminatedStringLiteral()
  119. if self.theA == '\\':
  120. self._outA()
  121. self.theA = self._get()
  122. if action <= 3:
  123. self.theB = self._next()
  124. if self.theB == '/' and (self.theA == '(' or self.theA == ',' or
  125. self.theA == '=' or self.theA == ':' or
  126. self.theA == '[' or self.theA == '?' or
  127. self.theA == '!' or self.theA == '&' or
  128. self.theA == '|' or self.theA == ';' or
  129. self.theA == '{' or self.theA == '}' or
  130. self.theA == '\n'):
  131. self._outA()
  132. self._outB()
  133. while 1:
  134. self.theA = self._get()
  135. if self.theA == '/':
  136. break
  137. elif self.theA == '\\':
  138. self._outA()
  139. self.theA = self._get()
  140. elif self.theA <= '\n':
  141. raise UnterminatedRegularExpression()
  142. self._outA()
  143. self.theB = self._next()
  144. def _jsmin(self):
  145. """Copy the input to the output, deleting the characters which are
  146. insignificant to JavaScript. Comments will be removed. Tabs will be
  147. replaced with spaces. Carriage returns will be replaced with linefeeds.
  148. Most spaces and linefeeds will be removed.
  149. """
  150. self.theA = '\n'
  151. self._action(3)
  152. while self.theA != '\000':
  153. if self.theA == ' ':
  154. if isAlphanum(self.theB):
  155. self._action(1)
  156. else:
  157. self._action(2)
  158. elif self.theA == '\n':
  159. if self.theB in ['{', '[', '(', '+', '-']:
  160. self._action(1)
  161. elif self.theB == ' ':
  162. self._action(3)
  163. else:
  164. if isAlphanum(self.theB):
  165. self._action(1)
  166. else:
  167. self._action(2)
  168. else:
  169. if self.theB == ' ':
  170. if isAlphanum(self.theA):
  171. self._action(1)
  172. else:
  173. self._action(3)
  174. elif self.theB == '\n':
  175. if self.theA in ['}', ']', ')', '+', '-', '"', '\'']:
  176. self._action(1)
  177. else:
  178. if isAlphanum(self.theA):
  179. self._action(1)
  180. else:
  181. self._action(3)
  182. else:
  183. self._action(1)
  184. def minify(self, instream, outstream):
  185. self.instream = instream
  186. self.outstream = outstream
  187. self.theA = '\n'
  188. self.theB = None
  189. self.theLookahead = None
  190. self._jsmin()
  191. self.instream.close()
  192. if __name__ == '__main__':
  193. import sys
  194. jsm = JavascriptMinify()
  195. jsm.minify(sys.stdin, sys.stdout)