[git] In Jenkins, how to checkout a project into a specific directory (using GIT)

Sorry for the 'svn' style - we are in a process of migration from SVN to GIT (including our CI Jenkins environment).

What we need is to be able to make Jenkins to checkout (or should I say clone?) the GIT project (repository?) into a specific directory. We've tried some refspecs magic but it wasn't too obvious to understand and use successfully.

Furthermore, if in the same Jenkins project we need to checkout several private GitHub repositories into several separate dirs under a project root, how can we do it please?

We have GitHub plugin installed. Hope we've phrased the things right.

This question is related to git github hudson jenkins jenkins-plugins

The answer is


Find repoName from the url, and then checkout to the specified directory.

String url = 'https://github.com/foo/bar.git';
String[] res = url.split('/');
String repoName = res[res.length-1];
if (repoName.endsWith('.git')) repoName=repoName.substring(0, repoName.length()-4);

checkout([
  $class: 'GitSCM', 
  branches: [[name: 'refs/heads/'+env.BRANCH_NAME]],
  doGenerateSubmoduleConfigurations: false,
  extensions: [
    [$class: 'RelativeTargetDirectory', relativeTargetDir: repoName],
    [$class: 'GitLFSPull'],
    [$class: 'CheckoutOption', timeout: 20],
    [$class: 'CloneOption',
        depth: 3,
        noTags: false,
        reference: '/other/optional/local/reference/clone',
        shallow: true,
        timeout: 120],
    [$class: 'SubmoduleOption', depth: 5, disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', shallow: true, trackingSubmodules: true]
  ],
  submoduleCfg: [],
  userRemoteConfigs: [
    [credentialsId: 'foobar',
    url: url]
  ]
])

In the new Jenkins 2.0 pipeline (previously named the Workflow Plugin), this is done differently for:

  • The main repository
  • Other additional repositories

Here I am specifically referring to the Multibranch Pipeline version 2.9.

Main repository

This is the repository that contains your Jenkinsfile.

In the Configure screen for your pipeline project, enter your repository name, etc.

Do not use Additional Behaviors > Check out to a sub-directory. This will put your Jenkinsfile in the sub-directory where Jenkins cannot find it.

In Jenkinsfile, check out the main repository in the subdirectory using dir():

dir('subDir') {
    checkout scm
}

Additional repositories

If you want to check out more repositories, use the Pipeline Syntax generator to automatically generate a Groovy code snippet.

In the Configure screen for your pipeline project:

  1. Select Pipeline Syntax. In the Sample Step drop down menu, choose checkout: General SCM.
  2. Select your SCM system, such as Git. Fill in the usual information about your repository or depot.
  3. Note that in the Multibranch Pipeline, environment variable env.BRANCH_NAME contains the branch name of the main repository.
  4. In the Additional Behaviors drop down menu, select Check out to a sub-directory
  5. Click Generate Groovy. Jenkins will display the Groovy code snippet corresponding to the SCM checkout that you specified.
  6. Copy this code into your pipeline script or Jenkinsfile.

In the new Pipeline flow, following image may help ..

enter image description here


I do not use github plugin, but from the introduction page, it is more or less like gerrit-trigger plugin.

You can install git plugin, which can help you checkout your projects, if you want to include multi-projects in one jenkins job, just add Repository into your job.


I agree with @Lukasz Rzanek that we can use git plugin

But, I use option: checkout to a sub-direction what is enable as follow:
In Source Code Management, tick Git
click add button, choose checkout to a sub-directory

enter image description here


It's worth investigating the Pipeline plugin. With the plugin you can checkout multiple VCS projects into relative directory paths. Beforehand creating a directory per VCS checkout. Then issue commands to the newly checked out VCS workspace. In my case I am using git. But you should get the idea.

node{
    def exists = fileExists 'foo'
    if (!exists){
        new File('foo').mkdir()
    }
    dir ('foo') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
    def exists = fileExists 'bar'
    if (!exists){
        new File('bar').mkdir()
    }
    dir ('bar') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
    def exists = fileExists 'baz'
    if (!exists){
        new File('baz').mkdir()
    }
    dir ('baz') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
}

Furthermore, if in the same Jenkins project we need to checkout several private GitHub repositories into several separate dirs under a project root. How can we do it please?

The Jenkin's Multiple SCMs Plugin has solved the several repositories problem for me very nicely. I have just got working a project build that checks out four different git repos under a common folder. (I'm a bit reluctant to use git super-projects as suggested previously by Lukasz Rzanek, as git is complex enough without submodules.)


Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to github

Does the target directory for a git clone have to match the repo name? Issue in installing php7.2-mcrypt How can I switch to another branch in git? How to draw checkbox or tick mark in GitHub Markdown table? How to add a new project to Github using VS Code git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054 How to add empty spaces into MD markdown readme on GitHub? key_load_public: invalid format git - remote add origin vs remote set-url origin Cloning specific branch

Examples related to hudson

How/When does Execute Shell mark a build as failure in Jenkins? How to create and add users to a group in Jenkins for authentication? In Jenkins, how to checkout a project into a specific directory (using GIT) Jenkins - passing variables between jobs? How are environment variables used in Jenkins with Windows Batch Command? Jenkins/Hudson - accessing the current build number? Error - trustAnchors parameter must be non-empty Archive the artifacts in Jenkins Jenkins / Hudson environment variables How to trigger a build only if changes happen on particular set of files

Examples related to jenkins

Maven dependencies are failing with a 501 error Jenkins pipeline how to change to another folder Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding How to solve npm install throwing fsevents warning on non-MAC OS? Run bash command on jenkins pipeline Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Jenkins pipeline if else not working Error "The input device is not a TTY"

Examples related to jenkins-plugins

How to set and reference a variable in a Jenkinsfile Jenkins: Is there any way to cleanup Jenkins workspace? How to get build time stamp from Jenkins build variables? gpg: no valid OpenPGP data found How to install a plugin in Jenkins manually Execute Shell Script after post build in Jenkins Jenkins CI: How to trigger builds on SVN commit How to get a list of installed Jenkins plugins with name and version pair In Jenkins, how to checkout a project into a specific directory (using GIT)