0
votes

I would like to get the git commit hash of the current build from within a plugin (that is, in a Java class that extends hudson.tasks.Recorder).

This works for a freestyle project:

EnvVars env = run.getEnvironment(listener);
String hash = env.get("GIT_COMMIT");

However, in pipeline projects, the GIT_COMMIT environment variable is evidently not set, so hash becomes null. This is true even for a declarative pipeline where the scm checkout step is implicit.

Is there an alternative way to get the commit hash in a pipeline project?

Edit: To clarify, this is regarding getting git commit hash from the Java code in a Jenkins plugin, not in groovy/Jenkinsfile. It seems like the environment variable will not exist when the plugin is used in pipeline jobs, so I'm looking for a workaround.

2

2 Answers

1
votes

I had a very similar issue - here's how I solved it. The trick is to do it inside you StepExecution class, as it has access to the StepContext - you can then get the set of environment variables from there. The code is like this:

public class MyExecution extends SynchronousNonBlockingStepExecution<ReturnType> {
    ...

    @Override
    protected ReturnType run() throws Exception {
        try {
            StepContext context = getContex();
            EnvVars env = context.get(EnvVars.class);
            ...
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    ...
}
0
votes

Try using currentBuild variable. It holds a changeSets field which has the details about the list of commits.

From the doc:

changeSets

a list of changesets coming from distinct SCM checkouts; each has a kind and is a list of commits; each commit has a commitId, timestamp, msg, author, and affectedFiles each of which has an editType and path;