Search code examples
batch-filevariablesjenkinscommitenvironment

Save commit message strng value in an envionment variable via Jenkins with bat (Windows) and using Pipeline?


I would like to save the value of some string (in this case the commit message from Git) as an environment variable for a multibranch pipeline in Jenkins. This is part of my my pipeline:

pipeline {
  agent any
  environment {
        GIT_MESSAGE = """${bat(
            script: 'git log --no-walk --format=format:%s ${%GIT_COMMIT%}', 
            returnStdout: true
            )}""".trim()
    }
  stages {
      stage('Environment A'){
      steps{
        bat 'echo %GIT_MESSAGE%'
        bat '%GIT_MESSAGE%'
      }
    }
...
}

But after this, the echo %GIT_MESSAGE% is retruning:

echo D:\.jenkins\workspace\folder log --no-walk --format=format:GIT_COMMIT}  1>git

And naturally if I run it with bat '%GIT_MESSAGE%' it fails. I know part of the answer may lay in the way to pass the environment variable to the bat script ${%GIT_COMMIT%} but I do not seem to be able to figure out how.

Any ideas?


Solution

  • I just solved this issue. It had to do with the way groovy performs string interpolation. I left it working with single line strings (i.e. "...") but I am pretty sure it should work with multiline strings ("""..."""). This is the working solution for now:

    pipeline {
      agent any
      environment {
            GIT_MESSAGE = "${bat(script: "git log --no-walk --format=format:%%s ${GIT_COMMIT}", returnStdout: true)}".readLines().drop(2).join(" ")
        }
      stages {
          stage('Environment A'){
          steps{
            bat 'echo %GIT_MESSAGE%'
            bat '%GIT_MESSAGE%'
          }
        }
    ...
    }
    

    Notice that readLines(), drop(2) and join(" ") where necessary in order to get the commit message only without the path from which the command was run. Also it was important to use "..." inside the script parameter of the bat function, otherwise interpolation does not happen and the environment variable GIT_COMMIT would have not been recognized.