Search code examples
mavenjenkinsdependenciespom.xmljenkins-groovy

Jenkins: how to get specific dependency version in pom.xml via readMavenPom or mvn help:evaluate?


Already read a ton of pages and howtos and learnt that readMavenPom returns a Model object. It's quite easy to get root values, but how can I get a specific dependency version?

Using mvn help:evaluate doesn't help either: I don't know what to evaluate to get the info.

Can anyone give some advice?

Made a lot of tests but I actually totally ignore what should I evaluate.


Solution

  • Model object contains all the information related to dependencies as well:

    pipeline{
        
        agent{label "master"}
        stages{
            stage('1'){
                steps{
                    script{
                        def pom = """
                        <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                                 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.passfailerror</groupId>
        <artifactId>some-artifact</artifactId>
        <version>1.0.0</version>
    
        <dependencies>
            <dependency>
                <groupId>com.dependency.one</groupId>
                <artifactId>artifact-name1</artifactId>
                <version>1.0</version>
            </dependency>
            <dependency>
                <groupId>com.dependency.two</groupId>
                <artifactId>artifact-name2</artifactId>
                <version>2.0</version>
            </dependency>
            </dependencies>
            </project>
                        """
                        
                        writeFile file:"pom.xml", text:pom
                        def model = readMavenPom file:"pom.xml"
                        
                        echo model.getDependencies().findAll{it.artifactId == "artifact-name2"}.first().getVersion()
                        echo model.getDependencies().findAll{it.groupId == "com.dependency.one"}.first().getVersion()
                    }
                }
            }
        }
        
    }
    

    You can easily find version of each dependency entry by artifactId, groupId or anything you want.