Search code examples
javajenkinsgroovyjenkins-groovy

String filtering


I have a Java like Groovy script, using for Jenkins Pipelines.

In there I have the following scenario. There's a ArrayList with Strings, specifying versions of a script, such as:

def version_list = [] as ArrayList<String>
-> [Version-2.5.0.0, Version-2.4.0.0, Version-2.3.1.0, Version-2.3.0.0, Version-2.0.0.0]

This list is fixed and cannot be modified. I am iterating over the list to get each element, to do some processing.

Additionally I need to check for each element, if there is a point release of the same version i.e.:

   version_list.each{each_version -> //each_version = Version-2.3.0.0
                    if(version_list.contains(2.3.x.0)){ //while x!=0
                       print("Version " + each_version + "has point_release")
                    }
                }

I already tried the following, but this is not working.

 def version_list = [] as ArrayList<String>
 def splitted_ver = [] as ArrayList<String>
 
 version_list.each{each_version ->
                        splitted_ver = each_version.split("\\.")
                        if (version_list.contains("^" + splitted_ver[0] + "." +  splitted_ver[1] + "(.([1-9]+)\\.([0-9]+)\$)")){
                            print(each_version + " has a point_release!")   
                        }else{
                            print("has no point_release")
                        }
                    }

Solution

  • I believe you're going for something like this

    //example list
    def version_list = ["Version-2.2.0.0","Version-2.2.1.0","Version-2.1.1.0","Version-2.1.0.0","Version-2.3.0.0"]
    //group by version first 2 digits
    def ver_map = version_list.groupBy{ ver -> ver.substring(8,11) }
    
    ver_map.each{ k, v ->
        //prints the lowest (root) version in each set, 
        //then determines if any has point version
        println new StringBuilder().append(v.min{it}).append(" ").append(v.any{ 
            it.matches("^Version\\-([0-9])\\.([0-9])\\.([1-9])\\.([0-9])\$")} 
                ? "has a point release!" : "has no point release")}
    

    In this example, prints out

    Version-2.2.0.0 has a point release!
    Version-2.1.0.0 has a point release!
    Version-2.3.0.0 has no point release