Search code examples
jenkinsjenkins-pipeline

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?


Solution

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