I am running a jenkins pipeline, which is fetching git repo like this
Code
stage('Stash sources') {
steps {
script {
stash name: 'repo_source'
}
}
}
Output
Then I want to compare to branches like this
git diff --name-only -r ${env.CHANGE_BRANCH} ${env.CHANGE_TARGET} | xargs -L1 dirname | uniq | awk '{print "./"\$0}'
But, Jenkins doesn`t has the branches now, getting this output
CodePudding user response:
Do you have both branches checked out into your local workspace? If your CHANGE_TARGET
branch is in a remote and not checked out locally, then git cannot find the branch to do the diff. The error states that the branch is not available in your working tree, and this refers to your local file system. So do the checkout first, and then you should have no trouble performing the diff.
CodePudding user response:
Your Jenkins setup, according to the censored image you showed (by the way, don't use images where cut and paste text will serve), "clones" the repository by:
- creating an empty repository (one with no commits and no branches:
git init <path>
) - adding a remote (
git config remote.origin.url <url>
,git config remote.origin.fetch <refspec>
) - running
git fetch ... -- <url> <refspec>
This process is a little bit silly as it could be done with git clone
and/or without repeating the URL and/or refspec.
The refspec
that your Jenkins code uses is:
refs/heads/PRCI:refs/remotes/origin/PR-262
This refspec means that your Git copies only the commits reachable from the origin
Git repository's PRCI
branch; those commits are, in your repository, on no branch, but are found by the name origin/PR-262
.
Your Jenkins code then runs git checkout 1b6c2cf8af034bb41661dce739d9a0058<something-obscured>
. Presumably this is a full raw hash ID. This creates no new branches, so your repository continues to have no branches at all; HEAD
is now detached at the specified commit.
Jenkins itself is pretty horrible and I'm no Jenkins expert, but this is clearly not what you want it to do. You'll need to reconfigure it, or use a different plug-in, or something, or write a Jenkinsfile so that you control everything much more directly. Have your Jenkins run git clone
properly and/or have it copy or create all the branches you want using a proper refspec. A simple (though slightly expensive) way would be to make a full clone and copy all branches:
git fetch origin ' refs/heads/*:refs/heads/*'
or you could use the refs/remotes/origin/
names in your git diff
. That is, instead of:
git diff --name-only -r ${env.CHANGE_BRANCH} ${env.CHANGE_TARGET} | ...
you could use:
git diff --name-only -r origin/${env.CHANGE_BRANCH} origin/${env.CHANGE_TARGET} | ...
(but you'd still need a full clone, not one that changes branch PRCI
into remote-tracking-name PR-262
).
There is probably something else going on here that explains the reason for the weird refspec passed to git fetch
, and it would be worth figuring out what that is.