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.

CGitVsJGitRandomIgnorePatternTest.java 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * Copyright (C) 2015, Sebastien Arod <sebastien.arod@gmail.com>
  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;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import java.io.BufferedReader;
  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.io.InputStreamReader;
  50. import java.io.OutputStream;
  51. import java.nio.file.Files;
  52. import java.nio.file.StandardOpenOption;
  53. import java.util.Arrays;
  54. import java.util.List;
  55. import java.util.Random;
  56. import org.eclipse.jgit.api.Git;
  57. import org.eclipse.jgit.util.FileUtils;
  58. import org.junit.Assert;
  59. import org.junit.Test;
  60. /**
  61. * This test generates random ignore patterns and random path and compares the
  62. * output of Cgit check-ignore to the output of {@link FastIgnoreRule}.
  63. */
  64. public class CGitVsJGitRandomIgnorePatternTest {
  65. private static class PseudoRandomPatternGenerator {
  66. private static final int DEFAULT_MAX_FRAGMENTS_PER_PATTERN = 15;
  67. /**
  68. * Generates 75% Special fragments and 25% "standard" characters
  69. */
  70. private static final double DEFAULT_SPECIAL_FRAGMENTS_FREQUENCY = 0.75d;
  71. private static final List<String> SPECIAL_FRAGMENTS = Arrays.asList(
  72. "\\", "!", "#", "[", "]", "|", "/", "*", "?", "{", "}", "(",
  73. ")", "\\d", "(", "**", "[a\\]]", "\\ ", "+", "-", "^", "$", ".",
  74. ":", "=", "[[:", ":]]"
  75. );
  76. private static final String STANDARD_CHARACTERS = new String(
  77. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
  78. private final Random random = new Random();
  79. private final int maxFragmentsPerPattern;
  80. private final double specialFragmentsFrequency;
  81. public PseudoRandomPatternGenerator() {
  82. this(DEFAULT_MAX_FRAGMENTS_PER_PATTERN,
  83. DEFAULT_SPECIAL_FRAGMENTS_FREQUENCY);
  84. }
  85. public PseudoRandomPatternGenerator(int maxFragmentsPerPattern,
  86. double specialFragmentsFrequency) {
  87. this.maxFragmentsPerPattern = maxFragmentsPerPattern;
  88. this.specialFragmentsFrequency = specialFragmentsFrequency;
  89. }
  90. public String nextRandomString() {
  91. StringBuilder builder = new StringBuilder();
  92. int length = randomFragmentCount();
  93. for (int i = 0; i < length; i++) {
  94. if (useSpecialFragment()) {
  95. builder.append(randomSpecialFragment());
  96. } else {
  97. builder.append(randomStandardCharacters());
  98. }
  99. }
  100. return builder.toString();
  101. }
  102. private int randomFragmentCount() {
  103. // We want at least one fragment
  104. return 1 + random.nextInt(maxFragmentsPerPattern - 1);
  105. }
  106. private char randomStandardCharacters() {
  107. return STANDARD_CHARACTERS
  108. .charAt(random.nextInt(STANDARD_CHARACTERS.length()));
  109. }
  110. private boolean useSpecialFragment() {
  111. return random.nextDouble() < specialFragmentsFrequency;
  112. }
  113. private String randomSpecialFragment() {
  114. return SPECIAL_FRAGMENTS
  115. .get(random.nextInt(SPECIAL_FRAGMENTS.size()));
  116. }
  117. }
  118. @SuppressWarnings("serial")
  119. public static class CgitFatalException extends Exception {
  120. public CgitFatalException(int cgitExitCode, String pattern, String path,
  121. String cgitStdError) {
  122. super("CgitFatalException (" + cgitExitCode + ") for pattern:["
  123. + pattern + "] and path:[" + path + "]\n" + cgitStdError);
  124. }
  125. }
  126. public static class CGitIgnoreRule {
  127. private File gitDir;
  128. private String pattern;
  129. public CGitIgnoreRule(File gitDir, String pattern) throws IOException {
  130. this.gitDir = gitDir;
  131. this.pattern = pattern;
  132. Files.write(FileUtils.toPath(new File(gitDir, ".gitignore")),
  133. (pattern + "\n").getBytes(UTF_8), StandardOpenOption.CREATE,
  134. StandardOpenOption.TRUNCATE_EXISTING,
  135. StandardOpenOption.WRITE);
  136. }
  137. public boolean isMatch(String path)
  138. throws IOException, InterruptedException, CgitFatalException {
  139. Process proc = startCgitCheckIgnore(path);
  140. String cgitStdOutput = readProcessStream(proc.getInputStream());
  141. String cgitStdError = readProcessStream(proc.getErrorStream());
  142. int cgitExitCode = proc.waitFor();
  143. if (cgitExitCode == 128) {
  144. throw new CgitFatalException(cgitExitCode, pattern, path,
  145. cgitStdError);
  146. }
  147. return !cgitStdOutput.startsWith("::");
  148. }
  149. private Process startCgitCheckIgnore(String path) throws IOException {
  150. // Use --stdin instead of using argument otherwise paths starting
  151. // with "-" were interpreted as
  152. // options by git check-ignore
  153. String[] command = new String[] { "git", "check-ignore",
  154. "--no-index", "-v", "-n", "--stdin" };
  155. Process proc = Runtime.getRuntime().exec(command, new String[0],
  156. gitDir);
  157. try (OutputStream out = proc.getOutputStream()) {
  158. out.write((path + "\n").getBytes(UTF_8));
  159. out.flush();
  160. }
  161. return proc;
  162. }
  163. private String readProcessStream(InputStream processStream)
  164. throws IOException {
  165. try (BufferedReader stdOut = new BufferedReader(
  166. new InputStreamReader(processStream))) {
  167. StringBuilder out = new StringBuilder();
  168. String s;
  169. while ((s = stdOut.readLine()) != null) {
  170. out.append(s);
  171. }
  172. return out.toString();
  173. }
  174. }
  175. }
  176. private static final int NB_PATTERN = 1000;
  177. private static final int PATH_PER_PATTERN = 1000;
  178. @Test
  179. public void testRandomPatterns() throws Exception {
  180. // Initialize new git repo
  181. File gitDir = Files.createTempDirectory("jgit").toFile();
  182. Git.init().setDirectory(gitDir).call();
  183. PseudoRandomPatternGenerator generator = new PseudoRandomPatternGenerator();
  184. // Generate random patterns and paths
  185. for (int i = 0; i < NB_PATTERN; i++) {
  186. String pattern = generator.nextRandomString();
  187. FastIgnoreRule jgitIgnoreRule = new FastIgnoreRule(pattern);
  188. CGitIgnoreRule cgitIgnoreRule = new CGitIgnoreRule(gitDir, pattern);
  189. // Test path with pattern as path
  190. assertCgitAndJgitMatch(pattern, jgitIgnoreRule, cgitIgnoreRule,
  191. pattern);
  192. for (int p = 0; p < PATH_PER_PATTERN; p++) {
  193. String path = generator.nextRandomString();
  194. assertCgitAndJgitMatch(pattern, jgitIgnoreRule, cgitIgnoreRule,
  195. path);
  196. }
  197. }
  198. }
  199. @SuppressWarnings({ "boxing" })
  200. private void assertCgitAndJgitMatch(String pattern,
  201. FastIgnoreRule jgitIgnoreRule, CGitIgnoreRule cgitIgnoreRule,
  202. String pathToTest) throws IOException, InterruptedException {
  203. try {
  204. boolean cgitMatch = cgitIgnoreRule.isMatch(pathToTest);
  205. boolean jgitMatch = jgitIgnoreRule.isMatch(pathToTest,
  206. pathToTest.endsWith("/"));
  207. if (cgitMatch != jgitMatch) {
  208. System.err.println(
  209. buildAssertionToAdd(pattern, pathToTest, cgitMatch));
  210. }
  211. Assert.assertEquals("jgit:" + jgitMatch + " <> cgit:" + cgitMatch
  212. + " for pattern:[" + pattern + "] and path:[" + pathToTest
  213. + "]", cgitMatch, jgitMatch);
  214. } catch (CgitFatalException e) {
  215. // Lots of generated patterns or path are rejected by Cgit with a
  216. // fatal error. We want to ignore them.
  217. }
  218. }
  219. private String buildAssertionToAdd(String pattern, String pathToTest,
  220. boolean cgitMatch) {
  221. return "assertMatch(" + toJavaString(pattern) + ", "
  222. + toJavaString(pathToTest) + ", " + cgitMatch
  223. + " /*cgit result*/);";
  224. }
  225. private String toJavaString(String pattern2) {
  226. return "\"" + pattern2.replace("\\", "\\\\").replace("\"", "\\\"")
  227. + "\"";
  228. }
  229. }