Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 1 | package 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 Josef | 7dccebe | 2017-03-06 18:08:32 +0100 | [diff] [blame] | 16 | * @param poll Enable git polling (default true) |
| 17 | * @param timeout Set checkout timeout (default 10) |
Jakub Josef | 61f29e6 | 2017-03-08 16:42:06 +0100 | [diff] [blame] | 18 | * @param depth Git depth param (default 0 means no depth) |
Alexandr Lovtsov | e818e10 | 2019-07-29 14:45:01 +0300 | [diff] [blame] | 19 | * @param reference Git reference param to checkout (default empyt, i.e. no reference) |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 20 | */ |
Alexandr Lovtsov | e818e10 | 2019-07-29 14:45:01 +0300 | [diff] [blame] | 21 | def checkoutGitRepository(path, url, branch, credentialsId = null, poll = true, timeout = 10, depth = 0, reference = ''){ |
Alexandr Lovtsov | 7378614 | 2019-09-02 17:45:12 +0300 | [diff] [blame] | 22 | def branch_name = reference ? 'FETCH_HEAD' : "*/${branch}" |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 23 | dir(path) { |
Jakub Josef | 6fa8cb1 | 2017-03-06 18:20:08 +0100 | [diff] [blame] | 24 | checkout( |
| 25 | changelog:true, |
| 26 | poll: poll, |
| 27 | scm: [ |
| 28 | $class: 'GitSCM', |
Alexandr Lovtsov | 7378614 | 2019-09-02 17:45:12 +0300 | [diff] [blame] | 29 | branches: [[name: branch_name]], |
Jakub Josef | 6fa8cb1 | 2017-03-06 18:20:08 +0100 | [diff] [blame] | 30 | doGenerateSubmoduleConfigurations: false, |
| 31 | extensions: [ |
Jakub Josef | 61f29e6 | 2017-03-08 16:42:06 +0100 | [diff] [blame] | 32 | [$class: 'CheckoutOption', timeout: timeout], |
Alexandr Lovtsov | 7378614 | 2019-09-02 17:45:12 +0300 | [diff] [blame] | 33 | [$class: 'CloneOption', depth: depth, noTags: false, shallow: depth > 0, timeout: timeout]], |
Jakub Josef | 6fa8cb1 | 2017-03-06 18:20:08 +0100 | [diff] [blame] | 34 | submoduleCfg: [], |
Alexandr Lovtsov | 7378614 | 2019-09-02 17:45:12 +0300 | [diff] [blame] | 35 | userRemoteConfigs: [[url: url, credentialsId: credentialsId, refspec: reference]]] |
Jakub Josef | 6fa8cb1 | 2017-03-06 18:20:08 +0100 | [diff] [blame] | 36 | ) |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 37 | sh(returnStdout: true, script: 'git rev-parse HEAD').trim() |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Parse HEAD of current directory and return commit hash |
| 43 | */ |
| 44 | def getGitCommit() { |
| 45 | git_commit = sh ( |
| 46 | script: 'git rev-parse HEAD', |
| 47 | returnStdout: true |
| 48 | ).trim() |
| 49 | return git_commit |
| 50 | } |
| 51 | |
| 52 | /** |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 53 | * Change actual working branch of repo |
| 54 | * |
| 55 | * @param path Path to the git repository |
| 56 | * @param branch Branch desired to switch to |
| 57 | */ |
| 58 | def changeGitBranch(path, branch) { |
| 59 | dir(path) { |
| 60 | git_cmd = sh ( |
Leontii Istomin | b4f4ae1 | 2018-02-27 20:25:43 +0100 | [diff] [blame] | 61 | script: "git checkout ${branch}", |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 62 | returnStdout: true |
| 63 | ).trim() |
| 64 | } |
| 65 | return git_cmd |
| 66 | } |
| 67 | |
| 68 | /** |
Ales Komarek | c3a8b97 | 2017-03-24 13:57:25 +0100 | [diff] [blame] | 69 | * Get remote URL |
| 70 | * |
| 71 | * @param name Name of remote (default any) |
| 72 | * @param type Type (fetch or push, default fetch) |
| 73 | */ |
| 74 | def 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 Lovtsov | d154061 | 2020-05-07 14:10:37 +0300 | [diff] [blame] | 83 | * Get commit message for given commit reference |
| 84 | */ |
| 85 | def 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 Komarek | c3a8b97 | 2017-03-24 13:57:25 +0100 | [diff] [blame] | 96 | * Create new working branch for repo |
| 97 | * |
| 98 | * @param path Path to the git repository |
| 99 | * @param branch Branch desired to switch to |
| 100 | */ |
| 101 | def 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 Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 113 | * Commit changes to the git repo |
| 114 | * |
| 115 | * @param path Path to the git repository |
| 116 | * @param message A commit message |
Denis Egorenko | f4c4551 | 2019-03-04 15:53:36 +0400 | [diff] [blame] | 117 | * @param global Use global config |
Oleksii Grudev | a64e5b2 | 2019-06-11 11:21:02 +0300 | [diff] [blame] | 118 | * @param amend Whether to use "--amend" in commit command |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 119 | */ |
Oleksii Grudev | a64e5b2 | 2019-06-11 11:21:02 +0300 | [diff] [blame] | 120 | def commitGitChanges(path, message, gitEmail='jenkins@localhost', gitName='jenkins-slave', global=false, amend=false) { |
Ales Komarek | c3a8b97 | 2017-03-24 13:57:25 +0100 | [diff] [blame] | 121 | def git_cmd |
Oleksii Grudev | a64e5b2 | 2019-06-11 11:21:02 +0300 | [diff] [blame] | 122 | def gitOpts |
Denis Egorenko | f4c4551 | 2019-03-04 15:53:36 +0400 | [diff] [blame] | 123 | def global_arg = '' |
| 124 | if (global) { |
| 125 | global_arg = '--global' |
| 126 | } |
Oleksii Grudev | a64e5b2 | 2019-06-11 11:21:02 +0300 | [diff] [blame] | 127 | if (amend) { |
| 128 | gitOpts = '--amend' |
| 129 | } else { |
| 130 | gitOpts = '' |
| 131 | } |
Alexandr Lovtsov | 2fb9348 | 2020-06-16 14:39:43 +0300 | [diff] [blame] | 132 | def gitEnv = [ |
| 133 | "GIT_AUTHOR_NAME=${gitName}", |
| 134 | "GIT_AUTHOR_EMAIL=${gitEmail}", |
| 135 | "GIT_COMMITTER_NAME=${gitName}", |
| 136 | "GIT_COMMITTER_EMAIL=${gitEmail}", |
| 137 | ] |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 138 | dir(path) { |
Denis Egorenko | f4c4551 | 2019-03-04 15:53:36 +0400 | [diff] [blame] | 139 | sh "git config ${global_arg} user.email '${gitEmail}'" |
| 140 | sh "git config ${global_arg} user.name '${gitName}'" |
Tomáš Kukrál | df7bebc | 2017-03-27 15:12:43 +0200 | [diff] [blame] | 141 | |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 142 | sh( |
| 143 | script: 'git add -A', |
| 144 | returnStdout: true |
| 145 | ).trim() |
Alexandr Lovtsov | 2fb9348 | 2020-06-16 14:39:43 +0300 | [diff] [blame] | 146 | withEnv(gitEnv) { |
| 147 | git_cmd = sh( |
| 148 | script: "git commit ${gitOpts} -m '${message}'", |
| 149 | returnStdout: true |
| 150 | ).trim() |
| 151 | } |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 152 | } |
| 153 | return git_cmd |
| 154 | } |
| 155 | |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 156 | /** |
| 157 | * Push git changes to remote repo |
| 158 | * |
Ales Komarek | c3a8b97 | 2017-03-24 13:57:25 +0100 | [diff] [blame] | 159 | * @param path Path to the local git repository |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 160 | * @param branch Branch on the remote git repository |
| 161 | * @param remote Name of the remote repository |
Ales Komarek | c3a8b97 | 2017-03-24 13:57:25 +0100 | [diff] [blame] | 162 | * @param credentialsId Credentials with write permissions |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 163 | */ |
Ales Komarek | c3a8b97 | 2017-03-24 13:57:25 +0100 | [diff] [blame] | 164 | def pushGitChanges(path, branch = 'master', remote = 'origin', credentialsId = null) { |
| 165 | def ssh = new com.mirantis.mk.Ssh() |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 166 | dir(path) { |
Ales Komarek | c3a8b97 | 2017-03-24 13:57:25 +0100 | [diff] [blame] | 167 | 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 Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 174 | } |
Ales Komarek | fb7cbcb | 2017-02-24 14:02:03 +0100 | [diff] [blame] | 175 | } |
| 176 | |
Ales Komarek | c3a8b97 | 2017-03-24 13:57:25 +0100 | [diff] [blame] | 177 | |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 178 | /** |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 179 | * 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 Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 184 | * @param credentialsId Credentials id to use for accessing target repositories |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 185 | * @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 Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 191 | */ |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 192 | def mirrorGit(sourceUrl, targetUrl, credentialsId, branches, followTags = false, pushSource = false, pushSourceTags = false, gitEmail = 'jenkins@localhost', gitName = 'Jenkins', sourceRemote = 'origin') { |
Jakub Josef | 668dc2b | 2017-06-19 16:55:26 +0200 | [diff] [blame] | 193 | def common = new com.mirantis.mk.Common() |
| 194 | def ssh = new com.mirantis.mk.Ssh() |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 195 | if (branches instanceof String) { |
| 196 | branches = branches.tokenize(',') |
| 197 | } |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 198 | // 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 Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 202 | |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 203 | 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 Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 224 | sh "git config user.email '${gitEmail}'" |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 225 | |
Jakub Josef | 1caa7ae | 2017-08-21 16:39:00 +0200 | [diff] [blame] | 226 | def remoteExistence = sh(script: "git remote -v | grep ${TARGET_URL} | grep target", returnStatus: true) |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 227 | if(remoteExistence == 0) { |
| 228 | // silently try to remove target |
| 229 | sh(script: "git remote remove target", returnStatus: true) |
Jakub Josef | 1caa7ae | 2017-08-21 16:39:00 +0200 | [diff] [blame] | 230 | } |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 231 | 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 Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 240 | |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 241 | for (i=0; i < branches.size; i++) { |
| 242 | branch = branches[i] |
Jakub Josef | 668dc2b | 2017-06-19 16:55:26 +0200 | [diff] [blame] | 243 | 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 Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 252 | |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 253 | 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 Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 255 | if (sshCreds) { |
| 256 | ssh.agentSh "git push ${followTagsArg} target HEAD:${branch}" |
| 257 | } else { |
| 258 | sh "git push ${followTagsArg} target HEAD:${branch}" |
| 259 | } |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 260 | |
| 261 | if (pushSource == true) { |
| 262 | followTagsArg = followTags && pushSourceTags ? "--follow-tags" : "" |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 263 | if (sshCreds) { |
| 264 | ssh.agentSh "git push ${followTagsArg} origin HEAD:${branch}" |
| 265 | } else { |
| 266 | sh "git push ${followTagsArg} origin HEAD:${branch}" |
| 267 | } |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 268 | } |
| 269 | } |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 270 | if (followTags == true) { |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 271 | if (sshCreds) { |
| 272 | ssh.agentSh "git push -f target --tags" |
| 273 | } else { |
| 274 | sh "git push -f target --tags" |
| 275 | } |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 276 | |
| 277 | if (pushSourceTags == true) { |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 278 | if (sshCreds) { |
| 279 | ssh.agentSh "git push -f origin --tags" |
| 280 | } else { |
| 281 | sh "git push -f origin --tags" |
| 282 | } |
Filip Pytloun | 49d6630 | 2017-03-06 10:26:22 +0100 | [diff] [blame] | 283 | } |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 284 | } |
Jakub Josef | ecf8b45 | 2017-04-20 13:34:29 +0200 | [diff] [blame] | 285 | sh "git remote rm target" |
Ivan Berezovskiy | cf26944 | 2019-07-18 16:15:26 +0400 | [diff] [blame] | 286 | if (!sshCreds) { |
| 287 | sh "set +x; rm -f ${targetAskPass}" |
| 288 | sh "git config --global --unset credential.${targetUrl}.username" |
| 289 | } |
Sergey Kolekonov | ba20398 | 2016-12-21 18:32:17 +0400 | [diff] [blame] | 290 | } |
Martin Polreich | 765f7ba | 2019-03-12 16:39:25 +0100 | [diff] [blame] | 291 | |
| 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 | |
| 301 | def 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 Grudev | a64e5b2 | 2019-06-11 11:21:02 +0300 | [diff] [blame] | 311 | } |
| 312 | |
Mykyta Karpin | 8243793 | 2019-06-06 14:08:18 +0300 | [diff] [blame] | 313 | /** |
| 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 | |
| 324 | def 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 | |
| 348 | def 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 | |
| 360 | def 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 | */ |
| 381 | def 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 Karpin | f5b6c16 | 2019-08-08 14:28:15 +0300 | [diff] [blame] | 432 | |
| 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 | */ |
| 444 | def 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 | */ |
| 473 | def 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 Lovtsov | 4fdafd9 | 2019-09-09 17:52:16 +0200 | [diff] [blame] | 497 | |
| 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 | */ |
| 514 | def 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 Rasskazov | 427435f | 2020-09-16 15:38:56 +0400 | [diff] [blame] | 532 | def changeId = params.get('changeId', '') |
Alexandr Lovtsov | 4fdafd9 | 2019-09-09 17:52:16 +0200 | [diff] [blame] | 533 | 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 | } |