Skip to content

Instantly share code, notes, and snippets.

@ThabetAmer
Last active February 9, 2023 16:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ThabetAmer/798427c72eb980841eb52c90020abb2c to your computer and use it in GitHub Desktop.
Save ThabetAmer/798427c72eb980841eb52c90020abb2c to your computer and use it in GitHub Desktop.
Jenkins Groovy script to read Git repo branches and list them in an array, can be suited with Active Choice Jenkins Plugin
#!/usr/bin/env groovy
/**
* List all Git branches of a repo.
* @author thabet.amer@gmail.com
* @since Jenkins 2.204.1
* @params String url for Git repo URL, String credentialID, Bool activeChoice if ActiveChoice plugin used, String defaultBranch
* @return String array of branch names
*
* Dependencies:
* - Jenkins 2.
* - Jenkins credentials.
* - Key SSH credentials for the Git repo.
* - Commands of ssh-agent, ssh-add and git.
* - Optional: Active Choice Jenkins plugin.
*
* Tested on Jenkins Script Console
*
* For Jenkins, you need to approve below methods, if sandbox security is enabled:
* - staticMethod com.cloudbees.plugins.credentials.CredentialsProvider lookupCredentials java.lang.Class hudson.model.ItemGroup
* - signature : method com.cloudbees.plugins.credentials.common.IdCredentials getId
* - signature : method com.cloudbees.jenkins.plugins.sshcredentials.SSHUserPrivateKey getPrivateKey
* - signature : staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.util.List
* - signature : new java.lang.StringBuffer
* - signature : staticMethod org.codehaus.groovy.runtime.ProcessGroovyMethods consumeProcessOutput java.lang.Process java.lang.Appendable java.lang.Appendable
*/
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import jenkins.model.Jenkins
def getAllBranches(url, credentialID, activeChoice = false, defaultBranch = 'master') {
def jenkinsCredentials = CredentialsProvider.lookupCredentials(
com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey,
Jenkins.instance
);
def key = jenkinsCredentials.findResult { it.id == credentialID ? it.privateKey : null }
if( !key ) {
return 'Error: credentials not found'
}
Process process = ['ssh-agent','bash','-c', "echo '" + key + "' | ssh-add - 2> /dev/null && git ls-remote -t -h " + url].execute()
def out = new StringBuilder()
def err = new StringBuilder()
process.consumeProcessOutput( out, err )
process.waitFor()
if( err.size() > 0 ) return err
if( out.size() > 0 ) {
def branches = out.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') }
if( activeChoice ) {
def defaultBranchIndex = branches.indexOf(defaultBranch)
if( defaultBranchIndex >= 0 ) branches.set(defaultBranchIndex, defaultBranch + ':selected')
}
return branches
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment