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.

TreeWalk.java 46KB

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