/
build.py
225 lines (179 loc) · 7.7 KB
/
build.py
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
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python
import os
import codecs
import time
import util
import log
try:
import json
except ImportError, e:
import simplejson as json
class Builder():
timeFormat = '%Y-%m-%d_%H-%M-%S'
def __init__(self, config=None, simulate=False):
self.log = log.Logger()
self.simulate = simulate
self.config = config
try:
buildStatusFile = os.path.join(self.config["stageDir"], "trunk", "qooxdoo", "buildStatus.json")
self.buildStatus = self.getBuildStatusFromFile(buildStatusFile)
except Exception, e:
self.buildStatus = {}
def prepareBuildLog(self, buildLogDir, target):
try:
if not os.path.isdir(buildLogDir):
os.mkdir(buildLogDir)
except Exception, e:
self.log.error("Failed to create build log directory %s" %buildLogDir)
self.log.logError(e)
return False
buildLog = os.path.join(buildLogDir, target + '_' + util.getTimestamp() + '.log')
self.log.info("Opening build log file %s" %buildLog)
try:
buildLogFile = codecs.open(buildLog, 'a', 'utf-8')
except Exception, e:
self.log.error("Error while opening build log file")
self.logError(e)
return buildLogFile
def buildApp(self, target):
buildLog = None
if "buildLogDir" in self.config:
buildLog = self.prepareBuildLog(self.config["buildLogDir"], target)
cmd = "%s -w %s %s" %(self.config["batbuild"], self.config["stageDir"], self.config["targets"][target])
buildStatusFile = os.path.join(self.config["stageDir"], "trunk", "qooxdoo", "buildStatus.json")
self.buildStatus = self.getBuildStatusFromFile(buildStatusFile)
self.buildStatus[target] = {
"SVNRevision" : util.getSvnVersion(os.path.join(self.config["stageDir"], "trunk")),
"BuildError" : False,
"BuildStarted" : time.strftime(Builder.timeFormat),
"BuildFinished" : False
}
if "branch" in self.config:
self.buildStatus[target]["branch"] = self.config["branch"]
if (self.simulate):
if buildLog:
buildLog.write("Building target %s: %s" %(target, cmd))
buildLog.close()
return
if (self.config["buildLogLevel"] == "debug" and buildLog):
# Start build with full logging
util.invokeLog(cmd, buildLog)
buildLog.close()
return
# Start build, only log errors
self.buildAppWithErrorLogging(target, cmd, buildLog)
self.storeBuildStatus()
def buildAppWithErrorLogging(self, target, cmd, buildLog):
self.log.info("Building %s: %s" %(target,cmd))
status, std, err = util.invokePiped(cmd) #@UnusedVariable
if status > 0:
if buildLog:
self.logBuildErrors(buildLog, target, cmd, err)
buildLog.close()
self.buildStatus[target]["BuildError"] = "Unknown build error"
"""Get the last line of batbuild.py's STDERR output which contains
the actual error message. """
error = util.getLastLineFromString(err)
if error:
self.buildStatus[target]["BuildError"] = error
else:
self.log.info("%s build finished without errors." %target)
self.buildStatus[target]["BuildFinished"] = time.strftime(Builder.timeFormat)
def logBuildErrors(self, buildLogFile, target, cmd, err):
self.log.error("Error while building %s, see build log file for details." %target)
err = err.rstrip('\n')
err = err.rstrip('\r')
buildLogFile.write(target + "\n" + cmd + "\n" + err)
buildLogFile.write("\n========================================================\n\n")
def storeBuildStatus(self, path=None):
if not path:
path = os.path.join(self.config["stageDir"], "trunk", "qooxdoo")
jsonData = json.dumps(self.buildStatus, sort_keys=True, indent=2)
fPath = os.path.join(path,'buildStatus.json')
if (self.simulate):
self.log.debug("SIMULATION: Storing build status in file " + fPath)
else:
self.log.debug("Storing build status in file " + fPath)
rFile = codecs.open(fPath, 'w', 'utf-8')
rFile.write(jsonData)
rFile.close()
@classmethod
def getBuildStatusFromFile(cls, path=None):
buildStatus = {}
if not os.path.isfile(path):
return buildStatus
try:
statusFile = codecs.open(path, 'r', 'utf-8')
statusJson = statusFile.read()
except Exception, e:
log.Logger().warn("Unable to open build status file %s" %path)
try:
buildStatus = json.loads(statusJson)
log.Logger().debug("Build status retrieved from file %s" %path)
except Exception, e:
log.Logger().warn("Unable to parse build status from file %s" %path)
return buildStatus
def buildAll(self):
rootPath = os.path.join(self.config["stageDir"], "trunk", "qooxdoo")
if self.config["svnRevert"]:
util.svnRevert(rootPath)
if self.config["svnUpdate"]:
util.svnUpdate(rootPath)
self.log.info("Updated to revision %s" %util.getSvnVersion(rootPath))
self.log.info("Building all configured targets.")
for target in self.config["targets"]:
self.buildApp(target)
@classmethod
def testGenerator(cls, config):
initialPath = os.getcwd()
results = []
for test in config:
os.chdir(test["path"])
jobList = Builder.__getGeneratorJobs(test)
configOption = ""
if "config" in test:
configOption = " -c %s" %test["config"]
for job in jobList:
cmd = "python generate.py -s %s %s" %(configOption, job)
result = Builder.__getGeneratorResultDict(job, test["path"])
(ret,out,err) = util.invokePiped(cmd)
result["stopDate"] = util.getTimestamp()
result["command"] = cmd
result["returncode"] = ret
result["stdout"] = out
result["stderr"] = err
results.append(result)
os.chdir(initialPath)
return results
@classmethod
def __getGeneratorJobs(cls, test):
if "jobs" in test:
return test["jobs"]
elif "config" in test:
jobList = []
import re
cmd = "python generate.py -c %s x" %test["config"]
(ret,out,err) = util.invokePiped(cmd)
reg = re.compile("^ - (.+?)(?:\s|$)")
strParts = out.split("\n")
for part in strParts:
match = reg.search(part)
if match:
if match.group(1):
jobList.append(match.group(1))
return jobList
@classmethod
def __getGeneratorResultDict(cls, job, path):
result = {
"job" : job,
"path" : path,
"command" : False,
"startDate" : util.getTimestamp(),
"revision" : util.getSvnVersion(path),
"host" : util.getHostName(),
"stopDate" : False,
"returncode" : False,
"stdout" : False,
"stderr" : False
}
return result