Jenkins can't find a git SHA key provided by sh

245 views Asked by At

I have a Jenkins app that monitors SCM changes and creates, deletes, or builds jobs accordingly. I have strange errors relating to the git environment.

  • I use a Jenkins git command to fetch data
  • I get the SHA key before and after
  • After that I do a diff between the "before" SHA key and the "after"
  • I get an error message saying it can't find the "after" SHA key
  • I don't know whether this has anything to do with it, but my directory for git seems to have moved from /var/lib/jenkins/workspace/jobName to /var/lib/jenkins/jobs/jobName/workspace. This seems to have occurred a while ago, I can't track down how it happened.

Here is the code. I have simplified it to concentrate on the error.

shaBeforePull = currentGitSha()
echo "before git"
git credentialsId: '7a7eaf05-0bdf-457f-81cf-28be7be3a18c', url: '[email protected]:documentation/classification_upload_to_zoomin.git'
// PRIVATE_KEY = '../../keys/zoomin-private-key_open.ppk'
echo "after git"
shaAfterPull = currentGitSha()
changedFilesBetweenSha(shaBeforePull, shaAfterPull)
...
def currentGitSha() {
    myShCommand = "git rev-parse HEAD"
    currentGitSha = sh(returnStdout: true, script: myShCommand)
    echo "currentGitSha=$currentGitSha"
    return currentGitSha

def changedFilesBetweenSha(sha1, sha2) {
    myShCommand = "git diff --name-only ${sha1} ${sha2}"
    myShOutput = sh(returnStdout: true, script: myShCommand).trim()
    echo "changedFilesBetweenSha = ${myShOutput}"
    myFileList = myShOutput.split('\n')
    return myFileList
}
}

Here is an example of the error output. I've shortened the SHA keys, they are actually 40 chars long:

+ git diff --name-only d70c...ec05
+ c1c8...a41
/var/lib/jenkins/jobs/_upload_jobs_from_gitlab/workspace@tmp/durable-47bfa16f/script.sh: 2: c1c8f...a41: not found
axway.zoominsoftware.io/confluence/AGGGG/EBICSClient_11_MigrationGuide_allOS_en_HTML5-excel.xml
axway.zoominsoftware.io/confluence/AGGGG/custom.properties
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
ERROR: script returned exit code 127
1

There are 1 answers

0
Francis On

Problem was due to a parasite \n in the SHA string. Solved the problem by trimming the SHA string returned. See below the .trim().replace('\n', '')

def currentGitSha() {
    myShCommand = "git rev-parse HEAD"
    currentGitSha = sh(returnStdout: true, script: myShCommand)
    echo "currentGitSha=$currentGitSha"
    currentGitSha = currentGitSha.trim().replace('\n', '')
    return currentGitSha
}

The output is now

+ git diff --name-only d70c...ec05 c1c8...a41

rather than

+ git diff --name-only d70c...ec05
+ c1c8...a41