groovyjenkinsjenkins-scriptler

Returning a list of files in Groovy sorted by modified time


I’m trying to return a list of directories to populate a drop down menu in Jenkins (Scriptler). This is what I have so far:

import groovy.io.FileType

String snapshotBase="/(path-I-wish-to-look-at)/"
  def result=[];assert result.size()==0
  def releaseDir=new File(snapshotBase)
  if ( releaseDir.exists() ) {
  releaseDir.eachFile FileType.DIRECTORIES,{
    result.add(it.name)
    }
  }
return result

This returns the list of directories, but for convenience I would like them sorted so that the most recently modified directories appear at the top/beginning of the list. I’m new to Groovy and Java, but I’ve taken a few stabs at some options. I thought maybe there would be some attributes to FileType.DIRECTORIES other than just the name, but I so far haven’t been able to find what I’m looking for. (I guessed at it.date and it.modified, but those appear to be invalid.) I found a snippet of code from virtualeyes that looked promising:

new File(path-to-your-directory).eachFileRecurse{file->
println file.lastModified()
}

I haven’t been able to cobble together the correct syntax, though, to fit that into what I’m doing. I was thinking maybe the Java method lastModified() would hold some solution, but I haven’t been able to find success with that, either.


Solution

  • Instead of adding the names, add the files. Then sort by reverse lastModified and gather the names (*.name is like .collect{it.name})

    def files=[]
    ("/tmp" as File).eachFile groovy.io.FileType.DIRECTORIES, {
        files << it
    }
    def result = files.sort{ a,b -> b.lastModified() <=> a.lastModified() }*.name