1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.resourceloader.file;
35
36 import java.io.IOException;
37 import java.nio.file.DirectoryStream;
38 import java.nio.file.Path;
39 import java.nio.file.PathMatcher;
40 import java.util.ArrayList;
41 import java.util.List;
42 import java.util.regex.Pattern;
43
44 import com.google.common.base.Predicate;
45
46
47
48
49
50
51
52
53 public class ExclusionsFilter implements Predicate<Path>, DirectoryStream.Filter<Path> {
54
55 private final Path rootPath;
56 private final List<String> excludePatterns;
57
58
59
60
61
62
63
64
65 public ExclusionsFilter(Path rootPath, List<String> excludedDirectories, List<String> excludedExtensions, List<String> otherPatterns) {
66 this.rootPath = validateRootPath(rootPath);
67 this.excludePatterns = new ArrayList<>();
68 addDirectoryExcludes(excludePatterns, excludedDirectories);
69 addExtensionExcludes(excludePatterns, excludedExtensions);
70 addPatternList(excludePatterns, otherPatterns);
71 }
72
73 @Override
74 public boolean accept(Path entry) throws IOException {
75 return apply(entry);
76 }
77
78 @Override
79 public boolean apply(Path dir) {
80
81 if (!dir.isAbsolute() || !dir.startsWith(rootPath)) {
82 return false;
83 }
84
85 Path rel = rootPath.relativize(dir);
86
87
88 for (String excludePattern : excludePatterns) {
89
90 final PathMatcher matcher = dir.getFileSystem().getPathMatcher(excludePattern);
91 if (matcher.matches(rel)) {
92 return false;
93 }
94 }
95
96 return true;
97 }
98
99 private Path validateRootPath(Path rootPath) {
100 if (!rootPath.isAbsolute()) {
101 throw new IllegalStateException(rootPath + " is not an absolute Path.");
102 }
103 return rootPath;
104 }
105
106 private void addDirectoryExcludes(List<String> excludePatterns, List<String> excludedDirectories) {
107 for (String directory : excludedDirectories) {
108 excludePatterns.add("regex:(^|.*/)" + Pattern.quote(directory) + "($|/.*)");
109 }
110 }
111
112 private void addExtensionExcludes(List<String> excludePatterns, List<String> excludedExtensions) {
113 for (String ext : excludedExtensions) {
114 excludePatterns.add("regex:.*\\." + Pattern.quote(ext) + "$");
115 }
116 }
117
118 private void addPatternList(List<String> excludePatterns, List<String> stringPatterns) {
119 for (String pattern : stringPatterns) {
120 if (pattern.startsWith("glob:") || pattern.startsWith("regex:")) {
121 excludePatterns.add(pattern);
122 } else {
123 excludePatterns.add("regex:" + pattern);
124 }
125 }
126 }
127
128 }