forked from ikmdev/komet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile-workflow
330 lines (276 loc) · 13 KB
/
Jenkinsfile-workflow
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!groovy
@Library("titan-library") _
// Helper method to get feature branch name
def getBranchName(currentBranch, customBranch) {
if (currentBranch == "main" && customBranch.trim() == '') {
echo "Error: Please provide branch name"
fail()
}
def branchName = (currentBranch== 'main') ? "feature/${customBranch}" : currentBranch
return branchName.toString();
}
pipeline {
agent any
tools {
jdk "java-21"
maven "default"
git "git"
}
environment {
TRUNK_BRANCH_NAME = 'main'
REPO_NAME = "${GIT_URL.split('/')[4].split('\\.')[0]}"
BRANCH_NAME = "${GIT_BRANCH.startsWith('origin/') ? GIT_BRANCH['origin/'.length()..-1] : GIT_BRANCH}"
CUSTOM_BRANCH_NAME = " "
MERGE_REQUEST_EXIST = false
MERGE_REQUEST_ID = ""
MERGE_REQUEST_IID = ""
GITLAB_OWNER = "${GIT_URL.split('/')[3]}"
GITLAB_REPO = "https://gitlab.tinkarbuild.com/${GITLAB_OWNER}/${REPO_NAME}.git"
GITLAB_RELEASE_API = "https://gitlab.tinkarbuild.com/api/v4/projects/${GITLAB_OWNER}%2F${REPO_NAME}/releases"
GITLAB_CREDS_ID = 'vault-gitlab-user-pat'
GITLAB_MERGE_REQUEST_API = "https://gitlab.tinkarbuild.com/api/v4/projects/${GITLAB_OWNER}%2F${REPO_NAME}/merge_requests"
GITLAB_GET_OPEN_MERGE_REQUESTS_API = "${GITLAB_MERGE_REQUEST_API}/?state=opened"
TAG_VERSION = "1.0.1"
}
options {
buildDiscarder logRotator(
daysToKeepStr: '16',
numToKeepStr: '10'
)
disableConcurrentBuilds()
}
parameters {
choice(name: 'action', choices: ['Select An Action', 'start', 'finish'], description: 'Build Action. Start = starts/resumes feature , Finish = ends feature. Finish - feature branch must already exist.')
string(name: 'feature_branch', defaultValue: '', description: 'Name of branch without feature/ prefix. Must follow ABC-123_description format. ABC = JIRA prefix.')
}
stages {
stage('Setup') {
steps {
sh """
printenv
echo Action ${params.action}
"""
script {
pomModel = readMavenPom(file: 'pom.xml')
pomVersion = pomModel.getVersion()
isSnapshot = pomVersion.contains("-SNAPSHOT")
releaseVersion = pomVersion.split("-")[0]
}
}
}
stage ("Setup Parameters") {
when {
expression { return BRANCH_NAME.startsWith("feature/") }
expression { return params.action == ''}
}
steps{
script {
parameters([
choice(name: 'action', choices: ['Select An Action', 'start', 'finish'], description: 'Build Action. Start = starts/resumes feature , Finish = ends feature. Finish - feature branch must already exist.'),
string(name: 'feature_branch', defaultValue: '', description: 'Name of branch without feature/ prefix. Must follow ABC-123_description format. ABC = JIRA prefix.')
])
}
}
}
stage ("Get Branch Name"){
when {
expression { return params.action == 'start' || params.action == 'finish'}
}
steps {
echo "Getting Branch Name"
script {
def feature_name = feature_branch.replaceAll("/s", "_")
CUSTOM_BRANCH_NAME = getBranchName(BRANCH_NAME, feature_name)
}
echo "Done getting branch name: ${CUSTOM_BRANCH_NAME}"
}
}
stage ('If Merge Request Exist'){
when {
expression { return params.action == 'start' || params.action == 'finish'}
}
tools {
git 'git'
}
steps {
script {
withCredentials([usernamePassword(credentialsId: GITLAB_CREDS_ID, passwordVariable: 'token', usernameVariable: 'user')]) {
echo "GitLab User ${user}"
echo "Check if Merge Request exists For ${CUSTOM_BRANCH_NAME}"
def postResponse = sh(
script: """
curl -L \
-H "PRIVATE-TOKEN: ${token}" \
-H "Content-Type: application/json" \
-X GET \
${GITLAB_GET_OPEN_MERGE_REQUESTS_API}
""",
returnStdout: true
).trim()
echo "Done checking if Merge Requests exists for ${CUSTOM_BRANCH_NAME}"
def jsonPostResponse = readJSON text: postResponse
for (mergeRequest in jsonPostResponse) {
if(mergeRequest.source_branch == "${CUSTOM_BRANCH_NAME}"){
MERGE_REQUEST_EXIST = true
MERGE_REQUEST_ID = mergeRequest.id
MERGE_REQUEST_IID = mergeRequest.iid
}
}
echo "Merge Request Exists: ${MERGE_REQUEST_EXIST}"
}
}
}
}
stage('Start Branch') {
when {
branch 'main'
expression { return params.action == 'start' }
expression { return params.feature_branch }
}
steps {
withCredentials([gitUsernamePassword(credentialsId: GITLAB_CREDS_ID, gitToolName: 'git')]) {
sh """
git checkout main
git pull -p
git checkout -b ${CUSTOM_BRANCH_NAME}
mvn versions:set -DnewVersion=${releaseVersion}-${params.feature_branch}-SNAPSHOT -DgenerateBackupPoms=false
git commit -am "Draft: Update feature version to ${releaseVersion}-${params.feature_branch}-SNAPSHOT"
git push -u origin ${CUSTOM_BRANCH_NAME}
"""
}
}
}
// Starting Stage For Feature Branch Only
stage('Start Branch -- Feature Branch') {
when {
expression { return BRANCH_NAME.startsWith('feature/')}
expression { return params.action == 'start'}
}
steps {
script {
FEATURE_BRANCH_NAME = "${BRANCH_NAME.split("/")[1]}"
}
withCredentials([gitUsernamePassword(credentialsId: GITLAB_CREDS_ID, gitToolName: 'git')]) {
sh """
git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git config --get remote.origin.fetch
echo Start Branch -- Feature Branch
echo ${BRANCH_NAME}
git checkout ${BRANCH_NAME}
mvn versions:set -DnewVersion=${releaseVersion}-${FEATURE_BRANCH_NAME}-SNAPSHOT -DgenerateBackupPoms=false
git commit -am "Draft: Update feature version to ${releaseVersion}-${FEATURE_BRANCH_NAME}-SNAPSHOT"
git push origin ${BRANCH_NAME}
"""
}
}
}
stage ('Create GitLab Merge Request'){
when {
expression { return params.action == 'start' }
expression { return MERGE_REQUEST_EXIST == 'false' }
}
tools {
git 'git'
}
steps {
script {
withCredentials([usernamePassword(credentialsId: GITLAB_CREDS_ID, passwordVariable: 'token', usernameVariable: 'user')]) {
echo "GitLab User ${user}"
echo "Create Merge Request For ${CUSTOM_BRANCH_NAME}"
def data = "{\"title\": \"Draft: ${CUSTOM_BRANCH_NAME}\",\"source_branch\": " +
"\"${CUSTOM_BRANCH_NAME}\", \"description\": \"Currently work in progress for ${CUSTOM_BRANCH_NAME}\", " +
"\"target_branch\" : \"${TRUNK_BRANCH_NAME}\" }"
def postResponse = sh(
script: """
curl -L \
-H "PRIVATE-TOKEN: ${token}" \
-H "Content-Type: application/json" \
-X POST \
--data '${data}' \
${GITLAB_MERGE_REQUEST_API}
""",
returnStdout: true
).trim()
echo "Done creating Merge Request For ${CUSTOM_BRANCH_NAME}"
def jsonPostResponse = readJSON text: postResponse
echo "${jsonPostResponse}"
}
}
}
}
stage('End Branch') {
when {
expression { return params.action == 'finish' }
}
steps {
script{
withCredentials([gitUsernamePassword(credentialsId: GITLAB_CREDS_ID, gitToolName: 'git')]) {
if (MERGE_REQUEST_EXIST == 'false'){
echo "Error: Merge request does not exist for ${CUSTOM_BRANCH_NAME}"
fail()
}
def checkoutBranch = (BRANCH_NAME == 'main') ? TRUNK_BRANCH_NAME : CUSTOM_BRANCH_NAME
sh """
echo Finish Action For ${CUSTOM_BRANCH_NAME}
git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git config --get remote.origin.fetch
git checkout ${checkoutBranch}
git pull -p
git checkout ${CUSTOM_BRANCH_NAME}
mvn versions:set -DnewVersion=${releaseVersion}-SNAPSHOT -DgenerateBackupPoms=false
git commit -am "Branch Ready For Review - Reverted back to original snapshot version ${releaseVersion}-SNAPSHOT"
git push origin ${CUSTOM_BRANCH_NAME}
"""
}
}
}
}
stage ('Update Merge Request'){
when {
expression { return params.action == 'finish' || (params.action == 'start' && BRANCH_NAME.startsWith('feature/'))}
expression { return MERGE_REQUEST_EXIST == true}
}
tools {
git 'git'
}
steps {
script {
withCredentials([usernamePassword(credentialsId: GITLAB_CREDS_ID, passwordVariable: 'token', usernameVariable: 'user')]) {
echo "GitLab User ${user}"
echo "Updating Merge Request For ${CUSTOM_BRANCH_NAME}"
def mergeRequestTitle = mergeRequestDescription = "Ready For Review: ${CUSTOM_BRANCH_NAME}".toString()
if(params.action == 'start' && BRANCH_NAME.startsWith('feature/')){
mergeRequestTitle = "Draft: ${CUSTOM_BRANCH_NAME}"
mergeRequestDescription = "Currently work in progress for ${CUSTOM_BRANCH_NAME}"
}
def data = "{\"title\": \"${mergeRequestTitle}\", \"description\": \"${mergeRequestDescription}\"}"
def postResponse = sh(
script: """
curl -L \
-H "PRIVATE-TOKEN: ${token}" \
-H "Content-Type: application/json" \
-X PUT \
--data '${data}' \
"https://gitlab.tinkarbuild.com/api/v4/projects/${GITLAB_OWNER}%2F${REPO_NAME}/merge_requests/${MERGE_REQUEST_IID}"
""",
returnStdout: true
).trim()
echo "Done updating Merge Request For ${CUSTOM_BRANCH_NAME}"
def jsonPostResponse = readJSON text: postResponse
echo "${jsonPostResponse}"
}
}
}
}
stage('Cleanup Workspace') {
steps {
cleanWs()
sh """
echo "${env.BRANCH_NAME}"
echo branch "${CUSTOM_BRANCH_NAME}"
echo "${currentBuild.buildCauses}"
"""
}
}
}
}