python-compile /compile.py

Language Python Lines 212
MD5 Hash 883f1157fecadea75322eea5d66b9dd0
Repository https://github.com/wesdu/python-compile.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/python
#coding:utf-8
#python2.6

import json
import sys
import re
import os
import shutil
import platform
import commands
import time
from compile_config import *

jsKeyP = re.compile('([^"\s]\S+[^"])\s*:')
revFieldP = re.compile('Revision\:\s*(\d+)\s*')
dateFieldP = re.compile('Last Changed Date\:\s*(.+)\n*')

def pickMode(args):
	for name in args:
		Compile(rules[name], name)

class Compile(object):
	def __init__(self, rule, name):
		print 'Compile', name, 60*'+'
		self.target = rule["target"]
		self.source = rule["source"]
		self.name = name
		self.sourcename = os.path.basename(self.source)
		if not self.sourcename:
			self.ext = None
		else:
			self.ext = os.path.splitext(self.sourcename)[1][1:]
		if self.ext == "qzmin":
			self.loadQzmin()
		elif self.ext is None:
			self.recursive = rule.get("recursive")
			self.allowext = rule.get("ext")
			self.moveFiles()
		else:
			self.moveFile(self.source, self.target)
			
	def moveFiles(self):
		if not self.recursive:
			for f in os.listdir(self.source):
				ext = os.path.splitext(f)[1][1:]
				if not self.allowext or self.allowext and ext in self.allowext:
					sourcefile = os.path.join(self.source, f)
					if os.path.isfile(sourcefile):
						self.moveFile(sourcefile, os.path.join(self.target, f))
		else:
			lists = []
			for root, dirs, files in os.walk(self.source, True):
				for f in files:
					ext = os.path.splitext(f)[1][1:]
					if not self.allowext or self.allowext and ext in self.allowext:
						spath = os.path.join(root, f)
						tpath = os.path.join(self.target, os.path.relpath(root, self.source), f)
						lists.append([spath, tpath])
			makeDirs([l[1] for l in lists])
			for l in lists:
				self.moveFile(l[0], l[1])
		
	def moveFile(self, source, target):
		print 'copyfile %s  to %s ' % (source, target)
		filename = os.path.basename(source)
		if filename in revisionUpdatefiles:
			print 'replace', filename
			if os.path.isdir(target):
				target = os.path.join(target, filename)
			open(target, "w").write("".join([line for line in open(source).xreadlines()]).replace(revisionMark, REV))
		else:
			shutil.copy(source, target)
		self.compressor([target])
		
	def loadQzmin(self, format=True):
		print 'load qzmin start', self.name
		f = open(self.source)
		ll = [];
		for l in f.xreadlines():
			if format:
				ll.append(js2json(l))
			else:
				ll.append(l)
		print 'load qzmin finish', self.name
		self.combine(json.loads("".join(ll)))
		
	def combine(self, j):
		print 'combine start', self.name
		projects = j["projects"]
		results = []
		for p in projects:
			target = p["target"]
			files =  p["include"]
			t = []
			combineContent = []
			for f in files:
				fileName = os.path.basename(f)
				filepath = os.path.join(os.path.dirname(self.source), f)
				for line in open(filepath).xreadlines():
					t.append(line);
				if fileName in revisionUpdatefiles:
					print 'replace', fileName
					combineContent.append("".join(t).replace(revisionMark, REV))
				else:
					combineContent.append("".join(t))
				del t[:]
			results.append("".join(combineContent))
		print 'combine finish', self.name
		self.createFiles(results)
		
	def createFiles(self, contents):
		print 'createFiles start', self.name
		results = []
		for c in contents:
			print 'createFiles...'
			open(self.target, "w").write(c)
			results.append(self.target);
		print 'createFiles finish', self.name
		self.compressor(results)
		
	def compressor(self, files):
		if ifCompress:
			for f in files:
				filetype = os.path.splitext(f)[1][1:]
				if filetype in ["js", "css"]:
					print 'compressor start', self.name, "-"*40
					if filetype == "js":
						cmd = 'java -jar %s --%s %s --%s_output_file %s.min' % (googleclosurePath, filetype, f, filetype, f)
					elif filetype == "css":
						cmd = 'java -jar %s %s -o %s.min --charset utf-8' % (yuicompiressorPath, f, f)
					print cmd
					os.system(cmd)
					t = [prefix % DATE]
					for line in open(f+".min").xreadlines():
						t.append(line);
					open(f,"w").write("".join(t))
					os.remove(f+".min")
					print 'compressor finish', self.name, "-"*40
	
def makeDirs(items):
	isCheck = {}
	for v in items:
		path = os.path.dirname(v)
		if not isCheck.get(path):
			mkdir(path)
			isCheck[path] = True
	isCheck.clear()

def js2json(fileline):
	l = jsKeyP.sub(lambda l:'"%s" : ' % l.group(1), fileline)
	return '"'.join(l.split('\''))

def mkdir(path):
	if os.path.exists(path):
		print "Path", path, "exists"
	else:
		os.makedirs(path)
		print "Craete path", path

if __name__ == "__main__":
	print platform.platform()
	if len(sys.argv) > 1:
		argS = (" ").join(sys.argv[1:])
	else:
		argS = ""
	argS = argS.lower()
	
	if "-h" in argS or "-help" in argS or argS is "":
		print '''Options and arguments:
-h             : Help
-produce       : For produce enviroment
-debug         : For debug enviroment
-noup          : Publish without svn up
-nocompress    : Publish without google closure
-norevision    : Publish without version string replacement
For example:
	python compile.py -produce
	python compile.py -debug
	python compile.py -debug -noup -nocompress 
		'''
		sys.exit()

	if "-noup" in argS:
		pass
	else:
		if "Windows" not in platform.platform():
			os.system("svn up")
	
	if "-norevision" in argS:
		REV = DATE = str(time.time())
	else:
		if "Windows" not in platform.platform():
			output = commands.getoutput("svn info")
			REV = revFieldP.search(output).group(1)
			DATE = dateFieldP.search(output).group(1)[:19]
		else:
			REV = DATE = str(time.time())
		
	if "-nocompress" in argS:
		ifCompress = False
	else:
		ifCompress = True
	
	for cmd in sys.argv[1:]:
		if modes.get(cmd):
			print cmd, "mode on ", "-"*60
			items = [v["target"] for k, v in rules.items() if k in modes.get(cmd)]
			makeDirs(items)
			pickMode(modes.get(cmd))
			print 'All done.'
			sys.exit()
Back to Top