blob: 5108cda53f296414b731ce46ce68107d9a88c74e [file] [log] [blame]
Sergey Kolekonovba203982016-12-21 18:32:17 +04001package com.mirantis.mk
2
3/**
4 *
5 * Git functions
6 *
7 */
8
9/**
10 * Checkout single git repository
11 *
12 * @param path Directory to checkout repository to
13 * @param url Source Git repository URL
14 * @param branch Source Git repository branch
15 * @param credentialsId Credentials ID to use for source Git
Jakub Josef7dccebe2017-03-06 18:08:32 +010016 * @param poll Enable git polling (default true)
17 * @param timeout Set checkout timeout (default 10)
Jakub Josef61f29e62017-03-08 16:42:06 +010018 * @param depth Git depth param (default 0 means no depth)
Alexandr Lovtsove818e102019-07-29 14:45:01 +030019 * @param reference Git reference param to checkout (default empyt, i.e. no reference)
Sergey Kolekonovba203982016-12-21 18:32:17 +040020 */
Alexandr Lovtsove818e102019-07-29 14:45:01 +030021def checkoutGitRepository(path, url, branch, credentialsId = null, poll = true, timeout = 10, depth = 0, reference = ''){
Alexandr Lovtsov73786142019-09-02 17:45:12 +030022 def branch_name = reference ? 'FETCH_HEAD' : "*/${branch}"
Sergey Kolekonovba203982016-12-21 18:32:17 +040023 dir(path) {
Jakub Josef6fa8cb12017-03-06 18:20:08 +010024 checkout(
25 changelog:true,
26 poll: poll,
27 scm: [
28 $class: 'GitSCM',
Alexandr Lovtsov73786142019-09-02 17:45:12 +030029 branches: [[name: branch_name]],
Jakub Josef6fa8cb12017-03-06 18:20:08 +010030 doGenerateSubmoduleConfigurations: false,
31 extensions: [
Jakub Josef61f29e62017-03-08 16:42:06 +010032 [$class: 'CheckoutOption', timeout: timeout],
Alexandr Lovtsov73786142019-09-02 17:45:12 +030033 [$class: 'CloneOption', depth: depth, noTags: false, shallow: depth > 0, timeout: timeout]],
Jakub Josef6fa8cb12017-03-06 18:20:08 +010034 submoduleCfg: [],
Alexandr Lovtsov73786142019-09-02 17:45:12 +030035 userRemoteConfigs: [[url: url, credentialsId: credentialsId, refspec: reference]]]
Jakub Josef6fa8cb12017-03-06 18:20:08 +010036 )
Sergey Kolekonovba203982016-12-21 18:32:17 +040037 sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
38 }
39}
40
41/**
42 * Parse HEAD of current directory and return commit hash
43 */
44def getGitCommit() {
45 git_commit = sh (
46 script: 'git rev-parse HEAD',
47 returnStdout: true
48 ).trim()
49 return git_commit
50}
51
52/**
Ales Komarekfb7cbcb2017-02-24 14:02:03 +010053 * Change actual working branch of repo
54 *
55 * @param path Path to the git repository
56 * @param branch Branch desired to switch to
57 */
58def changeGitBranch(path, branch) {
59 dir(path) {
60 git_cmd = sh (
Leontii Istominb4f4ae12018-02-27 20:25:43 +010061 script: "git checkout ${branch}",
Ales Komarekfb7cbcb2017-02-24 14:02:03 +010062 returnStdout: true
63 ).trim()
64 }
65 return git_cmd
66}
67
68/**
Ales Komarekc3a8b972017-03-24 13:57:25 +010069 * Get remote URL
70 *
71 * @param name Name of remote (default any)
72 * @param type Type (fetch or push, default fetch)
73 */
74def getGitRemote(name = '', type = 'fetch') {
75 gitRemote = sh (
76 script: "git remote -v | grep '${name}' | grep ${type} | awk '{print \$2}' | head -1",
77 returnStdout: true
78 ).trim()
79 return gitRemote
80}
81
82/**
Alexandr Lovtsovd1540612020-05-07 14:10:37 +030083 * Get commit message for given commit reference
84 */
85def getGitCommitMessage(String path, String commitRef = 'HEAD') {
86 dir(path) {
87 commitMsg = sh (
88 script: "git log --format=%B -n 1 ${commitRef}",
89 returnStdout: true
90 ).trim()
91 }
92 return commitMsg
93}
94
95/**
Ales Komarekc3a8b972017-03-24 13:57:25 +010096 * Create new working branch for repo
97 *
98 * @param path Path to the git repository
99 * @param branch Branch desired to switch to
100 */
101def createGitBranch(path, branch) {
102 def git_cmd
103 dir(path) {
104 git_cmd = sh (
105 script: "git checkout -b ${branch}",
106 returnStdout: true
107 ).trim()
108 }
109 return git_cmd
110}
111
112/**
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100113 * Commit changes to the git repo
114 *
115 * @param path Path to the git repository
116 * @param message A commit message
Denis Egorenkof4c45512019-03-04 15:53:36 +0400117 * @param global Use global config
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300118 * @param amend Whether to use "--amend" in commit command
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100119 */
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300120def commitGitChanges(path, message, gitEmail='jenkins@localhost', gitName='jenkins-slave', global=false, amend=false) {
Ales Komarekc3a8b972017-03-24 13:57:25 +0100121 def git_cmd
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300122 def gitOpts
Denis Egorenkof4c45512019-03-04 15:53:36 +0400123 def global_arg = ''
124 if (global) {
125 global_arg = '--global'
126 }
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300127 if (amend) {
128 gitOpts = '--amend'
129 } else {
130 gitOpts = ''
131 }
Alexandr Lovtsov2fb93482020-06-16 14:39:43 +0300132 def gitEnv = [
133 "GIT_AUTHOR_NAME=${gitName}",
134 "GIT_AUTHOR_EMAIL=${gitEmail}",
135 "GIT_COMMITTER_NAME=${gitName}",
136 "GIT_COMMITTER_EMAIL=${gitEmail}",
137 ]
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100138 dir(path) {
Denis Egorenkof4c45512019-03-04 15:53:36 +0400139 sh "git config ${global_arg} user.email '${gitEmail}'"
140 sh "git config ${global_arg} user.name '${gitName}'"
Tomáš Kukráldf7bebc2017-03-27 15:12:43 +0200141
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100142 sh(
143 script: 'git add -A',
144 returnStdout: true
145 ).trim()
Alexandr Lovtsov2fb93482020-06-16 14:39:43 +0300146 withEnv(gitEnv) {
147 git_cmd = sh(
148 script: "git commit ${gitOpts} -m '${message}'",
149 returnStdout: true
150 ).trim()
151 }
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100152 }
153 return git_cmd
154}
155
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100156/**
157 * Push git changes to remote repo
158 *
Ales Komarekc3a8b972017-03-24 13:57:25 +0100159 * @param path Path to the local git repository
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100160 * @param branch Branch on the remote git repository
161 * @param remote Name of the remote repository
Ales Komarekc3a8b972017-03-24 13:57:25 +0100162 * @param credentialsId Credentials with write permissions
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100163 */
Ales Komarekc3a8b972017-03-24 13:57:25 +0100164def pushGitChanges(path, branch = 'master', remote = 'origin', credentialsId = null) {
165 def ssh = new com.mirantis.mk.Ssh()
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100166 dir(path) {
Ales Komarekc3a8b972017-03-24 13:57:25 +0100167 if (credentialsId == null) {
168 sh script: "git push ${remote} ${branch}"
169 }
170 else {
171 ssh.prepareSshAgentKey(credentialsId)
172 ssh.runSshAgentCommand("git push ${remote} ${branch}")
173 }
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100174 }
Ales Komarekfb7cbcb2017-02-24 14:02:03 +0100175}
176
Ales Komarekc3a8b972017-03-24 13:57:25 +0100177
Sergey Kolekonovba203982016-12-21 18:32:17 +0400178/**
Filip Pytloun49d66302017-03-06 10:26:22 +0100179 * Mirror git repository, merge target changes (downstream) on top of source
180 * (upstream) and push target or both if pushSource is true
181 *
182 * @param sourceUrl Source git repository
183 * @param targetUrl Target git repository
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400184 * @param credentialsId Credentials id to use for accessing target repositories
Filip Pytloun49d66302017-03-06 10:26:22 +0100185 * @param branches List or comma-separated string of branches to sync
186 * @param followTags Mirror tags
187 * @param pushSource Push back into source branch, resulting in 2-way sync
188 * @param pushSourceTags Push target tags into source or skip pushing tags
189 * @param gitEmail Email for creation of merge commits
190 * @param gitName Name for creation of merge commits
Sergey Kolekonovba203982016-12-21 18:32:17 +0400191 */
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400192def mirrorGit(sourceUrl, targetUrl, credentialsId, branches, followTags = false, pushSource = false, pushSourceTags = false, gitEmail = 'jenkins@localhost', gitName = 'Jenkins', sourceRemote = 'origin') {
Jakub Josef668dc2b2017-06-19 16:55:26 +0200193 def common = new com.mirantis.mk.Common()
194 def ssh = new com.mirantis.mk.Ssh()
Sergey Kolekonovba203982016-12-21 18:32:17 +0400195 if (branches instanceof String) {
196 branches = branches.tokenize(',')
197 }
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400198 // If both source and target repos are secured and accessible via http/https,
199 // we need to switch GIT_ASKPASS value when running git commands
200 def sourceAskPass
201 def targetAskPass
Sergey Kolekonovba203982016-12-21 18:32:17 +0400202
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400203 def sshCreds = common.getCredentialsById(credentialsId, 'sshKey') // True if found
204 if (sshCreds) {
205 ssh.prepareSshAgentKey(credentialsId)
206 ssh.ensureKnownHosts(targetUrl)
207 sh "git config user.name '${gitName}'"
208 } else {
209 withCredentials([[$class : 'UsernamePasswordMultiBinding',
210 credentialsId : credentialsId,
211 passwordVariable: 'GIT_PASSWORD',
212 usernameVariable: 'GIT_USERNAME']]) {
213 sh """
214 set +x
215 git config --global credential.${targetUrl}.username \${GIT_USERNAME}
216 echo "echo \${GIT_PASSWORD}" > ${WORKSPACE}/${credentialsId}_askpass.sh
217 chmod +x ${WORKSPACE}/${credentialsId}_askpass.sh
218 git config user.name \${GIT_USERNAME}
219 """
220 sourceAskPass = env.GIT_ASKPASS ?: ''
221 targetAskPass = "${WORKSPACE}/${credentialsId}_askpass.sh"
222 }
223 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100224 sh "git config user.email '${gitEmail}'"
Filip Pytloun49d66302017-03-06 10:26:22 +0100225
Jakub Josef1caa7ae2017-08-21 16:39:00 +0200226 def remoteExistence = sh(script: "git remote -v | grep ${TARGET_URL} | grep target", returnStatus: true)
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400227 if(remoteExistence == 0) {
228 // silently try to remove target
229 sh(script: "git remote remove target", returnStatus: true)
Jakub Josef1caa7ae2017-08-21 16:39:00 +0200230 }
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400231 sh("git remote add target ${TARGET_URL}")
232 if (sshCreds) {
233 ssh.agentSh "git remote update --prune"
234 } else {
235 env.GIT_ASKPASS = sourceAskPass
236 sh "git remote update ${sourceRemote} --prune"
237 env.GIT_ASKPASS = targetAskPass
238 sh "git remote update target --prune"
239 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100240
Sergey Kolekonovba203982016-12-21 18:32:17 +0400241 for (i=0; i < branches.size; i++) {
242 branch = branches[i]
Jakub Josef668dc2b2017-06-19 16:55:26 +0200243 sh "git branch | grep ${branch} || git checkout -b ${branch}"
244 def resetResult = sh(script: "git checkout ${branch} && git reset --hard origin/${branch}", returnStatus: true)
245 if(resetResult != 0){
246 common.warningMsg("Cannot reset to origin/${branch} for perform git mirror, trying to reset from target/${branch}")
247 resetResult = sh(script: "git checkout ${branch} && git reset --hard target/${branch}", returnStatus: true)
248 if(resetResult != 0){
249 throw new Exception("Cannot reset even to target/${branch}, git mirroring failed!")
250 }
251 }
Sergey Kolekonovba203982016-12-21 18:32:17 +0400252
Sergey Kolekonovba203982016-12-21 18:32:17 +0400253 sh "git ls-tree target/${branch} && git merge --no-edit --ff target/${branch} || echo 'Target repository is empty, skipping merge'"
254 followTagsArg = followTags ? "--follow-tags" : ""
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400255 if (sshCreds) {
256 ssh.agentSh "git push ${followTagsArg} target HEAD:${branch}"
257 } else {
258 sh "git push ${followTagsArg} target HEAD:${branch}"
259 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100260
261 if (pushSource == true) {
262 followTagsArg = followTags && pushSourceTags ? "--follow-tags" : ""
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400263 if (sshCreds) {
264 ssh.agentSh "git push ${followTagsArg} origin HEAD:${branch}"
265 } else {
266 sh "git push ${followTagsArg} origin HEAD:${branch}"
267 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100268 }
269 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100270 if (followTags == true) {
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400271 if (sshCreds) {
272 ssh.agentSh "git push -f target --tags"
273 } else {
274 sh "git push -f target --tags"
275 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100276
277 if (pushSourceTags == true) {
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400278 if (sshCreds) {
279 ssh.agentSh "git push -f origin --tags"
280 } else {
281 sh "git push -f origin --tags"
282 }
Filip Pytloun49d66302017-03-06 10:26:22 +0100283 }
Sergey Kolekonovba203982016-12-21 18:32:17 +0400284 }
Jakub Josefecf8b452017-04-20 13:34:29 +0200285 sh "git remote rm target"
Ivan Berezovskiycf269442019-07-18 16:15:26 +0400286 if (!sshCreds) {
287 sh "set +x; rm -f ${targetAskPass}"
288 sh "git config --global --unset credential.${targetUrl}.username"
289 }
Sergey Kolekonovba203982016-12-21 18:32:17 +0400290}
Martin Polreich765f7ba2019-03-12 16:39:25 +0100291
292
293/**
294 * Return all branches for the defined git repository that match the matcher.
295 *
296 * @param repoUrl URL of git repository
297 * @param branchMatcher matcher to filter out the branches (If '' or '*', returns all branches without filtering)
298 * @return branchesList list of branches
299 */
300
301def getBranchesForGitRepo(repoUrl, branchMatcher = ''){
302
303 if (branchMatcher.equals("*")) {
304 branchMatcher = ''
305 }
306 branchesList = sh (
307 script: "git ls-remote --heads ${repoUrl} | cut -f2 | grep -e '${branchMatcher}' | sed 's/refs\\/heads\\///g'",
308 returnStdout: true
309 ).trim()
310 return branchesList.tokenize('\n')
Oleksii Grudeva64e5b22019-06-11 11:21:02 +0300311}
312
Mykyta Karpin82437932019-06-06 14:08:18 +0300313/**
314 * Method for preparing a tag to be SemVer 2 compatible, and can handle next cases:
315 * - length of tag splitted by dots is more than 3
316 * - first part of splitted tag starts not from digit
317 * - length of tag is lower than 3
318 *
319 * @param tag String which contains a git tag from repository
320 * @return HashMap HashMap in the form: ['version': 'x.x.x', 'extra': 'x.x.x'], extra
321 * is added only if size of original tag splitted by dots is more than 3
322 */
323
324def prepareTag(tag){
325 def parts = tag.tokenize('.')
326 def res = [:]
327 // Handle case with tags like v1.1.1
328 parts[0] = parts[0].replaceFirst("[^\\d.]", '')
329 // handle different sizes of tags - 1.1.1.1 or 1.1.1.1rc1
330 if (parts.size() > 3){
331 res['extra'] = parts[3..-1].join('.')
332 } else if (parts.size() < 3){
333 (parts.size()..2).each {
334 parts[it] = '0'
335 }
336 }
337 res['version'] = "${parts[0]}.${parts[1]}.${parts[2]}"
338 return res
339}
340
341/**
342 * Method for incrementing SemVer 2 compatible version
343 *
344 * @param version String which contains main part of SemVer2 version - '2.1.0'
345 * @return string String conaining version with Patch part of version incremented by 1
346 */
347
348def incrementVersion(version){
349 def parts = checkVersion(version)
350 return "${parts[0]}.${parts[1]}.${parts[2].toInteger() + 1}"
351}
352
353/**
354 * Method for checking whether version is compatible with Sem Ver 2
355 *
356 * @param version String which contains main part of SemVer2 version - '2.1.0'
357 * @return list With 3 strings as result of splitting version by dots
358 */
359
360def checkVersion(version) {
361 def parts = version.tokenize('.')
362 if (parts.size() != 3 || !(parts[0] ==~ /^\d+/)) {
363 error "Bad version ${version}"
364 }
365 return parts
366}
367
368/**
369 * Method for constructing SemVer2 compatible version from tag in Git repository:
370 * - if current commit matches the last tag, last tag will be returned as version
371 * - if no tag found assuming no release was done, version will be 0.0.1 with pre release metadata
372 * - if tag found - patch part of version will be incremented and pre-release metadata will be added
373 *
374 *
375 * @param repoDir String which contains path to directory with git repository
376 * @param allowNonSemVer2 Bool whether to allow working with tags which aren't compatible
377 * with Sem Ver 2 (not in form X.Y.Z). if set to true tag will be
378* converted to Sem Ver 2 version e.g tag 1.1.1.1rc1 -> version 1.1.1-1rc1
379 * @return version String
380 */
381def getVersion(repoDir, allowNonSemVer2 = false) {
382 def common = new com.mirantis.mk.Common()
383 dir(repoDir){
384 def cmd = common.shCmdStatus('git describe --tags --first-parent --abbrev=0')
385 def tag_data = [:]
386 def last_tag = cmd['stdout'].trim()
387 def commits_since_tag
388 if (cmd['status'] != 0){
389 if (cmd['stderr'].contains('fatal: No names found, cannot describe anything')){
390 common.warningMsg('No parent tag found, using initial version 0.0.0')
391 tag_data['version'] = '0.0.0'
392 commits_since_tag = sh(script: 'git rev-list --count HEAD', returnStdout: true).trim()
393 } else {
394 error("Something went wrong, cannot find git information ${cmd['stderr']}")
395 }
396 } else {
397 tag_data['version'] = last_tag
398 commits_since_tag = sh(script: "git rev-list --count ${last_tag}..HEAD", returnStdout: true).trim()
399 }
400 try {
401 checkVersion(tag_data['version'])
402 } catch (Exception e) {
403 if (allowNonSemVer2){
404 common.errorMsg(
405 """Git tag isn't compatible with SemVer2, but allowNonSemVer2 is set.
406 Trying to convert git tag to Sem Ver 2 compatible version
407 ${e.message}""")
408 tag_data = prepareTag(tag_data['version'])
409 } else {
410 error("Git tag isn't compatible with SemVer2\n${e.message}")
411 }
412 }
413 // If current commit is exact match to the first parent tag than return it
414 def pre_release_meta = []
415 if (tag_data.get('extra')){
416 pre_release_meta.add(tag_data['extra'])
417 }
418 if (common.shCmdStatus('git describe --tags --first-parent --exact-match')['status'] == 0){
419 if (pre_release_meta){
420 return "${tag_data['version']}-${pre_release_meta[0]}"
421 } else {
422 return tag_data['version']
423 }
424 }
425 // If we away from last tag for some number of commits - add additional metadata and increment version
426 pre_release_meta.add(commits_since_tag)
427 def next_version = incrementVersion(tag_data['version'])
428 def commit_sha = sh(script: 'git rev-parse --short=7 HEAD', returnStdout: true).trim()
429 return "${next_version}-${pre_release_meta.join('.')}-${commit_sha}"
430 }
431}
Mykyta Karpinf5b6c162019-08-08 14:28:15 +0300432
433
434/**
435 * Method for uploading a change request
436 *
437 * @param repo String which contains path to directory with git repository
438 * @param credentialsId Credentials id to use for accessing target repositories
439 * @param commit Id of commit which should be uploaded
440 * @param branch Name of the branch for uploading
441 * @param topic Topic of the change
442 *
443 */
444def pushForReview(repo, credentialsId, commit, branch, topic='', remote='origin') {
445 def common = new com.mirantis.mk.Common()
446 def ssh = new com.mirantis.mk.Ssh()
447 common.infoMsg("Uploading commit ${commit} to ${branch} for review...")
448
449 def pushArg = "${commit}:refs/for/${branch}"
450 def process = [:]
451 if (topic){
452 pushArg += '%topic=' + topic
453 }
454 dir(repo){
455 ssh.prepareSshAgentKey(credentialsId)
456 ssh.runSshAgentCommand("git push ${remote} ${pushArg}")
457 }
458}
459
460/**
461 * Generates a commit message with predefined or auto generate change id. If change
462 * id isn't provided, changeIdSeed and current sha of git head will be used in
463 * generation of commit change id.
464 *
465 * @param repo String which contains path to directory with git repository
466 * @param message Commit message main part
467 * @param changeId User defined change-id usually sha1 hash
468 * @param changeIdSeed Custom part of change id which can be added during change id generation
469 *
470 *
471 * @return commitMessage Multiline String with generated commit message
472 */
473def genCommitMessage(repo, message, changeId = '', changeIdSeed = ''){
474 def git = new com.mirantis.mk.Git()
475 def common = new com.mirantis.mk.Common()
476 def commitMessage
477 def id = changeId
478 def seed = changeIdSeed
479 if (!id) {
480 if (!seed){
481 seed = common.generateRandomHashString(32)
482 }
483 def head_sha
484 dir(repo){
485 head_sha = git.getGitCommit()
486 }
487 id = 'I' + sh(script: 'echo -n ' + seed + head_sha + ' | sha1sum | awk \'{print $1}\'', returnStdout: true)
488 }
489 commitMessage =
490 """${message}
491
492 |Change-Id: ${id}
493 """.stripMargin()
494
495 return commitMessage
496}
Alexandr Lovtsov4fdafd92019-09-09 17:52:16 +0200497
498/**
499 * Update (or create if cannot find) gerrit change request
500 *
501 * @param params Map of parameters to customize commit
502 * - gerritAuth A map containing information about Gerrit. Should include HOST, PORT and USER
503 * - credentialsId Jenkins credentials id for gerrit
504 * - repo Local directory with repository
505 * - comment Commit comment
506 * - change_id_seed Custom part of change id which can be added during change id generation
507 * - branch Name of the branch for uploading
508 * - topic Topic of the change
509 * - project Gerrit project to search in for gerrit change request
510 * - status Change request's status to search for
511 * - changeAuthorEmail Author's email of the change
512 * - changeAuthorName Author's name of the change
513 */
514def updateChangeRequest(Map params) {
515 def gerrit = new com.mirantis.mk.Gerrit()
516
517 def commitMessage
518 def auth = params['gerritAuth']
519 def creds = params['credentialsId']
520 def repo = params['repo']
521 def comment = params['comment']
522 def change_id_seed = params.get('change_id_seed', JOB_NAME)
523 def branch = params['branch']
524 def topic = params['topic']
525 def project = params['project']
526 def status = params.get('status', 'open')
527 def changeAuthorEmail = params['changeAuthorEmail']
528 def changeAuthorName = params['changeAuthorName']
529
530 def changeParams = ['owner': auth['USER'], 'status': status, 'project': project, 'branch': branch, 'topic': topic]
531 def gerritChange = gerrit.findGerritChange(creds, auth, changeParams)
Maxim Rasskazov427435f2020-09-16 15:38:56 +0400532 def changeId = params.get('changeId', '')
Alexandr Lovtsov4fdafd92019-09-09 17:52:16 +0200533 def commit
534 if (gerritChange) {
535 def jsonChange = readJSON text: gerritChange
536 changeId = jsonChange['id']
537 }
538 commitMessage = genCommitMessage(repo, comment, changeId, change_id_seed)
539 commitGitChanges(repo, commitMessage, changeAuthorEmail, changeAuthorName, false, false)
540 dir(repo){
541 commit = getGitCommit()
542 }
543 pushForReview(repo, creds, commit, branch, topic)
544}