使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:23:02  来源:igfitidea点击:

Git branch select in Jenkins with groovy script

gitgroovyjenkins

提问by Danial

I am trying to make a Parameterized buildin 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:

有两种可能的方式:

  1. 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.

  2. 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.

  1. 在文件中写入分支名称并配置 Jenkins 以读取此文件 ( project configuration > extend choice parameter and selecting Property file)。

    问题:您必须将本地存储库作为远程存储库的镜像,并使该本地存储库与远程存储库保持同步。换句话说,您必须更新包含可用分支名称 updated 的文件。这需要 cron 安排的作业,我不允许使用这种方法。

  2. 使用 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

尝试使用

Use the following steps:

使用以下步骤:

  1. Add an extensible choice parameter to your job

    enter image description here

  2. select System Groovy Choice parameterin Choice parameter field

    enter image description here

  3. 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
    }
    
  4. Add an active choice reactive parameter to your job

    enter image description here

  5. 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
    }
    

    enter image description here

    Note:

    • $repositorytakes dynamic value from repository parameter.
    • ignore for public repository.
  6. Now try build job with parameter

    enter image description hereenter image description here

  1. 向您的作业添加可扩展的选择参数

    在此处输入图片说明

  2. 在 Choice 参数字段中选择System Groovy Choice 参数

    在此处输入图片说明

  3. 将以下脚本放在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
    }
    
  4. 为您的工作添加主动选择反应参数

    在此处输入图片说明

  5. 参考参数作为存储库和以下脚本放置在 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从存储库参数中获取动态值。
    • 忽略公共存储库。
  6. 现在尝试使用参数构建作业

    在此处输入图片说明在此处输入图片说明

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 属性,例如:

enter image description here

在此处输入图片说明

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_*”):

enter image description here

在此处输入图片说明

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 gitto 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 ValueGroovy 脚本,如下所示:

Extended choice parameter

扩展选择参数

And then you'll be able to select from a list of branches as build parameters:

然后您将能够从分支列表中选择作为构建参数:

Branch list

分公司名单