001/* 002 * SonarQube 003 * Copyright (C) 2009-2017 SonarSource SA 004 * mailto:info AT sonarsource DOT com 005 * 006 * This program is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * This program is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020package org.sonar.api.utils; 021 022import java.util.HashMap; 023import java.util.Map; 024import java.util.regex.Pattern; 025import javax.annotation.Nullable; 026import org.apache.commons.lang.StringUtils; 027 028/** 029 * Implementation of Ant-style matching patterns. 030 * Contrary to other implementations (like AntPathMatcher from Spring Framework) it is based on {@link Pattern Java Regular Expressions}. 031 * To increase performance it holds an internal cache of all processed patterns. 032 * <p> 033 * Following rules are applied: 034 * <ul> 035 * <li>? matches single character</li> 036 * <li>* matches zero or more characters</li> 037 * <li>** matches zero or more 'directories'</li> 038 * </ul> 039 * <p> 040 * Some examples of patterns: 041 * <ul> 042 * <li><code>org/T?st.java</code> - matches <code>org/Test.java</code> and also <code>org/Tost.java</code></li> 043 * <li><code>org/*.java</code> - matches all <code>.java</code> files in the <code>org</code> directory, 044 * e.g. <code>org/Foo.java</code> or <code>org/Bar.java</code></li> 045 * <li><code>org/**</code> - matches all files underneath the <code>org</code> directory, 046 * e.g. <code>org/Foo.java</code> or <code>org/foo/bar.jsp</code></li> 047 * <li><code>org/**/Test.java</code> - matches all <code>Test.java</code> files underneath the <code>org</code> directory, 048 * e.g. <code>org/Test.java</code> or <code>org/foo/Test.java</code> or <code>org/foo/bar/Test.java</code></li> 049 * <li><code>org/**/*.java</code> - matches all <code>.java</code> files underneath the <code>org</code> directory, 050 * e.g. <code>org/Foo.java</code> or <code>org/foo/Bar.java</code> or <code>org/foo/bar/Baz.java</code></li> 051 * </ul> 052 * <p> 053 * Another implementation, which is also based on Java Regular Expressions, can be found in 054 * <a href="https://github.com/JetBrains/intellij-community/blob/idea/107.743/platform/util/src/com/intellij/openapi/util/io/FileUtil.java#L847">FileUtil</a> 055 * from IntelliJ OpenAPI. 056 * 057 * 058 * @since 1.10 059 */ 060public class WildcardPattern { 061 062 private static final Map<String, WildcardPattern> CACHE = new HashMap<>(); 063 private static final String SPECIAL_CHARS = "()[]^$.{}+|"; 064 065 private Pattern pattern; 066 private String stringRepresentation; 067 068 protected WildcardPattern(String pattern, String directorySeparator) { 069 this.stringRepresentation = pattern; 070 this.pattern = Pattern.compile(toRegexp(pattern, directorySeparator)); 071 } 072 073 private static String toRegexp(String antPattern, String directorySeparator) { 074 final String escapedDirectorySeparator = '\\' + directorySeparator; 075 076 final StringBuilder sb = new StringBuilder(antPattern.length()); 077 078 sb.append('^'); 079 080 int i = antPattern.startsWith("/") || antPattern.startsWith("\\") ? 1 : 0; 081 while (i < antPattern.length()) { 082 final char ch = antPattern.charAt(i); 083 084 if (SPECIAL_CHARS.indexOf(ch) != -1) { 085 // Escape regexp-specific characters 086 sb.append('\\').append(ch); 087 } else if (ch == '*') { 088 if (i + 1 < antPattern.length() && antPattern.charAt(i + 1) == '*') { 089 // Double asterisk 090 // Zero or more directories 091 if (i + 2 < antPattern.length() && isSlash(antPattern.charAt(i + 2))) { 092 sb.append("(?:.*").append(escapedDirectorySeparator).append("|)"); 093 i += 2; 094 } else { 095 sb.append(".*"); 096 i += 1; 097 } 098 } else { 099 // Single asterisk 100 // Zero or more characters excluding directory separator 101 sb.append("[^").append(escapedDirectorySeparator).append("]*?"); 102 } 103 } else if (ch == '?') { 104 // Any single character excluding directory separator 105 sb.append("[^").append(escapedDirectorySeparator).append("]"); 106 } else if (isSlash(ch)) { 107 // Directory separator 108 sb.append(escapedDirectorySeparator); 109 } else { 110 // Single character 111 sb.append(ch); 112 } 113 114 i++; 115 } 116 117 sb.append('$'); 118 119 return sb.toString(); 120 } 121 122 private static boolean isSlash(char ch) { 123 return ch == '/' || ch == '\\'; 124 } 125 126 /** 127 * Returns string representation of this pattern. 128 * 129 * @since 2.5 130 */ 131 @Override 132 public String toString() { 133 return stringRepresentation; 134 } 135 136 /** 137 * Returns true if specified value matches this pattern. 138 */ 139 public boolean match(String value) { 140 value = StringUtils.removeStart(value, "/"); 141 value = StringUtils.removeEnd(value, "/"); 142 return pattern.matcher(value).matches(); 143 } 144 145 /** 146 * Returns true if specified value matches one of specified patterns. 147 * 148 * @since 2.4 149 */ 150 public static boolean match(WildcardPattern[] patterns, String value) { 151 for (WildcardPattern pattern : patterns) { 152 if (pattern.match(value)) { 153 return true; 154 } 155 } 156 return false; 157 } 158 159 /** 160 * Creates pattern with "/" as a directory separator. 161 * 162 * @see #create(String, String) 163 */ 164 public static WildcardPattern create(String pattern) { 165 return create(pattern, "/"); 166 } 167 168 /** 169 * Creates array of patterns with "/" as a directory separator. 170 * 171 * @see #create(String, String) 172 */ 173 public static WildcardPattern[] create(@Nullable String[] patterns) { 174 if (patterns == null) { 175 return new WildcardPattern[0]; 176 } 177 WildcardPattern[] exclusionPAtterns = new WildcardPattern[patterns.length]; 178 for (int i = 0; i < patterns.length; i++) { 179 exclusionPAtterns[i] = create(patterns[i]); 180 } 181 return exclusionPAtterns; 182 } 183 184 /** 185 * Creates pattern with specified separator for directories. 186 * <p> 187 * This is used to match Java-classes, i.e. <code>org.foo.Bar</code> against <code>org/**</code>. 188 * <b>However usage of character other than "/" as a directory separator is misleading and should be avoided, 189 * so method {@link #create(String)} is preferred over this one.</b> 190 * 191 * <p> 192 * Also note that no matter whether forward or backward slashes were used in the <code>antPattern</code> 193 * the returned pattern will use <code>directorySeparator</code>. 194 * Thus to match Windows-style path "dir\file.ext" against pattern "dir/file.ext" normalization should be performed. 195 * 196 */ 197 public static WildcardPattern create(String pattern, String directorySeparator) { 198 String key = pattern + directorySeparator; 199 WildcardPattern wildcardPattern = CACHE.get(key); 200 if (wildcardPattern == null) { 201 wildcardPattern = new WildcardPattern(pattern, directorySeparator); 202 CACHE.put(key, wildcardPattern); 203 } 204 return wildcardPattern; 205 } 206}