Skip to content

Instantly share code, notes, and snippets.

@navidurrahman
Last active October 3, 2019 18:16
Show Gist options
  • Save navidurrahman/551af240b2b2ba5769d86e7667e5ad96 to your computer and use it in GitHub Desktop.
Save navidurrahman/551af240b2b2ba5769d86e7667e5ad96 to your computer and use it in GitHub Desktop.
Jenkins Job DSL Example - Bitbucket project and branches
// URL components
String baseUrl = "https://bitbucket.org/rest/api"
String version = "1.0"
String project = "SYS"
// Put it all together
String reposUrl = [baseUrl, version, "projects", project, "repos"].join("/")
def send_request(url_string){
// Create URL
Boolean enableAuthentication = true
URL url = url_string.toURL()
// Open connection
URLConnection connection = url.openConnection()
if (enableAuthentication) {
String username = "dummy_user"
String password = "dummy_pass"
// Create authorization header using Base64 encoding
String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
// Set authorization header
connection.setRequestProperty ("Authorization", basicAuth)
}
// Open input stream
InputStream inputStream = connection.getInputStream()
json_data = new groovy.json.JsonSlurper().parseText(inputStream.text)
// Close the stream
inputStream.close()
return json_data
}
def reposJson = send_request(reposUrl)
def repos = reposJson.get('values')
repos.each { repo_item->
def repoName = repo_item.get('name')
String branchesUrl = [baseUrl, version, "projects", project, "repos" ,repoName, "branches"].join("/")
// Get JSON output
def branchesJson = send_request(branchesUrl)
def branches = branchesJson.get('values')
// Iterate through branches JSON
branches.each { branch_item->
def branchName = branch_item.get('displayId')
// Check if branch name and age are valid
def jobName = "${project}-${repoName}-${branchName}".replaceAll('/', '-')
job(jobName) {
scm {
// git or bitbucket URL
git("git://github.com/${project}/${repoName}.git", branchName)
}
steps {
maven("test -Dproject.name=${repoName}/${branchName}")
}
}
}
}
@NasAmin
Copy link

NasAmin commented May 24, 2017

That is good, how do you get age of the branch? I don't see anything in the returned json about created/modified date at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment