4

Using the env.BRANCH_NAME variable accessible in the Jenkinsfile outside of the pipeline{} block, I have set up a variable used to conditionally set the node used to build the git branch. I would like to also access the name of the developer who committed the change, but I do not know how to access it.

I need a variable assigned before the pipeline block to assign to pipeline { agent { label selected_agent }}. If I attempt to use a method call instead of a variable there, the Java parser complains:

java.lang.ClassCastException: org.jenkinsci.plugins.pipeline.modeldefinition.agent.impl.Label.label expects class java.lang.String but received class org.jenkinsci.plugins.pipeline.modeldefinition.ClosureModelTranslator

I cannot run code inside the pipeline block before the agent block to define the variable, and the agent block has to be the first part of the pipeline declaration.

If I could run bash commands, I could access the author's name, and in fact I do use it at the end of the Jenkinsfile to pull the git committer's name for the status email, but if I attempt to use sh() before the pipeline block I get this error:

Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node

I am not sure what else to try. Does anyone have a suggestion?

Dan Cornilescu
  • 6,730
  • 2
  • 19
  • 44

1 Answers1

4

I'm not entirely sure what you're trying to ask in your question, so I'm answering the question I believe you're trying to ask.

A build does not necessarily have a single commit author. It has a list of committers, which can be empty or can contain many committers. To create this list, you can use this snippet in a scripted Pipeline (note that you may need to disable the sandbox in order to use .collect()):

changeAuthors = currentBuild.changeSets.collect { set ->
  set.collect { entry -> entry.author.fullName }
}.flatten()

I use this with Git as my SCM; I'm not sure if it works with other SCMs.

See also the following questions on StackOverflow (some answers may be outdated):

jayhendren
  • 2,952
  • 7
  • 15