001/* 002 * SonarQube 003 * Copyright (C) 2009-2016 SonarSource SA 004 * mailto:contact 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 org.apache.commons.lang.StringUtils; 026 027/** 028 * Implementation of Ant-style matching patterns. 029 * Contrary to other implementations (like AntPathMatcher from Spring Framework) it is based on {@link Pattern Java Regular Expressions}. 030 * To increase performance it holds an internal cache of all processed patterns. 031 * <p> 032 * Following rules are applied: 033 * <ul> 034 * <li>? matches single character</li> 035 * <li>* matches zero or more characters</li> 036 * <li>** matches zero or more 'directories'</li> 037 * </ul> 038 * <p> 039 * Some examples of patterns: 040 * <ul> 041 * <li><code>org/T?st.java</code> - matches <code>org/Test.java</code> and also <code>org/Tost.java</code></li> 042 * <li><code>org/*.java</code> - matches all <code>.java</code> files in the <code>org</code> directory, 043 * e.g. <code>org/Foo.java</code> or <code>org/Bar.java</code></li> 044 * <li><code>org/**</code> - matches all files underneath the <code>org</code> directory, 045 * e.g. <code>org/Foo.java</code> or <code>org/foo/bar.jsp</code></li> 046 * <li><code>org/**/Test.java</code> - matches all <code>Test.java</code> files underneath the <code>org</code> directory, 047 * e.g. <code>org/Test.java</code> or <code>org/foo/Test.java</code> or <code>org/foo/bar/Test.java</code></li> 048 * <li><code>org/**/*.java</code> - matches all <code>.java</code> files underneath the <code>org</code> directory, 049 * e.g. <code>org/Foo.java</code> or <code>org/foo/Bar.java</code> or <code>org/foo/bar/Baz.java</code></li> 050 * </ul> 051 * <p> 052 * Another implementation, which is also based on Java Regular Expressions, can be found in 053 * <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> 054 * from IntelliJ OpenAPI. 055 * 056 * 057 * @since 1.10 058 */ 059public class WildcardPattern { 060 061 private static final Map<String, WildcardPattern> CACHE = new HashMap<>(); 062 private static final String SPECIAL_CHARS = "()[]^$.{}+|"; 063 064 private Pattern pattern; 065 private String stringRepresentation; 066 067 protected WildcardPattern(String pattern, String directorySeparator) { 068 this.stringRepresentation = pattern; 069 this.pattern = Pattern.compile(toRegexp(pattern, directorySeparator)); 070 } 071 072 private static String toRegexp(String antPattern, String directorySeparator) { 073 final String escapedDirectorySeparator = '\\' + directorySeparator; 074 075 final StringBuilder sb = new StringBuilder(antPattern.length()); 076 077 sb.append('^'); 078 079 int i = antPattern.startsWith("/") || antPattern.startsWith("\\") ? 1 : 0; 080 while (i < antPattern.length()) { 081 final char ch = antPattern.charAt(i); 082 083 if (SPECIAL_CHARS.indexOf(ch) != -1) { 084 // Escape regexp-specific characters 085 sb.append('\\').append(ch); 086 } else if (ch == '*') { 087 if (i + 1 < antPattern.length() && antPattern.charAt(i + 1) == '*') { 088 // Double asterisk 089 // Zero or more directories 090 if (i + 2 < antPattern.length() && isSlash(antPattern.charAt(i + 2))) { 091 sb.append("(?:.*").append(escapedDirectorySeparator).append("|)"); 092 i += 2; 093 } else { 094 sb.append(".*"); 095 i += 1; 096 } 097 } else { 098 // Single asterisk 099 // Zero or more characters excluding directory separator 100 sb.append("[^").append(escapedDirectorySeparator).append("]*?"); 101 } 102 } else if (ch == '?') { 103 // Any single character excluding directory separator 104 sb.append("[^").append(escapedDirectorySeparator).append("]"); 105 } else if (isSlash(ch)) { 106 // Directory separator 107 sb.append(escapedDirectorySeparator); 108 } else { 109 // Single character 110 sb.append(ch); 111 } 112 113 i++; 114 } 115 116 sb.append('$'); 117 118 return sb.toString(); 119 } 120 121 private static boolean isSlash(char ch) { 122 return ch == '/' || ch == '\\'; 123 } 124 125 /** 126 * Returns string representation of this pattern. 127 * 128 * @since 2.5 129 */ 130 @Override 131 public String toString() { 132 return stringRepresentation; 133 } 134 135 /** 136 * Returns true if specified value matches this pattern. 137 */ 138 public boolean match(String value) { 139 value = StringUtils.removeStart(value, "/"); 140 value = StringUtils.removeEnd(value, "/"); 141 return pattern.matcher(value).matches(); 142 } 143 144 /** 145 * Returns true if specified value matches one of specified patterns. 146 * 147 * @since 2.4 148 */ 149 public static boolean match(WildcardPattern[] patterns, String value) { 150 for (WildcardPattern pattern : patterns) { 151 if (pattern.match(value)) { 152 return true; 153 } 154 } 155 return false; 156 } 157 158 /** 159 * Creates pattern with "/" as a directory separator. 160 * 161 * @see #create(String, String) 162 */ 163 public static WildcardPattern create(String pattern) { 164 return create(pattern, "/"); 165 } 166 167 /** 168 * Creates array of patterns with "/" as a directory separator. 169 * 170 * @see #create(String, String) 171 */ 172 public static WildcardPattern[] create(String[] patterns) { 173 if (patterns == null) { 174 return new WildcardPattern[0]; 175 } 176 WildcardPattern[] exclusionPAtterns = new WildcardPattern[patterns.length]; 177 for (int i = 0; i < patterns.length; i++) { 178 exclusionPAtterns[i] = create(patterns[i]); 179 } 180 return exclusionPAtterns; 181 } 182 183 /** 184 * Creates pattern with specified separator for directories. 185 * <p> 186 * This is used to match Java-classes, i.e. <code>org.foo.Bar</code> against <code>org/**</code>. 187 * <b>However usage of character other than "/" as a directory separator is misleading and should be avoided, 188 * so method {@link #create(String)} is preferred over this one.</b> 189 * 190 * <p> 191 * Also note that no matter whether forward or backward slashes were used in the <code>antPattern</code> 192 * the returned pattern will use <code>directorySeparator</code>. 193 * Thus to match Windows-style path "dir\file.ext" against pattern "dir/file.ext" normalization should be performed. 194 * 195 */ 196 public static WildcardPattern create(String pattern, String directorySeparator) { 197 String key = pattern + directorySeparator; 198 WildcardPattern wildcardPattern = CACHE.get(key); 199 if (wildcardPattern == null) { 200 wildcardPattern = new WildcardPattern(pattern, directorySeparator); 201 CACHE.put(key, wildcardPattern); 202 } 203 return wildcardPattern; 204 } 205}