3

I am trying to extract git branch and commit information in my Jenkinsfile as following:

def commit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
def branch = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()

I am trying to print it afterwards like this:

println("Branch: ${branch}, Commit: ${commit}")

Instead of getting real values, I am left with this:

Branch: org.jenkinsci.plugins.pipeline.modeldefinition.ClosureModelTranslator@545511bf, Commit: org.jenkinsci.plugins.pipeline.modeldefinition.ClosureModelTranslator@545511bf

Am I doing something wrong and how can I retrieve values I need properly?

Edit: No, the suggested duplicate is not an answer, because I am aware of the shell commands used to retrieve the info I need. My Problem is the way that info is being delivered to me, as a ClosureModelTranslator instead of a String.

ioreskovic
  • 5,531
  • 5
  • 39
  • 70
  • Possible duplicate of [Jenkins Workflow Checkout Accessing BRANCH\_NAME and GIT\_COMMIT](http://stackoverflow.com/questions/36304208/jenkins-workflow-checkout-accessing-branch-name-and-git-commit) – burnettk May 02 '17 at 12:55
  • If you cared to read the post you claim to be a duplicate of, you would have actually noticed it is NOT a duplicate @KevinBurnett – ioreskovic May 02 '17 at 13:00
  • i was trying to be helpful. does the answer to that question not help you get the branch and commit information? – burnettk May 02 '17 at 13:06
  • My problem is of a different kind, as you might have noticed. I am indeed trying what is suggested in that thread, but the result I'm getting is of a different type than it should have been. – ioreskovic May 02 '17 at 13:08
  • do you get the same bad result if you do `sh 'git rev-parse HEAD > commit'; def commit = readFile('commit').trim()` ? – burnettk May 02 '17 at 13:14
  • What you are referring to is a hack being used before 'returnStdout' was implemented. I would rather not create and read unnecessary files on my disk just to get a commit. My question is targeted at a specific method, not workarounds that were used before. I understand you're trying to be helpful, but unfortunately, you are not. – ioreskovic May 02 '17 at 13:20
  • And yes, to answer your question, the result is the same as in my problem. – ioreskovic May 02 '17 at 13:27

1 Answers1

9

does this full pipeline work for you? working for me with Pipeline plugin 2.4.

pipeline {
  agent { label 'docker' }
  stages {
    stage("test_capture_output_and_print") {
      steps {
        script {
          def commitSha = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
          println("commitSha: ${commitSha}")
        }
      }
    }
  }
}
burnettk
  • 13,557
  • 4
  • 51
  • 52