選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

TreeWalk.java 46KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  1. /*
  2. * Copyright (C) 2008-2009, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  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.treewalk;
  45. import java.io.IOException;
  46. import java.util.HashMap;
  47. import java.util.Map;
  48. import java.util.Set;
  49. import org.eclipse.jgit.annotations.Nullable;
  50. import org.eclipse.jgit.api.errors.JGitInternalException;
  51. import org.eclipse.jgit.attributes.Attribute;
  52. import org.eclipse.jgit.attributes.Attribute.State;
  53. import org.eclipse.jgit.attributes.Attributes;
  54. import org.eclipse.jgit.attributes.AttributesNode;
  55. import org.eclipse.jgit.attributes.AttributesNodeProvider;
  56. import org.eclipse.jgit.attributes.AttributesProvider;
  57. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  58. import org.eclipse.jgit.dircache.DirCacheIterator;
  59. import org.eclipse.jgit.errors.CorruptObjectException;
  60. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  61. import org.eclipse.jgit.errors.MissingObjectException;
  62. import org.eclipse.jgit.errors.StopWalkException;
  63. import org.eclipse.jgit.lib.AnyObjectId;
  64. import org.eclipse.jgit.lib.Config;
  65. import org.eclipse.jgit.lib.Constants;
  66. import org.eclipse.jgit.lib.FileMode;
  67. import org.eclipse.jgit.lib.MutableObjectId;
  68. import org.eclipse.jgit.lib.ObjectId;
  69. import org.eclipse.jgit.lib.ObjectReader;
  70. import org.eclipse.jgit.lib.Repository;
  71. import org.eclipse.jgit.revwalk.RevTree;
  72. import org.eclipse.jgit.treewalk.filter.PathFilter;
  73. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  74. import org.eclipse.jgit.util.QuotedString;
  75. import org.eclipse.jgit.util.RawParseUtils;
  76. /**
  77. * Walks one or more {@link AbstractTreeIterator}s in parallel.
  78. * <p>
  79. * This class can perform n-way differences across as many trees as necessary.
  80. * <p>
  81. * Each tree added must have the same root as existing trees in the walk.
  82. * <p>
  83. * A TreeWalk instance can only be used once to generate results. Running a
  84. * second time requires creating a new TreeWalk instance, or invoking
  85. * {@link #reset()} and adding new trees before starting again. Resetting an
  86. * existing instance may be faster for some applications as some internal
  87. * buffers may be recycled.
  88. * <p>
  89. * TreeWalk instances are not thread-safe. Applications must either restrict
  90. * usage of a TreeWalk instance to a single thread, or implement their own
  91. * synchronization at a higher level.
  92. * <p>
  93. * Multiple simultaneous TreeWalk instances per {@link Repository} are
  94. * permitted, even from concurrent threads.
  95. */
  96. public class TreeWalk implements AutoCloseable, AttributesProvider {
  97. private static final AbstractTreeIterator[] NO_TREES = {};
  98. /**
  99. * @since 4.2
  100. */
  101. public static enum OperationType {
  102. /**
  103. * Represents a checkout operation (for example a checkout or reset
  104. * operation).
  105. */
  106. CHECKOUT_OP,
  107. /**
  108. * Represents a checkin operation (for example an add operation)
  109. */
  110. CHECKIN_OP
  111. }
  112. /**
  113. * Type of operation you want to retrieve the git attributes for.
  114. */
  115. private OperationType operationType = OperationType.CHECKOUT_OP;
  116. /**
  117. * The filter command as defined in gitattributes. The keys are
  118. * filterName+"."+filterCommandType. E.g. "lfs.clean"
  119. */
  120. private Map<String, String> filterCommandsByNameDotType = new HashMap<String, String>();
  121. /**
  122. * @param operationType
  123. * @since 4.2
  124. */
  125. public void setOperationType(OperationType operationType) {
  126. this.operationType = operationType;
  127. }
  128. /**
  129. * Open a tree walk and filter to exactly one path.
  130. * <p>
  131. * The returned tree walk is already positioned on the requested path, so
  132. * the caller should not need to invoke {@link #next()} unless they are
  133. * looking for a possible directory/file name conflict.
  134. *
  135. * @param reader
  136. * the reader the walker will obtain tree data from.
  137. * @param path
  138. * single path to advance the tree walk instance into.
  139. * @param trees
  140. * one or more trees to walk through, all with the same root.
  141. * @return a new tree walk configured for exactly this one path; null if no
  142. * path was found in any of the trees.
  143. * @throws IOException
  144. * reading a pack file or loose object failed.
  145. * @throws CorruptObjectException
  146. * an tree object could not be read as its data stream did not
  147. * appear to be a tree, or could not be inflated.
  148. * @throws IncorrectObjectTypeException
  149. * an object we expected to be a tree was not a tree.
  150. * @throws MissingObjectException
  151. * a tree object was not found.
  152. */
  153. public static TreeWalk forPath(final ObjectReader reader, final String path,
  154. final AnyObjectId... trees) throws MissingObjectException,
  155. IncorrectObjectTypeException, CorruptObjectException, IOException {
  156. TreeWalk tw = new TreeWalk(reader);
  157. PathFilter f = PathFilter.create(path);
  158. tw.setFilter(f);
  159. tw.reset(trees);
  160. tw.setRecursive(false);
  161. while (tw.next()) {
  162. if (f.isDone(tw)) {
  163. return tw;
  164. } else if (tw.isSubtree()) {
  165. tw.enterSubtree();
  166. }
  167. }
  168. return null;
  169. }
  170. /**
  171. * Open a tree walk and filter to exactly one path.
  172. * <p>
  173. * The returned tree walk is already positioned on the requested path, so
  174. * the caller should not need to invoke {@link #next()} unless they are
  175. * looking for a possible directory/file name conflict.
  176. *
  177. * @param db
  178. * repository to read tree object data from.
  179. * @param path
  180. * single path to advance the tree walk instance into.
  181. * @param trees
  182. * one or more trees to walk through, all with the same root.
  183. * @return a new tree walk configured for exactly this one path; null if no
  184. * path was found in any of the trees.
  185. * @throws IOException
  186. * reading a pack file or loose object failed.
  187. * @throws CorruptObjectException
  188. * an tree object could not be read as its data stream did not
  189. * appear to be a tree, or could not be inflated.
  190. * @throws IncorrectObjectTypeException
  191. * an object we expected to be a tree was not a tree.
  192. * @throws MissingObjectException
  193. * a tree object was not found.
  194. */
  195. public static TreeWalk forPath(final Repository db, final String path,
  196. final AnyObjectId... trees) throws MissingObjectException,
  197. IncorrectObjectTypeException, CorruptObjectException, IOException {
  198. try (ObjectReader reader = db.newObjectReader()) {
  199. return forPath(reader, path, trees);
  200. }
  201. }
  202. /**
  203. * Open a tree walk and filter to exactly one path.
  204. * <p>
  205. * The returned tree walk is already positioned on the requested path, so
  206. * the caller should not need to invoke {@link #next()} unless they are
  207. * looking for a possible directory/file name conflict.
  208. *
  209. * @param db
  210. * repository to read tree object data from.
  211. * @param path
  212. * single path to advance the tree walk instance into.
  213. * @param tree
  214. * the single tree to walk through.
  215. * @return a new tree walk configured for exactly this one path; null if no
  216. * path was found in any of the trees.
  217. * @throws IOException
  218. * reading a pack file or loose object failed.
  219. * @throws CorruptObjectException
  220. * an tree object could not be read as its data stream did not
  221. * appear to be a tree, or could not be inflated.
  222. * @throws IncorrectObjectTypeException
  223. * an object we expected to be a tree was not a tree.
  224. * @throws MissingObjectException
  225. * a tree object was not found.
  226. */
  227. public static TreeWalk forPath(final Repository db, final String path,
  228. final RevTree tree) throws MissingObjectException,
  229. IncorrectObjectTypeException, CorruptObjectException, IOException {
  230. return forPath(db, path, new ObjectId[] { tree });
  231. }
  232. private final ObjectReader reader;
  233. private final boolean closeReader;
  234. private final MutableObjectId idBuffer = new MutableObjectId();
  235. private TreeFilter filter;
  236. AbstractTreeIterator[] trees;
  237. private boolean recursive;
  238. private boolean postOrderTraversal;
  239. int depth;
  240. private boolean advance;
  241. private boolean postChildren;
  242. private AttributesNodeProvider attributesNodeProvider;
  243. AbstractTreeIterator currentHead;
  244. /** Cached attribute for the current entry */
  245. private Attributes attrs = null;
  246. private Config config;
  247. /**
  248. * Create a new tree walker for a given repository.
  249. *
  250. * @param repo
  251. * the repository the walker will obtain data from. An
  252. * ObjectReader will be created by the walker, and will be closed
  253. * when the walker is closed.
  254. */
  255. public TreeWalk(final Repository repo) {
  256. this(repo.newObjectReader(), true);
  257. config = repo.getConfig();
  258. attributesNodeProvider = repo.createAttributesNodeProvider();
  259. }
  260. /**
  261. * Create a new tree walker for a given repository.
  262. *
  263. * @param or
  264. * the reader the walker will obtain tree data from. The reader
  265. * is not closed when the walker is closed.
  266. */
  267. public TreeWalk(final ObjectReader or) {
  268. this(or, false);
  269. }
  270. private TreeWalk(final ObjectReader or, final boolean closeReader) {
  271. reader = or;
  272. filter = TreeFilter.ALL;
  273. trees = NO_TREES;
  274. this.closeReader = closeReader;
  275. }
  276. /** @return the reader this walker is using to load objects. */
  277. public ObjectReader getObjectReader() {
  278. return reader;
  279. }
  280. /**
  281. * Release any resources used by this walker's reader.
  282. * <p>
  283. * A walker that has been released can be used again, but may need to be
  284. * released after the subsequent usage.
  285. *
  286. * @since 4.0
  287. */
  288. @Override
  289. public void close() {
  290. if (closeReader) {
  291. reader.close();
  292. }
  293. }
  294. /**
  295. * Get the currently configured filter.
  296. *
  297. * @return the current filter. Never null as a filter is always needed.
  298. */
  299. public TreeFilter getFilter() {
  300. return filter;
  301. }
  302. /**
  303. * Set the tree entry filter for this walker.
  304. * <p>
  305. * Multiple filters may be combined by constructing an arbitrary tree of
  306. * <code>AndTreeFilter</code> or <code>OrTreeFilter</code> instances to
  307. * describe the boolean expression required by the application. Custom
  308. * filter implementations may also be constructed by applications.
  309. * <p>
  310. * Note that filters are not thread-safe and may not be shared by concurrent
  311. * TreeWalk instances. Every TreeWalk must be supplied its own unique
  312. * filter, unless the filter implementation specifically states it is (and
  313. * always will be) thread-safe. Callers may use {@link TreeFilter#clone()}
  314. * to create a unique filter tree for this TreeWalk instance.
  315. *
  316. * @param newFilter
  317. * the new filter. If null the special {@link TreeFilter#ALL}
  318. * filter will be used instead, as it matches every entry.
  319. * @see org.eclipse.jgit.treewalk.filter.AndTreeFilter
  320. * @see org.eclipse.jgit.treewalk.filter.OrTreeFilter
  321. */
  322. public void setFilter(final TreeFilter newFilter) {
  323. filter = newFilter != null ? newFilter : TreeFilter.ALL;
  324. }
  325. /**
  326. * Is this walker automatically entering into subtrees?
  327. * <p>
  328. * If the walker is recursive then the caller will not see a subtree node
  329. * and instead will only receive file nodes in all relevant subtrees.
  330. *
  331. * @return true if automatically entering subtrees is enabled.
  332. */
  333. public boolean isRecursive() {
  334. return recursive;
  335. }
  336. /**
  337. * Set the walker to enter (or not enter) subtrees automatically.
  338. * <p>
  339. * If recursive mode is enabled the walker will hide subtree nodes from the
  340. * calling application and will produce only file level nodes. If a tree
  341. * (directory) is deleted then all of the file level nodes will appear to be
  342. * deleted, recursively, through as many levels as necessary to account for
  343. * all entries.
  344. *
  345. * @param b
  346. * true to skip subtree nodes and only obtain files nodes.
  347. */
  348. public void setRecursive(final boolean b) {
  349. recursive = b;
  350. }
  351. /**
  352. * Does this walker return a tree entry after it exits the subtree?
  353. * <p>
  354. * If post order traversal is enabled then the walker will return a subtree
  355. * after it has returned the last entry within that subtree. This may cause
  356. * a subtree to be seen by the application twice if {@link #isRecursive()}
  357. * is false, as the application will see it once, call
  358. * {@link #enterSubtree()}, and then see it again as it leaves the subtree.
  359. * <p>
  360. * If an application does not enable {@link #isRecursive()} and it does not
  361. * call {@link #enterSubtree()} then the tree is returned only once as none
  362. * of the children were processed.
  363. *
  364. * @return true if subtrees are returned after entries within the subtree.
  365. */
  366. public boolean isPostOrderTraversal() {
  367. return postOrderTraversal;
  368. }
  369. /**
  370. * Set the walker to return trees after their children.
  371. *
  372. * @param b
  373. * true to get trees after their children.
  374. * @see #isPostOrderTraversal()
  375. */
  376. public void setPostOrderTraversal(final boolean b) {
  377. postOrderTraversal = b;
  378. }
  379. /**
  380. * Sets the {@link AttributesNodeProvider} for this {@link TreeWalk}.
  381. * <p>
  382. * This is a requirement for a correct computation of the git attributes.
  383. * If this {@link TreeWalk} has been built using
  384. * {@link #TreeWalk(Repository)} constructor, the
  385. * {@link AttributesNodeProvider} has already been set. Indeed,the
  386. * {@link Repository} can provide an {@link AttributesNodeProvider} using
  387. * {@link Repository#createAttributesNodeProvider()} method. Otherwise you
  388. * should provide one.
  389. * </p>
  390. *
  391. * @see Repository#createAttributesNodeProvider()
  392. * @param provider
  393. * @since 4.2
  394. */
  395. public void setAttributesNodeProvider(AttributesNodeProvider provider) {
  396. attributesNodeProvider = provider;
  397. }
  398. /** Reset this walker so new tree iterators can be added to it. */
  399. public void reset() {
  400. attrs = null;
  401. trees = NO_TREES;
  402. advance = false;
  403. depth = 0;
  404. }
  405. /**
  406. * Reset this walker to run over a single existing tree.
  407. *
  408. * @param id
  409. * the tree we need to parse. The walker will execute over this
  410. * single tree if the reset is successful.
  411. * @throws MissingObjectException
  412. * the given tree object does not exist in this repository.
  413. * @throws IncorrectObjectTypeException
  414. * the given object id does not denote a tree, but instead names
  415. * some other non-tree type of object. Note that commits are not
  416. * trees, even if they are sometimes called a "tree-ish".
  417. * @throws CorruptObjectException
  418. * the object claimed to be a tree, but its contents did not
  419. * appear to be a tree. The repository may have data corruption.
  420. * @throws IOException
  421. * a loose object or pack file could not be read.
  422. */
  423. public void reset(final AnyObjectId id) throws MissingObjectException,
  424. IncorrectObjectTypeException, CorruptObjectException, IOException {
  425. if (trees.length == 1) {
  426. AbstractTreeIterator o = trees[0];
  427. while (o.parent != null)
  428. o = o.parent;
  429. if (o instanceof CanonicalTreeParser) {
  430. o.matches = null;
  431. o.matchShift = 0;
  432. ((CanonicalTreeParser) o).reset(reader, id);
  433. trees[0] = o;
  434. } else {
  435. trees[0] = parserFor(id);
  436. }
  437. } else {
  438. trees = new AbstractTreeIterator[] { parserFor(id) };
  439. }
  440. advance = false;
  441. depth = 0;
  442. attrs = null;
  443. }
  444. /**
  445. * Reset this walker to run over a set of existing trees.
  446. *
  447. * @param ids
  448. * the trees we need to parse. The walker will execute over this
  449. * many parallel trees if the reset is successful.
  450. * @throws MissingObjectException
  451. * the given tree object does not exist in this repository.
  452. * @throws IncorrectObjectTypeException
  453. * the given object id does not denote a tree, but instead names
  454. * some other non-tree type of object. Note that commits are not
  455. * trees, even if they are sometimes called a "tree-ish".
  456. * @throws CorruptObjectException
  457. * the object claimed to be a tree, but its contents did not
  458. * appear to be a tree. The repository may have data corruption.
  459. * @throws IOException
  460. * a loose object or pack file could not be read.
  461. */
  462. public void reset(final AnyObjectId... ids) throws MissingObjectException,
  463. IncorrectObjectTypeException, CorruptObjectException, IOException {
  464. final int oldLen = trees.length;
  465. final int newLen = ids.length;
  466. final AbstractTreeIterator[] r = newLen == oldLen ? trees
  467. : new AbstractTreeIterator[newLen];
  468. for (int i = 0; i < newLen; i++) {
  469. AbstractTreeIterator o;
  470. if (i < oldLen) {
  471. o = trees[i];
  472. while (o.parent != null)
  473. o = o.parent;
  474. if (o instanceof CanonicalTreeParser && o.pathOffset == 0) {
  475. o.matches = null;
  476. o.matchShift = 0;
  477. ((CanonicalTreeParser) o).reset(reader, ids[i]);
  478. r[i] = o;
  479. continue;
  480. }
  481. }
  482. o = parserFor(ids[i]);
  483. r[i] = o;
  484. }
  485. trees = r;
  486. advance = false;
  487. depth = 0;
  488. attrs = null;
  489. }
  490. /**
  491. * Add an already existing tree object for walking.
  492. * <p>
  493. * The position of this tree is returned to the caller, in case the caller
  494. * has lost track of the order they added the trees into the walker.
  495. * <p>
  496. * The tree must have the same root as existing trees in the walk.
  497. *
  498. * @param id
  499. * identity of the tree object the caller wants walked.
  500. * @return position of this tree within the walker.
  501. * @throws MissingObjectException
  502. * the given tree object does not exist in this repository.
  503. * @throws IncorrectObjectTypeException
  504. * the given object id does not denote a tree, but instead names
  505. * some other non-tree type of object. Note that commits are not
  506. * trees, even if they are sometimes called a "tree-ish".
  507. * @throws CorruptObjectException
  508. * the object claimed to be a tree, but its contents did not
  509. * appear to be a tree. The repository may have data corruption.
  510. * @throws IOException
  511. * a loose object or pack file could not be read.
  512. */
  513. public int addTree(final AnyObjectId id) throws MissingObjectException,
  514. IncorrectObjectTypeException, CorruptObjectException, IOException {
  515. return addTree(parserFor(id));
  516. }
  517. /**
  518. * Add an already created tree iterator for walking.
  519. * <p>
  520. * The position of this tree is returned to the caller, in case the caller
  521. * has lost track of the order they added the trees into the walker.
  522. * <p>
  523. * The tree which the iterator operates on must have the same root as
  524. * existing trees in the walk.
  525. *
  526. * @param p
  527. * an iterator to walk over. The iterator should be new, with no
  528. * parent, and should still be positioned before the first entry.
  529. * The tree which the iterator operates on must have the same
  530. * root as other trees in the walk.
  531. * @return position of this tree within the walker.
  532. */
  533. public int addTree(AbstractTreeIterator p) {
  534. int n = trees.length;
  535. AbstractTreeIterator[] newTrees = new AbstractTreeIterator[n + 1];
  536. System.arraycopy(trees, 0, newTrees, 0, n);
  537. newTrees[n] = p;
  538. p.matches = null;
  539. p.matchShift = 0;
  540. trees = newTrees;
  541. return n;
  542. }
  543. /**
  544. * Get the number of trees known to this walker.
  545. *
  546. * @return the total number of trees this walker is iterating over.
  547. */
  548. public int getTreeCount() {
  549. return trees.length;
  550. }
  551. /**
  552. * Advance this walker to the next relevant entry.
  553. *
  554. * @return true if there is an entry available; false if all entries have
  555. * been walked and the walk of this set of tree iterators is over.
  556. * @throws MissingObjectException
  557. * {@link #isRecursive()} was enabled, a subtree was found, but
  558. * the subtree object does not exist in this repository. The
  559. * repository may be missing objects.
  560. * @throws IncorrectObjectTypeException
  561. * {@link #isRecursive()} was enabled, a subtree was found, and
  562. * the subtree id does not denote a tree, but instead names some
  563. * other non-tree type of object. The repository may have data
  564. * corruption.
  565. * @throws CorruptObjectException
  566. * the contents of a tree did not appear to be a tree. The
  567. * repository may have data corruption.
  568. * @throws IOException
  569. * a loose object or pack file could not be read.
  570. */
  571. public boolean next() throws MissingObjectException,
  572. IncorrectObjectTypeException, CorruptObjectException, IOException {
  573. try {
  574. attrs = null;
  575. if (advance) {
  576. advance = false;
  577. postChildren = false;
  578. popEntriesEqual();
  579. }
  580. for (;;) {
  581. final AbstractTreeIterator t = min();
  582. if (t.eof()) {
  583. if (depth > 0) {
  584. exitSubtree();
  585. if (postOrderTraversal) {
  586. advance = true;
  587. postChildren = true;
  588. return true;
  589. }
  590. popEntriesEqual();
  591. continue;
  592. }
  593. return false;
  594. }
  595. currentHead = t;
  596. if (!filter.include(this)) {
  597. skipEntriesEqual();
  598. continue;
  599. }
  600. if (recursive && FileMode.TREE.equals(t.mode)) {
  601. enterSubtree();
  602. continue;
  603. }
  604. advance = true;
  605. return true;
  606. }
  607. } catch (StopWalkException stop) {
  608. stopWalk();
  609. return false;
  610. }
  611. }
  612. /**
  613. * Notify iterators the walk is aborting.
  614. * <p>
  615. * Primarily to notify {@link DirCacheBuildIterator} the walk is aborting so
  616. * that it can copy any remaining entries.
  617. *
  618. * @throws IOException
  619. * if traversal of remaining entries throws an exception during
  620. * object access. This should never occur as remaining trees
  621. * should already be in memory, however the methods used to
  622. * finish traversal are declared to throw IOException.
  623. */
  624. void stopWalk() throws IOException {
  625. for (AbstractTreeIterator t : trees) {
  626. t.stopWalk();
  627. }
  628. }
  629. /**
  630. * Obtain the tree iterator for the current entry.
  631. * <p>
  632. * Entering into (or exiting out of) a subtree causes the current tree
  633. * iterator instance to be changed for the nth tree. This allows the tree
  634. * iterators to manage only one list of items, with the diving handled by
  635. * recursive trees.
  636. *
  637. * @param <T>
  638. * type of the tree iterator expected by the caller.
  639. * @param nth
  640. * tree to obtain the current iterator of.
  641. * @param clazz
  642. * type of the tree iterator expected by the caller.
  643. * @return r the current iterator of the requested type; null if the tree
  644. * has no entry to match the current path.
  645. */
  646. @SuppressWarnings("unchecked")
  647. public <T extends AbstractTreeIterator> T getTree(final int nth,
  648. final Class<T> clazz) {
  649. final AbstractTreeIterator t = trees[nth];
  650. return t.matches == currentHead ? (T) t : null;
  651. }
  652. /**
  653. * Obtain the raw {@link FileMode} bits for the current entry.
  654. * <p>
  655. * Every added tree supplies mode bits, even if the tree does not contain
  656. * the current entry. In the latter case {@link FileMode#MISSING}'s mode
  657. * bits (0) are returned.
  658. *
  659. * @param nth
  660. * tree to obtain the mode bits from.
  661. * @return mode bits for the current entry of the nth tree.
  662. * @see FileMode#fromBits(int)
  663. */
  664. public int getRawMode(final int nth) {
  665. final AbstractTreeIterator t = trees[nth];
  666. return t.matches == currentHead ? t.mode : 0;
  667. }
  668. /**
  669. * Obtain the {@link FileMode} for the current entry.
  670. * <p>
  671. * Every added tree supplies a mode, even if the tree does not contain the
  672. * current entry. In the latter case {@link FileMode#MISSING} is returned.
  673. *
  674. * @param nth
  675. * tree to obtain the mode from.
  676. * @return mode for the current entry of the nth tree.
  677. */
  678. public FileMode getFileMode(final int nth) {
  679. return FileMode.fromBits(getRawMode(nth));
  680. }
  681. /**
  682. * Obtain the ObjectId for the current entry.
  683. * <p>
  684. * Using this method to compare ObjectId values between trees of this walker
  685. * is very inefficient. Applications should try to use
  686. * {@link #idEqual(int, int)} or {@link #getObjectId(MutableObjectId, int)}
  687. * whenever possible.
  688. * <p>
  689. * Every tree supplies an object id, even if the tree does not contain the
  690. * current entry. In the latter case {@link ObjectId#zeroId()} is returned.
  691. *
  692. * @param nth
  693. * tree to obtain the object identifier from.
  694. * @return object identifier for the current tree entry.
  695. * @see #getObjectId(MutableObjectId, int)
  696. * @see #idEqual(int, int)
  697. */
  698. public ObjectId getObjectId(final int nth) {
  699. final AbstractTreeIterator t = trees[nth];
  700. return t.matches == currentHead ? t.getEntryObjectId() : ObjectId
  701. .zeroId();
  702. }
  703. /**
  704. * Obtain the ObjectId for the current entry.
  705. * <p>
  706. * Every tree supplies an object id, even if the tree does not contain the
  707. * current entry. In the latter case {@link ObjectId#zeroId()} is supplied.
  708. * <p>
  709. * Applications should try to use {@link #idEqual(int, int)} when possible
  710. * as it avoids conversion overheads.
  711. *
  712. * @param out
  713. * buffer to copy the object id into.
  714. * @param nth
  715. * tree to obtain the object identifier from.
  716. * @see #idEqual(int, int)
  717. */
  718. public void getObjectId(final MutableObjectId out, final int nth) {
  719. final AbstractTreeIterator t = trees[nth];
  720. if (t.matches == currentHead)
  721. t.getEntryObjectId(out);
  722. else
  723. out.clear();
  724. }
  725. /**
  726. * Compare two tree's current ObjectId values for equality.
  727. *
  728. * @param nthA
  729. * first tree to compare the object id from.
  730. * @param nthB
  731. * second tree to compare the object id from.
  732. * @return result of
  733. * <code>getObjectId(nthA).equals(getObjectId(nthB))</code>.
  734. * @see #getObjectId(int)
  735. */
  736. public boolean idEqual(final int nthA, final int nthB) {
  737. final AbstractTreeIterator ch = currentHead;
  738. final AbstractTreeIterator a = trees[nthA];
  739. final AbstractTreeIterator b = trees[nthB];
  740. if (a.matches != ch && b.matches != ch) {
  741. // If neither tree matches the current path node then neither
  742. // tree has this entry. In such case the ObjectId is zero(),
  743. // and zero() is always equal to zero().
  744. //
  745. return true;
  746. }
  747. if (!a.hasId() || !b.hasId())
  748. return false;
  749. if (a.matches == ch && b.matches == ch)
  750. return a.idEqual(b);
  751. return false;
  752. }
  753. /**
  754. * Get the current entry's name within its parent tree.
  755. * <p>
  756. * This method is not very efficient and is primarily meant for debugging
  757. * and final output generation. Applications should try to avoid calling it,
  758. * and if invoked do so only once per interesting entry, where the name is
  759. * absolutely required for correct function.
  760. *
  761. * @return name of the current entry within the parent tree (or directory).
  762. * The name never includes a '/'.
  763. */
  764. public String getNameString() {
  765. final AbstractTreeIterator t = currentHead;
  766. final int off = t.pathOffset;
  767. final int end = t.pathLen;
  768. return RawParseUtils.decode(Constants.CHARSET, t.path, off, end);
  769. }
  770. /**
  771. * Get the current entry's complete path.
  772. * <p>
  773. * This method is not very efficient and is primarily meant for debugging
  774. * and final output generation. Applications should try to avoid calling it,
  775. * and if invoked do so only once per interesting entry, where the name is
  776. * absolutely required for correct function.
  777. *
  778. * @return complete path of the current entry, from the root of the
  779. * repository. If the current entry is in a subtree there will be at
  780. * least one '/' in the returned string.
  781. */
  782. public String getPathString() {
  783. return pathOf(currentHead);
  784. }
  785. /**
  786. * Get the current entry's complete path as a UTF-8 byte array.
  787. *
  788. * @return complete path of the current entry, from the root of the
  789. * repository. If the current entry is in a subtree there will be at
  790. * least one '/' in the returned string.
  791. */
  792. public byte[] getRawPath() {
  793. final AbstractTreeIterator t = currentHead;
  794. final int n = t.pathLen;
  795. final byte[] r = new byte[n];
  796. System.arraycopy(t.path, 0, r, 0, n);
  797. return r;
  798. }
  799. /**
  800. * @return The path length of the current entry.
  801. */
  802. public int getPathLength() {
  803. return currentHead.pathLen;
  804. }
  805. /**
  806. * Test if the supplied path matches the current entry's path.
  807. * <p>
  808. * This method tests that the supplied path is exactly equal to the current
  809. * entry or is one of its parent directories. It is faster to use this
  810. * method then to use {@link #getPathString()} to first create a String
  811. * object, then test <code>startsWith</code> or some other type of string
  812. * match function.
  813. * <p>
  814. * If the current entry is a subtree, then all paths within the subtree
  815. * are considered to match it.
  816. *
  817. * @param p
  818. * path buffer to test. Callers should ensure the path does not
  819. * end with '/' prior to invocation.
  820. * @param pLen
  821. * number of bytes from <code>buf</code> to test.
  822. * @return &lt; 0 if p is before the current path; 0 if p matches the current
  823. * path; 1 if the current path is past p and p will never match
  824. * again on this tree walk.
  825. */
  826. public int isPathPrefix(final byte[] p, final int pLen) {
  827. final AbstractTreeIterator t = currentHead;
  828. final byte[] c = t.path;
  829. final int cLen = t.pathLen;
  830. int ci;
  831. for (ci = 0; ci < cLen && ci < pLen; ci++) {
  832. final int c_value = (c[ci] & 0xff) - (p[ci] & 0xff);
  833. if (c_value != 0)
  834. return c_value;
  835. }
  836. if (ci < cLen) {
  837. // Ran out of pattern but we still had current data.
  838. // If c[ci] == '/' then pattern matches the subtree.
  839. // Otherwise we cannot be certain so we return -1.
  840. //
  841. return c[ci] == '/' ? 0 : -1;
  842. }
  843. if (ci < pLen) {
  844. // Ran out of current, but we still have pattern data.
  845. // If p[ci] == '/' then pattern matches this subtree,
  846. // otherwise we cannot be certain so we return -1.
  847. //
  848. return p[ci] == '/' && FileMode.TREE.equals(t.mode) ? 0 : -1;
  849. }
  850. // Both strings are identical.
  851. //
  852. return 0;
  853. }
  854. /**
  855. * Test if the supplied path matches (being suffix of) the current entry's
  856. * path.
  857. * <p>
  858. * This method tests that the supplied path is exactly equal to the current
  859. * entry, or is relative to one of entry's parent directories. It is faster
  860. * to use this method then to use {@link #getPathString()} to first create
  861. * a String object, then test <code>endsWith</code> or some other type of
  862. * string match function.
  863. *
  864. * @param p
  865. * path buffer to test.
  866. * @param pLen
  867. * number of bytes from <code>buf</code> to test.
  868. * @return true if p is suffix of the current path;
  869. * false if otherwise
  870. */
  871. public boolean isPathSuffix(final byte[] p, final int pLen) {
  872. final AbstractTreeIterator t = currentHead;
  873. final byte[] c = t.path;
  874. final int cLen = t.pathLen;
  875. for (int i = 1; i <= pLen; i++) {
  876. // Pattern longer than current path
  877. if (i > cLen)
  878. return false;
  879. // Current path doesn't match pattern
  880. if (c[cLen - i] != p[pLen - i])
  881. return false;
  882. }
  883. // Whole pattern tested -> matches
  884. return true;
  885. }
  886. /**
  887. * Get the current subtree depth of this walker.
  888. *
  889. * @return the current subtree depth of this walker.
  890. */
  891. public int getDepth() {
  892. return depth;
  893. }
  894. /**
  895. * Is the current entry a subtree?
  896. * <p>
  897. * This method is faster then testing the raw mode bits of all trees to see
  898. * if any of them are a subtree. If at least one is a subtree then this
  899. * method will return true.
  900. *
  901. * @return true if {@link #enterSubtree()} will work on the current node.
  902. */
  903. public boolean isSubtree() {
  904. return FileMode.TREE.equals(currentHead.mode);
  905. }
  906. /**
  907. * Is the current entry a subtree returned after its children?
  908. *
  909. * @return true if the current node is a tree that has been returned after
  910. * its children were already processed.
  911. * @see #isPostOrderTraversal()
  912. */
  913. public boolean isPostChildren() {
  914. return postChildren && isSubtree();
  915. }
  916. /**
  917. * Enter into the current subtree.
  918. * <p>
  919. * If the current entry is a subtree this method arranges for its children
  920. * to be returned before the next sibling following the subtree is returned.
  921. *
  922. * @throws MissingObjectException
  923. * a subtree was found, but the subtree object does not exist in
  924. * this repository. The repository may be missing objects.
  925. * @throws IncorrectObjectTypeException
  926. * a subtree was found, and the subtree id does not denote a
  927. * tree, but instead names some other non-tree type of object.
  928. * The repository may have data corruption.
  929. * @throws CorruptObjectException
  930. * the contents of a tree did not appear to be a tree. The
  931. * repository may have data corruption.
  932. * @throws IOException
  933. * a loose object or pack file could not be read.
  934. */
  935. public void enterSubtree() throws MissingObjectException,
  936. IncorrectObjectTypeException, CorruptObjectException, IOException {
  937. attrs = null;
  938. final AbstractTreeIterator ch = currentHead;
  939. final AbstractTreeIterator[] tmp = new AbstractTreeIterator[trees.length];
  940. for (int i = 0; i < trees.length; i++) {
  941. final AbstractTreeIterator t = trees[i];
  942. final AbstractTreeIterator n;
  943. if (t.matches == ch && !t.eof() && FileMode.TREE.equals(t.mode))
  944. n = t.createSubtreeIterator(reader, idBuffer);
  945. else
  946. n = t.createEmptyTreeIterator();
  947. tmp[i] = n;
  948. }
  949. depth++;
  950. advance = false;
  951. System.arraycopy(tmp, 0, trees, 0, trees.length);
  952. }
  953. @SuppressWarnings("unused")
  954. AbstractTreeIterator min() throws CorruptObjectException {
  955. int i = 0;
  956. AbstractTreeIterator minRef = trees[i];
  957. while (minRef.eof() && ++i < trees.length)
  958. minRef = trees[i];
  959. if (minRef.eof())
  960. return minRef;
  961. minRef.matches = minRef;
  962. while (++i < trees.length) {
  963. final AbstractTreeIterator t = trees[i];
  964. if (t.eof())
  965. continue;
  966. final int cmp = t.pathCompare(minRef);
  967. if (cmp < 0) {
  968. t.matches = t;
  969. minRef = t;
  970. } else if (cmp == 0) {
  971. t.matches = minRef;
  972. }
  973. }
  974. return minRef;
  975. }
  976. void popEntriesEqual() throws CorruptObjectException {
  977. final AbstractTreeIterator ch = currentHead;
  978. for (int i = 0; i < trees.length; i++) {
  979. final AbstractTreeIterator t = trees[i];
  980. if (t.matches == ch) {
  981. t.next(1);
  982. t.matches = null;
  983. }
  984. }
  985. }
  986. void skipEntriesEqual() throws CorruptObjectException {
  987. final AbstractTreeIterator ch = currentHead;
  988. for (int i = 0; i < trees.length; i++) {
  989. final AbstractTreeIterator t = trees[i];
  990. if (t.matches == ch) {
  991. t.skip();
  992. t.matches = null;
  993. }
  994. }
  995. }
  996. void exitSubtree() {
  997. depth--;
  998. for (int i = 0; i < trees.length; i++)
  999. trees[i] = trees[i].parent;
  1000. AbstractTreeIterator minRef = null;
  1001. for (final AbstractTreeIterator t : trees) {
  1002. if (t.matches != t)
  1003. continue;
  1004. if (minRef == null || t.pathCompare(minRef) < 0)
  1005. minRef = t;
  1006. }
  1007. currentHead = minRef;
  1008. }
  1009. private CanonicalTreeParser parserFor(final AnyObjectId id)
  1010. throws IncorrectObjectTypeException, IOException {
  1011. final CanonicalTreeParser p = new CanonicalTreeParser();
  1012. p.reset(reader, id);
  1013. return p;
  1014. }
  1015. static String pathOf(final AbstractTreeIterator t) {
  1016. return RawParseUtils.decode(Constants.CHARSET, t.path, 0, t.pathLen);
  1017. }
  1018. static String pathOf(final byte[] buf, int pos, int end) {
  1019. return RawParseUtils.decode(Constants.CHARSET, buf, pos, end);
  1020. }
  1021. /**
  1022. * Retrieve the git attributes for the current entry.
  1023. *
  1024. * <h4>Git attribute computation</h4>
  1025. *
  1026. * <ul>
  1027. * <li>Get the attributes matching the current path entry from the info file
  1028. * (see {@link AttributesNodeProvider#getInfoAttributesNode()}).</li>
  1029. * <li>Completes the list of attributes using the .gitattributes files
  1030. * located on the current path (the further the directory that contains
  1031. * .gitattributes is from the path in question, the lower its precedence).
  1032. * For a checkin operation, it will look first on the working tree (if any).
  1033. * If there is no attributes file, it will fallback on the index. For a
  1034. * checkout operation, it will first use the index entry and then fallback
  1035. * on the working tree if none.</li>
  1036. * <li>In the end, completes the list of matching attributes using the
  1037. * global attribute file define in the configuration (see
  1038. * {@link AttributesNodeProvider#getGlobalAttributesNode()})</li>
  1039. *
  1040. * </ul>
  1041. *
  1042. *
  1043. * <h4>Iterator constraints</h4>
  1044. *
  1045. * <p>
  1046. * In order to have a correct list of attributes for the current entry, this
  1047. * {@link TreeWalk} requires to have at least one
  1048. * {@link AttributesNodeProvider} and a {@link DirCacheIterator} set up. An
  1049. * {@link AttributesNodeProvider} is used to retrieve the attributes from
  1050. * the info attributes file and the global attributes file. The
  1051. * {@link DirCacheIterator} is used to retrieve the .gitattributes files
  1052. * stored in the index. A {@link WorkingTreeIterator} can also be provided
  1053. * to access the local version of the .gitattributes files. If none is
  1054. * provided it will fallback on the {@link DirCacheIterator}.
  1055. * </p>
  1056. *
  1057. * @return a {@link Set} of {@link Attribute}s that match the current entry.
  1058. * @since 4.2
  1059. */
  1060. public Attributes getAttributes() {
  1061. if (attrs != null)
  1062. return attrs;
  1063. if (attributesNodeProvider == null) {
  1064. // The work tree should have a AttributesNodeProvider to be able to
  1065. // retrieve the info and global attributes node
  1066. throw new IllegalStateException(
  1067. "The tree walk should have one AttributesNodeProvider set in order to compute the git attributes."); //$NON-NLS-1$
  1068. }
  1069. WorkingTreeIterator workingTreeIterator = getTree(WorkingTreeIterator.class);
  1070. DirCacheIterator dirCacheIterator = getTree(DirCacheIterator.class);
  1071. CanonicalTreeParser other = getTree(CanonicalTreeParser.class);
  1072. if (workingTreeIterator == null && dirCacheIterator == null
  1073. && other == null) {
  1074. // Can not retrieve the attributes without at least one of the above
  1075. // iterators.
  1076. return new Attributes();
  1077. }
  1078. String path = currentHead.getEntryPathString();
  1079. final boolean isDir = FileMode.TREE.equals(currentHead.mode);
  1080. Attributes attributes = new Attributes();
  1081. try {
  1082. // Gets the global attributes node
  1083. AttributesNode globalNodeAttr = attributesNodeProvider
  1084. .getGlobalAttributesNode();
  1085. // Gets the info attributes node
  1086. AttributesNode infoNodeAttr = attributesNodeProvider
  1087. .getInfoAttributesNode();
  1088. // Gets the info attributes
  1089. if (infoNodeAttr != null) {
  1090. infoNodeAttr.getAttributes(path, isDir, attributes);
  1091. }
  1092. // Gets the attributes located on the current entry path
  1093. getPerDirectoryEntryAttributes(path, isDir, operationType,
  1094. workingTreeIterator, dirCacheIterator, other, attributes);
  1095. // Gets the attributes located in the global attribute file
  1096. if (globalNodeAttr != null) {
  1097. globalNodeAttr.getAttributes(path, isDir, attributes);
  1098. }
  1099. } catch (IOException e) {
  1100. throw new JGitInternalException("Error while parsing attributes", e); //$NON-NLS-1$
  1101. }
  1102. // now after all attributes are collected - in the correct hierarchy
  1103. // order - remove all unspecified entries (the ! marker)
  1104. for (Attribute a : attributes.getAll()) {
  1105. if (a.getState() == State.UNSPECIFIED)
  1106. attributes.remove(a.getKey());
  1107. }
  1108. return attributes;
  1109. }
  1110. /**
  1111. * Get the attributes located on the current entry path.
  1112. *
  1113. * @param path
  1114. * current entry path
  1115. * @param isDir
  1116. * holds true if the current entry is a directory
  1117. * @param opType
  1118. * type of operation
  1119. * @param workingTreeIterator
  1120. * a {@link WorkingTreeIterator} matching the current entry
  1121. * @param dirCacheIterator
  1122. * a {@link DirCacheIterator} matching the current entry
  1123. * @param other
  1124. * a {@link CanonicalTreeParser} matching the current entry
  1125. * @param attributes
  1126. * Non null map holding the existing attributes. This map will be
  1127. * augmented with new entry. None entry will be overrided.
  1128. * @throws IOException
  1129. * It raises an {@link IOException} if a problem appears while
  1130. * parsing one on the attributes file.
  1131. */
  1132. private void getPerDirectoryEntryAttributes(String path, boolean isDir,
  1133. OperationType opType, WorkingTreeIterator workingTreeIterator,
  1134. DirCacheIterator dirCacheIterator, CanonicalTreeParser other,
  1135. Attributes attributes)
  1136. throws IOException {
  1137. // Prevents infinite recurrence
  1138. if (workingTreeIterator != null || dirCacheIterator != null
  1139. || other != null) {
  1140. AttributesNode currentAttributesNode = getCurrentAttributesNode(
  1141. opType, workingTreeIterator, dirCacheIterator, other);
  1142. if (currentAttributesNode != null) {
  1143. currentAttributesNode.getAttributes(path, isDir, attributes);
  1144. }
  1145. getPerDirectoryEntryAttributes(path, isDir, opType,
  1146. getParent(workingTreeIterator, WorkingTreeIterator.class),
  1147. getParent(dirCacheIterator, DirCacheIterator.class),
  1148. getParent(other, CanonicalTreeParser.class), attributes);
  1149. }
  1150. }
  1151. private static <T extends AbstractTreeIterator> T getParent(T current,
  1152. Class<T> type) {
  1153. if (current != null) {
  1154. AbstractTreeIterator parent = current.parent;
  1155. if (type.isInstance(parent)) {
  1156. return type.cast(parent);
  1157. }
  1158. }
  1159. return null;
  1160. }
  1161. private <T extends AbstractTreeIterator> T getTree(Class<T> type) {
  1162. for (int i = 0; i < trees.length; i++) {
  1163. AbstractTreeIterator tree = trees[i];
  1164. if (type.isInstance(tree)) {
  1165. return type.cast(tree);
  1166. }
  1167. }
  1168. return null;
  1169. }
  1170. /**
  1171. * Get the {@link AttributesNode} for the current entry.
  1172. * <p>
  1173. * This method implements the fallback mechanism between the index and the
  1174. * working tree depending on the operation type
  1175. * </p>
  1176. *
  1177. * @param opType
  1178. * @param workingTreeIterator
  1179. * @param dirCacheIterator
  1180. * @param other
  1181. * @return a {@link AttributesNode} of the current entry,
  1182. * {@link NullPointerException} otherwise.
  1183. * @throws IOException
  1184. * It raises an {@link IOException} if a problem appears while
  1185. * parsing one on the attributes file.
  1186. */
  1187. private AttributesNode getCurrentAttributesNode(OperationType opType,
  1188. @Nullable WorkingTreeIterator workingTreeIterator,
  1189. @Nullable DirCacheIterator dirCacheIterator,
  1190. @Nullable CanonicalTreeParser other)
  1191. throws IOException {
  1192. AttributesNode attributesNode = null;
  1193. switch (opType) {
  1194. case CHECKIN_OP:
  1195. if (workingTreeIterator != null) {
  1196. attributesNode = workingTreeIterator.getEntryAttributesNode();
  1197. }
  1198. if (attributesNode == null && dirCacheIterator != null) {
  1199. attributesNode = getAttributesNode(dirCacheIterator
  1200. .getEntryAttributesNode(getObjectReader()),
  1201. attributesNode);
  1202. }
  1203. if (attributesNode == null && other != null) {
  1204. attributesNode = getAttributesNode(
  1205. other.getEntryAttributesNode(getObjectReader()),
  1206. attributesNode);
  1207. }
  1208. break;
  1209. case CHECKOUT_OP:
  1210. if (other != null) {
  1211. attributesNode = other
  1212. .getEntryAttributesNode(getObjectReader());
  1213. }
  1214. if (dirCacheIterator != null) {
  1215. attributesNode = getAttributesNode(dirCacheIterator
  1216. .getEntryAttributesNode(getObjectReader()),
  1217. attributesNode);
  1218. }
  1219. if (attributesNode == null && workingTreeIterator != null) {
  1220. attributesNode = getAttributesNode(
  1221. workingTreeIterator.getEntryAttributesNode(),
  1222. attributesNode);
  1223. }
  1224. break;
  1225. default:
  1226. throw new IllegalStateException(
  1227. "The only supported operation types are:" //$NON-NLS-1$
  1228. + OperationType.CHECKIN_OP + "," //$NON-NLS-1$
  1229. + OperationType.CHECKOUT_OP);
  1230. }
  1231. return attributesNode;
  1232. }
  1233. private static AttributesNode getAttributesNode(AttributesNode value,
  1234. AttributesNode defaultValue) {
  1235. return (value == null) ? defaultValue : value;
  1236. }
  1237. /**
  1238. * Inspect config and attributes to return a filtercommand applicable for
  1239. * the current path
  1240. *
  1241. * @param filterCommandType
  1242. * which type of filterCommand should be executed. E.g. "clean",
  1243. * "smudge"
  1244. * @return a filter command
  1245. * @throws IOException
  1246. * @since 4.2
  1247. */
  1248. public String getFilterCommand(String filterCommandType)
  1249. throws IOException {
  1250. Attributes attributes = getAttributes();
  1251. Attribute f = attributes.get(Constants.ATTR_FILTER);
  1252. if (f == null) {
  1253. return null;
  1254. }
  1255. String filterValue = f.getValue();
  1256. if (filterValue == null) {
  1257. return null;
  1258. }
  1259. String filterCommand = getFilterCommandDefinition(filterValue,
  1260. filterCommandType);
  1261. if (filterCommand == null) {
  1262. return null;
  1263. }
  1264. return filterCommand.replaceAll("%f", //$NON-NLS-1$
  1265. QuotedString.BOURNE.quote((getPathString())));
  1266. }
  1267. /**
  1268. * Get the filter command how it is defined in gitconfig. The returned
  1269. * string may contain "%f" which needs to be replaced by the current path
  1270. * before executing the filter command. These filter definitions are cached
  1271. * for better performance.
  1272. *
  1273. * @param filterDriverName
  1274. * The name of the filter driver as it is referenced in the
  1275. * gitattributes file. E.g. "lfs". For each filter driver there
  1276. * may be many commands defined in the .gitconfig
  1277. * @param filterCommandType
  1278. * The type of the filter command for a specific filter driver.
  1279. * May be "clean" or "smudge".
  1280. * @return the definition of the command to be executed for this filter
  1281. * driver and filter command
  1282. */
  1283. private String getFilterCommandDefinition(String filterDriverName,
  1284. String filterCommandType) {
  1285. String key = filterDriverName + "." + filterCommandType; //$NON-NLS-1$
  1286. String filterCommand = filterCommandsByNameDotType.get(key);
  1287. if (filterCommand != null)
  1288. return filterCommand;
  1289. filterCommand = config.getString(Constants.ATTR_FILTER,
  1290. filterDriverName, filterCommandType);
  1291. if (filterCommand != null)
  1292. filterCommandsByNameDotType.put(key, filterCommand);
  1293. return filterCommand;
  1294. }
  1295. }