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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. * Any character can be escaped by prepending it with a \
  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 = indexOfUnescaped(pattern, ']',
  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 = indexOfUnescaped(pattern, '[', 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. boolean escaped = false;
  236. for (int i = 0; i < patternPart.length(); i++) {
  237. final char c = patternPart.charAt(i);
  238. if (escaped) {
  239. final CharacterHead head = new CharacterHead(c);
  240. heads.add(head);
  241. escaped = false;
  242. } else {
  243. switch (c) {
  244. case '*': {
  245. final AbstractHead head = createWildCardHead(
  246. invalidWildgetCharacter, true);
  247. heads.add(head);
  248. break;
  249. }
  250. case '?': {
  251. final AbstractHead head = createWildCardHead(
  252. invalidWildgetCharacter, false);
  253. heads.add(head);
  254. break;
  255. }
  256. case '\\':
  257. escaped = true;
  258. break;
  259. default:
  260. final CharacterHead head = new CharacterHead(c);
  261. heads.add(head);
  262. }
  263. }
  264. }
  265. return heads;
  266. }
  267. private static AbstractHead createWildCardHead(
  268. final Character invalidWildgetCharacter, final boolean star) {
  269. if (invalidWildgetCharacter != null)
  270. return new RestrictedWildCardHead(invalidWildgetCharacter
  271. .charValue(), star);
  272. else
  273. return new WildCardHead(star);
  274. }
  275. private void extendStringToMatchByOneCharacter(final char c) {
  276. final List<Head> newHeads = listForLocalUseage;
  277. newHeads.clear();
  278. List<Head> lastAddedHeads = null;
  279. for (int i = 0; i < heads.size(); i++) {
  280. final Head head = heads.get(i);
  281. final List<Head> headsToAdd = head.getNextHeads(c);
  282. // Why the next performance optimization isn't wrong:
  283. // Some times two heads return the very same list.
  284. // We save future effort if we don't add these heads again.
  285. // This is the case with the heads "a" and "*" of "a*b" which
  286. // both can return the list ["*","b"]
  287. if (headsToAdd != lastAddedHeads) {
  288. newHeads.addAll(headsToAdd);
  289. lastAddedHeads = headsToAdd;
  290. }
  291. }
  292. listForLocalUseage = heads;
  293. heads = newHeads;
  294. }
  295. private static int indexOfUnescaped(final String searchString,
  296. final char ch, final int fromIndex) {
  297. for (int i = fromIndex; i < searchString.length(); i++) {
  298. char current = searchString.charAt(i);
  299. if (current == ch)
  300. return i;
  301. if (current == '\\')
  302. i++; // Skip the next char as it is escaped }
  303. }
  304. return -1;
  305. }
  306. /**
  307. *
  308. * @param stringToMatch
  309. * extends the string which is matched against the patterns of
  310. * this class.
  311. */
  312. public void append(final String stringToMatch) {
  313. for (int i = 0; i < stringToMatch.length(); i++) {
  314. final char c = stringToMatch.charAt(i);
  315. extendStringToMatchByOneCharacter(c);
  316. }
  317. }
  318. /**
  319. * Resets this matcher to it's state right after construction.
  320. */
  321. public void reset() {
  322. heads.clear();
  323. heads.addAll(headsStartValue);
  324. }
  325. /**
  326. *
  327. * @return a {@link FileNameMatcher} instance which uses the same pattern
  328. * like this matcher, but has the current state of this matcher as
  329. * reset and start point.
  330. */
  331. public FileNameMatcher createMatcherForSuffix() {
  332. final List<Head> copyOfHeads = new ArrayList<Head>(heads.size());
  333. copyOfHeads.addAll(heads);
  334. return new FileNameMatcher(copyOfHeads);
  335. }
  336. /**
  337. *
  338. * @return true, if the string currently being matched does match.
  339. */
  340. public boolean isMatch() {
  341. final ListIterator<Head> headIterator = heads
  342. .listIterator(heads.size());
  343. while (headIterator.hasPrevious()) {
  344. final Head head = headIterator.previous();
  345. if (head == LastHead.INSTANCE) {
  346. return true;
  347. }
  348. }
  349. return false;
  350. }
  351. /**
  352. *
  353. * @return false, if the string being matched will not match when the string
  354. * gets extended.
  355. */
  356. public boolean canAppendMatch() {
  357. for (int i = 0; i < heads.size(); i++) {
  358. if (heads.get(i) != LastHead.INSTANCE) {
  359. return true;
  360. }
  361. }
  362. return false;
  363. }
  364. }