-
Notifications
You must be signed in to change notification settings - Fork 4
/
maven-to-freestyle.groovy
291 lines (217 loc) · 8.41 KB
/
maven-to-freestyle.groovy
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/**
maven-to-freestyle.groovy
See https://github.com/akomakom/jenkins-scripts for details
This script converts Maven jobs that rely on unsupported JDK version (1.6 and 1.7) to FreeStyle jobs.
It is meant to be run as a System Groovy Script
Configuration options (via jenkins job parameters)
DRY_RUN (boolean) - do not make changes
MODE (choice) - Possible values:
RENAME: rename matching jobs to "DEPRECATED-X", create new jobs with the original name (some relationships may point to disabled jobs)
DELETE: delete old job, then create new one with the old name. Solves wrong project relationship issues. Back up everything!
KEEP: leave the old job alone, create new jobs named "X.new"
DISABLE (boolean) - disable old job after processing.
DISABLE=false and MODE=keep will allow this script be run over and over while testing
FOLDER (string) - restrict processing to the named folder (Cloudbees Folder Plugin). Use "TOP" to disable folder processing (top-level only).
VIEW (string) - restrict processing to items in the named view. Use DRY_RUN to check what will be processed
What this actually does:
1) moves maven job's prebuilders to steps
2) moves the main maven configuration to a maven build step (some config is lost as it's not supported)
3) moves maven job's postbuilders to steps
4) keeps everything else the same, including publishers, properties, etc.
5) attempts to take any maven-inferred downstream releationships (pom dependencies) and keep them
as static job relationships for the new jobs. Note that in KEEP mode, these relationships will point to the original name.
NOTE: JDK names are hardcoded below!
*/
import groovy.xml.*;
import hudson.model.*;
import hudson.maven.*;
import jenkins.model.*;
import jenkins.maven.*;
import hudson.*;
def makeChanges = (build.buildVariableResolver.resolve("DRY_RUN") == "false")
def mode = build.buildVariableResolver.resolve("MODE")
def disable = (build.buildVariableResolver.resolve("DISABLE") == "true")
def restrictToFolder = build.buildVariableResolver.resolve("FOLDER")
def restrictToView = build.buildVariableResolver.resolve("VIEW")
if (!makeChanges) {
println "\n\nDry run mode, add boolean build param 'DRY_RUN' to control\n\n"
}
println "MODE is ${mode}, disable old jobs is ${disable}"
def selectFrom = Jenkins.instance.allItems
def createIn
if (restrictToFolder != null && restrictToFolder != '') {
if (restrictToFolder == 'TOP') {
selectFrom = Jenkins.instance.items
println "Restricting execution to the top level and ignoring folders"
} else {
def folder = Jenkins.instance.getItemByFullName(restrictToFolder)
if (folder == null) {
println "Folder not found"
return
}
selectFrom = folder.items
println "Restricting execution to folder ${restrictToFolder}, found ${selectFrom.size()} items"
}
} else if (restrictToView != null && restrictToView != '') {
def view = Hudson.instance.getView(restrictToView)
if(view == null) {
println "View ${restrictToView} not found"
return
}
selectFrom = view.getItems()
println "Restricting execution to view ${restrictToView}, found ${selectFrom.size()} items"
}
def count = 0
selectFrom.findAll{job -> job instanceof MavenModuleSet && job.JDK && (job.JDK.name.indexOf('1.6') || job.JDK.name.indexOf('1.7')) > 0 && !job.isDisabled() }.each{
job ->
count++
println("\nBegin Processing ${job.fullName}")
oldName = job.name
createIn = job.parent
xml = getModifiedXml(job)
// write old and new configurations to files for historical reference
getWorkspaceFile("${job.name}-config.old.xml").write(job.getConfigFile().asString(), null)
getWorkspaceFile("${job.name}-config.new.xml").write(xml, null)
println "Processed ${job.fullName}, new xml size is ${xml.length()}"
if (makeChanges) {
switch(mode) {
case 'DELETE':
job.delete()
newName = oldName
break
case 'RENAME':
newName = oldName
//rename old job
job.renameTo("DEPRECATED-${job.name}")
break
case 'KEEP':
newName = "${oldName}.new"
existingNewJob = createIn.getItem(newName)
if (existingNewJob) {
println "Job ${newName} already exists, deleting"
existingNewJob.delete()
}
break
default:
println "Unknown mode '${mode}', please add build param MODE. Supported choices: RENAME,KEEP"
return
}
if (disable) {
job.makeDisabled(true)
}
//now
//push to a new job (can't overwrite with different job type)
inputStream = new StringBufferInputStream(xml)
createIn.createProjectFromXML(newName, inputStream)
println "(Renamed?) and converted ${oldName} to ${newName}"
}
}
println "\nProcessing completed, ${count} jobs visited\n\n"
def getModifiedXml(job) {
def parser = new XmlParser()
def response = parser.parse(job.getConfigFile().readRaw())
builders = response.appendNode(new QName('builders'), [:])
// Move prebuilders to builders
if (response.prebuilders && response.prebuilders[0]) {
response.prebuilders[0].children().each{ step ->
builders.append(step)
}
response.remove(response.prebuilders[0])
}
//Create a maven block
mavenNode = builders.appendNode(
new QName("hudson.tasks.Maven"),
[:]
)
//mavenNode.appendNode(new QName('targets'), [:], response.goals[0].value())
move(response.goals[0], mavenNode, 'targets')
move(response.mavenName[0], mavenNode)
if (response.rootPOM) {
move(response.rootPOM[0], mavenNode, 'pom')
}
if (response.mavenOpts) {
move(response.mavenOpts[0], mavenNode, 'jvmOptions')
}
move(response.settings[0], mavenNode)
move(response.globalSettings[0], mavenNode)
//items that don't exist in maven step:
remove(response, [
'resolveDependencies',
'processPlugins',
'siteArchivingDisabled',
'archivingDisabled',
'mavenValidationLevel',
'disableTriggerDownstreamProjects',
'blockTriggerWhenBuilding',
'fingerprintingDisabled',
'incrementalBuild',
'processPlugins',
'siteArchivingDisabled',
'ignoreUpstremChanges',
'rootModule'
])
// Move postbuilders to builders
if (response.postbuilders && response.postbuilders[0]) {
response.postbuilders[0].children().each{ step ->
builders.append(step)
}
response.remove(response.postbuilders[0])
}
// If there are any inferred relationships with other maven projects,
// convert them to hard relationships (permanently)
// This may result in duplicate BuildTrigger's if job had an explicit one already.
makeBuildTriggerNode(job.getDownstreamProjects(), response.publishers[0])
response.description[0].setValue(response.description[0].value + " Job was converted from a Maven project on ${new Date()}. Any maven job relationships were converted to build triggers.")
//rename top-level element
//new parent node
newDoc = new groovy.util.Node(null, 'project')
response.children().each{ c ->
newDoc.append(c)
}
//println XmlUtil.serialize(newDoc)
//println response.text()
return XmlUtil.serialize(newDoc)
}
def makeBuildTriggerNode(downstreamJobs, appendTo) {
if (downstreamJobs.size() == 0) {
return;
}
jobNames = []
downstreamJobs.each{ job ->
jobNames << job.name
}
root = new groovy.util.Node(appendTo, "hudson.tasks.BuildTrigger")
new groovy.util.Node(root, 'childProjects', jobNames.join(', '))
// not adding the rest of the values since defaults should work?
return root;
}
def remove(from, listOfNames) {
//println from.children().findAll { listOfNames.contains(it.name()) }
from.children().findAll { listOfNames.contains(it.name()) }.each{node ->
//println "Removing: ${node.name()}"
from.remove(node)
}
}
def move(from, to, toName = null) {
// if source is null, we don't need to do anything
if (from) {
if (toName == null) {
//just move it, no name change
from.parent().remove(from)
to.append(from)
} else {
to.appendNode(new QName(toName), from.attributes(), from.value())
from.parent().remove(from)
}
}
}
def getWorkspaceFile(name) {
if(build.workspace.isRemote())
{
channel = build.workspace.channel;
fp = new FilePath(channel, build.workspace.toString() + "/" + name)
} else {
fp = new FilePath(new File(build.workspace.toString() + "/" + name))
}
return fp
}