Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

FileNameMatcher.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. * Any character can be escaped by prepending it with a \
  81. */
  82. public class FileNameMatcher {
  83. static final List<Head> EMPTY_HEAD_LIST = Collections.emptyList();
  84. private static final Pattern characterClassStartPattern = Pattern
  85. .compile("\\[[.:=]"); //$NON-NLS-1$
  86. private List<Head> headsStartValue;
  87. private List<Head> heads;
  88. /**
  89. * {{@link #extendStringToMatchByOneCharacter(char)} needs a list for the
  90. * new heads, allocating a new array would be bad for the performance, as
  91. * the method gets called very often.
  92. *
  93. */
  94. private List<Head> listForLocalUseage;
  95. /**
  96. *
  97. * @param headsStartValue
  98. * must be a list which will never be modified.
  99. */
  100. private FileNameMatcher(final List<Head> headsStartValue) {
  101. this(headsStartValue, headsStartValue);
  102. }
  103. /**
  104. *
  105. * @param headsStartValue
  106. * must be a list which will never be modified.
  107. * @param heads
  108. * a list which will be cloned and then used as current head
  109. * list.
  110. */
  111. private FileNameMatcher(final List<Head> headsStartValue,
  112. final List<Head> heads) {
  113. this.headsStartValue = headsStartValue;
  114. this.heads = new ArrayList<Head>(heads.size());
  115. this.heads.addAll(heads);
  116. this.listForLocalUseage = new ArrayList<Head>(heads.size());
  117. }
  118. /**
  119. * @param patternString
  120. * must contain a pattern which fnmatch would accept.
  121. * @param invalidWildgetCharacter
  122. * if this parameter isn't null then this character will not
  123. * match at wildcards(* and ? are wildcards).
  124. * @throws InvalidPatternException
  125. * if the patternString contains a invalid fnmatch pattern.
  126. */
  127. public FileNameMatcher(final String patternString,
  128. final Character invalidWildgetCharacter)
  129. throws InvalidPatternException {
  130. this(createHeadsStartValues(patternString, invalidWildgetCharacter));
  131. }
  132. /**
  133. * A Copy Constructor which creates a new {@link FileNameMatcher} with the
  134. * same state and reset point like <code>other</code>.
  135. *
  136. * @param other
  137. * another {@link FileNameMatcher} instance.
  138. */
  139. public FileNameMatcher(FileNameMatcher other) {
  140. this(other.headsStartValue, other.heads);
  141. }
  142. private static List<Head> createHeadsStartValues(
  143. final String patternString, final Character invalidWildgetCharacter)
  144. throws InvalidPatternException {
  145. final List<AbstractHead> allHeads = parseHeads(patternString,
  146. invalidWildgetCharacter);
  147. List<Head> nextHeadsSuggestion = new ArrayList<Head>(2);
  148. nextHeadsSuggestion.add(LastHead.INSTANCE);
  149. for (int i = allHeads.size() - 1; i >= 0; i--) {
  150. final AbstractHead head = allHeads.get(i);
  151. // explanation:
  152. // a and * of the pattern "a*b"
  153. // need *b as newHeads
  154. // that's why * extends the list for it self and it's left neighbor.
  155. if (head.isStar()) {
  156. nextHeadsSuggestion.add(head);
  157. head.setNewHeads(nextHeadsSuggestion);
  158. } else {
  159. head.setNewHeads(nextHeadsSuggestion);
  160. nextHeadsSuggestion = new ArrayList<Head>(2);
  161. nextHeadsSuggestion.add(head);
  162. }
  163. }
  164. return nextHeadsSuggestion;
  165. }
  166. private static int findGroupEnd(final int indexOfStartBracket,
  167. final String pattern) throws InvalidPatternException {
  168. int firstValidCharClassIndex = indexOfStartBracket + 1;
  169. int firstValidEndBracketIndex = indexOfStartBracket + 2;
  170. if (indexOfStartBracket + 1 >= pattern.length())
  171. throw new NoClosingBracketException(indexOfStartBracket, "[", "]", //$NON-NLS-1$ //$NON-NLS-2$
  172. pattern);
  173. if (pattern.charAt(firstValidCharClassIndex) == '!') {
  174. firstValidCharClassIndex++;
  175. firstValidEndBracketIndex++;
  176. }
  177. final Matcher charClassStartMatcher = characterClassStartPattern
  178. .matcher(pattern);
  179. int groupEnd = -1;
  180. while (groupEnd == -1) {
  181. final int possibleGroupEnd = indexOfUnescaped(pattern, ']',
  182. firstValidEndBracketIndex);
  183. if (possibleGroupEnd == -1)
  184. throw new NoClosingBracketException(indexOfStartBracket, "[", //$NON-NLS-1$
  185. "]", pattern); //$NON-NLS-1$
  186. final boolean foundCharClass = charClassStartMatcher
  187. .find(firstValidCharClassIndex);
  188. if (foundCharClass
  189. && charClassStartMatcher.start() < possibleGroupEnd) {
  190. final String classStart = charClassStartMatcher.group(0);
  191. final String classEnd = classStart.charAt(1) + "]"; //$NON-NLS-1$
  192. final int classStartIndex = charClassStartMatcher.start();
  193. final int classEndIndex = pattern.indexOf(classEnd,
  194. classStartIndex + 2);
  195. if (classEndIndex == -1)
  196. throw new NoClosingBracketException(classStartIndex,
  197. classStart, classEnd, pattern);
  198. firstValidCharClassIndex = classEndIndex + 2;
  199. firstValidEndBracketIndex = firstValidCharClassIndex;
  200. } else {
  201. groupEnd = possibleGroupEnd;
  202. }
  203. }
  204. return groupEnd;
  205. }
  206. private static List<AbstractHead> parseHeads(final String pattern,
  207. final Character invalidWildgetCharacter)
  208. throws InvalidPatternException {
  209. int currentIndex = 0;
  210. List<AbstractHead> heads = new ArrayList<AbstractHead>();
  211. while (currentIndex < pattern.length()) {
  212. final int groupStart = indexOfUnescaped(pattern, '[', currentIndex);
  213. if (groupStart == -1) {
  214. final String patternPart = pattern.substring(currentIndex);
  215. heads.addAll(createSimpleHeads(patternPart,
  216. invalidWildgetCharacter));
  217. currentIndex = pattern.length();
  218. } else {
  219. final String patternPart = pattern.substring(currentIndex,
  220. groupStart);
  221. heads.addAll(createSimpleHeads(patternPart,
  222. invalidWildgetCharacter));
  223. final int groupEnd = findGroupEnd(groupStart, pattern);
  224. final String groupPart = pattern.substring(groupStart + 1,
  225. groupEnd);
  226. heads.add(new GroupHead(groupPart, pattern));
  227. currentIndex = groupEnd + 1;
  228. }
  229. }
  230. return heads;
  231. }
  232. private static List<AbstractHead> createSimpleHeads(
  233. final String patternPart, final Character invalidWildgetCharacter) {
  234. final List<AbstractHead> heads = new ArrayList<AbstractHead>(
  235. patternPart.length());
  236. boolean escaped = false;
  237. for (int i = 0; i < patternPart.length(); i++) {
  238. final char c = patternPart.charAt(i);
  239. if (escaped) {
  240. final CharacterHead head = new CharacterHead(c);
  241. heads.add(head);
  242. escaped = false;
  243. } else {
  244. switch (c) {
  245. case '*': {
  246. final AbstractHead head = createWildCardHead(
  247. invalidWildgetCharacter, true);
  248. heads.add(head);
  249. break;
  250. }
  251. case '?': {
  252. final AbstractHead head = createWildCardHead(
  253. invalidWildgetCharacter, false);
  254. heads.add(head);
  255. break;
  256. }
  257. case '\\':
  258. escaped = true;
  259. break;
  260. default:
  261. final CharacterHead head = new CharacterHead(c);
  262. heads.add(head);
  263. }
  264. }
  265. }
  266. return heads;
  267. }
  268. private static AbstractHead createWildCardHead(
  269. final Character invalidWildgetCharacter, final boolean star) {
  270. if (invalidWildgetCharacter != null)
  271. return new RestrictedWildCardHead(invalidWildgetCharacter
  272. .charValue(), star);
  273. else
  274. return new WildCardHead(star);
  275. }
  276. private void extendStringToMatchByOneCharacter(final char c) {
  277. final List<Head> newHeads = listForLocalUseage;
  278. newHeads.clear();
  279. List<Head> lastAddedHeads = null;
  280. for (int i = 0; i < heads.size(); i++) {
  281. final Head head = heads.get(i);
  282. final List<Head> headsToAdd = head.getNextHeads(c);
  283. // Why the next performance optimization isn't wrong:
  284. // Some times two heads return the very same list.
  285. // We save future effort if we don't add these heads again.
  286. // This is the case with the heads "a" and "*" of "a*b" which
  287. // both can return the list ["*","b"]
  288. if (headsToAdd != lastAddedHeads) {
  289. newHeads.addAll(headsToAdd);
  290. lastAddedHeads = headsToAdd;
  291. }
  292. }
  293. listForLocalUseage = heads;
  294. heads = newHeads;
  295. }
  296. private static int indexOfUnescaped(final String searchString,
  297. final char ch, final int fromIndex) {
  298. for (int i = fromIndex; i < searchString.length(); i++) {
  299. char current = searchString.charAt(i);
  300. if (current == ch)
  301. return i;
  302. if (current == '\\')
  303. i++; // Skip the next char as it is escaped }
  304. }
  305. return -1;
  306. }
  307. /**
  308. *
  309. * @param stringToMatch
  310. * extends the string which is matched against the patterns of
  311. * this class.
  312. */
  313. public void append(final String stringToMatch) {
  314. for (int i = 0; i < stringToMatch.length(); i++) {
  315. final char c = stringToMatch.charAt(i);
  316. extendStringToMatchByOneCharacter(c);
  317. }
  318. }
  319. /**
  320. * Resets this matcher to it's state right after construction.
  321. */
  322. public void reset() {
  323. heads.clear();
  324. heads.addAll(headsStartValue);
  325. }
  326. /**
  327. *
  328. * @return a {@link FileNameMatcher} instance which uses the same pattern
  329. * like this matcher, but has the current state of this matcher as
  330. * reset and start point.
  331. */
  332. public FileNameMatcher createMatcherForSuffix() {
  333. final List<Head> copyOfHeads = new ArrayList<Head>(heads.size());
  334. copyOfHeads.addAll(heads);
  335. return new FileNameMatcher(copyOfHeads);
  336. }
  337. /**
  338. *
  339. * @return true, if the string currently being matched does match.
  340. */
  341. public boolean isMatch() {
  342. final ListIterator<Head> headIterator = heads
  343. .listIterator(heads.size());
  344. while (headIterator.hasPrevious()) {
  345. final Head head = headIterator.previous();
  346. if (head == LastHead.INSTANCE) {
  347. return true;
  348. }
  349. }
  350. return false;
  351. }
  352. /**
  353. *
  354. * @return false, if the string being matched will not match when the string
  355. * gets extended.
  356. */
  357. public boolean canAppendMatch() {
  358. for (int i = 0; i < heads.size(); i++) {
  359. if (heads.get(i) != LastHead.INSTANCE) {
  360. return true;
  361. }
  362. }
  363. return false;
  364. }
  365. }