blob: a48f5540118657c4e977a59b345b6a8d8f1b20d9 [file] [log] [blame]
Jakub Josef1b75ca82017-02-20 16:08:13 +01001package com.mirantis.mk
Jakub Josefc70c2a32017-03-29 16:38:30 +02002import java.util.regex.Pattern
Jakub Josefec5098f2017-06-15 18:15:32 +02003import com.cloudbees.groovy.cps.NonCPS
4import com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.GerritCause
Jakub Josef1b75ca82017-02-20 16:08:13 +01005/**
6 * Gerrit functions
7 *
8 */
9
10/**
11 * Execute git clone and checkout stage from gerrit review
12 *
13 * @param config LinkedHashMap
14 * config includes next parameters:
15 * - credentialsId, id of user which should make checkout
Jakub Josefbccd7862017-05-30 14:27:15 +020016 * - withMerge, merge master before build
17 * - withLocalBranch, prevent detached mode in repo
Jakub Josef1b75ca82017-02-20 16:08:13 +010018 * - withWipeOut, wipe repository and force clone
azvyagintseved1d63e2018-09-10 14:25:13 +030019 * - GerritTriggerBuildChooser - use magic GerritTriggerBuildChooser class from gerrit-trigger-plugin.
20 * By default,enabled.
Jakub Josefbccd7862017-05-30 14:27:15 +020021 * Gerrit properties like GERRIT_SCHEMA can be passed in config as gerritSchema or will be obtained from env
22 * @param extraScmExtensions list of extra scm extensions which will be used for checkout (optional)
Jakub Josefc70c2a32017-03-29 16:38:30 +020023 * @return boolean result
Jakub Josef1b75ca82017-02-20 16:08:13 +010024 *
25 * Usage example:
26 * //anonymous gerrit checkout
27 * def gitFunc = new com.mirantis.mcp.Git()
28 * gitFunc.gerritPatchsetCheckout([
29 * withMerge : true
30 * ])
31 *
32 * def gitFunc = new com.mirantis.mcp.Git()
33 * gitFunc.gerritPatchsetCheckout([
34 * credentialsId : 'mcp-ci-gerrit',
35 * withMerge : true
36 * ])
37 */
Jakub Josefbccd7862017-05-30 14:27:15 +020038def gerritPatchsetCheckout(LinkedHashMap config, List extraScmExtensions = []) {
Jakub Josef1b75ca82017-02-20 16:08:13 +010039 def merge = config.get('withMerge', false)
40 def wipe = config.get('withWipeOut', false)
Jakub Josefbccd7862017-05-30 14:27:15 +020041 def localBranch = config.get('withLocalBranch', false)
Jakub Josef1b75ca82017-02-20 16:08:13 +010042 def credentials = config.get('credentialsId','')
Jakub Josef71c46a62017-03-29 14:55:33 +020043 def gerritScheme = config.get('gerritScheme', env["GERRIT_SCHEME"] ? env["GERRIT_SCHEME"] : "")
44 def gerritRefSpec = config.get('gerritRefSpec', env["GERRIT_REFSPEC"] ? env["GERRIT_REFSPEC"] : "")
45 def gerritName = config.get('gerritName', env["GERRIT_NAME"] ? env["GERRIT_NAME"] : "")
46 def gerritHost = config.get('gerritHost', env["GERRIT_HOST"] ? env["GERRIT_HOST"] : "")
47 def gerritPort = config.get('gerritPort', env["GERRIT_PORT"] ? env["GERRIT_PORT"] : "")
48 def gerritProject = config.get('gerritProject', env["GERRIT_PROJECT"] ? env["GERRIT_PROJECT"] : "")
49 def gerritBranch = config.get('gerritBranch', env["GERRIT_BRANCH"] ? env["GERRIT_BRANCH"] : "")
chnyda96a1e8a2017-03-28 16:02:13 +020050 def path = config.get('path', "")
chnyda7d25fc92017-03-29 10:51:59 +020051 def depth = config.get('depth', 0)
52 def timeout = config.get('timeout', 20)
azvyagintseved1d63e2018-09-10 14:25:13 +030053 def GerritTriggerBuildChooser = config.get('useGerritTriggerBuildChooser', true)
Jakub Josef1b75ca82017-02-20 16:08:13 +010054
Dmitry Pyzhov169f8122017-12-06 14:44:41 +030055 def invalidParams = _getInvalidGerritParams(config)
56 if (invalidParams.isEmpty()) {
Jakub Josefc70c2a32017-03-29 16:38:30 +020057 // default parameters
58 def scmExtensions = [
59 [$class: 'CleanCheckout'],
Jakub Josefc70c2a32017-03-29 16:38:30 +020060 [$class: 'CheckoutOption', timeout: timeout],
61 [$class: 'CloneOption', depth: depth, noTags: false, reference: '', shallow: depth > 0, timeout: timeout]
62 ]
63 def scmUserRemoteConfigs = [
64 name: 'gerrit',
Jakub Josefc70c2a32017-03-29 16:38:30 +020065 ]
Jakub Josef30fc9212017-04-04 11:47:19 +020066 if(gerritRefSpec && gerritRefSpec != ""){
67 scmUserRemoteConfigs.put('refspec', gerritRefSpec)
68 }
Jakub Josef1b75ca82017-02-20 16:08:13 +010069
Jakub Josefc70c2a32017-03-29 16:38:30 +020070 if (credentials == '') {
71 // then try to checkout in anonymous mode
72 scmUserRemoteConfigs.put('url',"${gerritScheme}://${gerritHost}/${gerritProject}")
73 } else {
74 // else use ssh checkout
75 scmUserRemoteConfigs.put('url',"ssh://${gerritName}@${gerritHost}:${gerritPort}/${gerritProject}.git")
76 scmUserRemoteConfigs.put('credentialsId',credentials)
77 }
Jakub Josef1b75ca82017-02-20 16:08:13 +010078
azvyagintseved1d63e2018-09-10 14:25:13 +030079 // Usefull, if we only need to clone branch. W\o any refspec magic
80 if (GerritTriggerBuildChooser) {
81 scmExtensions.add([$class: 'BuildChooserSetting', buildChooser: [$class: 'GerritTriggerBuildChooser']],)
82 }
83
Jakub Josefc70c2a32017-03-29 16:38:30 +020084 // if we need to "merge" code from patchset to GERRIT_BRANCH branch
85 if (merge) {
vnaumov37b735d2018-08-27 16:55:07 +040086 scmExtensions.add([$class: 'PreBuildMerge', options: [fastForwardMode: 'FF', mergeRemote: 'gerrit', mergeStrategy: 'DEFAULT', mergeTarget: gerritBranch]])
Jakub Josefc70c2a32017-03-29 16:38:30 +020087 }
88 // we need wipe workspace before checkout
89 if (wipe) {
90 scmExtensions.add([$class: 'WipeWorkspace'])
91 }
Jakub Josef1b75ca82017-02-20 16:08:13 +010092
Jakub Josefbccd7862017-05-30 14:27:15 +020093 if(localBranch){
94 scmExtensions.add([$class: 'LocalBranch', localBranch: gerritBranch])
95 }
96
97 if(!extraScmExtensions.isEmpty()){
98 scmExtensions.addAll(extraScmExtensions)
99 }
Jakub Josefc70c2a32017-03-29 16:38:30 +0200100 if (path == "") {
chnyda96a1e8a2017-03-28 16:02:13 +0200101 checkout(
102 scm: [
103 $class: 'GitSCM',
104 branches: [[name: "${gerritBranch}"]],
105 extensions: scmExtensions,
106 userRemoteConfigs: [scmUserRemoteConfigs]
107 ]
108 )
Jakub Josefc70c2a32017-03-29 16:38:30 +0200109 } else {
110 dir(path) {
111 checkout(
112 scm: [
113 $class: 'GitSCM',
114 branches: [[name: "${gerritBranch}"]],
115 extensions: scmExtensions,
116 userRemoteConfigs: [scmUserRemoteConfigs]
117 ]
118 )
119 }
chnyda96a1e8a2017-03-28 16:02:13 +0200120 }
Jakub Josefc70c2a32017-03-29 16:38:30 +0200121 return true
Jakub Josef73d62142017-03-29 17:07:18 +0200122 }else{
Dmitry Pyzhov169f8122017-12-06 14:44:41 +0300123 throw new Exception("Cannot perform gerrit checkout, missed config options: " + invalidParams)
chnyda96a1e8a2017-03-28 16:02:13 +0200124 }
Jakub Josef30fc9212017-04-04 11:47:19 +0200125 return false
Jakub Josefc70c2a32017-03-29 16:38:30 +0200126}
127/**
128 * Execute git clone and checkout stage from gerrit review
129 *
Jakub Josefad34dbf2017-03-29 17:52:31 +0200130 * @param gerritUrl gerrit url with scheme
Jakub Josefc70c2a32017-03-29 16:38:30 +0200131 * "${GERRIT_SCHEME}://${GERRIT_NAME}@${GERRIT_HOST}:${GERRIT_PORT}/${GERRIT_PROJECT}.git
Jakub Josefad34dbf2017-03-29 17:52:31 +0200132 * @param gerritRef gerrit ref spec
133 * @param gerritBranch gerrit branch
134 * @param credentialsId jenkins credentials id
Dmitry Pyzhove832b0a2017-12-06 14:43:25 +0300135 * @param path checkout path, optional, default is empty string which means workspace root
Jakub Josefc70c2a32017-03-29 16:38:30 +0200136 * @return boolean result
137 */
Dmitry Pyzhove832b0a2017-12-06 14:43:25 +0300138def gerritPatchsetCheckout(gerritUrl, gerritRef, gerritBranch, credentialsId, path="") {
Jakub Josefad34dbf2017-03-29 17:52:31 +0200139 def gerritParams = _getGerritParamsFromUrl(gerritUrl)
Jakub Josefd383f392017-03-29 16:52:04 +0200140 if(gerritParams.size() == 5){
Dmitry Pyzhove832b0a2017-12-06 14:43:25 +0300141 if (path==""){
142 gerritPatchsetCheckout([
143 credentialsId : credentialsId,
144 gerritBranch: gerritBranch,
145 gerritRefSpec: gerritRef,
146 gerritScheme: gerritParams[0],
147 gerritName: gerritParams[1],
148 gerritHost: gerritParams[2],
149 gerritPort: gerritParams[3],
150 gerritProject: gerritParams[4]
151 ])
152 return true
153 } else {
154 dir(path) {
155 gerritPatchsetCheckout([
156 credentialsId : credentialsId,
157 gerritBranch: gerritBranch,
158 gerritRefSpec: gerritRef,
159 gerritScheme: gerritParams[0],
160 gerritName: gerritParams[1],
161 gerritHost: gerritParams[2],
162 gerritPort: gerritParams[3],
163 gerritProject: gerritParams[4]
164 ])
165 return true
166 }
167 }
Jakub Josefc70c2a32017-03-29 16:38:30 +0200168 }
169 return false
170}
171
Jakub Josef50c9c3a2017-04-10 14:32:35 +0200172/**
173 * Return gerrit change object from gerrit API
Jakub Josef50c9c3a2017-04-10 14:32:35 +0200174 * @param gerritName gerrit user name (usually GERRIT_NAME property)
Jakub Josefb735dd42017-04-10 15:31:19 +0200175 * @param gerritHost gerrit host (usually GERRIT_HOST property)
Sergey Otpuschennikov8d1aec12020-06-17 00:54:07 +0400176 * @param gerritPort gerrit port (usually GERRIT_PORT property, default 29418)
Jakub Josef50c9c3a2017-04-10 14:32:35 +0200177 * @param gerritChangeNumber gerrit change number (usually GERRIT_CHANGE_NUMBER property)
178 * @param credentialsId jenkins credentials id for gerrit
Jakub Josef5aa33de2017-06-16 12:23:45 +0200179 * @param includeCurrentPatchset do you want to include current (last) patchset
Jakub Josef50c9c3a2017-04-10 14:32:35 +0200180 * @return gerrit change object
181 */
Sergey Otpuschennikov8d1aec12020-06-17 00:54:07 +0400182def getGerritChange(gerritName, gerritHost, gerritChangeNumber, credentialsId, includeCurrentPatchset = false, gerritPort = '29418'){
Jakub Josef50c9c3a2017-04-10 14:32:35 +0200183 def common = new com.mirantis.mk.Common()
184 def ssh = new com.mirantis.mk.Ssh()
185 ssh.prepareSshAgentKey(credentialsId)
Sergey Otpuschennikov8d1aec12020-06-17 00:54:07 +0400186 ssh.ensureKnownHosts("${gerritHost}:${gerritPort}")
Jakub Josef5aa33de2017-06-16 12:23:45 +0200187 def curPatchset = "";
188 if(includeCurrentPatchset){
189 curPatchset = "--current-patch-set"
190 }
Dmitry Burmistrov066f3d42022-10-28 15:49:33 +0400191 return common.parseJSON(ssh.agentSh(String.format("ssh -p %s %s@%s gerrit query ${curPatchset} --commit-message --format=JSON change:%s", gerritPort, gerritName, gerritHost, gerritChangeNumber)))
Jakub Josef50c9c3a2017-04-10 14:32:35 +0200192}
193
Jakub Josef4edd7432017-05-10 17:58:56 +0200194/**
195 * Returns list of Gerrit trigger requested builds
196 * @param allBuilds list of all builds of some job
197 * @param gerritChange gerrit change number
198 * @param excludePatchset gerrit patchset number which will be excluded from builds, optional null
199 */
200@NonCPS
201def getGerritTriggeredBuilds(allBuilds, gerritChange, excludePatchset = null){
202 return allBuilds.findAll{job ->
203 def cause = job.causes[0]
Jakub Josefec5098f2017-06-15 18:15:32 +0200204 if(cause instanceof GerritCause &&
Denis Egorenkof0568dd2019-01-16 13:53:34 +0400205 (cause.getEvent() instanceof com.sonymobile.tools.gerrit.gerritevents.dto.events.PatchsetCreated ||
206 cause.getEvent() instanceof com.sonymobile.tools.gerrit.gerritevents.dto.events.CommentAdded)) {
Jakub Josef4edd7432017-05-10 17:58:56 +0200207 if(excludePatchset == null || excludePatchset == 0){
208 return cause.event.change.number.equals(String.valueOf(gerritChange))
209 }else{
210 return cause.event.change.number.equals(String.valueOf(gerritChange)) && !cause.event.patchSet.number.equals(String.valueOf(excludePatchset))
211 }
212 }
213 return false
214 }
215}
Jakub Josef62899fd2017-06-15 18:53:46 +0200216/**
Jakub Josef5aa33de2017-06-16 12:23:45 +0200217 * Returns boolean result of test given gerrit patchset for given approval type and value
218 * @param patchset gerrit patchset
Jakub Josef62899fd2017-06-15 18:53:46 +0200219 * @param approvalType type of tested approval (optional, default Verified)
Jakub Josef798bfc52017-06-16 12:44:23 +0200220 * @param approvalValue value of tested approval (optional, default empty string which means any value)
Jakub Josef62899fd2017-06-15 18:53:46 +0200221 * @return boolean result
Jakub Josef5aa33de2017-06-16 12:23:45 +0200222 * @example patchsetHasApproval(gerrit.getGerritChange(*,*,*,*, true).currentPatchSet)
Jakub Josef62899fd2017-06-15 18:53:46 +0200223 */
Jakub Josef5aa33de2017-06-16 12:23:45 +0200224@NonCPS
Jakub Josef798bfc52017-06-16 12:44:23 +0200225def patchsetHasApproval(patchSet, approvalType="Verified", approvalValue = ""){
Jakub Josef5aa33de2017-06-16 12:23:45 +0200226 if(patchSet && patchSet.approvals){
227 for(int i=0; i < patchSet.approvals.size();i++){
228 def approval = patchSet.approvals.get(i)
Jakub Josef798bfc52017-06-16 12:44:23 +0200229 if(approval.type.equals(approvalType)){
230 if(approvalValue.equals("") || approval.value.equals(approvalValue)){
231 return true
Jakub Josef996ada82017-06-16 12:59:43 +0200232 }else if(approvalValue.equals("+") && Integer.parseInt(approval.value) > 0) {
233 return true
234 }else if(approvalValue.equals("-") && Integer.parseInt(approval.value) < 0) {
235 return true
Jakub Josef798bfc52017-06-16 12:44:23 +0200236 }
Jakub Josef5aa33de2017-06-16 12:23:45 +0200237 }
238 }
Jakub Josef62899fd2017-06-15 18:53:46 +0200239 }
240 return false
241}
Jakub Josef4edd7432017-05-10 17:58:56 +0200242
Jakub Josefd383f392017-03-29 16:52:04 +0200243@NonCPS
244def _getGerritParamsFromUrl(gitUrl){
245 def gitUrlPattern = Pattern.compile("(.+):\\/\\/(.+)@(.+):(.+)\\/(.+)")
246 def gitUrlMatcher = gitUrlPattern.matcher(gitUrl)
247 if(gitUrlMatcher.find() && gitUrlMatcher.groupCount() == 5){
248 return [gitUrlMatcher.group(1),gitUrlMatcher.group(2),gitUrlMatcher.group(3),gitUrlMatcher.group(4),gitUrlMatcher.group(5)]
249 }
250 return []
251}
252
Dmitry Pyzhov169f8122017-12-06 14:44:41 +0300253def _getInvalidGerritParams(LinkedHashMap config){
254 def requiredParams = ["gerritScheme", "gerritName", "gerritHost", "gerritPort", "gerritProject", "gerritBranch"]
255 def missedParams = requiredParams - config.keySet()
256 def badParams = config.subMap(requiredParams).findAll{it.value in [null, '']}.keySet()
257 return badParams + missedParams
vnaumov37b735d2018-08-27 16:55:07 +0400258}
Denis Egorenko3253f462018-12-05 19:05:41 +0400259
260/**
261 * Post Gerrit comment from CI user
262 *
263 * @param config map which contains next params:
264 * gerritName - gerrit user name (usually GERRIT_NAME property)
265 * gerritHost - gerrit host (usually GERRIT_HOST property)
266 * gerritChangeNumber - gerrit change number (usually GERRIT_CHANGE_NUMBER property)
267 * gerritPatchSetNumber - gerrit patch set number (usually GERRIT_PATCHSET_NUMBER property)
268 * message - message to send to gerrit review patch
269 * credentialsId - jenkins credentials id for gerrit
270 */
271def postGerritComment(LinkedHashMap config) {
272 def common = new com.mirantis.mk.Common()
273 def ssh = new com.mirantis.mk.Ssh()
274 String gerritName = config.get('gerritName')
275 String gerritHost = config.get('gerritHost')
276 String gerritChangeNumber = config.get('gerritChangeNumber')
277 String gerritPatchSetNumber = config.get('gerritPatchSetNumber')
278 String message = config.get('message')
279 String credentialsId = config.get('credentialsId')
280
281 ssh.prepareSshAgentKey(credentialsId)
282 ssh.ensureKnownHosts(gerritHost)
283 ssh.agentSh(String.format("ssh -p 29418 %s@%s gerrit review %s,%s -m \"'%s'\" --code-review 0", gerritName, gerritHost, gerritChangeNumber, gerritPatchSetNumber, message))
284}
Denis Egorenko26da6c12018-11-16 14:38:42 +0400285
286/**
287 * Return map of dependent patches info for current patch set
288 * based on commit message hints: Depends-On: https://gerrit_address/_CHANGE_NUMBER_
289 * @param changeInfo Map Info about current patch set, such as:
290 * gerritName Gerrit user name (usually GERRIT_NAME property)
291 * gerritHost Gerrit host (usually GERRIT_HOST property)
292 * gerritChangeNumber Gerrit change number (usually GERRIT_CHANGE_NUMBER property)
293 * credentialsId Jenkins credentials id for gerrit
294 * @return map of dependent patches info
295 */
296LinkedHashMap getDependentPatches(LinkedHashMap changeInfo) {
297 def dependentPatches = [:]
Anna Arhipova1b3d3672022-10-24 14:32:38 +0200298 def dependentCommits = changeInfo.gerritCommitMessage.tokenize('\n').findAll { it ==~ /Depends-On: \b[^ ]+\b(\/)?/ }
Denis Egorenko26da6c12018-11-16 14:38:42 +0400299 if (dependentCommits) {
300 dependentCommits.each { commit ->
301 def patchLink = commit.tokenize(' ')[1]
302 def changeNumber = patchLink.tokenize('/')[-1].trim()
303 def dependentCommit = getGerritChange(changeInfo.gerritName, changeInfo.gerritHost, changeNumber, changeInfo.credentialsId, true)
304 if (dependentCommit.status == "NEW") {
305 dependentPatches[dependentCommit.project] = [
306 'number': dependentCommit.number,
307 'ref': dependentCommit.currentPatchSet.ref,
308 'branch': dependentCommit.branch,
309 ]
310 }
311 }
312 }
313 return dependentPatches
314}
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300315
316/**
317 * Find Gerrit change(s) according to various input parameters like owner, topic, etc.
318 * @param gerritAuth A map containing information about Gerrit. Should include
319 * HOST, PORT and USER
320 * @param changeParams Parameters to identify Geriit change e.g.: owner, topic,
321 * status, branch, project
Alexandr Lovtsov5d22b2d2020-12-16 14:52:57 +0300322 * @param extraFlags Additional flags for gerrit querry for example
323 * '--current-patch-set' or '--comments' as a simple string
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300324 */
Alexandr Lovtsov5d22b2d2020-12-16 14:52:57 +0300325def findGerritChange(credentialsId, LinkedHashMap gerritAuth, LinkedHashMap changeParams, String extraFlags = '') {
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300326 scriptText = """
327 ssh -p ${gerritAuth['PORT']} ${gerritAuth['USER']}@${gerritAuth['HOST']} \
Alexandr Lovtsov5d22b2d2020-12-16 14:52:57 +0300328 gerrit query ${extraFlags} \
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300329 --format JSON \
330 """
331 changeParams.each {
332 scriptText += " ${it.key}:${it.value}"
333 }
334 scriptText += " | fgrep -v runTimeMilliseconds || :"
335 sshagent([credentialsId]) {
336 jsonChange = sh(
337 script:scriptText,
338 returnStdout: true,
339 ).trim()
340 }
341 return jsonChange
342}
343
344/**
345 * Download Gerrit review by number
346 *
347 * @param credentialsId credentials ID
348 * @param virtualenv virtualenv path
349 * @param repoDir repository directory
350 * @param gitRemote the value of git remote
351 * @param changeNum the number of change to download
352 */
353def getGerritChangeByNum(credentialsId, virtualEnv, repoDir, gitRemote, changeNum) {
354 def python = new com.mirantis.mk.Python()
355 sshagent([credentialsId]) {
356 dir(repoDir) {
357 python.runVirtualenvCommand(virtualEnv, "git review -r ${gitRemote} -d ${changeNum}")
358 }
359 }
360}
361
362/**
363 * Post Gerrit review
364 * @param credentialsId credentials ID
365 * @param virtualenv virtualenv path
366 * @param repoDir repository directory
367 * @param gitName committer name
368 * @param gitEmail committer email
369 * @param gitRemote the value of git remote
370 * @param gitTopic the name of the topic
371 * @param gitBranch the name of git branch
372 */
373def postGerritReview(credentialsId, virtualEnv, repoDir, gitName, gitEmail, gitRemote, gitTopic, gitBranch) {
374 def python = new com.mirantis.mk.Python()
Dmitry Teselkin3bb1c032019-12-12 19:33:58 +0300375 def common = new com.mirantis.mk.Common()
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300376 def cmdText = """
377 GIT_COMMITTER_NAME=${gitName} \
378 GIT_COMMITTER_EMAIL=${gitEmail} \
379 git review -r ${gitRemote} \
380 -t ${gitTopic} \
381 ${gitBranch}
382 """
383 sshagent([credentialsId]) {
384 dir(repoDir) {
Dmitry Teselkin3bb1c032019-12-12 19:33:58 +0300385 res = python.runVirtualenvCommand(virtualEnv, cmdText)
386 common.infoMsg(res)
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300387 }
388 }
389}
Denis Egorenkof35e00b2019-11-13 16:29:50 +0400390
391/**
392 * Prepare and upload Gerrit commit from prepared repo
393 * @param LinkedHashMap params dict with parameters
394 * venvDir - Absolute path to virtualenv dir
395 * gerritCredentials - credentialsId
396 * gerritHost - gerrit host
397 * gerritPort - gerrit port
398 * repoDir - path to repo dir
399 * repoProject - repo name
400 * repoBranch - repo branch
401 * changeCommitComment - comment for commit message
402 * changeAuthorName - change author
403 * changeAuthorEmail - author email
404 * changeTopic - change topic
405 * gitRemote - git remote
406 * returnChangeInfo - whether to return info about uploaded change
407 *
408 * @return map with change info if returnChangeInfo set to true
409*/
410def prepareGerritAutoCommit(LinkedHashMap params) {
411 def common = new com.mirantis.mk.Common()
412 def git = new com.mirantis.mk.Git()
413 String venvDir = params.get('venvDir')
414 String gerritCredentials = params.get('gerritCredentials')
415 String gerritHost = params.get('gerritHost', 'gerrit.mcp.mirantis.net')
416 String gerritPort = params.get('gerritPort', '29418')
417 String gerritUser = common.getCredentialsById(gerritCredentials, 'sshKey').username
418 String repoDir = params.get('repoDir')
419 String repoProject = params.get('repoProject')
420 String repoBranch = params.get('repoBranch', 'master')
421 String changeCommitComment = params.get('changeCommitComment')
422 String changeAuthorName = params.get('changeAuthorName', 'MCP-CI')
423 String changeAuthorEmail = params.get('changeAuthorEmail', 'mcp-ci-jenkins@ci.mcp.mirantis.net')
424 String changeTopic = params.get('changeTopic', 'auto_ci')
425 Boolean returnChangeInfo = params.get('returnChangeInfo', false)
426 String gitRemote = params.get('gitRemote', '')
427 if (! gitRemote) {
428 dir(repoDir) {
429 gitRemote = sh(
430 script:
431 'git remote -v | head -n1 | cut -f1',
432 returnStdout: true,
433 ).trim()
434 }
435 }
436 def gerritAuth = ['PORT': gerritPort, 'USER': gerritUser, 'HOST': gerritHost ]
437 def changeParams = ['owner': gerritUser, 'status': 'open', 'project': repoProject, 'branch': repoBranch, 'topic': changeTopic]
438 // find if there is old commit present
439 def gerritChange = findGerritChange(gerritCredentials, gerritAuth, changeParams)
440 def changeId = ''
441 if (gerritChange) {
442 try {
443 def jsonChange = readJSON text: gerritChange
444 changeId = "Change-Id: ${jsonChange['id']}".toString()
445 } catch (Exception error) {
446 common.errorMsg("Can't parse ouput from Gerrit. Check that user ${changeAuthorName} does not have several \
447 open commits to ${repoProject} repo and ${repoBranch} branch with topic ${changeTopic}")
448 throw error
449 }
450 }
451 def commitMessage =
452 """${changeCommitComment}
453
454 |${changeId}
455 """.stripMargin()
456 git.commitGitChanges(repoDir, commitMessage, changeAuthorEmail, changeAuthorName, false)
457 //post change
458 postGerritReview(gerritCredentials, venvDir, repoDir, changeAuthorName, changeAuthorEmail, gitRemote, changeTopic, repoBranch)
459 if (returnChangeInfo) {
460 gerritChange = findGerritChange(gerritCredentials, gerritAuth, changeParams)
461 jsonChange = readJSON text: gerritChange
462 return getGerritChange(gerritUser, gerritHost, jsonChange['number'], gerritCredentials, true)
463 }
464}
Mykyta Karpin0373e492020-04-17 11:30:19 +0300465
466/**
Mykyta Karpin82a2e2a2021-07-09 17:53:01 +0300467 * Get email and username from credentials id
468 * @param credentialsId Credentials ID to use for source Git
469 */
470def getGerritUserOptions(credentialsId) {
471 def changeAuthorName = "MCP-CI"
472 def changeAuthorEmail = "mcp-ci-jenkins@ci.mcp.mirantis.net"
473
474 switch (credentialsId) {
475 case 'mos-ci':
476 changeAuthorName = "MOS-CI"
477 changeAuthorEmail = "infra+mos-ci@mirantis.com"
478 break;
479 case 'mcp-ci-gerrit':
480 changeAuthorName = "MCP-CI"
481 changeAuthorEmail = "mcp-ci-jenkins@ci.mcp.mirantis.net"
482 break;
483 }
484 return ["changeAuthorName": changeAuthorName,
485 "changeAuthorEmail": changeAuthorEmail]
486}
487
488/**
Mykyta Karpin0373e492020-04-17 11:30:19 +0300489 * Download change from gerrit, if needed repository maybe pre cloned
490 *
491 * @param path Directory to checkout repository to
492 * @param url Source Gerrit repository URL
493 * @param reference Gerrit reference to download (e.g refs/changes/77/66777/16)
494 * @param type type of gerrit download
495 * @param credentialsId Credentials ID to use for source Git
496 * @param gitCheckoutParams map with additional parameters for git.checkoutGitRepository method e.g:
497 * [ branch: 'master', poll: true, timeout: 10, depth: 0 ]
498 * @param doGitClone boolean whether to pre clone and do some checkout
499 */
500def downloadChange(path, url, reference, credentialsId, type = 'cherry-pick', doGitClone = true, Map gitCheckoutParams = [:]){
Mykyta Karpin32cafd62021-07-01 17:28:03 +0300501 def common = new com.mirantis.mk.Common()
Mykyta Karpin0373e492020-04-17 11:30:19 +0300502 def git = new com.mirantis.mk.Git()
503 def ssh = new com.mirantis.mk.Ssh()
504 def cmd
Mykyta Karpin32cafd62021-07-01 17:28:03 +0300505 def credentials = common.getCredentialsById(credentialsId)
Mykyta Karpin82a2e2a2021-07-09 17:53:01 +0300506 Map gerritUserOptions = getGerritUserOptions(credentialsId)
Mykyta Karpin0ff68782021-07-09 18:38:43 +0300507 String gitCommiterOpts = "GIT_COMMITTER_EMAIL=\'${gerritUserOptions['changeAuthorEmail']}\' GIT_COMMITTER_NAME=\'${gerritUserOptions['changeAuthorName']}\'"
Mykyta Karpin0373e492020-04-17 11:30:19 +0300508 switch(type) {
509 case 'cherry-pick':
Mykyta Karpin82a2e2a2021-07-09 17:53:01 +0300510 cmd = "git fetch ${url} ${reference} && ${gitCommiterOpts} git cherry-pick FETCH_HEAD"
Mykyta Karpin0373e492020-04-17 11:30:19 +0300511 break;
512 case 'format-patch':
513 cmd = "git fetch ${url} ${reference} && git format-patch -1 --stdout FETCH_HEAD"
514 break;
515 case 'pull':
516 cmd = "git pull ${url} ${reference}"
517 break;
518 default:
519 error("Unsupported gerrit download type")
520 }
521 if (doGitClone) {
522 def branch = gitCheckoutParams.get('branch', 'master')
523 def poll = gitCheckoutParams.get('poll', true)
524 def timeout = gitCheckoutParams.get('timeout', 10)
525 def depth = gitCheckoutParams.get('depth', 0)
526 git.checkoutGitRepository(path, url, branch, credentialsId, poll, timeout, depth, '')
527 }
Mykyta Karpin32cafd62021-07-01 17:28:03 +0300528 sshagent (credentials: [credentialsId]) {
529 dir(path){
530 sh(script: "GIT_SSH_COMMAND='ssh -l ${credentials.username}' ${cmd}", returnStdout:true)
531 }
Mykyta Karpin0373e492020-04-17 11:30:19 +0300532 }
533}
534
535/**
536 * Parse gerrit event text and if Workflow +1 is detected,
537 * return true
538 *
539 * @param gerritEventCommentText gerrit event comment text
540 * @param gerritEventType type of gerrit event
541 */
542def isGate(gerritEventCommentText, gerritEventType) {
543 def common = new com.mirantis.mk.Common()
544 def gerritEventCommentTextStr = ''
545 def res = false
546 if (gerritEventCommentText) {
547 try{
548 gerritEventCommentTextStr = new String(gerritEventCommentText.decodeBase64())
549 } catch (e) {
550 gerritEventCommentTextStr = gerritEventCommentText
551 }
552 common.infoMsg("GERRIT_EVENT_COMMENT_TEXT is ${gerritEventCommentTextStr}")
553 }
554 if (gerritEventType == 'comment-added' && gerritEventCommentTextStr =~ /^Patch Set \d+:\s.*Workflow\+1$/) {
555 common.infoMsg("Running in gate mode")
556 res = true
557 }
558 return res
559}