如何从git repo制作一个groovy脚本列表文件?

时间:2017-09-13 05:51:07

标签: github jenkins groovy jenkins-plugins gitlab

我需要编写一个groovy脚本,与git对话,转到存储库,获取文件名列表,将其存储在数组中并返回。然后我将在Jenkins选择参数中显示。这可能吗?

3 个答案:

答案 0 :(得分:0)

如果您打算使用管道,那将更容易。 您可以使用以下命令以递归方式从目录中获取文件:

import groovy.io.FileType

def fileList = []

def dir = new File("your_repo_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
  fileList << file
}

然后在作业属性中,您需要添加选择参数:

choiceParam(name: 'Repo Files', choices: fileList.join("\n"), description: '')

答案 1 :(得分:0)

将activeChoiceReactiveParam与公共Git存储库一起使用:

parameters {
    stringParam {
        name('BRANCH_NAME')
        defaultValue('master')
        description('git branche name')
        trim(true)
    }
    activeChoiceReactiveParam('PLAYBOOK') {
        description('Select a playbook')
        filterable()
        choiceType('SINGLE_SELECT')
        groovyScript {
            script("""
                |def fileList = ['/bin/bash', '-c', "git clone --single-branch --branch " + BRANCH_NAME + " https://git.repository.com/scm/project/repo.git > /dev/null 2>&1 ; cd repo ; git ls-tree -r origin/" + BRANCH_NAME + " --name-only"].execute()
                |fileList.waitFor()
                |return ["playbook-default.yml"] + fileList.text.readLines().findAll { it.startsWith("playbook").endsWith(".yml") }
                """.stripMargin())
            fallbackScript('return ["playbook-default.yml"]')
        }
        referencedParameter('BRANCH_NAME')
    }

注意:目前,我还没有使用凭据(SSH事件)。我可能是一个很好的进步。

答案 2 :(得分:0)

如果要从HTTPS GIT URL + Jenkins凭据获取分支列表,请使用以下activeChoiceReactiveParam:

activeChoiceReactiveParam('BRANCH_NAME') {
        description('Branch from git repo')
        filterable()
        choiceType('SINGLE_SELECT')
        groovyScript {
            script("""
                |credentialsId = '<TO-REPLACE-WITH-YOUR-CREDENTIAL-ID'
                |def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class, jenkins.model.Jenkins.instance, null, null ).find{it.id == credentialsId}
                |def url = 'https://' + creds.username + ':' + java.net.URLEncoder.encode(creds.password.getPlainText()) + '@bitbucket.url.com/scm/project/repo.git'
                |def fileList = ['/bin/bash', '-c', 'rm -rf branch-name > /dev/null 2>&1 ; git clone ' + url + ' branch-name > /dev/null 2>&1 ; cd branch-name ; git for-each-ref --format="%(refname)" --sort -committerdate | sed "s|refs/[a-z]*/||g" | sed "s|origin/||g" '].execute()
                |fileList.waitFor()
                |return fileList.text.readLines()
                |""".stripMargin())
            fallbackScript('return ["branch-name-not-found"]')
        }
    }