View Javadoc
1   /*
2    * Copyright (C) 2014, Andrey Loskutov <loskutov@gmx.de>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.ignore.internal;
44  
45  import static org.eclipse.jgit.ignore.internal.Strings.checkWildCards;
46  import static org.eclipse.jgit.ignore.internal.Strings.count;
47  import static org.eclipse.jgit.ignore.internal.Strings.getPathSeparator;
48  import static org.eclipse.jgit.ignore.internal.Strings.isWildCard;
49  import static org.eclipse.jgit.ignore.internal.Strings.split;
50  
51  import java.util.ArrayList;
52  import java.util.List;
53  
54  import org.eclipse.jgit.errors.InvalidPatternException;
55  import org.eclipse.jgit.ignore.internal.Strings.PatternState;
56  
57  /**
58   * Matcher built by patterns consists of multiple path segments.
59   * <p>
60   * This class is immutable and thread safe.
61   */
62  public class PathMatcher extends AbstractMatcher {
63  
64  	private static final WildMatcher WILD = WildMatcher.INSTANCE;
65  
66  	private final List<IMatcher> matchers;
67  
68  	private final char slash;
69  
70  	private final boolean beginning;
71  
72  	private PathMatcher(String pattern, Character pathSeparator,
73  			boolean dirOnly)
74  			throws InvalidPatternException {
75  		super(pattern, dirOnly);
76  		slash = getPathSeparator(pathSeparator);
77  		beginning = pattern.indexOf(slash) == 0;
78  		if (isSimplePathWithSegments(pattern))
79  			matchers = null;
80  		else
81  			matchers = createMatchers(split(pattern, slash), pathSeparator,
82  					dirOnly);
83  	}
84  
85  	private boolean isSimplePathWithSegments(String path) {
86  		return !isWildCard(path) && path.indexOf('\\') < 0
87  				&& count(path, slash, true) > 0;
88  	}
89  
90  	private static List<IMatcher> createMatchers(List<String> segments,
91  			Character pathSeparator, boolean dirOnly)
92  			throws InvalidPatternException {
93  		List<IMatcher> matchers = new ArrayList<>(segments.size());
94  		for (int i = 0; i < segments.size(); i++) {
95  			String segment = segments.get(i);
96  			IMatcher matcher = createNameMatcher0(segment, pathSeparator,
97  					dirOnly);
98  			if (matcher == WILD && i > 0
99  					&& matchers.get(matchers.size() - 1) == WILD)
100 				// collapse wildmatchers **/** is same as **
101 				continue;
102 			matchers.add(matcher);
103 		}
104 		return matchers;
105 	}
106 
107 	/**
108 	 * Create path matcher
109 	 *
110 	 * @param pattern
111 	 *            a pattern
112 	 * @param pathSeparator
113 	 *            if this parameter isn't null then this character will not
114 	 *            match at wildcards(* and ? are wildcards).
115 	 * @param dirOnly
116 	 *            a boolean.
117 	 * @return never null
118 	 * @throws org.eclipse.jgit.errors.InvalidPatternException
119 	 */
120 	public static IMatcher createPathMatcher(String pattern,
121 			Character pathSeparator, boolean dirOnly)
122 			throws InvalidPatternException {
123 		pattern = trim(pattern);
124 		char slash = Strings.getPathSeparator(pathSeparator);
125 		// ignore possible leading and trailing slash
126 		int slashIdx = pattern.indexOf(slash, 1);
127 		if (slashIdx > 0 && slashIdx < pattern.length() - 1)
128 			return new PathMatcher(pattern, pathSeparator, dirOnly);
129 		return createNameMatcher0(pattern, pathSeparator, dirOnly);
130 	}
131 
132 	/**
133 	 * Trim trailing spaces, unless they are escaped with backslash, see
134 	 * https://www.kernel.org/pub/software/scm/git/docs/gitignore.html
135 	 *
136 	 * @param pattern
137 	 *            non null
138 	 * @return trimmed pattern
139 	 */
140 	private static String trim(String pattern) {
141 		while (pattern.length() > 0
142 				&& pattern.charAt(pattern.length() - 1) == ' ') {
143 			if (pattern.length() > 1
144 					&& pattern.charAt(pattern.length() - 2) == '\\') {
145 				// last space was escaped by backslash: remove backslash and
146 				// keep space
147 				pattern = pattern.substring(0, pattern.length() - 2) + " "; //$NON-NLS-1$
148 				return pattern;
149 			}
150 			pattern = pattern.substring(0, pattern.length() - 1);
151 		}
152 		return pattern;
153 	}
154 
155 	private static IMatcher createNameMatcher0(String segment,
156 			Character pathSeparator, boolean dirOnly)
157 			throws InvalidPatternException {
158 		// check if we see /** or ** segments => double star pattern
159 		if (WildMatcher.WILDMATCH.equals(segment)
160 				|| WildMatcher.WILDMATCH2.equals(segment))
161 			return WILD;
162 
163 		PatternState state = checkWildCards(segment);
164 		switch (state) {
165 		case LEADING_ASTERISK_ONLY:
166 			return new LeadingAsteriskMatcher(segment, pathSeparator, dirOnly);
167 		case TRAILING_ASTERISK_ONLY:
168 			return new TrailingAsteriskMatcher(segment, pathSeparator, dirOnly);
169 		case COMPLEX:
170 			return new WildCardMatcher(segment, pathSeparator, dirOnly);
171 		default:
172 			return new NameMatcher(segment, pathSeparator, dirOnly, true);
173 		}
174 	}
175 
176 	/** {@inheritDoc} */
177 	@Override
178 	public boolean matches(String path, boolean assumeDirectory,
179 			boolean pathMatch) {
180 		if (matchers == null) {
181 			return simpleMatch(path, assumeDirectory, pathMatch);
182 		}
183 		return iterate(path, 0, path.length(), assumeDirectory, pathMatch);
184 	}
185 
186 	/*
187 	 * Stupid but fast string comparison: the case where we don't have to match
188 	 * wildcards or single segments (mean: this is multi-segment path which must
189 	 * be at the beginning of the another string)
190 	 */
191 	private boolean simpleMatch(String path, boolean assumeDirectory,
192 			boolean pathMatch) {
193 		boolean hasSlash = path.indexOf(slash) == 0;
194 		if (beginning && !hasSlash) {
195 			path = slash + path;
196 		}
197 		if (!beginning && hasSlash) {
198 			path = path.substring(1);
199 		}
200 		if (path.equals(pattern)) {
201 			// Exact match: must meet directory expectations
202 			return !dirOnly || assumeDirectory;
203 		}
204 		/*
205 		 * Add slashes for startsWith check. This avoids matching e.g.
206 		 * "/src/new" to /src/newfile" but allows "/src/new" to match
207 		 * "/src/new/newfile", as is the git standard
208 		 */
209 		String prefix = pattern + slash;
210 		if (pathMatch) {
211 			return path.equals(prefix) && (!dirOnly || assumeDirectory);
212 		}
213 		if (path.startsWith(prefix)) {
214 			return true;
215 		}
216 		return false;
217 	}
218 
219 	/** {@inheritDoc} */
220 	@Override
221 	public boolean matches(String segment, int startIncl, int endExcl,
222 			boolean assumeDirectory) {
223 		throw new UnsupportedOperationException(
224 				"Path matcher works only on entire paths"); //$NON-NLS-1$
225 	}
226 
227 	private boolean iterate(final String path, final int startIncl,
228 			final int endExcl, boolean assumeDirectory, boolean pathMatch) {
229 		int matcher = 0;
230 		int right = startIncl;
231 		boolean match = false;
232 		int lastWildmatch = -1;
233 		// ** matches may get extended if a later match fails. When that
234 		// happens, we must extend the ** by exactly one segment.
235 		// wildmatchBacktrackPos records the end of the segment after a **
236 		// match, so that we can reset correctly.
237 		int wildmatchBacktrackPos = -1;
238 		while (true) {
239 			int left = right;
240 			right = path.indexOf(slash, right);
241 			if (right == -1) {
242 				if (left < endExcl) {
243 					match = matches(matcher, path, left, endExcl,
244 							assumeDirectory);
245 				} else {
246 					// a/** should not match a/ or a
247 					match = match && matchers.get(matcher) != WILD;
248 				}
249 				if (match) {
250 					if (matcher < matchers.size() - 1
251 							&& matchers.get(matcher) == WILD) {
252 						// ** can match *nothing*: a/**/b match also a/b
253 						matcher++;
254 						match = matches(matcher, path, left, endExcl,
255 								assumeDirectory);
256 					} else if (dirOnly && !assumeDirectory) {
257 						// Directory expectations not met
258 						return false;
259 					}
260 				}
261 				return match && matcher + 1 == matchers.size();
262 			}
263 			if (wildmatchBacktrackPos < 0) {
264 				wildmatchBacktrackPos = right;
265 			}
266 			if (right - left > 0) {
267 				match = matches(matcher, path, left, right, assumeDirectory);
268 			} else {
269 				// path starts with slash???
270 				right++;
271 				continue;
272 			}
273 			if (match) {
274 				boolean wasWild = matchers.get(matcher) == WILD;
275 				if (wasWild) {
276 					lastWildmatch = matcher;
277 					wildmatchBacktrackPos = -1;
278 					// ** can match *nothing*: a/**/b match also a/b
279 					right = left - 1;
280 				}
281 				matcher++;
282 				if (matcher == matchers.size()) {
283 					// We had a prefix match here.
284 					if (!pathMatch) {
285 						return true;
286 					} else {
287 						if (right == endExcl - 1) {
288 							// Extra slash at the end: actually a full match.
289 							// Must meet directory expectations
290 							return !dirOnly || assumeDirectory;
291 						}
292 						// Prefix matches only if pattern ended with /**
293 						if (wasWild) {
294 							return true;
295 						}
296 						if (lastWildmatch >= 0) {
297 							// Consider pattern **/x and input x/x.
298 							// We've matched the prefix x/ so far: we
299 							// must try to extend the **!
300 							matcher = lastWildmatch + 1;
301 							right = wildmatchBacktrackPos;
302 							wildmatchBacktrackPos = -1;
303 						} else {
304 							return false;
305 						}
306 					}
307 				}
308 			} else if (lastWildmatch != -1) {
309 				matcher = lastWildmatch + 1;
310 				right = wildmatchBacktrackPos;
311 				wildmatchBacktrackPos = -1;
312 			} else {
313 				return false;
314 			}
315 			right++;
316 		}
317 	}
318 
319 	private boolean matches(int matcherIdx, String path, int startIncl,
320 			int endExcl,
321 			boolean assumeDirectory) {
322 		IMatcher matcher = matchers.get(matcherIdx);
323 		return matcher.matches(path, startIncl, endExcl, assumeDirectory);
324 	}
325 }