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 31KB

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