Skip to content

Instantly share code, notes, and snippets.

@yangkun
Created April 4, 2013 17:03
Show Gist options
  • Save yangkun/5312119 to your computer and use it in GitHub Desktop.
Save yangkun/5312119 to your computer and use it in GitHub Desktop.
[groovy] list dirs/files (dir first and sort as name)
import groovy.io.*
def listfiles(dir) {
dlist = []
flist = []
new File(dir).eachDir {dlist << it.name }
dlist.sort()
new File(dir).eachFile(FileType.FILES, {flist << it.name })
flist.sort()
return (dlist << flist).flatten()
}
fs = listfiles(".")
fs.each {
println it
}
@herculosh
Copy link

Nice Script, thanks @yangkun

@TendsToInfinity
Copy link

I am trying to use the same script to list all the files present in a folder while running Jenkins pipeline, but its throwing error, can you help me with that!

@herculosh
Copy link

So if I understand you correctly you want to use the script in the Jenkins pipeline. I haven't tried that yet, but I know that a loop and then more calls from sh-instructions in the scripted-pipeline have to be converted to functions and have to be marked as such.
I am using the script in connection with "Active Choises Reactive Parameter". Works very well under Windows. On Mac OSX, I'm having permissions issues since the upgrade to Catalina.

What do you get for an error in the console log?

@TendsToInfinity
Copy link

Well, I figured it out, and I was running it on a Linux machine.
Thanks, @herculosh for a Quick reply :)

Below is my code, Hopefully, it will useful for someone, I am running this code as a groovy script in Jenkins Pipeline

**@NonCPS
def fetFilenamesFromDir(def dir, def list){
dir.eachFileRecurse (FileType.FILES) { file ->
file = file.toString()
if (file.endsWith("json")){
list << file
}
}
}

node('master'){
def list = []

def dir = new File("dirPathToBeDefined")
fetFilenamesFromDir(dir,list)

for (i in list){
print i
print("\n")
}**

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment