Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

SimpleIgnoreCache.java 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. * Copyright (C) 2010, Red Hat Inc.
  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 java.io.File;
  45. import java.io.IOException;
  46. import java.net.URI;
  47. import java.util.HashMap;
  48. import org.eclipse.jgit.lib.Constants;
  49. import org.eclipse.jgit.lib.Repository;
  50. import org.eclipse.jgit.treewalk.FileTreeIterator;
  51. import org.eclipse.jgit.treewalk.TreeWalk;
  52. import org.eclipse.jgit.treewalk.filter.PathSuffixFilter;
  53. import org.eclipse.jgit.util.FS;
  54. /**
  55. * A simple ignore cache. Stores ignore information on .gitignore and exclude files.
  56. * <br><br>
  57. * The cache can be initialized by calling {@link #initialize()} on a
  58. * target file.
  59. *
  60. * Inspiration from: Ferry Huberts
  61. */
  62. public class SimpleIgnoreCache {
  63. /**
  64. * Map of ignore nodes, indexed by base directory. By convention, the
  65. * base directory string should NOT start or end with a "/". Use
  66. * {@link #relativize(File)} before appending nodes to the ignoreMap
  67. * <br>
  68. * e.g: path/to/directory is a valid String
  69. */
  70. private HashMap<String, IgnoreNode> ignoreMap;
  71. //Repository associated with this cache
  72. private Repository repository;
  73. //Base directory of this cache
  74. private URI rootFileURI;
  75. /**
  76. * Creates a base implementation of an ignore cache. This default implementation
  77. * will search for all .gitignore files in all children of the base directory,
  78. * and grab the exclude file from baseDir/.git/info/exclude.
  79. * <br><br>
  80. * Call {@link #initialize()} to fetch the ignore information relevant
  81. * to a target file.
  82. * @param repository
  83. * Repository to associate this cache with. The cache's base directory will
  84. * be set to this repository's GIT_DIR
  85. *
  86. */
  87. public SimpleIgnoreCache(Repository repository) {
  88. ignoreMap = new HashMap<String, IgnoreNode>();
  89. this.repository = repository;
  90. this.rootFileURI = repository.getWorkDir().toURI();
  91. }
  92. /**
  93. * Initializes the ignore map for the target file and all parents.
  94. * This will delete existing ignore information for all folders
  95. * on the partial initialization path. Will only function for files
  96. * that are children of the cache's basePath.
  97. * <br><br>
  98. * Note that this does not initialize the ignore rules. Ignore rules will
  99. * be parsed when needed during a call to {@link #isIgnored(String)}
  100. *
  101. * @throws IOException
  102. * The tree could not be walked.
  103. */
  104. public void initialize() throws IOException {
  105. TreeWalk tw = new TreeWalk(repository);
  106. tw.reset();
  107. tw.addTree(new FileTreeIterator(repository.getWorkDir(), FS.DETECTED));
  108. tw.setFilter(PathSuffixFilter.create("/" + Constants.DOT_GIT_IGNORE));
  109. tw.setRecursive(true);
  110. while (tw.next())
  111. addNodeFromTree(tw.getTree(0, FileTreeIterator.class));
  112. //The base is special
  113. //TODO: Test alternate locations for GIT_DIR
  114. readRulesAtBase();
  115. }
  116. /**
  117. * Creates rules for .git/info/exclude and .gitignore to the base node.
  118. * It will overwrite the existing base ignore node. There will always
  119. * be a base ignore node, even if there is no .gitignore file
  120. */
  121. private void readRulesAtBase() {
  122. //Add .gitignore rules
  123. File f = new File(repository.getWorkDir(), Constants.DOT_GIT_IGNORE);
  124. String path = f.getAbsolutePath();
  125. IgnoreNode n = new IgnoreNode(f.getParentFile());
  126. //Add exclude rules
  127. //TODO: Get /info directory without string concat
  128. path = new File(repository.getDirectory(), "info/exclude").getAbsolutePath();
  129. f = new File(path);
  130. if (f.canRead())
  131. n.addSecondarySource(f);
  132. ignoreMap.put("", n);
  133. }
  134. /**
  135. * Adds a node located at the FileTreeIterator's current position.
  136. *
  137. * @param t
  138. * FileTreeIterator to check for ignore info. The name of the
  139. * entry should be ".gitignore".
  140. */
  141. protected void addNodeFromTree(FileTreeIterator t) {
  142. IgnoreNode n = ignoreMap.get(relativize(t.getDirectory()));
  143. long time = t.getEntryLastModified();
  144. if (n != null) {
  145. if (n.getLastModified() == time)
  146. //TODO: Test and optimize
  147. return;
  148. }
  149. n = addIgnoreNode(t.getDirectory());
  150. n.setLastModified(time);
  151. }
  152. /**
  153. * Maps the directory to an IgnoreNode, but does not initialize
  154. * the IgnoreNode. If a node already exists it will be emptied. Empty nodes
  155. * will be initialized when needed, see {@link #isIgnored(String)}
  156. *
  157. * @param dir
  158. * directory to load rules from
  159. * @return
  160. * true if set successfully, false if directory does not exist
  161. * or if directory does not contain a .gitignore file.
  162. */
  163. protected IgnoreNode addIgnoreNode(File dir) {
  164. String relativeDir = relativize(dir);
  165. IgnoreNode n = ignoreMap.get(relativeDir);
  166. if (n != null)
  167. n.clear();
  168. else {
  169. n = new IgnoreNode(dir);
  170. ignoreMap.put(relativeDir, n);
  171. }
  172. return n;
  173. }
  174. /**
  175. * Returns the ignored status of the file based on the current state
  176. * of the ignore nodes. Ignore nodes will not be updated and new ignore
  177. * nodes will not be created.
  178. * <br><br>
  179. * Traverses from highest to lowest priority and quits as soon as a match
  180. * is made. If no match is made anywhere, the file is assumed
  181. * to be not ignored.
  182. *
  183. * @param file
  184. * Path string relative to Repository.getWorkDir();
  185. * @return true
  186. * True if file is ignored, false if the file matches a negation statement
  187. * or if there are no rules pertaining to the file.
  188. * @throws IOException
  189. * Failed to check ignore status
  190. */
  191. public boolean isIgnored(String file) throws IOException{
  192. String currentPriority = file;
  193. boolean ignored = false;
  194. String target = rootFileURI.getPath() + file;
  195. while (currentPriority.length() > 1) {
  196. currentPriority = getParent(currentPriority);
  197. IgnoreNode n = ignoreMap.get(currentPriority);
  198. if (n != null) {
  199. ignored = n.isIgnored(target);
  200. if (n.wasMatched()) {
  201. if (ignored)
  202. return ignored;
  203. else
  204. target = getParent(target);
  205. }
  206. }
  207. }
  208. return false;
  209. }
  210. /**
  211. * String manipulation to get the parent directory of the given path.
  212. * It may be more efficient to make a file and call File.getParent().
  213. * This function is only called in {@link #initialize}
  214. *
  215. * @param filePath
  216. * Will seek parent directory for this path. Returns empty string
  217. * if the filePath does not contain a File.separator
  218. * @return
  219. * Parent of the filePath, or blank string if non-existent
  220. */
  221. private String getParent(String filePath) {
  222. int lastSlash = filePath.lastIndexOf("/");
  223. if (filePath.length() > 0 && lastSlash != -1)
  224. return filePath.substring(0, lastSlash);
  225. else
  226. //This line should be unreachable with the current partiallyInitialize
  227. return "";
  228. }
  229. /**
  230. * @param relativePath
  231. * Directory to find rules for, should be relative to the repository root
  232. * @return
  233. * Ignore rules for given base directory, contained in an IgnoreNode
  234. */
  235. public IgnoreNode getRules(String relativePath) {
  236. return ignoreMap.get(relativePath);
  237. }
  238. /**
  239. * @return
  240. * True if there are no ignore rules in this cache
  241. */
  242. public boolean isEmpty() {
  243. return ignoreMap.isEmpty();
  244. }
  245. /**
  246. * Clears the cache
  247. */
  248. public void clear() {
  249. ignoreMap.clear();
  250. }
  251. /**
  252. * Returns the relative path versus the repository root.
  253. *
  254. * @param directory
  255. * Directory to find relative path for.
  256. * @return
  257. * Relative path versus the repository root. This function will
  258. * strip the last trailing "/" from its return string
  259. */
  260. private String relativize(File directory) {
  261. String retVal = rootFileURI.relativize(directory.toURI()).getPath();
  262. if (retVal.endsWith("/"))
  263. retVal = retVal.substring(0, retVal.length() - 1);
  264. return retVal;
  265. }
  266. }