简体   繁体   中英

Howto fetch additonal remote git branch in jenkins pipeline

I want to do the following in jenkins:

  1. Checkout/clone my git repostiory in branch1
  2. Fetch branch2 (which is ahead of branch1)
  3. Get all commiting users between branch1 and branch2

I am using a pipeline.

So I do the checkout with:

git branch: 'branch1', credentialsId: 'XXX', url: 'XXX'

Now, I want to additionaly fetch 'branch2', I tried:

sh 'git fetch origin branch2:branch2'

But that fails because of missing credentials.

So how to do this?

You can use the git credential helper, coupled with the credentials plugin. Git credential doco: https://git-scm.com/docs/gitcredentials Credentials plugin: https://jenkins.io/doc/pipeline/steps/credentials-binding/

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'git', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD']]) {
    try {
        sh("git config credential.username ${env.GIT_USERNAME}")
        sh("git config credential.helper '!f() { echo password=\$GIT_PASSWORD; }; f'")
        sh("GIT_ASKPASS=true git fetch origin branch2:branch2")
    } catch (err) {
        println err
        error "ERROR: Failed to fetch changes"
    } finally {
        sh("git config --unset credential.username")
        sh("git config --unset credential.helper")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM