srini
srini

Reputation: 1208

how to get repo name in Jenkins pipeline

I'm using Jenkins Scripted Pipeline that uses Groovy style scripting, and created a Jenkinsfile to describe the pipeline. I need to create the workspace with the folder name same as git repo name, and then checkout the code in the workspace folder. My question is, before doing the checkout scm, is there a way to know the git repo name or the git repo url?

Upvotes: 16

Views: 33523

Answers (3)

Yeo
Yeo

Reputation: 11784

If your Jenkins server uses Git Plugin, you could use GIT_URL env variable to shorten your code. It support most Git Server (e.g. Bitbucket, Github, GitLab, Gitea, Tuleap)

GIT_URL.tokenize('/.')[-2]

PS: Crediting Ben Lee for his suggestion on the tokenizer tips below.

Upvotes: 2

Brini
Brini

Reputation: 81

Maybe a silly answer, but isn't it possible using the environment Jenkins environment variable env.BITBUCKET_REPOSITORY?

Upvotes: 1

herm
herm

Reputation: 16315

String determineRepoName() {
    return scm.getUserRemoteConfigs()[0].getUrl().tokenize('/')[3].split("\\.")[0]
}

This relatively ugly code is what I use to get the repoName. The key is that the URL of the repo is stored in:

scm.getUserRemoteConfigs()[0].getUrl()

from there you need to do some string ops to get what you want.


Update:

String determineRepoName() {
    return scm.getUserRemoteConfigs()[0].getUrl().tokenize('/').last().split("\\.")[0]
}

This works also for repositories with a deeper hierarchy (https://domain/project/subproject/repo or ssh git repo which does not contain the two // at the start.

Upvotes: 23

Related Questions