使用 groovy 脚本在 Jenkins 中选择 Git 分支
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25509067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Git branch select in Jenkins with groovy script
提问by Danial
I am trying to make a Parameterized build
in Jenkins. In this way user can choose the git branch he/she wants to deploy from a cascade menu.
我想Parameterized build
在詹金斯做一个。通过这种方式,用户可以从级联菜单中选择他/她想要部署的 git 分支。
There are two possible ways:
有两种可能的方式:
Writing branch names in file and configuring Jenkins to read this file (
project configuration > extend choice parameter and selecting Property file
).Problem : You have to make a local repository as a mirror of remote repo and keep this local repo in sync with remote repo. In the other words, you have to update the file containing the available branch name updated. This needs a scheduled job by cron and I am not allowed using this approach.
Using Groovy script (
project configuration > extend choice parameter and selecting "Groovy script"
). Then you need a groovy script to retrieve the branch name as follows:branches=master,feature/Feature-1,feature/Feature-2,hotfix/Hotfix-1,release/Release-1
.
在文件中写入分支名称并配置 Jenkins 以读取此文件 (
project configuration > extend choice parameter and selecting Property file
)。问题:您必须将本地存储库作为远程存储库的镜像,并使该本地存储库与远程存储库保持同步。换句话说,您必须更新包含可用分支名称 updated 的文件。这需要 cron 安排的作业,我不允许使用这种方法。
使用 Groovy 脚本 (
project configuration > extend choice parameter and selecting "Groovy script"
)。然后,你需要一个Groovy脚本来检索分支名称如下:branches=master,feature/Feature-1,feature/Feature-2,hotfix/Hotfix-1,release/Release-1
。
I found a groovy script in herebut it doesn't work. I have installed groovy on my machine.
我在这里找到了一个 groovy 脚本,但它不起作用。我已经在我的机器上安装了 groovy。
Can anybody help me? To make the story short: I need a groovy script which returns the available branch names of a remote repository.
有谁能够帮助我?简而言之:我需要一个 groovy 脚本,它返回远程存储库的可用分支名称。
回答by Pawe? Piecyk
The script below should be helpful. It's based on the scripts from linked question. It filters git command output with simple regular expression and creates list of branch names for specified git repository. Tested on grails-core github repo:
下面的脚本应该会有所帮助。它基于来自链接问题的脚本。它使用简单的正则表达式过滤 git 命令输出,并为指定的 git 存储库创建分支名称列表。在grails-core github repo上测试:
def gitURL = "https://github.com/grails/grails-core.git"
def command = "git ls-remote -h $gitURL"
def proc = command.execute()
proc.waitFor()
if ( proc.exitValue() != 0 ) {
println "Error, ${proc.err.text}"
System.exit(-1)
}
def branches = proc.in.text.readLines().collect {
it.replaceAll(/[a-z0-9]*\trefs\/heads\//, '')
}
println branches
回答by Wilfred Hughes
You don't need a Groovy Script for this. The Git Parameter Pluginlets you add git branches as a parameter.
为此,您不需要 Groovy 脚本。在Git的参数插件可以让你添加的Git分支作为参数。
回答by codenio
Try Using
尝试使用
- Active Choiceplugin and Extensible choiceparameter plugin for dynamic repo and branch selections
- Extensible choiceparameter plugin for branch selection for a default repo.
- 用于动态回购和分支选择的Active Choice插件和可扩展选择参数插件
- 用于默认存储库分支选择的可扩展选择参数插件。
Use the following steps:
使用以下步骤:
Add an extensible choice parameter to your job
select System Groovy Choice parameterin Choice parameter field
Place the following script in Groovy scripttext box and replace the place holders "< >" with required values.
import groovy.json.JsonSlurper; try{ List<String>params = new ArrayList<String>() URL apiUrl = "https://api.github.com/users/<repo-owner>/repos?access_token=<github-access-token>".toURL() List branches = new JsonSlurper().parse(apiUrl.newReader()) for (branch in branches ) { params.add(branch.name) } return params } catch(IOException ex){ print ex }
Add an active choice reactive parameter to your job
Place Reference Parameteras repositoryand following script in Groovy Script text box
import groovy.json.JsonSlurper; try{ List<String>params = new ArrayList<String>() URL apiUrl = "https://api.github.com/repos/<repo-owner>/$repository/branches?access_token=<github-access-token>".toURL() List json = new JsonSlurper().parse(apiUrl.newReader()) for (repo in json ) { params.add(repo.name) } return params } catch(IOException ex){ print ex }
Note:
$repository
takes dynamic value from repository parameter.- ignore for public repository.
Now try build job with parameter
向您的作业添加可扩展的选择参数
在 Choice 参数字段中选择System Groovy Choice 参数
将以下脚本放在Groovy 脚本文本框中,并将占位符“< >”替换为所需的值。
import groovy.json.JsonSlurper; try{ List<String>params = new ArrayList<String>() URL apiUrl = "https://api.github.com/users/<repo-owner>/repos?access_token=<github-access-token>".toURL() List branches = new JsonSlurper().parse(apiUrl.newReader()) for (branch in branches ) { params.add(branch.name) } return params } catch(IOException ex){ print ex }
为您的工作添加主动选择反应参数
将参考参数作为存储库和以下脚本放置在 Groovy 脚本文本框中
import groovy.json.JsonSlurper; try{ List<String>params = new ArrayList<String>() URL apiUrl = "https://api.github.com/repos/<repo-owner>/$repository/branches?access_token=<github-access-token>".toURL() List json = new JsonSlurper().parse(apiUrl.newReader()) for (repo in json ) { params.add(repo.name) } return params } catch(IOException ex){ print ex }
笔记:
$repository
从存储库参数中获取动态值。- 忽略公共存储库。
现在尝试使用参数构建作业
checkout github api docs for more informations. Hope this yould be helpful..!! ;-)
查看 github api 文档以获取更多信息。希望这对你有帮助..!!;-)
回答by Noam Manos
You can use Extensible Choice Parameter pluginto retrieve Git branches of your cloned repository. To do so, add to Master-Node property an environment variable of .git directory path, e.g.:
您可以使用可扩展选择参数插件来检索克隆存储库的 Git 分支。为此,将 .git 目录路径的环境变量添加到 Master-Node 属性,例如:
Then add an Extensible Choice parameter with the following groovy script (and check "Use predefined variables"):
然后使用以下 groovy 脚本添加可扩展选择参数(并选中“使用预定义变量”):
def envVars = jenkins.getNodeProperties()[0].getEnvVars()
def NODE_PROJECT_PATH = envVars.get('NODE_PROJECT_PATH')
def gettags = "git ls-remote -t --heads origin".execute(null, new File(NODE_PROJECT_PATH))
return gettags.text.readLines()
.collect { it.split()[1].replaceAll('\^\{\}', '').replaceAll('refs/\w+/', '') }
.unique()
.findAll { !it.startsWith('Branch_') }
That should list your branches (I filtered out all "Branch_*" from the list):
那应该列出您的分支(我从列表中过滤掉了所有“Branch_*”):
Notes:In case you see nothing when validating the script (with "Run the script now" button), it's probably due to required user/password prompt - so initially run "git ls-remote -t --heads origin" in .git directory. To save credential on Windows, try to run "git config --global credential.helper wincred".
注意:如果您在验证脚本时看不到任何内容(使用“立即运行脚本”按钮),这可能是由于需要用户/密码提示 - 所以最初在 .git 中运行“git ls-remote -t --heads origin”目录。要在 Windows 上保存凭据,请尝试运行“git config --global credential.helper wincred”。
回答by Andrew Bobulsky
This was the only technique I came up with that doesn't require you to dig git repo information out of the workspace. This uses Groovy code to inspect the job parameters for the Git URI, and then shells out to git
to do the rest of the work.
这是我想出的唯一一种不需要您从工作区中挖掘 git repo 信息的技术。这使用 Groovy 代码检查 Git URI 的作业参数,然后git
执行剩余的工作。
It should be possible to use JGitto access the repository in native Groovy way, but I can't figure it out.
应该可以使用JGit以本机 Groovy 方式访问存储库,但我无法弄清楚。
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
def build = Thread.currentThread().toString()
def regexp= ".+?/job/([^/]+)/.*"
def match = build =~ regexp
def jobName = match[0][1]
def job = Jenkins.instance.getJob(jobName)
def workspace = job.lastBuild.workspace
for(project in Hudson.instance.items) {
scm = job.scm;
if (scm instanceof hudson.plugins.git.GitSCM) {
for (RemoteConfig cfg : scm.getRepositories()) {
for (URIish uri : cfg.getURIs()) {
gitUri = uri
}
}
}
}
def branchlist = ["/bin/bash", "-c", "git ls-remote --heads ${gitUri}"].execute() | ["/bin/bash", "-c", "cut -f2"].execute()
branchlist.waitFor()
return branchlist.in.text.readLines()
Set that as the Groovy Scriptfor your Source for Valueon an Extended Choice Parameterlike this:
将其设置为扩展选择参数上的Source for Value的Groovy 脚本,如下所示:
And then you'll be able to select from a list of branches as build parameters:
然后您将能够从分支列表中选择作为构建参数: