Home > Back-end >  hudson.FilePath : How to list subDirectories as well whole using excludes glob filter
hudson.FilePath : How to list subDirectories as well whole using excludes glob filter

Time:08-24

I am working on a Jenkins custom Plugin, where I need to list all valid FilePaths: sub-Directories and child files, excluding some temporary files like .git,.npm,.cache etc, the full list is included in below code sample:

String excludes = "node_modules/**/*,**/node_modules/**/*,.git/**,.npm*/**,**/.npm*/**,**/.nvm*/**,**/cronus/**,**/.cache/**,**/npmtmp/**,**/.tmp/**";
FilePath[] validFileAndFolderPaths = workspace.list("**/*", excludes);

The above code is giving me all of the files in the workspace FilePath, but not the sub-directories.

There is a method for listing all sub-directories hudson.FilePath#listDirectories, but that doesn't support exclusion list. Any help on how to achieve this requirement?

CodePudding user response:

You can't use hudson.FilePath#listDirectories with a exclude/include patterns. Hence you will have to implement your own method to get the directories supporting Ant pattern matching. Here is a sample code.

Dependency

<dependency>
  <groupId>org.apache.ant</groupId>
  <artifactId>ant</artifactId>
</dependency>

Java Code

private String [] getDirectories(String baseDir, String excludes) {

    DirSet ds = new DirSet();
    ds.setDir(new File(baseDir));
    for (String token : excludes.split(",")) {
        ds.createExclude().setName(token);
    }
    DirectoryScanner scanner = ds.getDirectoryScanner(new Project());
    String[] directories = scanner.getIncludedDirectories();

    return directories;
}

Calling the method

String excludes = "node_modules/**/*,**/node_modules/**/*,.git/**,.npm*/**,**/.npm*/**,**/.nvm*/**,**/cronus/**,**/.cache/**,**/npmtmp/**,**/.tmp/**";
String dir = "/SOME/DIR";
String[] directories = getDirectories(dir, excludes);
  • Related