Jason
Jason

Reputation: 2492

Cannot get git commits for multiple repos using Multiple-SCM-Plugin in Jenkins

So, I have configured a jenkins job which checks out master branch from 3 repos. Now I want to get the latest changes for all the three repos.

Currently, the GIT_COMMIT env variable only gives the commit has for the last repo added in the configuration and not for all three of them.

Is there any way to get the previous commit and the current git commit for all the three repositories ?

Upvotes: 8

Views: 2633

Answers (1)

Jake Stoeffler
Jake Stoeffler

Reputation: 2885

I ran into the same issue and decided to fork the Multiple SCMs plugin in order to fix it: https://github.com/JakeStoeffler/multiple-scms-plugin

If you wish, simply clone my repo and run mvn to build the HPI file (located at target/multiple-scms.hpi), which you can upload manually and install in Jenkins. If you'd rather do the tweaking yourself, clone the original repo directly, open up MultiSCM.java, and replace the code in the buildEnvVars() method with something like the following:

@Override
public void buildEnvVars(AbstractBuild<?,?> build, Map<String, String> env) {
    // Add each SCM's env vars, appending indices where needed to avoid collisions
    for (int i = 0; i < scms.size(); i++) {
        try {
            EnvVars currScmVars = new EnvVars();
            scms.get(i).buildEnvVars(build, currScmVars);
            for (Entry<String, String> entry : currScmVars.entrySet()) {
                if (env.containsKey(entry.getKey())) {
                    // We have a collision; append the index of this SCM to the env var name
                    env.put(entry.getKey() + "_" + i, entry.getValue());
                } else {
                    // No collision; just put the var as usual
                    env.put(entry.getKey(), entry.getValue());
                }
            }
        }
        catch(NullPointerException npe) {}
    }
}

Hopefully the comments are pretty self-explanatory there. Basically, the bug in the original code is that when you have multiple SCMs with the same environment variable names, the variables get overwritten as they're being iterated through. We work around this by preventing these overwrites and instead appending an index to the variable name.

Here's an example of how to use it: if our project has 3 Git SCMs configured, we can now access the latest commit hash of each Git repo individually by using the env vars GIT_COMMIT, GIT_COMMIT_1, and GIT_COMMIT_2. The appended indices correspond to the order of the SCMs in the project configuration in Jenkins.

Obviously this is a quick and dirty solution, but it works for what I needed to do. Feel free to customize it to fit your needs.

Upvotes: 2

Related Questions