recurrence of problems
Recently wrote a groovy replacement program incremental pipeline script (will Java can also read), schematic script is as follows:
// Get the list of files method
def listFiles(folder) {
def output = sh(script: "ls ${folder}", returnStdout: true).trim()
return ('\n') as List
}
// Call the above method to get the list of jars to add in the lib directory.
def addJars = listFiles("lib")
println "addJars value is "+addJars
//List will be empty.
if(addJars ! = null && ! ()){
println "addJars list length = " + ()
for(addJar in addJars){
println "addJar="+addJar
}
}
Final output results:
addJars value is []
addJars list length=1
addJar=
What? My judgment didn't take effect?
analyze
ls Catalog
The returned string is typically\n document 1\n document 2\n
Strings of this format are represented by the\n
Separation should be fine.
Continued analysis('\n') as List
This line, after testing, you can find a phenomenon: when the output string is an empty string, the output string is the same as the output string, but the output string is the same as the output string.""
When the array/list is converted by this split method, it is with an empty string element!
The code here can be simplified for testing:
This split method is a groovy inheritance of java's String type, and writing code in Java also has this problem:
So, the split method returns an array with the elements of the empty string when the string is empty!
settle (a dispute)
- Option 1: After split, if the length of the array is 1 and the first element is an empty string, return an empty array/list.
- Option 2: The array returned by split removes the empty string elements.
My solution uses option 2, along with groovy's operator overloading:
def listFiles(folder) {
def output = sh(script: "ls ${folder}", returnStdout: true).trim()
def list = ('\n') as List
return list - ''
}