PageRenderTime 69ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/compile.py

https://github.com/wesdu/python-compile
Python | 212 lines | 203 code | 6 blank | 3 comment | 22 complexity | 883f1157fecadea75322eea5d66b9dd0 MD5 | raw file
  1. #!/usr/bin/python
  2. #coding:utf-8
  3. #python2.6
  4. import json
  5. import sys
  6. import re
  7. import os
  8. import shutil
  9. import platform
  10. import commands
  11. import time
  12. from compile_config import *
  13. jsKeyP = re.compile('([^"\s]\S+[^"])\s*:')
  14. revFieldP = re.compile('Revision\:\s*(\d+)\s*')
  15. dateFieldP = re.compile('Last Changed Date\:\s*(.+)\n*')
  16. def pickMode(args):
  17. for name in args:
  18. Compile(rules[name], name)
  19. class Compile(object):
  20. def __init__(self, rule, name):
  21. print 'Compile', name, 60*'+'
  22. self.target = rule["target"]
  23. self.source = rule["source"]
  24. self.name = name
  25. self.sourcename = os.path.basename(self.source)
  26. if not self.sourcename:
  27. self.ext = None
  28. else:
  29. self.ext = os.path.splitext(self.sourcename)[1][1:]
  30. if self.ext == "qzmin":
  31. self.loadQzmin()
  32. elif self.ext is None:
  33. self.recursive = rule.get("recursive")
  34. self.allowext = rule.get("ext")
  35. self.moveFiles()
  36. else:
  37. self.moveFile(self.source, self.target)
  38. def moveFiles(self):
  39. if not self.recursive:
  40. for f in os.listdir(self.source):
  41. ext = os.path.splitext(f)[1][1:]
  42. if not self.allowext or self.allowext and ext in self.allowext:
  43. sourcefile = os.path.join(self.source, f)
  44. if os.path.isfile(sourcefile):
  45. self.moveFile(sourcefile, os.path.join(self.target, f))
  46. else:
  47. lists = []
  48. for root, dirs, files in os.walk(self.source, True):
  49. for f in files:
  50. ext = os.path.splitext(f)[1][1:]
  51. if not self.allowext or self.allowext and ext in self.allowext:
  52. spath = os.path.join(root, f)
  53. tpath = os.path.join(self.target, os.path.relpath(root, self.source), f)
  54. lists.append([spath, tpath])
  55. makeDirs([l[1] for l in lists])
  56. for l in lists:
  57. self.moveFile(l[0], l[1])
  58. def moveFile(self, source, target):
  59. print 'copyfile %s to %s ' % (source, target)
  60. filename = os.path.basename(source)
  61. if filename in revisionUpdatefiles:
  62. print 'replace', filename
  63. if os.path.isdir(target):
  64. target = os.path.join(target, filename)
  65. open(target, "w").write("".join([line for line in open(source).xreadlines()]).replace(revisionMark, REV))
  66. else:
  67. shutil.copy(source, target)
  68. self.compressor([target])
  69. def loadQzmin(self, format=True):
  70. print 'load qzmin start', self.name
  71. f = open(self.source)
  72. ll = [];
  73. for l in f.xreadlines():
  74. if format:
  75. ll.append(js2json(l))
  76. else:
  77. ll.append(l)
  78. print 'load qzmin finish', self.name
  79. self.combine(json.loads("".join(ll)))
  80. def combine(self, j):
  81. print 'combine start', self.name
  82. projects = j["projects"]
  83. results = []
  84. for p in projects:
  85. target = p["target"]
  86. files = p["include"]
  87. t = []
  88. combineContent = []
  89. for f in files:
  90. fileName = os.path.basename(f)
  91. filepath = os.path.join(os.path.dirname(self.source), f)
  92. for line in open(filepath).xreadlines():
  93. t.append(line);
  94. if fileName in revisionUpdatefiles:
  95. print 'replace', fileName
  96. combineContent.append("".join(t).replace(revisionMark, REV))
  97. else:
  98. combineContent.append("".join(t))
  99. del t[:]
  100. results.append("".join(combineContent))
  101. print 'combine finish', self.name
  102. self.createFiles(results)
  103. def createFiles(self, contents):
  104. print 'createFiles start', self.name
  105. results = []
  106. for c in contents:
  107. print 'createFiles...'
  108. open(self.target, "w").write(c)
  109. results.append(self.target);
  110. print 'createFiles finish', self.name
  111. self.compressor(results)
  112. def compressor(self, files):
  113. if ifCompress:
  114. for f in files:
  115. filetype = os.path.splitext(f)[1][1:]
  116. if filetype in ["js", "css"]:
  117. print 'compressor start', self.name, "-"*40
  118. if filetype == "js":
  119. cmd = 'java -jar %s --%s %s --%s_output_file %s.min' % (googleclosurePath, filetype, f, filetype, f)
  120. elif filetype == "css":
  121. cmd = 'java -jar %s %s -o %s.min --charset utf-8' % (yuicompiressorPath, f, f)
  122. print cmd
  123. os.system(cmd)
  124. t = [prefix % DATE]
  125. for line in open(f+".min").xreadlines():
  126. t.append(line);
  127. open(f,"w").write("".join(t))
  128. os.remove(f+".min")
  129. print 'compressor finish', self.name, "-"*40
  130. def makeDirs(items):
  131. isCheck = {}
  132. for v in items:
  133. path = os.path.dirname(v)
  134. if not isCheck.get(path):
  135. mkdir(path)
  136. isCheck[path] = True
  137. isCheck.clear()
  138. def js2json(fileline):
  139. l = jsKeyP.sub(lambda l:'"%s" : ' % l.group(1), fileline)
  140. return '"'.join(l.split('\''))
  141. def mkdir(path):
  142. if os.path.exists(path):
  143. print "Path", path, "exists"
  144. else:
  145. os.makedirs(path)
  146. print "Craete path", path
  147. if __name__ == "__main__":
  148. print platform.platform()
  149. if len(sys.argv) > 1:
  150. argS = (" ").join(sys.argv[1:])
  151. else:
  152. argS = ""
  153. argS = argS.lower()
  154. if "-h" in argS or "-help" in argS or argS is "":
  155. print '''Options and arguments:
  156. -h : Help
  157. -produce : For produce enviroment
  158. -debug : For debug enviroment
  159. -noup : Publish without svn up
  160. -nocompress : Publish without google closure
  161. -norevision : Publish without version string replacement
  162. For example:
  163. python compile.py -produce
  164. python compile.py -debug
  165. python compile.py -debug -noup -nocompress
  166. '''
  167. sys.exit()
  168. if "-noup" in argS:
  169. pass
  170. else:
  171. if "Windows" not in platform.platform():
  172. os.system("svn up")
  173. if "-norevision" in argS:
  174. REV = DATE = str(time.time())
  175. else:
  176. if "Windows" not in platform.platform():
  177. output = commands.getoutput("svn info")
  178. REV = revFieldP.search(output).group(1)
  179. DATE = dateFieldP.search(output).group(1)[:19]
  180. else:
  181. REV = DATE = str(time.time())
  182. if "-nocompress" in argS:
  183. ifCompress = False
  184. else:
  185. ifCompress = True
  186. for cmd in sys.argv[1:]:
  187. if modes.get(cmd):
  188. print cmd, "mode on ", "-"*60
  189. items = [v["target"] for k, v in rules.items() if k in modes.get(cmd)]
  190. makeDirs(items)
  191. pickMode(modes.get(cmd))
  192. print 'All done.'
  193. sys.exit()