blob: b3bb3a251888b7046ca70c409b3588336bbf0d93 [file] [log] [blame]
Alexander Evseevbdf97c92018-08-09 17:21:37 +02001#!groovy
2
3/**
4 * (Re-)Create git branches
5 *
6 * @param GIT_REPO_LIST List of repositories to handle
7 * Multiline text: '<name> <url> <src_obj>' (full format)
8 * or: '<url>' (assuming src_obj=='SUBS_SOURCE_REF')
9 * @param GIT_CREDENTIALS Credentials ID to use for the ALL given repositories
10 * @param BRANCH New branch name
11 * @param SOURCE_REVISION Source object (commit/tag/branch) to apply to all repos
12 * having empty src_obj or src_obj=='SUBS_SOURCE_REF'
13 *
14 * @see <a href="https://mirantis.jira.com/browse/PROD-17759">PROD-17759</a>
15 */
16
17// Get job environment to use as a map to get values with defaults
18Map jobEnv = env.getEnvironment().findAll { k, v -> v }
19
20// Prepare job parameters
21ArrayList gitRepoList = jobEnv.get('GIT_REPO_LIST', '').readLines()
22String gitBranchNew = jobEnv.get('BRANCH')
23String srcObj = jobEnv.get('SOURCE_REVISION', 'master')
24String gitCredentialsId = jobEnv.get('GIT_CREDENTIALS')
25
26// Check if new branch name is given
27if (! gitBranchNew) {
28 error ('No new branch name is given')
29}
30
31/**
32 * Returns local path for the given URL constructed from hostname and repository
33 *
34 * @param repoUrl git repository URL
35 * @return string representing local relative patch
36 */
37String getRepoLocalPath(String repoUrl) {
38 // Regex to split git repository URLs
39 String re = '^(?:(?<proto>[a-z]+)://)?(?:(?<creds>[^@]+)@)?(?<host>[^:/]+)(?::(?<port>[0-9]+)/|[:/])(?<repo>.+)$'
40
41 java.util.regex.Matcher urlMatcher = repoUrl =~ re
42 if (urlMatcher.matches()) {
43 return new File(
44 urlMatcher.group('host'),
45 urlMatcher.group('repo').replaceAll(/\.git$/,'')
46 ).toString()
47 } else {
48 return ''
49 }
50}
51
52// Variables to use as repo parameters
53String gitRepoName
54String gitRepoUrl
55String gitSrcObj
56
57// Store current commit SHA
58String gitCommit
59
60node() {
61 for (gitRepo in gitRepoList) {
62 (gitRepoName, gitRepoUrl, gitSrcObj) = gitRepo.trim().tokenize(' ')
63
64 if (gitRepoName.startsWith('#')){
65 echo ("Skipping repo '${gitRepo}'")
66 continue
67 }
68
69 if (! gitRepoUrl) {
70 // The only token is the git repo url
71 gitRepoUrl = gitRepoName
72 gitRepoName = getRepoLocalPath(gitRepoUrl)
73 gitSrcObj = srcObj
74 } else if (! gitSrcObj) {
75 // Two tokens - can't decide is gitRepoName or gitSrcObj given
76 error ("Wrong repository string format: '${gitRepo}'")
77 }
78
79 if (gitSrcObj.contains('SUBS_SOURCE_REF')) {
80 echo ("Replacing 'SUBS_SOURCE_REF' => ${SOURCE_REVISION}")
Alexander Evseev5064d622018-08-27 15:56:37 +020081 gitSrcObj = gitSrcObj.replace('SUBS_SOURCE_REF', srcObj)
Alexander Evseevbdf97c92018-08-09 17:21:37 +020082 }
83
Alexander Evseevbdf97c92018-08-09 17:21:37 +020084 checkout([
85 $class: 'GitSCM',
Alexander Evseevbdf97c92018-08-09 17:21:37 +020086 userRemoteConfigs: [
Alexander Evseeve9a17f32018-10-29 16:57:11 +030087 [url: gitRepoUrl, credentialsId: gitCredentialsId],
Alexander Evseevbdf97c92018-08-09 17:21:37 +020088 ],
89 extensions: [
90 [$class: 'PruneStaleBranch'],
91 [$class: 'RelativeTargetDirectory', relativeTargetDir: gitRepoName],
92 [$class: 'SubmoduleOption', disableSubmodules: true],
93 [$class: 'UserIdentity', name: 'MCP CI', email: 'ci+infra@mirantis.com'],
94 ],
95 ])
96
97 // Proceed branch creation
98 dir(gitRepoName) {
99 sshagent (credentials: [gitCredentialsId]) {
100 // FIXME: Ensure git has configured user and email
101 // See: https://issues.jenkins-ci.org/browse/JENKINS-46052
102 sh 'git config user.name "MCP CI"'
103 sh 'git config user.email "ci+infra@mirantis.com"'
104
105 // Update list of branches
Alexander Evseeve9a17f32018-10-29 16:57:11 +0300106 sh 'git checkout master'
107
108 int is_branch = sh(script: "git ls-remote --exit-code --heads origin ${gitBranchNew}", returnStatus: true)
109 int is_tag = sh(script: "git ls-remote --exit-code --tags origin ${gitBranchNew}", returnStatus: true)
Alexander Evseevbdf97c92018-08-09 17:21:37 +0200110
111 // Ensure there is no branch or tag with gitBranchNew name
Alexander Evseeve9a17f32018-10-29 16:57:11 +0300112 if (is_branch == 0) {
113 sh """\
114 git checkout 'origin/${gitBranchNew}' -t || :
115 git checkout master
116 git branch -d '${gitBranchNew}'
117 git push origin ':refs/heads/${gitBranchNew}'
118 """.stripIndent()
119 }
120 if (is_tag == 0) {
121 sh """\
122 git tag -d '${gitBranchNew}'
123 git push origin ':refs/tags/${gitBranchNew}'
124 """
125 }
Alexander Evseevbdf97c92018-08-09 17:21:37 +0200126
Alexander Evseevbdf97c92018-08-09 17:21:37 +0200127 // Create new branch
Alexander Evseeve9a17f32018-10-29 16:57:11 +0300128 sh "git branch '${gitBranchNew}' '${gitSrcObj}'" // Create new local branch
129 sh "git push --force origin '${gitBranchNew}'" // ... push new branch
Alexander Evseevbdf97c92018-08-09 17:21:37 +0200130 }
131 }
132 }
133}