You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileNameMatcher.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. * Copyright (C) 2008, Florian Koeberle <florianskarten@web.de>
  3. * Copyright (C) 2008, Florian Köberle <florianskarten@web.de>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.fnmatch;
  45. import java.util.ArrayList;
  46. import java.util.Collections;
  47. import java.util.List;
  48. import java.util.ListIterator;
  49. import java.util.regex.Matcher;
  50. import java.util.regex.Pattern;
  51. import org.eclipse.jgit.errors.InvalidPatternException;
  52. import org.eclipse.jgit.errors.NoClosingBracketException;
  53. /**
  54. * This class can be used to match filenames against fnmatch like patterns. It
  55. * is not thread save.
  56. * <p>
  57. * Supported are the wildcard characters * and ? and groups with:
  58. * <ul>
  59. * <li> characters e.g. [abc]</li>
  60. * <li> ranges e.g. [a-z]</li>
  61. * <li> the following character classes
  62. * <ul>
  63. * <li>[:alnum:]</li>
  64. * <li>[:alpha:]</li>
  65. * <li>[:blank:]</li>
  66. * <li>[:cntrl:]</li>
  67. * <li>[:digit:]</li>
  68. * <li>[:graph:]</li>
  69. * <li>[:lower:]</li>
  70. * <li>[:print:]</li>
  71. * <li>[:punct:]</li>
  72. * <li>[:space:]</li>
  73. * <li>[:upper:]</li>
  74. * <li>[:word:]</li>
  75. * <li>[:xdigit:]</li>
  76. * </ul>
  77. * e. g. [[:xdigit:]] </li>
  78. * </ul>
  79. * </p>
  80. */
  81. public class FileNameMatcher {
  82. static final List<Head> EMPTY_HEAD_LIST = Collections.emptyList();
  83. private static final Pattern characterClassStartPattern = Pattern
  84. .compile("\\[[.:=]"); //$NON-NLS-1$
  85. private List<Head> headsStartValue;
  86. private List<Head> heads;
  87. /**
  88. * {{@link #extendStringToMatchByOneCharacter(char)} needs a list for the
  89. * new heads, allocating a new array would be bad for the performance, as
  90. * the method gets called very often.
  91. *
  92. */
  93. private List<Head> listForLocalUseage;
  94. /**
  95. *
  96. * @param headsStartValue
  97. * must be a list which will never be modified.
  98. */
  99. private FileNameMatcher(final List<Head> headsStartValue) {
  100. this(headsStartValue, headsStartValue);
  101. }
  102. /**
  103. *
  104. * @param headsStartValue
  105. * must be a list which will never be modified.
  106. * @param heads
  107. * a list which will be cloned and then used as current head
  108. * list.
  109. */
  110. private FileNameMatcher(final List<Head> headsStartValue,
  111. final List<Head> heads) {
  112. this.headsStartValue = headsStartValue;
  113. this.heads = new ArrayList<Head>(heads.size());
  114. this.heads.addAll(heads);
  115. this.listForLocalUseage = new ArrayList<Head>(heads.size());
  116. }
  117. /**
  118. * @param patternString
  119. * must contain a pattern which fnmatch would accept.
  120. * @param invalidWildgetCharacter
  121. * if this parameter isn't null then this character will not
  122. * match at wildcards(* and ? are wildcards).
  123. * @throws InvalidPatternException
  124. * if the patternString contains a invalid fnmatch pattern.
  125. */
  126. public FileNameMatcher(final String patternString,
  127. final Character invalidWildgetCharacter)
  128. throws InvalidPatternException {
  129. this(createHeadsStartValues(patternString, invalidWildgetCharacter));
  130. }
  131. /**
  132. * A Copy Constructor which creates a new {@link FileNameMatcher} with the
  133. * same state and reset point like <code>other</code>.
  134. *
  135. * @param other
  136. * another {@link FileNameMatcher} instance.
  137. */
  138. public FileNameMatcher(FileNameMatcher other) {
  139. this(other.headsStartValue, other.heads);
  140. }
  141. private static List<Head> createHeadsStartValues(
  142. final String patternString, final Character invalidWildgetCharacter)
  143. throws InvalidPatternException {
  144. final List<AbstractHead> allHeads = parseHeads(patternString,
  145. invalidWildgetCharacter);
  146. List<Head> nextHeadsSuggestion = new ArrayList<Head>(2);
  147. nextHeadsSuggestion.add(LastHead.INSTANCE);
  148. for (int i = allHeads.size() - 1; i >= 0; i--) {
  149. final AbstractHead head = allHeads.get(i);
  150. // explanation:
  151. // a and * of the pattern "a*b"
  152. // need *b as newHeads
  153. // that's why * extends the list for it self and it's left neighbor.
  154. if (head.isStar()) {
  155. nextHeadsSuggestion.add(head);
  156. head.setNewHeads(nextHeadsSuggestion);
  157. } else {
  158. head.setNewHeads(nextHeadsSuggestion);
  159. nextHeadsSuggestion = new ArrayList<Head>(2);
  160. nextHeadsSuggestion.add(head);
  161. }
  162. }
  163. return nextHeadsSuggestion;
  164. }
  165. private static int findGroupEnd(final int indexOfStartBracket,
  166. final String pattern) throws InvalidPatternException {
  167. int firstValidCharClassIndex = indexOfStartBracket + 1;
  168. int firstValidEndBracketIndex = indexOfStartBracket + 2;
  169. if (indexOfStartBracket + 1 >= pattern.length())
  170. throw new NoClosingBracketException(indexOfStartBracket, "[", "]", //$NON-NLS-1$ //$NON-NLS-2$
  171. pattern);
  172. if (pattern.charAt(firstValidCharClassIndex) == '!') {
  173. firstValidCharClassIndex++;
  174. firstValidEndBracketIndex++;
  175. }
  176. final Matcher charClassStartMatcher = characterClassStartPattern
  177. .matcher(pattern);
  178. int groupEnd = -1;
  179. while (groupEnd == -1) {
  180. final int possibleGroupEnd = pattern.indexOf(']',
  181. firstValidEndBracketIndex);
  182. if (possibleGroupEnd == -1)
  183. throw new NoClosingBracketException(indexOfStartBracket, "[", //$NON-NLS-1$
  184. "]", pattern); //$NON-NLS-1$
  185. final boolean foundCharClass = charClassStartMatcher
  186. .find(firstValidCharClassIndex);
  187. if (foundCharClass
  188. && charClassStartMatcher.start() < possibleGroupEnd) {
  189. final String classStart = charClassStartMatcher.group(0);
  190. final String classEnd = classStart.charAt(1) + "]"; //$NON-NLS-1$
  191. final int classStartIndex = charClassStartMatcher.start();
  192. final int classEndIndex = pattern.indexOf(classEnd,
  193. classStartIndex + 2);
  194. if (classEndIndex == -1)
  195. throw new NoClosingBracketException(classStartIndex,
  196. classStart, classEnd, pattern);
  197. firstValidCharClassIndex = classEndIndex + 2;
  198. firstValidEndBracketIndex = firstValidCharClassIndex;
  199. } else {
  200. groupEnd = possibleGroupEnd;
  201. }
  202. }
  203. return groupEnd;
  204. }
  205. private static List<AbstractHead> parseHeads(final String pattern,
  206. final Character invalidWildgetCharacter)
  207. throws InvalidPatternException {
  208. int currentIndex = 0;
  209. List<AbstractHead> heads = new ArrayList<AbstractHead>();
  210. while (currentIndex < pattern.length()) {
  211. final int groupStart = pattern.indexOf('[', currentIndex);
  212. if (groupStart == -1) {
  213. final String patternPart = pattern.substring(currentIndex);
  214. heads.addAll(createSimpleHeads(patternPart,
  215. invalidWildgetCharacter));
  216. currentIndex = pattern.length();
  217. } else {
  218. final String patternPart = pattern.substring(currentIndex,
  219. groupStart);
  220. heads.addAll(createSimpleHeads(patternPart,
  221. invalidWildgetCharacter));
  222. final int groupEnd = findGroupEnd(groupStart, pattern);
  223. final String groupPart = pattern.substring(groupStart + 1,
  224. groupEnd);
  225. heads.add(new GroupHead(groupPart, pattern));
  226. currentIndex = groupEnd + 1;
  227. }
  228. }
  229. return heads;
  230. }
  231. private static List<AbstractHead> createSimpleHeads(
  232. final String patternPart, final Character invalidWildgetCharacter) {
  233. final List<AbstractHead> heads = new ArrayList<AbstractHead>(
  234. patternPart.length());
  235. for (int i = 0; i < patternPart.length(); i++) {
  236. final char c = patternPart.charAt(i);
  237. switch (c) {
  238. case '*': {
  239. final AbstractHead head = createWildCardHead(
  240. invalidWildgetCharacter, true);
  241. heads.add(head);
  242. break;
  243. }
  244. case '?': {
  245. final AbstractHead head = createWildCardHead(
  246. invalidWildgetCharacter, false);
  247. heads.add(head);
  248. break;
  249. }
  250. default:
  251. final CharacterHead head = new CharacterHead(c);
  252. heads.add(head);
  253. }
  254. }
  255. return heads;
  256. }
  257. private static AbstractHead createWildCardHead(
  258. final Character invalidWildgetCharacter, final boolean star) {
  259. if (invalidWildgetCharacter != null)
  260. return new RestrictedWildCardHead(invalidWildgetCharacter
  261. .charValue(), star);
  262. else
  263. return new WildCardHead(star);
  264. }
  265. private void extendStringToMatchByOneCharacter(final char c) {
  266. final List<Head> newHeads = listForLocalUseage;
  267. newHeads.clear();
  268. List<Head> lastAddedHeads = null;
  269. for (int i = 0; i < heads.size(); i++) {
  270. final Head head = heads.get(i);
  271. final List<Head> headsToAdd = head.getNextHeads(c);
  272. // Why the next performance optimization isn't wrong:
  273. // Some times two heads return the very same list.
  274. // We save future effort if we don't add these heads again.
  275. // This is the case with the heads "a" and "*" of "a*b" which
  276. // both can return the list ["*","b"]
  277. if (headsToAdd != lastAddedHeads) {
  278. newHeads.addAll(headsToAdd);
  279. lastAddedHeads = headsToAdd;
  280. }
  281. }
  282. listForLocalUseage = heads;
  283. heads = newHeads;
  284. }
  285. /**
  286. *
  287. * @param stringToMatch
  288. * extends the string which is matched against the patterns of
  289. * this class.
  290. */
  291. public void append(final String stringToMatch) {
  292. for (int i = 0; i < stringToMatch.length(); i++) {
  293. final char c = stringToMatch.charAt(i);
  294. extendStringToMatchByOneCharacter(c);
  295. }
  296. }
  297. /**
  298. * Resets this matcher to it's state right after construction.
  299. */
  300. public void reset() {
  301. heads.clear();
  302. heads.addAll(headsStartValue);
  303. }
  304. /**
  305. *
  306. * @return a {@link FileNameMatcher} instance which uses the same pattern
  307. * like this matcher, but has the current state of this matcher as
  308. * reset and start point.
  309. */
  310. public FileNameMatcher createMatcherForSuffix() {
  311. final List<Head> copyOfHeads = new ArrayList<Head>(heads.size());
  312. copyOfHeads.addAll(heads);
  313. return new FileNameMatcher(copyOfHeads);
  314. }
  315. /**
  316. *
  317. * @return true, if the string currently being matched does match.
  318. */
  319. public boolean isMatch() {
  320. final ListIterator<Head> headIterator = heads
  321. .listIterator(heads.size());
  322. while (headIterator.hasPrevious()) {
  323. final Head head = headIterator.previous();
  324. if (head == LastHead.INSTANCE) {
  325. return true;
  326. }
  327. }
  328. return false;
  329. }
  330. /**
  331. *
  332. * @return false, if the string being matched will not match when the string
  333. * gets extended.
  334. */
  335. public boolean canAppendMatch() {
  336. for (int i = 0; i < heads.size(); i++) {
  337. if (heads.get(i) != LastHead.INSTANCE) {
  338. return true;
  339. }
  340. }
  341. return false;
  342. }
  343. }