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.

Strings.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. import static java.lang.Character.isLetter;
  45. import java.util.*;
  46. import java.util.regex.Pattern;
  47. import org.eclipse.jgit.errors.InvalidPatternException;
  48. import org.eclipse.jgit.ignore.FastIgnoreRule;
  49. /**
  50. * Various {@link String} related utility methods, written mostly to avoid
  51. * generation of new String objects (e.g. via splitting Strings etc).
  52. *
  53. * @since 3.6
  54. */
  55. public class Strings {
  56. static char getPathSeparator(Character pathSeparator) {
  57. return pathSeparator == null ? FastIgnoreRule.PATH_SEPARATOR
  58. : pathSeparator.charValue();
  59. }
  60. /**
  61. * @param pattern
  62. * non null
  63. * @param c
  64. * character to remove
  65. * @return new string with all trailing characters removed
  66. */
  67. public static String stripTrailing(String pattern, char c) {
  68. while (pattern.length() > 0
  69. && pattern.charAt(pattern.length() - 1) == c)
  70. pattern = pattern.substring(0, pattern.length() - 1);
  71. return pattern;
  72. }
  73. static int count(String s, char c, boolean ignoreFirstLast) {
  74. int start = 0;
  75. int count = 0;
  76. while (true) {
  77. start = s.indexOf(c, start);
  78. if (start == -1)
  79. break;
  80. if (!ignoreFirstLast || (start != 0 && start != s.length()))
  81. count++;
  82. start++;
  83. }
  84. return count;
  85. }
  86. /**
  87. * Splits given string to substrings by given separator
  88. *
  89. * @param pattern
  90. * non null
  91. * @param slash
  92. * separator char
  93. * @return list of substrings
  94. */
  95. public static List<String> split(String pattern, char slash) {
  96. int count = count(pattern, slash, true);
  97. if (count < 1)
  98. throw new IllegalStateException(
  99. "Pattern must have at least two segments: " + pattern); //$NON-NLS-1$
  100. List<String> segments = new ArrayList<String>(count);
  101. int right = 0;
  102. while (true) {
  103. int left = right;
  104. right = pattern.indexOf(slash, right);
  105. if (right == -1) {
  106. if (left < pattern.length())
  107. segments.add(pattern.substring(left));
  108. break;
  109. }
  110. if (right - left > 0)
  111. if (left == 1)
  112. // leading slash should remain by the first pattern
  113. segments.add(pattern.substring(left - 1, right));
  114. else if (right == pattern.length() - 1)
  115. // trailing slash should remain too
  116. segments.add(pattern.substring(left, right + 1));
  117. else
  118. segments.add(pattern.substring(left, right));
  119. right++;
  120. }
  121. return segments;
  122. }
  123. static boolean isWildCard(String pattern) {
  124. return pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1
  125. || pattern.indexOf('[') != -1
  126. // required to match escaped backslashes '\\\\'
  127. || pattern.indexOf('\\') != -1 || pattern.indexOf(']') != -1;
  128. }
  129. final static List<String> POSIX_CHAR_CLASSES = Arrays.asList(
  130. "alnum", "alpha", "blank", "cntrl", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  131. // [:alnum:] [:alpha:] [:blank:] [:cntrl:]
  132. "digit", "graph", "lower", "print", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  133. // [:digit:] [:graph:] [:lower:] [:print:]
  134. "punct", "space", "upper", "xdigit", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  135. // [:punct:] [:space:] [:upper:] [:xdigit:]
  136. "word" //$NON-NLS-1$
  137. // [:word:] XXX I don't see it in
  138. // http://man7.org/linux/man-pages/man7/glob.7.html
  139. // but this was in org.eclipse.jgit.fnmatch.GroupHead.java ???
  140. );
  141. private static final String DL = "\\p{javaDigit}\\p{javaLetter}"; //$NON-NLS-1$
  142. final static List<String> JAVA_CHAR_CLASSES = Arrays
  143. .asList("\\p{Alnum}", "\\p{javaLetter}", "\\p{Blank}", "\\p{Cntrl}", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  144. // [:alnum:] [:alpha:] [:blank:] [:cntrl:]
  145. "\\p{javaDigit}", "[\\p{Graph}" + DL + "]", "\\p{Ll}", "[\\p{Print}" + DL + "]", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
  146. // [:digit:] [:graph:] [:lower:] [:print:]
  147. "\\p{Punct}", "\\p{Space}", "\\p{Lu}", "\\p{XDigit}", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  148. // [:punct:] [:space:] [:upper:] [:xdigit:]
  149. "[" + DL + "_]" //$NON-NLS-1$ //$NON-NLS-2$
  150. // [:word:]
  151. );
  152. // Collating symbols [[.a.]] or equivalence class expressions [[=a=]] are
  153. // not supported by CLI git (at least not by 1.9.1)
  154. final static Pattern UNSUPPORTED = Pattern
  155. .compile("\\[\\[[.=]\\w+[.=]\\]\\]"); //$NON-NLS-1$
  156. /**
  157. * Conversion from glob to Java regex following two sources: <li>
  158. * http://man7.org/linux/man-pages/man7/glob.7.html <li>
  159. * org.eclipse.jgit.fnmatch.FileNameMatcher.java Seems that there are
  160. * various ways to define what "glob" can be.
  161. *
  162. * @param pattern
  163. * non null pattern
  164. *
  165. * @return Java regex pattern corresponding to given glob pattern
  166. * @throws InvalidPatternException
  167. */
  168. static Pattern convertGlob(String pattern) throws InvalidPatternException {
  169. if (UNSUPPORTED.matcher(pattern).find())
  170. throw new InvalidPatternException(
  171. "Collating symbols [[.a.]] or equivalence class expressions [[=a=]] are not supported", //$NON-NLS-1$
  172. pattern);
  173. StringBuilder sb = new StringBuilder(pattern.length());
  174. int in_brackets = 0;
  175. boolean seenEscape = false;
  176. boolean ignoreLastBracket = false;
  177. boolean in_char_class = false;
  178. // 6 is the length of the longest posix char class "xdigit"
  179. char[] charClass = new char[6];
  180. for (int i = 0; i < pattern.length(); i++) {
  181. char c = pattern.charAt(i);
  182. switch (c) {
  183. case '*':
  184. if (seenEscape || in_brackets > 0)
  185. sb.append(c);
  186. else
  187. sb.append('.').append(c);
  188. break;
  189. case '.':
  190. if (seenEscape)
  191. sb.append(c);
  192. else
  193. sb.append('\\').append('.');
  194. break;
  195. case '?':
  196. if (seenEscape || in_brackets > 0)
  197. sb.append(c);
  198. else
  199. sb.append('.');
  200. break;
  201. case ':':
  202. if (in_brackets > 0)
  203. if (lookBehind(sb) == '['
  204. && isLetter(lookAhead(pattern, i)))
  205. in_char_class = true;
  206. sb.append(':');
  207. break;
  208. case '-':
  209. if (in_brackets > 0) {
  210. if (lookAhead(pattern, i) == ']')
  211. sb.append('\\').append(c);
  212. else
  213. sb.append(c);
  214. } else
  215. sb.append('-');
  216. break;
  217. case '\\':
  218. if (in_brackets > 0) {
  219. char lookAhead = lookAhead(pattern, i);
  220. if (lookAhead == ']' || lookAhead == '[')
  221. ignoreLastBracket = true;
  222. }
  223. sb.append(c);
  224. break;
  225. case '[':
  226. if (in_brackets > 0) {
  227. sb.append('\\').append('[');
  228. ignoreLastBracket = true;
  229. } else {
  230. if (!seenEscape) {
  231. in_brackets++;
  232. ignoreLastBracket = false;
  233. }
  234. sb.append('[');
  235. }
  236. break;
  237. case ']':
  238. if (seenEscape) {
  239. sb.append(']');
  240. ignoreLastBracket = true;
  241. break;
  242. }
  243. if (in_brackets <= 0) {
  244. sb.append('\\').append(']');
  245. ignoreLastBracket = true;
  246. break;
  247. }
  248. char lookBehind = lookBehind(sb);
  249. if ((lookBehind == '[' && !ignoreLastBracket)
  250. || lookBehind == '^') {
  251. sb.append('\\');
  252. sb.append(']');
  253. ignoreLastBracket = true;
  254. } else {
  255. ignoreLastBracket = false;
  256. if (!in_char_class) {
  257. in_brackets--;
  258. sb.append(']');
  259. } else {
  260. in_char_class = false;
  261. String charCl = checkPosixCharClass(charClass);
  262. // delete last \[:: chars and set the pattern
  263. if (charCl != null) {
  264. sb.setLength(sb.length() - 4);
  265. sb.append(charCl);
  266. }
  267. reset(charClass);
  268. }
  269. }
  270. break;
  271. case '!':
  272. if (in_brackets > 0) {
  273. if (lookBehind(sb) == '[')
  274. sb.append('^');
  275. else
  276. sb.append(c);
  277. } else
  278. sb.append(c);
  279. break;
  280. default:
  281. if (in_char_class)
  282. setNext(charClass, c);
  283. else
  284. sb.append(c);
  285. break;
  286. } // end switch
  287. seenEscape = c == '\\';
  288. } // end for
  289. if (in_brackets > 0)
  290. throw new InvalidPatternException("Not closed bracket?", pattern); //$NON-NLS-1$
  291. return Pattern.compile(sb.toString());
  292. }
  293. /**
  294. * @param buffer
  295. * @return zero of the buffer is empty, otherwise the last character from
  296. * buffer
  297. */
  298. private static char lookBehind(StringBuilder buffer) {
  299. return buffer.length() > 0 ? buffer.charAt(buffer.length() - 1) : 0;
  300. }
  301. /**
  302. * @param pattern
  303. * @param i
  304. * current pointer in the pattern
  305. * @return zero of the index is out of range, otherwise the next character
  306. * from given position
  307. */
  308. private static char lookAhead(String pattern, int i) {
  309. int idx = i + 1;
  310. return idx >= pattern.length() ? 0 : pattern.charAt(idx);
  311. }
  312. private static void setNext(char[] buffer, char c) {
  313. for (int i = 0; i < buffer.length; i++)
  314. if (buffer[i] == 0) {
  315. buffer[i] = c;
  316. break;
  317. }
  318. }
  319. private static void reset(char[] buffer) {
  320. for (int i = 0; i < buffer.length; i++)
  321. buffer[i] = 0;
  322. }
  323. private static String checkPosixCharClass(char[] buffer) {
  324. for (int i = 0; i < POSIX_CHAR_CLASSES.size(); i++) {
  325. String clazz = POSIX_CHAR_CLASSES.get(i);
  326. boolean match = true;
  327. for (int j = 0; j < clazz.length(); j++)
  328. if (buffer[j] != clazz.charAt(j)) {
  329. match = false;
  330. break;
  331. }
  332. if (match)
  333. return JAVA_CHAR_CLASSES.get(i);
  334. }
  335. return null;
  336. }
  337. }