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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright (C) 2014, 2017 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.text.MessageFormat;
  46. import java.util.ArrayList;
  47. import java.util.Arrays;
  48. import java.util.List;
  49. import java.util.regex.Pattern;
  50. import java.util.regex.PatternSyntaxException;
  51. import org.eclipse.jgit.errors.InvalidPatternException;
  52. import org.eclipse.jgit.ignore.FastIgnoreRule;
  53. import org.eclipse.jgit.internal.JGitText;
  54. /**
  55. * Various {@link String} related utility methods, written mostly to avoid
  56. * generation of new String objects (e.g. via splitting Strings etc).
  57. */
  58. public class Strings {
  59. static char getPathSeparator(Character pathSeparator) {
  60. return pathSeparator == null ? FastIgnoreRule.PATH_SEPARATOR
  61. : pathSeparator.charValue();
  62. }
  63. /**
  64. * @param pattern
  65. * non null
  66. * @param c
  67. * character to remove
  68. * @return new string with all trailing characters removed
  69. */
  70. public static String stripTrailing(String pattern, char c) {
  71. for (int i = pattern.length() - 1; i >= 0; i--) {
  72. char charAt = pattern.charAt(i);
  73. if (charAt != c) {
  74. if (i == pattern.length() - 1) {
  75. return pattern;
  76. }
  77. return pattern.substring(0, i + 1);
  78. }
  79. }
  80. return ""; //$NON-NLS-1$
  81. }
  82. /**
  83. * @param pattern
  84. * non null
  85. * @return new string with all trailing whitespace removed
  86. */
  87. public static String stripTrailingWhitespace(String pattern) {
  88. for (int i = pattern.length() - 1; i >= 0; i--) {
  89. char charAt = pattern.charAt(i);
  90. if (!Character.isWhitespace(charAt)) {
  91. if (i == pattern.length() - 1) {
  92. return pattern;
  93. }
  94. return pattern.substring(0, i + 1);
  95. }
  96. }
  97. return ""; //$NON-NLS-1$
  98. }
  99. /**
  100. * @param pattern
  101. * non null
  102. * @return true if the last character, which is not whitespace, is a path
  103. * separator
  104. */
  105. public static boolean isDirectoryPattern(String pattern) {
  106. for (int i = pattern.length() - 1; i >= 0; i--) {
  107. char charAt = pattern.charAt(i);
  108. if (!Character.isWhitespace(charAt)) {
  109. return charAt == FastIgnoreRule.PATH_SEPARATOR;
  110. }
  111. }
  112. return false;
  113. }
  114. static int count(String s, char c, boolean ignoreFirstLast) {
  115. int start = 0;
  116. int count = 0;
  117. int length = s.length();
  118. while (start < length) {
  119. start = s.indexOf(c, start);
  120. if (start == -1) {
  121. break;
  122. }
  123. if (!ignoreFirstLast || (start != 0 && start != length - 1)) {
  124. count++;
  125. }
  126. start++;
  127. }
  128. return count;
  129. }
  130. /**
  131. * Splits given string to substrings by given separator
  132. *
  133. * @param pattern
  134. * non null
  135. * @param slash
  136. * separator char
  137. * @return list of substrings
  138. */
  139. public static List<String> split(String pattern, char slash) {
  140. int count = count(pattern, slash, true);
  141. if (count < 1)
  142. throw new IllegalStateException(
  143. "Pattern must have at least two segments: " + pattern); //$NON-NLS-1$
  144. List<String> segments = new ArrayList<>(count);
  145. int right = 0;
  146. while (true) {
  147. int left = right;
  148. right = pattern.indexOf(slash, right);
  149. if (right == -1) {
  150. if (left < pattern.length())
  151. segments.add(pattern.substring(left));
  152. break;
  153. }
  154. if (right - left > 0)
  155. if (left == 1)
  156. // leading slash should remain by the first pattern
  157. segments.add(pattern.substring(left - 1, right));
  158. else if (right == pattern.length() - 1)
  159. // trailing slash should remain too
  160. segments.add(pattern.substring(left, right + 1));
  161. else
  162. segments.add(pattern.substring(left, right));
  163. right++;
  164. }
  165. return segments;
  166. }
  167. static boolean isWildCard(String pattern) {
  168. return pattern.indexOf('*') != -1 || isComplexWildcard(pattern);
  169. }
  170. private static boolean isComplexWildcard(String pattern) {
  171. int idx1 = pattern.indexOf('[');
  172. if (idx1 != -1) {
  173. return true;
  174. }
  175. if (pattern.indexOf('?') != -1) {
  176. return true;
  177. } else {
  178. // check if the backslash escapes one of the glob special characters
  179. // if not, backslash is not part of a regex and treated literally
  180. int backSlash = pattern.indexOf('\\');
  181. if (backSlash >= 0) {
  182. int nextIdx = backSlash + 1;
  183. if (pattern.length() == nextIdx) {
  184. return false;
  185. }
  186. char nextChar = pattern.charAt(nextIdx);
  187. if (escapedByBackslash(nextChar)) {
  188. return true;
  189. } else {
  190. return false;
  191. }
  192. }
  193. }
  194. return false;
  195. }
  196. private static boolean escapedByBackslash(char nextChar) {
  197. return nextChar == '?' || nextChar == '*' || nextChar == '[';
  198. }
  199. static PatternState checkWildCards(String pattern) {
  200. if (isComplexWildcard(pattern))
  201. return PatternState.COMPLEX;
  202. int startIdx = pattern.indexOf('*');
  203. if (startIdx < 0)
  204. return PatternState.NONE;
  205. if (startIdx == pattern.length() - 1)
  206. return PatternState.TRAILING_ASTERISK_ONLY;
  207. if (pattern.lastIndexOf('*') == 0)
  208. return PatternState.LEADING_ASTERISK_ONLY;
  209. return PatternState.COMPLEX;
  210. }
  211. static enum PatternState {
  212. LEADING_ASTERISK_ONLY, TRAILING_ASTERISK_ONLY, COMPLEX, NONE
  213. }
  214. final static List<String> POSIX_CHAR_CLASSES = Arrays.asList(
  215. "alnum", "alpha", "blank", "cntrl", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  216. // [:alnum:] [:alpha:] [:blank:] [:cntrl:]
  217. "digit", "graph", "lower", "print", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  218. // [:digit:] [:graph:] [:lower:] [:print:]
  219. "punct", "space", "upper", "xdigit", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  220. // [:punct:] [:space:] [:upper:] [:xdigit:]
  221. "word" //$NON-NLS-1$
  222. // [:word:] XXX I don't see it in
  223. // http://man7.org/linux/man-pages/man7/glob.7.html
  224. // but this was in org.eclipse.jgit.fnmatch.GroupHead.java ???
  225. );
  226. private static final String DL = "\\p{javaDigit}\\p{javaLetter}"; //$NON-NLS-1$
  227. final static List<String> JAVA_CHAR_CLASSES = Arrays
  228. .asList("\\p{Alnum}", "\\p{javaLetter}", "\\p{Blank}", "\\p{Cntrl}", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  229. // [:alnum:] [:alpha:] [:blank:] [:cntrl:]
  230. "\\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$
  231. // [:digit:] [:graph:] [:lower:] [:print:]
  232. "\\p{Punct}", "\\p{Space}", "\\p{Lu}", "\\p{XDigit}", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  233. // [:punct:] [:space:] [:upper:] [:xdigit:]
  234. "[" + DL + "_]" //$NON-NLS-1$ //$NON-NLS-2$
  235. // [:word:]
  236. );
  237. // Collating symbols [[.a.]] or equivalence class expressions [[=a=]] are
  238. // not supported by CLI git (at least not by 1.9.1)
  239. final static Pattern UNSUPPORTED = Pattern
  240. .compile("\\[\\[[.=]\\w+[.=]\\]\\]"); //$NON-NLS-1$
  241. /**
  242. * Conversion from glob to Java regex following two sources: <li>
  243. * http://man7.org/linux/man-pages/man7/glob.7.html <li>
  244. * org.eclipse.jgit.fnmatch.FileNameMatcher.java Seems that there are
  245. * various ways to define what "glob" can be.
  246. *
  247. * @param pattern
  248. * non null pattern
  249. *
  250. * @return Java regex pattern corresponding to given glob pattern
  251. * @throws InvalidPatternException
  252. */
  253. static Pattern convertGlob(String pattern) throws InvalidPatternException {
  254. if (UNSUPPORTED.matcher(pattern).find())
  255. throw new InvalidPatternException(
  256. "Collating symbols [[.a.]] or equivalence class expressions [[=a=]] are not supported", //$NON-NLS-1$
  257. pattern);
  258. StringBuilder sb = new StringBuilder(pattern.length());
  259. int in_brackets = 0;
  260. boolean seenEscape = false;
  261. boolean ignoreLastBracket = false;
  262. boolean in_char_class = false;
  263. // 6 is the length of the longest posix char class "xdigit"
  264. char[] charClass = new char[6];
  265. for (int i = 0; i < pattern.length(); i++) {
  266. final char c = pattern.charAt(i);
  267. switch (c) {
  268. case '*':
  269. if (seenEscape || in_brackets > 0)
  270. sb.append(c);
  271. else
  272. sb.append('.').append(c);
  273. break;
  274. case '(': // fall-through
  275. case ')': // fall-through
  276. case '{': // fall-through
  277. case '}': // fall-through
  278. case '+': // fall-through
  279. case '$': // fall-through
  280. case '^': // fall-through
  281. case '|':
  282. if (seenEscape || in_brackets > 0)
  283. sb.append(c);
  284. else
  285. sb.append('\\').append(c);
  286. break;
  287. case '.':
  288. if (seenEscape)
  289. sb.append(c);
  290. else
  291. sb.append('\\').append('.');
  292. break;
  293. case '?':
  294. if (seenEscape || in_brackets > 0)
  295. sb.append(c);
  296. else
  297. sb.append('.');
  298. break;
  299. case ':':
  300. if (in_brackets > 0)
  301. if (lookBehind(sb) == '['
  302. && isLetter(lookAhead(pattern, i)))
  303. in_char_class = true;
  304. sb.append(':');
  305. break;
  306. case '-':
  307. if (in_brackets > 0) {
  308. if (lookAhead(pattern, i) == ']')
  309. sb.append('\\').append(c);
  310. else
  311. sb.append(c);
  312. } else
  313. sb.append('-');
  314. break;
  315. case '\\':
  316. if (in_brackets > 0) {
  317. char lookAhead = lookAhead(pattern, i);
  318. if (lookAhead == ']' || lookAhead == '[')
  319. ignoreLastBracket = true;
  320. } else {
  321. //
  322. char lookAhead = lookAhead(pattern, i);
  323. if (lookAhead != '\\' && lookAhead != '['
  324. && lookAhead != '?' && lookAhead != '*'
  325. && lookAhead != ' ' && lookBehind(sb) != '\\') {
  326. break;
  327. }
  328. }
  329. sb.append(c);
  330. break;
  331. case '[':
  332. if (in_brackets > 0) {
  333. if (!seenEscape) {
  334. sb.append('\\');
  335. }
  336. sb.append('[');
  337. ignoreLastBracket = true;
  338. } else {
  339. if (!seenEscape) {
  340. in_brackets++;
  341. ignoreLastBracket = false;
  342. }
  343. sb.append('[');
  344. }
  345. break;
  346. case ']':
  347. if (seenEscape) {
  348. sb.append(']');
  349. ignoreLastBracket = true;
  350. break;
  351. }
  352. if (in_brackets <= 0) {
  353. sb.append('\\').append(']');
  354. ignoreLastBracket = true;
  355. break;
  356. }
  357. char lookBehind = lookBehind(sb);
  358. if ((lookBehind == '[' && !ignoreLastBracket)
  359. || lookBehind == '^') {
  360. sb.append('\\');
  361. sb.append(']');
  362. ignoreLastBracket = true;
  363. } else {
  364. ignoreLastBracket = false;
  365. if (!in_char_class) {
  366. in_brackets--;
  367. sb.append(']');
  368. } else {
  369. in_char_class = false;
  370. String charCl = checkPosixCharClass(charClass);
  371. // delete last \[:: chars and set the pattern
  372. if (charCl != null) {
  373. sb.setLength(sb.length() - 4);
  374. sb.append(charCl);
  375. }
  376. reset(charClass);
  377. }
  378. }
  379. break;
  380. case '!':
  381. if (in_brackets > 0) {
  382. if (lookBehind(sb) == '[')
  383. sb.append('^');
  384. else
  385. sb.append(c);
  386. } else
  387. sb.append(c);
  388. break;
  389. default:
  390. if (in_char_class)
  391. setNext(charClass, c);
  392. else
  393. sb.append(c);
  394. break;
  395. } // end switch
  396. seenEscape = c == '\\';
  397. } // end for
  398. if (in_brackets > 0)
  399. throw new InvalidPatternException("Not closed bracket?", pattern); //$NON-NLS-1$
  400. try {
  401. return Pattern.compile(sb.toString());
  402. } catch (PatternSyntaxException e) {
  403. InvalidPatternException patternException = new InvalidPatternException(
  404. MessageFormat.format(JGitText.get().invalidIgnoreRule,
  405. pattern),
  406. pattern);
  407. patternException.initCause(e);
  408. throw patternException;
  409. }
  410. }
  411. /**
  412. * @param buffer
  413. * @return zero of the buffer is empty, otherwise the last character from
  414. * buffer
  415. */
  416. private static char lookBehind(StringBuilder buffer) {
  417. return buffer.length() > 0 ? buffer.charAt(buffer.length() - 1) : 0;
  418. }
  419. /**
  420. * @param pattern
  421. * @param i
  422. * current pointer in the pattern
  423. * @return zero of the index is out of range, otherwise the next character
  424. * from given position
  425. */
  426. private static char lookAhead(String pattern, int i) {
  427. int idx = i + 1;
  428. return idx >= pattern.length() ? 0 : pattern.charAt(idx);
  429. }
  430. private static void setNext(char[] buffer, char c) {
  431. for (int i = 0; i < buffer.length; i++)
  432. if (buffer[i] == 0) {
  433. buffer[i] = c;
  434. break;
  435. }
  436. }
  437. private static void reset(char[] buffer) {
  438. for (int i = 0; i < buffer.length; i++)
  439. buffer[i] = 0;
  440. }
  441. private static String checkPosixCharClass(char[] buffer) {
  442. for (int i = 0; i < POSIX_CHAR_CLASSES.size(); i++) {
  443. String clazz = POSIX_CHAR_CLASSES.get(i);
  444. boolean match = true;
  445. for (int j = 0; j < clazz.length(); j++)
  446. if (buffer[j] != clazz.charAt(j)) {
  447. match = false;
  448. break;
  449. }
  450. if (match)
  451. return JAVA_CHAR_CLASSES.get(i);
  452. }
  453. return null;
  454. }
  455. static String deleteBackslash(String s) {
  456. if (s.indexOf('\\') < 0) {
  457. return s;
  458. }
  459. StringBuilder sb = new StringBuilder(s.length());
  460. for (int i = 0; i < s.length(); i++) {
  461. char ch = s.charAt(i);
  462. if (ch == '\\') {
  463. if (i + 1 == s.length()) {
  464. continue;
  465. }
  466. char next = s.charAt(i + 1);
  467. if (next == '\\') {
  468. sb.append(ch);
  469. i++;
  470. continue;
  471. }
  472. if (!escapedByBackslash(next)) {
  473. continue;
  474. }
  475. }
  476. sb.append(ch);
  477. }
  478. return sb.toString();
  479. }
  480. }