2

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?

ycr
  • 12,828
  • 2
  • 25
  • 45
kn_pavan
  • 1,510
  • 3
  • 21
  • 42
  • Do you want to recursively traverse and get all files and directories in the workspace? – ycr Aug 22 '22 at 12:29
  • That's correct @ycr. I would like to include both files and directories, except for the exclusion patten matched ones – kn_pavan Aug 22 '22 at 12:30

1 Answers1

1

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);
ycr
  • 12,828
  • 2
  • 25
  • 45
  • 1
    Thanks for your response, @ycr. I have implemented it in a different way with CustomFileFilter, but your suggestion is the better way to address this. – kn_pavan Aug 23 '22 at 07:39