1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.basepom.mojo.dvc;
16
17 import static com.google.common.base.Preconditions.checkNotNull;
18 import static com.google.common.base.Preconditions.checkState;
19
20 import java.util.List;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23
24 import com.google.common.annotations.VisibleForTesting;
25 import com.google.common.base.Splitter;
26
27
28
29
30 public final class QualifiedNameMatcher {
31
32 private static final Pattern WILDCARD_REGEXP = Pattern.compile("[^*]+|(\\*)");
33 private static final Pattern WILDCARD_MATCH = Pattern.compile(".*");
34
35 private final Pattern groupPattern;
36 private final Pattern artifactPattern;
37
38 public static QualifiedNameMatcher fromQualifiedName(final QualifiedName name) {
39 checkNotNull(name, "name is null");
40
41 return new QualifiedNameMatcher(name.getMinimalName());
42 }
43
44 public QualifiedNameMatcher(final String pattern) {
45 checkNotNull(pattern, "pattern is null");
46 final List<String> elements = Splitter.on(':').trimResults().splitToList(pattern);
47 checkState(!elements.isEmpty() && elements.size() < 3, "Pattern %s is not a valid inclusion pattern!", pattern);
48
49 this.groupPattern = compileWildcard(elements.get(0).trim());
50 this.artifactPattern = compileWildcard(elements.size() > 1 ? elements.get(1).trim() : "");
51 }
52
53 public boolean matches(QualifiedName artifactName) {
54 checkNotNull(artifactName, "artifactName is null");
55
56 return groupPattern.matcher(artifactName.getGroupId()).matches()
57 && artifactPattern.matcher(artifactName.getArtifactId()).matches();
58 }
59
60 @VisibleForTesting
61 static Pattern compileWildcard(final String wildcard) {
62 if (wildcard.isEmpty()) {
63 return WILDCARD_MATCH;
64 }
65
66 final Matcher m = WILDCARD_REGEXP.matcher(wildcard);
67 final StringBuffer b = new StringBuffer();
68 while (m.find()) {
69 if (m.group(1) != null) {
70 m.appendReplacement(b, ".*");
71 } else {
72 m.appendReplacement(b, "\\\\Q" + m.group(0) + "\\\\E");
73 }
74 }
75 m.appendTail(b);
76 return Pattern.compile(b.toString());
77 }
78 }