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.

WorkingTreeIterator.java 40KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  3. * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
  4. * Copyright (C) 2010, Matthias Sohn <matthias.sohn@sap.com>
  5. * Copyright (C) 2012-2013, Robin Rosenberg
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.treewalk;
  47. import java.io.ByteArrayInputStream;
  48. import java.io.File;
  49. import java.io.FileInputStream;
  50. import java.io.FileNotFoundException;
  51. import java.io.IOException;
  52. import java.io.InputStream;
  53. import java.nio.ByteBuffer;
  54. import java.nio.CharBuffer;
  55. import java.nio.charset.CharacterCodingException;
  56. import java.nio.charset.CharsetEncoder;
  57. import java.security.MessageDigest;
  58. import java.text.MessageFormat;
  59. import java.util.Arrays;
  60. import java.util.Collections;
  61. import java.util.Comparator;
  62. import org.eclipse.jgit.attributes.AttributesNode;
  63. import org.eclipse.jgit.attributes.AttributesRule;
  64. import org.eclipse.jgit.diff.RawText;
  65. import org.eclipse.jgit.dircache.DirCache;
  66. import org.eclipse.jgit.dircache.DirCacheEntry;
  67. import org.eclipse.jgit.dircache.DirCacheIterator;
  68. import org.eclipse.jgit.errors.CorruptObjectException;
  69. import org.eclipse.jgit.errors.MissingObjectException;
  70. import org.eclipse.jgit.errors.NoWorkTreeException;
  71. import org.eclipse.jgit.ignore.FastIgnoreRule;
  72. import org.eclipse.jgit.ignore.IgnoreNode;
  73. import org.eclipse.jgit.internal.JGitText;
  74. import org.eclipse.jgit.lib.Constants;
  75. import org.eclipse.jgit.lib.CoreConfig;
  76. import org.eclipse.jgit.lib.CoreConfig.CheckStat;
  77. import org.eclipse.jgit.lib.CoreConfig.SymLinks;
  78. import org.eclipse.jgit.lib.FileMode;
  79. import org.eclipse.jgit.lib.ObjectId;
  80. import org.eclipse.jgit.lib.ObjectLoader;
  81. import org.eclipse.jgit.lib.ObjectReader;
  82. import org.eclipse.jgit.lib.Repository;
  83. import org.eclipse.jgit.submodule.SubmoduleWalk;
  84. import org.eclipse.jgit.util.FS;
  85. import org.eclipse.jgit.util.IO;
  86. import org.eclipse.jgit.util.RawParseUtils;
  87. import org.eclipse.jgit.util.io.EolCanonicalizingInputStream;
  88. /**
  89. * Walks a working directory tree as part of a {@link TreeWalk}.
  90. * <p>
  91. * Most applications will want to use the standard implementation of this
  92. * iterator, {@link FileTreeIterator}, as that does all IO through the standard
  93. * <code>java.io</code> package. Plugins for a Java based IDE may however wish
  94. * to create their own implementations of this class to allow traversal of the
  95. * IDE's project space, as well as benefit from any caching the IDE may have.
  96. *
  97. * @see FileTreeIterator
  98. */
  99. public abstract class WorkingTreeIterator extends AbstractTreeIterator {
  100. /** An empty entry array, suitable for {@link #init(Entry[])}. */
  101. protected static final Entry[] EOF = {};
  102. /** Size we perform file IO in if we have to read and hash a file. */
  103. static final int BUFFER_SIZE = 2048;
  104. /**
  105. * Maximum size of files which may be read fully into memory for performance
  106. * reasons.
  107. */
  108. private static final long MAXIMUM_FILE_SIZE_TO_READ_FULLY = 65536;
  109. /** Inherited state of this iterator, describing working tree, etc. */
  110. private final IteratorState state;
  111. /** The {@link #idBuffer()} for the current entry. */
  112. private byte[] contentId;
  113. /** Index within {@link #entries} that {@link #contentId} came from. */
  114. private int contentIdFromPtr;
  115. /** List of entries obtained from the subclass. */
  116. private Entry[] entries;
  117. /** Total number of entries in {@link #entries} that are valid. */
  118. private int entryCnt;
  119. /** Current position within {@link #entries}. */
  120. private int ptr;
  121. /** If there is a .gitignore file present, the parsed rules from it. */
  122. private IgnoreNode ignoreNode;
  123. /** If there is a .gitattributes file present, the parsed rules from it. */
  124. private AttributesNode attributesNode;
  125. /** Repository that is the root level being iterated over */
  126. protected Repository repository;
  127. /** Cached canonical length, initialized from {@link #idBuffer()} */
  128. private long canonLen = -1;
  129. /** The offset of the content id in {@link #idBuffer()} */
  130. private int contentIdOffset;
  131. /**
  132. * Holds the {@link AttributesNode} that is stored in
  133. * $GIT_DIR/info/attributes file.
  134. */
  135. private AttributesNode infoAttributeNode;
  136. /**
  137. * Holds the {@link AttributesNode} that is stored in global attribute file.
  138. *
  139. * @see CoreConfig#getAttributesFile()
  140. */
  141. private AttributesNode globalAttributeNode;
  142. /**
  143. * Create a new iterator with no parent.
  144. *
  145. * @param options
  146. * working tree options to be used
  147. */
  148. protected WorkingTreeIterator(WorkingTreeOptions options) {
  149. super();
  150. state = new IteratorState(options);
  151. }
  152. /**
  153. * Create a new iterator with no parent and a prefix.
  154. * <p>
  155. * The prefix path supplied is inserted in front of all paths generated by
  156. * this iterator. It is intended to be used when an iterator is being
  157. * created for a subsection of an overall repository and needs to be
  158. * combined with other iterators that are created to run over the entire
  159. * repository namespace.
  160. *
  161. * @param prefix
  162. * position of this iterator in the repository tree. The value
  163. * may be null or the empty string to indicate the prefix is the
  164. * root of the repository. A trailing slash ('/') is
  165. * automatically appended if the prefix does not end in '/'.
  166. * @param options
  167. * working tree options to be used
  168. */
  169. protected WorkingTreeIterator(final String prefix,
  170. WorkingTreeOptions options) {
  171. super(prefix);
  172. state = new IteratorState(options);
  173. }
  174. /**
  175. * Create an iterator for a subtree of an existing iterator.
  176. *
  177. * @param p
  178. * parent tree iterator.
  179. */
  180. protected WorkingTreeIterator(final WorkingTreeIterator p) {
  181. super(p);
  182. state = p.state;
  183. infoAttributeNode = p.infoAttributeNode;
  184. globalAttributeNode = p.globalAttributeNode;
  185. }
  186. /**
  187. * Initialize this iterator for the root level of a repository.
  188. * <p>
  189. * This method should only be invoked after calling {@link #init(Entry[])},
  190. * and only for the root iterator.
  191. *
  192. * @param repo
  193. * the repository.
  194. */
  195. protected void initRootIterator(Repository repo) {
  196. repository = repo;
  197. Entry entry;
  198. if (ignoreNode instanceof PerDirectoryIgnoreNode)
  199. entry = ((PerDirectoryIgnoreNode) ignoreNode).entry;
  200. else
  201. entry = null;
  202. ignoreNode = new RootIgnoreNode(entry, repo);
  203. infoAttributeNode = new InfoAttributesNode(repo);
  204. globalAttributeNode = new GlobalAttributesNode(repo);
  205. }
  206. /**
  207. * Define the matching {@link DirCacheIterator}, to optimize ObjectIds.
  208. *
  209. * Once the DirCacheIterator has been set this iterator must only be
  210. * advanced by the TreeWalk that is supplied, as it assumes that itself and
  211. * the corresponding DirCacheIterator are positioned on the same file path
  212. * whenever {@link #idBuffer()} is invoked.
  213. *
  214. * @param walk
  215. * the walk that will be advancing this iterator.
  216. * @param treeId
  217. * index of the matching {@link DirCacheIterator}.
  218. */
  219. public void setDirCacheIterator(TreeWalk walk, int treeId) {
  220. state.walk = walk;
  221. state.dirCacheTree = treeId;
  222. }
  223. @Override
  224. public boolean hasId() {
  225. if (contentIdFromPtr == ptr)
  226. return true;
  227. return (mode & FileMode.TYPE_MASK) == FileMode.TYPE_FILE;
  228. }
  229. @Override
  230. public byte[] idBuffer() {
  231. if (contentIdFromPtr == ptr)
  232. return contentId;
  233. if (state.walk != null) {
  234. // If there is a matching DirCacheIterator, we can reuse
  235. // its idBuffer, but only if we appear to be clean against
  236. // the cached index information for the path.
  237. //
  238. DirCacheIterator i = state.walk.getTree(state.dirCacheTree,
  239. DirCacheIterator.class);
  240. if (i != null) {
  241. DirCacheEntry ent = i.getDirCacheEntry();
  242. if (ent != null && compareMetadata(ent) == MetadataDiff.EQUAL) {
  243. contentIdOffset = i.idOffset();
  244. contentIdFromPtr = ptr;
  245. return contentId = i.idBuffer();
  246. }
  247. contentIdOffset = 0;
  248. } else {
  249. contentIdOffset = 0;
  250. }
  251. }
  252. switch (mode & FileMode.TYPE_MASK) {
  253. case FileMode.TYPE_SYMLINK:
  254. case FileMode.TYPE_FILE:
  255. contentIdFromPtr = ptr;
  256. return contentId = idBufferBlob(entries[ptr]);
  257. case FileMode.TYPE_GITLINK:
  258. contentIdFromPtr = ptr;
  259. return contentId = idSubmodule(entries[ptr]);
  260. }
  261. return zeroid;
  262. }
  263. /**
  264. * Get submodule id for given entry.
  265. *
  266. * @param e
  267. * @return non-null submodule id
  268. */
  269. protected byte[] idSubmodule(Entry e) {
  270. if (repository == null)
  271. return zeroid;
  272. File directory;
  273. try {
  274. directory = repository.getWorkTree();
  275. } catch (NoWorkTreeException nwte) {
  276. return zeroid;
  277. }
  278. return idSubmodule(directory, e);
  279. }
  280. /**
  281. * Get submodule id using the repository at the location of the entry
  282. * relative to the directory.
  283. *
  284. * @param directory
  285. * @param e
  286. * @return non-null submodule id
  287. */
  288. protected byte[] idSubmodule(File directory, Entry e) {
  289. final Repository submoduleRepo;
  290. try {
  291. submoduleRepo = SubmoduleWalk.getSubmoduleRepository(directory,
  292. e.getName());
  293. } catch (IOException exception) {
  294. return zeroid;
  295. }
  296. if (submoduleRepo == null)
  297. return zeroid;
  298. final ObjectId head;
  299. try {
  300. head = submoduleRepo.resolve(Constants.HEAD);
  301. } catch (IOException exception) {
  302. return zeroid;
  303. } finally {
  304. submoduleRepo.close();
  305. }
  306. if (head == null)
  307. return zeroid;
  308. final byte[] id = new byte[Constants.OBJECT_ID_LENGTH];
  309. head.copyRawTo(id, 0);
  310. return id;
  311. }
  312. private static final byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
  313. '7', '8', '9' };
  314. private static final byte[] hblob = Constants
  315. .encodedTypeString(Constants.OBJ_BLOB);
  316. private byte[] idBufferBlob(final Entry e) {
  317. try {
  318. final InputStream is = e.openInputStream();
  319. if (is == null)
  320. return zeroid;
  321. try {
  322. state.initializeDigestAndReadBuffer();
  323. final long len = e.getLength();
  324. InputStream filteredIs = possiblyFilteredInputStream(e, is, len);
  325. return computeHash(filteredIs, canonLen);
  326. } finally {
  327. safeClose(is);
  328. }
  329. } catch (IOException err) {
  330. // Can't read the file? Don't report the failure either.
  331. return zeroid;
  332. }
  333. }
  334. private InputStream possiblyFilteredInputStream(final Entry e,
  335. final InputStream is, final long len) throws IOException {
  336. if (!mightNeedCleaning()) {
  337. canonLen = len;
  338. return is;
  339. }
  340. if (len <= MAXIMUM_FILE_SIZE_TO_READ_FULLY) {
  341. ByteBuffer rawbuf = IO.readWholeStream(is, (int) len);
  342. byte[] raw = rawbuf.array();
  343. int n = rawbuf.limit();
  344. if (!isBinary(raw, n)) {
  345. rawbuf = filterClean(raw, n);
  346. raw = rawbuf.array();
  347. n = rawbuf.limit();
  348. }
  349. canonLen = n;
  350. return new ByteArrayInputStream(raw, 0, n);
  351. }
  352. if (isBinary(e)) {
  353. canonLen = len;
  354. return is;
  355. }
  356. final InputStream lenIs = filterClean(e.openInputStream());
  357. try {
  358. canonLen = computeLength(lenIs);
  359. } finally {
  360. safeClose(lenIs);
  361. }
  362. return filterClean(is);
  363. }
  364. private static void safeClose(final InputStream in) {
  365. try {
  366. in.close();
  367. } catch (IOException err2) {
  368. // Suppress any error related to closing an input
  369. // stream. We don't care, we should not have any
  370. // outstanding data to flush or anything like that.
  371. }
  372. }
  373. private boolean mightNeedCleaning() {
  374. switch (getOptions().getAutoCRLF()) {
  375. case FALSE:
  376. default:
  377. return false;
  378. case TRUE:
  379. case INPUT:
  380. return true;
  381. }
  382. }
  383. private static boolean isBinary(byte[] content, int sz) {
  384. return RawText.isBinary(content, sz);
  385. }
  386. private static boolean isBinary(Entry entry) throws IOException {
  387. InputStream in = entry.openInputStream();
  388. try {
  389. return RawText.isBinary(in);
  390. } finally {
  391. safeClose(in);
  392. }
  393. }
  394. private static ByteBuffer filterClean(byte[] src, int n)
  395. throws IOException {
  396. InputStream in = new ByteArrayInputStream(src);
  397. try {
  398. return IO.readWholeStream(filterClean(in), n);
  399. } finally {
  400. safeClose(in);
  401. }
  402. }
  403. private static InputStream filterClean(InputStream in) {
  404. return new EolCanonicalizingInputStream(in, true);
  405. }
  406. /**
  407. * Returns the working tree options used by this iterator.
  408. *
  409. * @return working tree options
  410. */
  411. public WorkingTreeOptions getOptions() {
  412. return state.options;
  413. }
  414. @Override
  415. public int idOffset() {
  416. return contentIdOffset;
  417. }
  418. @Override
  419. public void reset() {
  420. if (!first()) {
  421. ptr = 0;
  422. if (!eof())
  423. parseEntry();
  424. }
  425. }
  426. @Override
  427. public boolean first() {
  428. return ptr == 0;
  429. }
  430. @Override
  431. public boolean eof() {
  432. return ptr == entryCnt;
  433. }
  434. @Override
  435. public void next(final int delta) throws CorruptObjectException {
  436. ptr += delta;
  437. if (!eof()) {
  438. parseEntry();
  439. }
  440. }
  441. @Override
  442. public void back(final int delta) throws CorruptObjectException {
  443. ptr -= delta;
  444. parseEntry();
  445. }
  446. private void parseEntry() {
  447. final Entry e = entries[ptr];
  448. mode = e.getMode().getBits();
  449. final int nameLen = e.encodedNameLen;
  450. ensurePathCapacity(pathOffset + nameLen, pathOffset);
  451. System.arraycopy(e.encodedName, 0, path, pathOffset, nameLen);
  452. pathLen = pathOffset + nameLen;
  453. canonLen = -1;
  454. }
  455. /**
  456. * Get the raw byte length of this entry.
  457. *
  458. * @return size of this file, in bytes.
  459. */
  460. public long getEntryLength() {
  461. return current().getLength();
  462. }
  463. /**
  464. * Get the filtered input length of this entry
  465. *
  466. * @return size of the content, in bytes
  467. * @throws IOException
  468. */
  469. public long getEntryContentLength() throws IOException {
  470. if (canonLen == -1) {
  471. long rawLen = getEntryLength();
  472. if (rawLen == 0)
  473. canonLen = 0;
  474. InputStream is = current().openInputStream();
  475. try {
  476. // canonLen gets updated here
  477. possiblyFilteredInputStream(current(), is, current()
  478. .getLength());
  479. } finally {
  480. safeClose(is);
  481. }
  482. }
  483. return canonLen;
  484. }
  485. /**
  486. * Get the last modified time of this entry.
  487. *
  488. * @return last modified time of this file, in milliseconds since the epoch
  489. * (Jan 1, 1970 UTC).
  490. */
  491. public long getEntryLastModified() {
  492. return current().getLastModified();
  493. }
  494. /**
  495. * Obtain an input stream to read the file content.
  496. * <p>
  497. * Efficient implementations are not required. The caller will usually
  498. * obtain the stream only once per entry, if at all.
  499. * <p>
  500. * The input stream should not use buffering if the implementation can avoid
  501. * it. The caller will buffer as necessary to perform efficient block IO
  502. * operations.
  503. * <p>
  504. * The caller will close the stream once complete.
  505. *
  506. * @return a stream to read from the file.
  507. * @throws IOException
  508. * the file could not be opened for reading.
  509. */
  510. public InputStream openEntryStream() throws IOException {
  511. InputStream rawis = current().openInputStream();
  512. if (mightNeedCleaning())
  513. return filterClean(rawis);
  514. else
  515. return rawis;
  516. }
  517. /**
  518. * Determine if the current entry path is ignored by an ignore rule.
  519. *
  520. * @return true if the entry was ignored by an ignore rule file.
  521. * @throws IOException
  522. * a relevant ignore rule file exists but cannot be read.
  523. */
  524. public boolean isEntryIgnored() throws IOException {
  525. return isEntryIgnored(pathLen);
  526. }
  527. /**
  528. * Determine if the entry path is ignored by an ignore rule.
  529. *
  530. * @param pLen
  531. * the length of the path in the path buffer.
  532. * @return true if the entry is ignored by an ignore rule.
  533. * @throws IOException
  534. * a relevant ignore rule file exists but cannot be read.
  535. */
  536. protected boolean isEntryIgnored(final int pLen) throws IOException {
  537. return isEntryIgnored(pLen, false);
  538. }
  539. /**
  540. * Determine if the entry path is ignored by an ignore rule. Consider
  541. * possible rule negation from child iterator.
  542. *
  543. * @param pLen
  544. * the length of the path in the path buffer.
  545. * @param negatePrevious
  546. * true if the previous matching iterator rule was negation
  547. * @return true if the entry is ignored by an ignore rule.
  548. * @throws IOException
  549. * a relevant ignore rule file exists but cannot be read.
  550. */
  551. private boolean isEntryIgnored(final int pLen, boolean negatePrevious)
  552. throws IOException {
  553. IgnoreNode rules = getIgnoreNode();
  554. if (rules != null) {
  555. // The ignore code wants path to start with a '/' if possible.
  556. // If we have the '/' in our path buffer because we are inside
  557. // a subdirectory include it in the range we convert to string.
  558. //
  559. int pOff = pathOffset;
  560. if (0 < pOff)
  561. pOff--;
  562. String p = TreeWalk.pathOf(path, pOff, pLen);
  563. switch (rules.isIgnored(p, FileMode.TREE.equals(mode),
  564. negatePrevious)) {
  565. case IGNORED:
  566. return true;
  567. case NOT_IGNORED:
  568. return false;
  569. case CHECK_PARENT:
  570. negatePrevious = false;
  571. break;
  572. case CHECK_PARENT_NEGATE_FIRST_MATCH:
  573. negatePrevious = true;
  574. break;
  575. }
  576. }
  577. if (parent instanceof WorkingTreeIterator)
  578. return ((WorkingTreeIterator) parent).isEntryIgnored(pLen,
  579. negatePrevious);
  580. return false;
  581. }
  582. private IgnoreNode getIgnoreNode() throws IOException {
  583. if (ignoreNode instanceof PerDirectoryIgnoreNode)
  584. ignoreNode = ((PerDirectoryIgnoreNode) ignoreNode).load();
  585. return ignoreNode;
  586. }
  587. /**
  588. * Retrieves the {@link AttributesNode} for the current entry.
  589. *
  590. * @return {@link AttributesNode} for the current entry.
  591. * @throws IOException
  592. * if an error is raised while parsing the .gitattributes file
  593. * @since 3.7
  594. */
  595. public AttributesNode getEntryAttributesNode() throws IOException {
  596. if (attributesNode instanceof PerDirectoryAttributesNode)
  597. attributesNode = ((PerDirectoryAttributesNode) attributesNode)
  598. .load();
  599. return attributesNode;
  600. }
  601. /**
  602. * Retrieves the {@link AttributesNode} that holds the information located
  603. * in $GIT_DIR/info/attributes file.
  604. *
  605. * @return the {@link AttributesNode} that holds the information located in
  606. * $GIT_DIR/info/attributes file.
  607. * @throws IOException
  608. * if an error is raised while parsing the attributes file
  609. * @since 3.7
  610. */
  611. public AttributesNode getInfoAttributesNode() throws IOException {
  612. if (infoAttributeNode instanceof InfoAttributesNode)
  613. infoAttributeNode = ((InfoAttributesNode) infoAttributeNode).load();
  614. return infoAttributeNode;
  615. }
  616. /**
  617. * Retrieves the {@link AttributesNode} that holds the information located
  618. * in system-wide file.
  619. *
  620. * @return the {@link AttributesNode} that holds the information located in
  621. * system-wide file.
  622. * @throws IOException
  623. * IOException if an error is raised while parsing the
  624. * attributes file
  625. * @see CoreConfig#getAttributesFile()
  626. * @since 3.7
  627. */
  628. public AttributesNode getGlobalAttributesNode() throws IOException {
  629. if (globalAttributeNode instanceof GlobalAttributesNode)
  630. globalAttributeNode = ((GlobalAttributesNode) globalAttributeNode)
  631. .load();
  632. return globalAttributeNode;
  633. }
  634. private static final Comparator<Entry> ENTRY_CMP = new Comparator<Entry>() {
  635. public int compare(final Entry o1, final Entry o2) {
  636. final byte[] a = o1.encodedName;
  637. final byte[] b = o2.encodedName;
  638. final int aLen = o1.encodedNameLen;
  639. final int bLen = o2.encodedNameLen;
  640. int cPos;
  641. for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
  642. final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
  643. if (cmp != 0)
  644. return cmp;
  645. }
  646. if (cPos < aLen)
  647. return (a[cPos] & 0xff) - lastPathChar(o2);
  648. if (cPos < bLen)
  649. return lastPathChar(o1) - (b[cPos] & 0xff);
  650. return lastPathChar(o1) - lastPathChar(o2);
  651. }
  652. };
  653. static int lastPathChar(final Entry e) {
  654. return e.getMode() == FileMode.TREE ? '/' : '\0';
  655. }
  656. /**
  657. * Constructor helper.
  658. *
  659. * @param list
  660. * files in the subtree of the work tree this iterator operates
  661. * on
  662. */
  663. protected void init(final Entry[] list) {
  664. // Filter out nulls, . and .. as these are not valid tree entries,
  665. // also cache the encoded forms of the path names for efficient use
  666. // later on during sorting and iteration.
  667. //
  668. entries = list;
  669. int i, o;
  670. final CharsetEncoder nameEncoder = state.nameEncoder;
  671. for (i = 0, o = 0; i < entries.length; i++) {
  672. final Entry e = entries[i];
  673. if (e == null)
  674. continue;
  675. final String name = e.getName();
  676. if (".".equals(name) || "..".equals(name)) //$NON-NLS-1$ //$NON-NLS-2$
  677. continue;
  678. if (Constants.DOT_GIT.equals(name))
  679. continue;
  680. if (Constants.DOT_GIT_IGNORE.equals(name))
  681. ignoreNode = new PerDirectoryIgnoreNode(e);
  682. if (Constants.DOT_GIT_ATTRIBUTES.equals(name))
  683. attributesNode = new PerDirectoryAttributesNode(e);
  684. if (i != o)
  685. entries[o] = e;
  686. e.encodeName(nameEncoder);
  687. o++;
  688. }
  689. entryCnt = o;
  690. Arrays.sort(entries, 0, entryCnt, ENTRY_CMP);
  691. contentIdFromPtr = -1;
  692. ptr = 0;
  693. if (!eof())
  694. parseEntry();
  695. else if (pathLen == 0) // see bug 445363
  696. pathLen = pathOffset;
  697. }
  698. /**
  699. * Obtain the current entry from this iterator.
  700. *
  701. * @return the currently selected entry.
  702. */
  703. protected Entry current() {
  704. return entries[ptr];
  705. }
  706. /**
  707. * The result of a metadata-comparison between the current entry and a
  708. * {@link DirCacheEntry}
  709. */
  710. public enum MetadataDiff {
  711. /**
  712. * The entries are equal by metaData (mode, length,
  713. * modification-timestamp) or the <code>assumeValid</code> attribute of
  714. * the index entry is set
  715. */
  716. EQUAL,
  717. /**
  718. * The entries are not equal by metaData (mode, length) or the
  719. * <code>isUpdateNeeded</code> attribute of the index entry is set
  720. */
  721. DIFFER_BY_METADATA,
  722. /** index entry is smudged - can't use that entry for comparison */
  723. SMUDGED,
  724. /**
  725. * The entries are equal by metaData (mode, length) but differ by
  726. * modification-timestamp.
  727. */
  728. DIFFER_BY_TIMESTAMP
  729. }
  730. /**
  731. * Is the file mode of the current entry different than the given raw mode?
  732. *
  733. * @param rawMode
  734. * @return true if different, false otherwise
  735. */
  736. public boolean isModeDifferent(final int rawMode) {
  737. // Determine difference in mode-bits of file and index-entry. In the
  738. // bitwise presentation of modeDiff we'll have a '1' when the two modes
  739. // differ at this position.
  740. int modeDiff = getEntryRawMode() ^ rawMode;
  741. if (modeDiff == 0)
  742. return false;
  743. // Do not rely on filemode differences in case of symbolic links
  744. if (getOptions().getSymLinks() == SymLinks.FALSE)
  745. if (FileMode.SYMLINK.equals(rawMode))
  746. return false;
  747. // Ignore the executable file bits if WorkingTreeOptions tell me to
  748. // do so. Ignoring is done by setting the bits representing a
  749. // EXECUTABLE_FILE to '0' in modeDiff
  750. if (!state.options.isFileMode())
  751. modeDiff &= ~FileMode.EXECUTABLE_FILE.getBits();
  752. return modeDiff != 0;
  753. }
  754. /**
  755. * Compare the metadata (mode, length, modification-timestamp) of the
  756. * current entry and a {@link DirCacheEntry}
  757. *
  758. * @param entry
  759. * the {@link DirCacheEntry} to compare with
  760. * @return a {@link MetadataDiff} which tells whether and how the entries
  761. * metadata differ
  762. */
  763. public MetadataDiff compareMetadata(DirCacheEntry entry) {
  764. if (entry.isAssumeValid())
  765. return MetadataDiff.EQUAL;
  766. if (entry.isUpdateNeeded())
  767. return MetadataDiff.DIFFER_BY_METADATA;
  768. if (!entry.isSmudged() && entry.getLength() != (int) getEntryLength())
  769. return MetadataDiff.DIFFER_BY_METADATA;
  770. if (isModeDifferent(entry.getRawMode()))
  771. return MetadataDiff.DIFFER_BY_METADATA;
  772. // Git under windows only stores seconds so we round the timestamp
  773. // Java gives us if it looks like the timestamp in index is seconds
  774. // only. Otherwise we compare the timestamp at millisecond precision,
  775. // unless core.checkstat is set to "minimal", in which case we only
  776. // compare the whole second part.
  777. long cacheLastModified = entry.getLastModified();
  778. long fileLastModified = getEntryLastModified();
  779. long lastModifiedMillis = fileLastModified % 1000;
  780. long cacheMillis = cacheLastModified % 1000;
  781. if (getOptions().getCheckStat() == CheckStat.MINIMAL) {
  782. fileLastModified = fileLastModified - lastModifiedMillis;
  783. cacheLastModified = cacheLastModified - cacheMillis;
  784. } else if (cacheMillis == 0)
  785. fileLastModified = fileLastModified - lastModifiedMillis;
  786. // Some Java version on Linux return whole seconds only even when
  787. // the file systems supports more precision.
  788. else if (lastModifiedMillis == 0)
  789. cacheLastModified = cacheLastModified - cacheMillis;
  790. if (fileLastModified != cacheLastModified)
  791. return MetadataDiff.DIFFER_BY_TIMESTAMP;
  792. else if (!entry.isSmudged())
  793. // The file is clean when you look at timestamps.
  794. return MetadataDiff.EQUAL;
  795. else
  796. return MetadataDiff.SMUDGED;
  797. }
  798. /**
  799. * Checks whether this entry differs from a given entry from the
  800. * {@link DirCache}.
  801. *
  802. * File status information is used and if status is same we consider the
  803. * file identical to the state in the working directory. Native git uses
  804. * more stat fields than we have accessible in Java.
  805. *
  806. * @param entry
  807. * the entry from the dircache we want to compare against
  808. * @param forceContentCheck
  809. * True if the actual file content should be checked if
  810. * modification time differs.
  811. * @param reader
  812. * access to repository objects if necessary. Should not be null.
  813. * @return true if content is most likely different.
  814. * @throws IOException
  815. * @since 3.3
  816. */
  817. public boolean isModified(DirCacheEntry entry, boolean forceContentCheck,
  818. ObjectReader reader) throws IOException {
  819. if (entry == null)
  820. return !FileMode.MISSING.equals(getEntryFileMode());
  821. MetadataDiff diff = compareMetadata(entry);
  822. switch (diff) {
  823. case DIFFER_BY_TIMESTAMP:
  824. if (forceContentCheck)
  825. // But we are told to look at content even though timestamps
  826. // tell us about modification
  827. return contentCheck(entry, reader);
  828. else
  829. // We are told to assume a modification if timestamps differs
  830. return true;
  831. case SMUDGED:
  832. // The file is clean by timestamps but the entry was smudged.
  833. // Lets do a content check
  834. return contentCheck(entry, reader);
  835. case EQUAL:
  836. return false;
  837. case DIFFER_BY_METADATA:
  838. if (mode == FileMode.SYMLINK.getBits())
  839. return contentCheck(entry, reader);
  840. return true;
  841. default:
  842. throw new IllegalStateException(MessageFormat.format(
  843. JGitText.get().unexpectedCompareResult, diff.name()));
  844. }
  845. }
  846. /**
  847. * Get the file mode to use for the current entry when it is to be updated
  848. * in the index.
  849. *
  850. * @param indexIter
  851. * {@link DirCacheIterator} positioned at the same entry as this
  852. * iterator or null if no {@link DirCacheIterator} is available
  853. * at this iterator's current entry
  854. * @return index file mode
  855. */
  856. public FileMode getIndexFileMode(final DirCacheIterator indexIter) {
  857. final FileMode wtMode = getEntryFileMode();
  858. if (indexIter == null)
  859. return wtMode;
  860. if (getOptions().isFileMode())
  861. return wtMode;
  862. final FileMode iMode = indexIter.getEntryFileMode();
  863. if (FileMode.REGULAR_FILE == wtMode
  864. && FileMode.EXECUTABLE_FILE == iMode)
  865. return iMode;
  866. if (FileMode.EXECUTABLE_FILE == wtMode
  867. && FileMode.REGULAR_FILE == iMode)
  868. return iMode;
  869. return wtMode;
  870. }
  871. /**
  872. * Compares the entries content with the content in the filesystem.
  873. * Unsmudges the entry when it is detected that it is clean.
  874. *
  875. * @param entry
  876. * the entry to be checked
  877. * @param reader
  878. * acccess to repository data if necessary
  879. * @return <code>true</code> if the content doesn't match,
  880. * <code>false</code> if it matches
  881. * @throws IOException
  882. */
  883. private boolean contentCheck(DirCacheEntry entry, ObjectReader reader)
  884. throws IOException {
  885. if (getEntryObjectId().equals(entry.getObjectId())) {
  886. // Content has not changed
  887. // We know the entry can't be racily clean because it's still clean.
  888. // Therefore we unsmudge the entry!
  889. // If by any chance we now unsmudge although we are still in the
  890. // same time-slot as the last modification to the index file the
  891. // next index write operation will smudge again.
  892. // Caution: we are unsmudging just by setting the length of the
  893. // in-memory entry object. It's the callers task to detect that we
  894. // have modified the entry and to persist the modified index.
  895. entry.setLength((int) getEntryLength());
  896. return false;
  897. } else {
  898. if (mode == FileMode.SYMLINK.getBits())
  899. return !new File(readContentAsNormalizedString(current()))
  900. .equals(new File((readContentAsNormalizedString(entry,
  901. reader))));
  902. // Content differs: that's a real change, perhaps
  903. if (reader == null) // deprecated use, do no further checks
  904. return true;
  905. switch (getOptions().getAutoCRLF()) {
  906. case INPUT:
  907. case TRUE:
  908. InputStream dcIn = null;
  909. try {
  910. ObjectLoader loader = reader.open(entry.getObjectId());
  911. if (loader == null)
  912. return true;
  913. // We need to compute the length, but only if it is not
  914. // a binary stream.
  915. dcIn = new EolCanonicalizingInputStream(
  916. loader.openStream(), true, true /* abort if binary */);
  917. long dcInLen;
  918. try {
  919. dcInLen = computeLength(dcIn);
  920. } catch (EolCanonicalizingInputStream.IsBinaryException e) {
  921. return true;
  922. } finally {
  923. dcIn.close();
  924. }
  925. dcIn = new EolCanonicalizingInputStream(
  926. loader.openStream(), true);
  927. byte[] autoCrLfHash = computeHash(dcIn, dcInLen);
  928. boolean changed = getEntryObjectId().compareTo(
  929. autoCrLfHash, 0) != 0;
  930. return changed;
  931. } catch (IOException e) {
  932. return true;
  933. } finally {
  934. if (dcIn != null)
  935. try {
  936. dcIn.close();
  937. } catch (IOException e) {
  938. // empty
  939. }
  940. }
  941. case FALSE:
  942. break;
  943. }
  944. return true;
  945. }
  946. }
  947. private static String readContentAsNormalizedString(DirCacheEntry entry,
  948. ObjectReader reader) throws MissingObjectException, IOException {
  949. ObjectLoader open = reader.open(entry.getObjectId());
  950. byte[] cachedBytes = open.getCachedBytes();
  951. return FS.detect().normalize(RawParseUtils.decode(cachedBytes));
  952. }
  953. private static String readContentAsNormalizedString(Entry entry) throws IOException {
  954. long length = entry.getLength();
  955. byte[] content = new byte[(int) length];
  956. InputStream is = entry.openInputStream();
  957. IO.readFully(is, content, 0, (int) length);
  958. return FS.detect().normalize(RawParseUtils.decode(content));
  959. }
  960. private static long computeLength(InputStream in) throws IOException {
  961. // Since we only care about the length, use skip. The stream
  962. // may be able to more efficiently wade through its data.
  963. //
  964. long length = 0;
  965. for (;;) {
  966. long n = in.skip(1 << 20);
  967. if (n <= 0)
  968. break;
  969. length += n;
  970. }
  971. return length;
  972. }
  973. private byte[] computeHash(InputStream in, long length) throws IOException {
  974. final MessageDigest contentDigest = state.contentDigest;
  975. final byte[] contentReadBuffer = state.contentReadBuffer;
  976. contentDigest.reset();
  977. contentDigest.update(hblob);
  978. contentDigest.update((byte) ' ');
  979. long sz = length;
  980. if (sz == 0) {
  981. contentDigest.update((byte) '0');
  982. } else {
  983. final int bufn = contentReadBuffer.length;
  984. int p = bufn;
  985. do {
  986. contentReadBuffer[--p] = digits[(int) (sz % 10)];
  987. sz /= 10;
  988. } while (sz > 0);
  989. contentDigest.update(contentReadBuffer, p, bufn - p);
  990. }
  991. contentDigest.update((byte) 0);
  992. for (;;) {
  993. final int r = in.read(contentReadBuffer);
  994. if (r <= 0)
  995. break;
  996. contentDigest.update(contentReadBuffer, 0, r);
  997. sz += r;
  998. }
  999. if (sz != length)
  1000. return zeroid;
  1001. return contentDigest.digest();
  1002. }
  1003. /** A single entry within a working directory tree. */
  1004. protected static abstract class Entry {
  1005. byte[] encodedName;
  1006. int encodedNameLen;
  1007. void encodeName(final CharsetEncoder enc) {
  1008. final ByteBuffer b;
  1009. try {
  1010. b = enc.encode(CharBuffer.wrap(getName()));
  1011. } catch (CharacterCodingException e) {
  1012. // This should so never happen.
  1013. throw new RuntimeException(MessageFormat.format(
  1014. JGitText.get().unencodeableFile, getName()));
  1015. }
  1016. encodedNameLen = b.limit();
  1017. if (b.hasArray() && b.arrayOffset() == 0)
  1018. encodedName = b.array();
  1019. else
  1020. b.get(encodedName = new byte[encodedNameLen]);
  1021. }
  1022. public String toString() {
  1023. return getMode().toString() + " " + getName(); //$NON-NLS-1$
  1024. }
  1025. /**
  1026. * Get the type of this entry.
  1027. * <p>
  1028. * <b>Note: Efficient implementation required.</b>
  1029. * <p>
  1030. * The implementation of this method must be efficient. If a subclass
  1031. * needs to compute the value they should cache the reference within an
  1032. * instance member instead.
  1033. *
  1034. * @return a file mode constant from {@link FileMode}.
  1035. */
  1036. public abstract FileMode getMode();
  1037. /**
  1038. * Get the byte length of this entry.
  1039. * <p>
  1040. * <b>Note: Efficient implementation required.</b>
  1041. * <p>
  1042. * The implementation of this method must be efficient. If a subclass
  1043. * needs to compute the value they should cache the reference within an
  1044. * instance member instead.
  1045. *
  1046. * @return size of this file, in bytes.
  1047. */
  1048. public abstract long getLength();
  1049. /**
  1050. * Get the last modified time of this entry.
  1051. * <p>
  1052. * <b>Note: Efficient implementation required.</b>
  1053. * <p>
  1054. * The implementation of this method must be efficient. If a subclass
  1055. * needs to compute the value they should cache the reference within an
  1056. * instance member instead.
  1057. *
  1058. * @return time since the epoch (in ms) of the last change.
  1059. */
  1060. public abstract long getLastModified();
  1061. /**
  1062. * Get the name of this entry within its directory.
  1063. * <p>
  1064. * Efficient implementations are not required. The caller will obtain
  1065. * the name only once and cache it once obtained.
  1066. *
  1067. * @return name of the entry.
  1068. */
  1069. public abstract String getName();
  1070. /**
  1071. * Obtain an input stream to read the file content.
  1072. * <p>
  1073. * Efficient implementations are not required. The caller will usually
  1074. * obtain the stream only once per entry, if at all.
  1075. * <p>
  1076. * The input stream should not use buffering if the implementation can
  1077. * avoid it. The caller will buffer as necessary to perform efficient
  1078. * block IO operations.
  1079. * <p>
  1080. * The caller will close the stream once complete.
  1081. *
  1082. * @return a stream to read from the file.
  1083. * @throws IOException
  1084. * the file could not be opened for reading.
  1085. */
  1086. public abstract InputStream openInputStream() throws IOException;
  1087. }
  1088. /** Magic type indicating we know rules exist, but they aren't loaded. */
  1089. private static class PerDirectoryIgnoreNode extends IgnoreNode {
  1090. final Entry entry;
  1091. PerDirectoryIgnoreNode(Entry entry) {
  1092. super(Collections.<FastIgnoreRule> emptyList());
  1093. this.entry = entry;
  1094. }
  1095. IgnoreNode load() throws IOException {
  1096. IgnoreNode r = new IgnoreNode();
  1097. InputStream in = entry.openInputStream();
  1098. try {
  1099. r.parse(in);
  1100. } finally {
  1101. in.close();
  1102. }
  1103. return r.getRules().isEmpty() ? null : r;
  1104. }
  1105. }
  1106. /** Magic type indicating there may be rules for the top level. */
  1107. private static class RootIgnoreNode extends PerDirectoryIgnoreNode {
  1108. final Repository repository;
  1109. RootIgnoreNode(Entry entry, Repository repository) {
  1110. super(entry);
  1111. this.repository = repository;
  1112. }
  1113. @Override
  1114. IgnoreNode load() throws IOException {
  1115. IgnoreNode r;
  1116. if (entry != null) {
  1117. r = super.load();
  1118. if (r == null)
  1119. r = new IgnoreNode();
  1120. } else {
  1121. r = new IgnoreNode();
  1122. }
  1123. FS fs = repository.getFS();
  1124. String path = repository.getConfig().get(CoreConfig.KEY)
  1125. .getExcludesFile();
  1126. if (path != null) {
  1127. File excludesfile;
  1128. if (path.startsWith("~/")) //$NON-NLS-1$
  1129. excludesfile = fs.resolve(fs.userHome(), path.substring(2));
  1130. else
  1131. excludesfile = fs.resolve(null, path);
  1132. loadRulesFromFile(r, excludesfile);
  1133. }
  1134. File exclude = fs.resolve(repository.getDirectory(),
  1135. Constants.INFO_EXCLUDE);
  1136. loadRulesFromFile(r, exclude);
  1137. return r.getRules().isEmpty() ? null : r;
  1138. }
  1139. private static void loadRulesFromFile(IgnoreNode r, File exclude)
  1140. throws FileNotFoundException, IOException {
  1141. if (FS.DETECTED.exists(exclude)) {
  1142. FileInputStream in = new FileInputStream(exclude);
  1143. try {
  1144. r.parse(in);
  1145. } finally {
  1146. in.close();
  1147. }
  1148. }
  1149. }
  1150. }
  1151. /** Magic type indicating we know rules exist, but they aren't loaded. */
  1152. private static class PerDirectoryAttributesNode extends AttributesNode {
  1153. final Entry entry;
  1154. PerDirectoryAttributesNode(Entry entry) {
  1155. super(Collections.<AttributesRule> emptyList());
  1156. this.entry = entry;
  1157. }
  1158. AttributesNode load() throws IOException {
  1159. AttributesNode r = new AttributesNode();
  1160. InputStream in = entry.openInputStream();
  1161. try {
  1162. r.parse(in);
  1163. } finally {
  1164. in.close();
  1165. }
  1166. return r.getRules().isEmpty() ? null : r;
  1167. }
  1168. }
  1169. /**
  1170. * Attributes node loaded from global system-wide file.
  1171. */
  1172. private static class GlobalAttributesNode extends AttributesNode {
  1173. final Repository repository;
  1174. GlobalAttributesNode(Repository repository) {
  1175. this.repository = repository;
  1176. }
  1177. AttributesNode load() throws IOException {
  1178. AttributesNode r = new AttributesNode();
  1179. FS fs = repository.getFS();
  1180. String path = repository.getConfig().get(CoreConfig.KEY)
  1181. .getAttributesFile();
  1182. if (path != null) {
  1183. File attributesFile;
  1184. if (path.startsWith("~/")) //$NON-NLS-1$
  1185. attributesFile = fs.resolve(fs.userHome(),
  1186. path.substring(2));
  1187. else
  1188. attributesFile = fs.resolve(null, path);
  1189. loadRulesFromFile(r, attributesFile);
  1190. }
  1191. return r.getRules().isEmpty() ? null : r;
  1192. }
  1193. }
  1194. /** Magic type indicating there may be rules for the top level. */
  1195. private static class InfoAttributesNode extends AttributesNode {
  1196. final Repository repository;
  1197. InfoAttributesNode(Repository repository) {
  1198. this.repository = repository;
  1199. }
  1200. AttributesNode load() throws IOException {
  1201. AttributesNode r = new AttributesNode();
  1202. FS fs = repository.getFS();
  1203. File attributes = fs.resolve(repository.getDirectory(),
  1204. "info/attributes"); //$NON-NLS-1$
  1205. loadRulesFromFile(r, attributes);
  1206. return r.getRules().isEmpty() ? null : r;
  1207. }
  1208. }
  1209. private static void loadRulesFromFile(AttributesNode r, File attrs)
  1210. throws FileNotFoundException, IOException {
  1211. if (attrs.exists()) {
  1212. FileInputStream in = new FileInputStream(attrs);
  1213. try {
  1214. r.parse(in);
  1215. } finally {
  1216. in.close();
  1217. }
  1218. }
  1219. }
  1220. private static final class IteratorState {
  1221. /** Options used to process the working tree. */
  1222. final WorkingTreeOptions options;
  1223. /** File name character encoder. */
  1224. final CharsetEncoder nameEncoder;
  1225. /** Digest computer for {@link #contentId} computations. */
  1226. MessageDigest contentDigest;
  1227. /** Buffer used to perform {@link #contentId} computations. */
  1228. byte[] contentReadBuffer;
  1229. /** TreeWalk with a (supposedly) matching DirCacheIterator. */
  1230. TreeWalk walk;
  1231. /** Position of the matching {@link DirCacheIterator}. */
  1232. int dirCacheTree;
  1233. IteratorState(WorkingTreeOptions options) {
  1234. this.options = options;
  1235. this.nameEncoder = Constants.CHARSET.newEncoder();
  1236. }
  1237. void initializeDigestAndReadBuffer() {
  1238. if (contentDigest == null) {
  1239. contentDigest = Constants.newMessageDigest();
  1240. contentReadBuffer = new byte[BUFFER_SIZE];
  1241. }
  1242. }
  1243. }
  1244. }