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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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.JGitText;
  62. import org.eclipse.jgit.diff.RawText;
  63. import org.eclipse.jgit.dircache.DirCache;
  64. import org.eclipse.jgit.dircache.DirCacheEntry;
  65. import org.eclipse.jgit.dircache.DirCacheIterator;
  66. import org.eclipse.jgit.errors.CorruptObjectException;
  67. import org.eclipse.jgit.errors.NoWorkTreeException;
  68. import org.eclipse.jgit.ignore.IgnoreNode;
  69. import org.eclipse.jgit.ignore.IgnoreRule;
  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.lib.RepositoryBuilder;
  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. /**
  117. * Create a new iterator with no parent.
  118. *
  119. * @param options
  120. * working tree options to be used
  121. */
  122. protected WorkingTreeIterator(WorkingTreeOptions options) {
  123. super();
  124. state = new IteratorState(options);
  125. }
  126. /**
  127. * Create a new iterator with no parent and a prefix.
  128. * <p>
  129. * The prefix path supplied is inserted in front of all paths generated by
  130. * this iterator. It is intended to be used when an iterator is being
  131. * created for a subsection of an overall repository and needs to be
  132. * combined with other iterators that are created to run over the entire
  133. * repository namespace.
  134. *
  135. * @param prefix
  136. * position of this iterator in the repository tree. The value
  137. * may be null or the empty string to indicate the prefix is the
  138. * root of the repository. A trailing slash ('/') is
  139. * automatically appended if the prefix does not end in '/'.
  140. * @param options
  141. * working tree options to be used
  142. */
  143. protected WorkingTreeIterator(final String prefix,
  144. WorkingTreeOptions options) {
  145. super(prefix);
  146. state = new IteratorState(options);
  147. }
  148. /**
  149. * Create an iterator for a subtree of an existing iterator.
  150. *
  151. * @param p
  152. * parent tree iterator.
  153. */
  154. protected WorkingTreeIterator(final WorkingTreeIterator p) {
  155. super(p);
  156. state = p.state;
  157. }
  158. /**
  159. * Initialize this iterator for the root level of a repository.
  160. * <p>
  161. * This method should only be invoked after calling {@link #init(Entry[])},
  162. * and only for the root iterator.
  163. *
  164. * @param repo
  165. * the repository.
  166. */
  167. protected void initRootIterator(Repository repo) {
  168. repository = repo;
  169. Entry entry;
  170. if (ignoreNode instanceof PerDirectoryIgnoreNode)
  171. entry = ((PerDirectoryIgnoreNode) ignoreNode).entry;
  172. else
  173. entry = null;
  174. ignoreNode = new RootIgnoreNode(entry, repo);
  175. }
  176. /**
  177. * Define the matching {@link DirCacheIterator}, to optimize ObjectIds.
  178. *
  179. * Once the DirCacheIterator has been set this iterator must only be
  180. * advanced by the TreeWalk that is supplied, as it assumes that itself and
  181. * the corresponding DirCacheIterator are positioned on the same file path
  182. * whenever {@link #idBuffer()} is invoked.
  183. *
  184. * @param walk
  185. * the walk that will be advancing this iterator.
  186. * @param treeId
  187. * index of the matching {@link DirCacheIterator}.
  188. */
  189. public void setDirCacheIterator(TreeWalk walk, int treeId) {
  190. state.walk = walk;
  191. state.dirCacheTree = treeId;
  192. }
  193. @Override
  194. public boolean hasId() {
  195. if (contentIdFromPtr == ptr)
  196. return true;
  197. return (mode & FileMode.TYPE_MASK) == FileMode.TYPE_FILE;
  198. }
  199. @Override
  200. public byte[] idBuffer() {
  201. if (contentIdFromPtr == ptr)
  202. return contentId;
  203. if (state.walk != null) {
  204. // If there is a matching DirCacheIterator, we can reuse
  205. // its idBuffer, but only if we appear to be clean against
  206. // the cached index information for the path.
  207. //
  208. DirCacheIterator i = state.walk.getTree(state.dirCacheTree,
  209. DirCacheIterator.class);
  210. if (i != null) {
  211. DirCacheEntry ent = i.getDirCacheEntry();
  212. if (ent != null && compareMetadata(ent) == MetadataDiff.EQUAL)
  213. return i.idBuffer();
  214. }
  215. }
  216. switch (mode & FileMode.TYPE_MASK) {
  217. case FileMode.TYPE_FILE:
  218. contentIdFromPtr = ptr;
  219. return contentId = idBufferBlob(entries[ptr]);
  220. case FileMode.TYPE_SYMLINK:
  221. // Java does not support symbolic links, so we should not
  222. // have reached this particular part of the walk code.
  223. //
  224. return zeroid;
  225. case FileMode.TYPE_GITLINK:
  226. contentIdFromPtr = ptr;
  227. return contentId = idSubmodule(entries[ptr]);
  228. }
  229. return zeroid;
  230. }
  231. /**
  232. * Get submodule id for given entry.
  233. *
  234. * @param e
  235. * @return non-null submodule id
  236. */
  237. protected byte[] idSubmodule(Entry e) {
  238. if (repository == null)
  239. return zeroid;
  240. File directory;
  241. try {
  242. directory = repository.getWorkTree();
  243. } catch (NoWorkTreeException nwte) {
  244. return zeroid;
  245. }
  246. return idSubmodule(directory, e);
  247. }
  248. /**
  249. * Get submodule id using the repository at the location of the entry
  250. * relative to the directory.
  251. *
  252. * @param directory
  253. * @param e
  254. * @return non-null submodule id
  255. */
  256. protected byte[] idSubmodule(File directory, Entry e) {
  257. final String gitDirPath = e.getName() + "/" + Constants.DOT_GIT;
  258. final File submoduleGitDir = new File(directory, gitDirPath);
  259. if (!submoduleGitDir.isDirectory())
  260. return zeroid;
  261. final Repository submoduleRepo;
  262. try {
  263. FS fs = repository != null ? repository.getFS() : FS.DETECTED;
  264. submoduleRepo = new RepositoryBuilder().setGitDir(submoduleGitDir)
  265. .setMustExist(true).setFS(fs).build();
  266. } catch (IOException exception) {
  267. return zeroid;
  268. }
  269. final ObjectId head;
  270. try {
  271. head = submoduleRepo.resolve(Constants.HEAD);
  272. } catch (IOException exception) {
  273. return zeroid;
  274. } finally {
  275. submoduleRepo.close();
  276. }
  277. if (head == null)
  278. return zeroid;
  279. final byte[] id = new byte[Constants.OBJECT_ID_LENGTH];
  280. head.copyRawTo(id, 0);
  281. return id;
  282. }
  283. private static final byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
  284. '7', '8', '9' };
  285. private static final byte[] hblob = Constants
  286. .encodedTypeString(Constants.OBJ_BLOB);
  287. private byte[] idBufferBlob(final Entry e) {
  288. try {
  289. final InputStream is = e.openInputStream();
  290. if (is == null)
  291. return zeroid;
  292. try {
  293. state.initializeDigestAndReadBuffer();
  294. final long len = e.getLength();
  295. if (!mightNeedCleaning())
  296. return computeHash(is, len);
  297. if (len <= MAXIMUM_FILE_SIZE_TO_READ_FULLY) {
  298. ByteBuffer rawbuf = IO.readWholeStream(is, (int) len);
  299. byte[] raw = rawbuf.array();
  300. int n = rawbuf.limit();
  301. if (!isBinary(raw, n)) {
  302. rawbuf = filterClean(raw, n);
  303. raw = rawbuf.array();
  304. n = rawbuf.limit();
  305. }
  306. return computeHash(new ByteArrayInputStream(raw, 0, n), n);
  307. }
  308. if (isBinary(e))
  309. return computeHash(is, len);
  310. final long canonLen;
  311. final InputStream lenIs = filterClean(e.openInputStream());
  312. try {
  313. canonLen = computeLength(lenIs);
  314. } finally {
  315. safeClose(lenIs);
  316. }
  317. return computeHash(filterClean(is), canonLen);
  318. } finally {
  319. safeClose(is);
  320. }
  321. } catch (IOException err) {
  322. // Can't read the file? Don't report the failure either.
  323. return zeroid;
  324. }
  325. }
  326. private static void safeClose(final InputStream in) {
  327. try {
  328. in.close();
  329. } catch (IOException err2) {
  330. // Suppress any error related to closing an input
  331. // stream. We don't care, we should not have any
  332. // outstanding data to flush or anything like that.
  333. }
  334. }
  335. private boolean mightNeedCleaning() {
  336. switch (getOptions().getAutoCRLF()) {
  337. case FALSE:
  338. default:
  339. return false;
  340. case TRUE:
  341. case INPUT:
  342. return true;
  343. }
  344. }
  345. private boolean isBinary(byte[] content, int sz) {
  346. return RawText.isBinary(content, sz);
  347. }
  348. private boolean isBinary(Entry entry) throws IOException {
  349. InputStream in = entry.openInputStream();
  350. try {
  351. return RawText.isBinary(in);
  352. } finally {
  353. safeClose(in);
  354. }
  355. }
  356. private ByteBuffer filterClean(byte[] src, int n)
  357. throws IOException {
  358. InputStream in = new ByteArrayInputStream(src);
  359. return IO.readWholeStream(filterClean(in), n);
  360. }
  361. private InputStream filterClean(InputStream in) {
  362. return new EolCanonicalizingInputStream(in);
  363. }
  364. /**
  365. * Returns the working tree options used by this iterator.
  366. *
  367. * @return working tree options
  368. */
  369. public WorkingTreeOptions getOptions() {
  370. return state.options;
  371. }
  372. @Override
  373. public int idOffset() {
  374. return 0;
  375. }
  376. @Override
  377. public void reset() {
  378. if (!first()) {
  379. ptr = 0;
  380. if (!eof())
  381. parseEntry();
  382. }
  383. }
  384. @Override
  385. public boolean first() {
  386. return ptr == 0;
  387. }
  388. @Override
  389. public boolean eof() {
  390. return ptr == entryCnt;
  391. }
  392. @Override
  393. public void next(final int delta) throws CorruptObjectException {
  394. ptr += delta;
  395. if (!eof())
  396. parseEntry();
  397. }
  398. @Override
  399. public void back(final int delta) throws CorruptObjectException {
  400. ptr -= delta;
  401. parseEntry();
  402. }
  403. private void parseEntry() {
  404. final Entry e = entries[ptr];
  405. mode = e.getMode().getBits();
  406. final int nameLen = e.encodedNameLen;
  407. ensurePathCapacity(pathOffset + nameLen, pathOffset);
  408. System.arraycopy(e.encodedName, 0, path, pathOffset, nameLen);
  409. pathLen = pathOffset + nameLen;
  410. }
  411. /**
  412. * Get the byte length of this entry.
  413. *
  414. * @return size of this file, in bytes.
  415. */
  416. public long getEntryLength() {
  417. return current().getLength();
  418. }
  419. /**
  420. * Get the last modified time of this entry.
  421. *
  422. * @return last modified time of this file, in milliseconds since the epoch
  423. * (Jan 1, 1970 UTC).
  424. */
  425. public long getEntryLastModified() {
  426. return current().getLastModified();
  427. }
  428. /**
  429. * Obtain an input stream to read the file content.
  430. * <p>
  431. * Efficient implementations are not required. The caller will usually
  432. * obtain the stream only once per entry, if at all.
  433. * <p>
  434. * The input stream should not use buffering if the implementation can avoid
  435. * it. The caller will buffer as necessary to perform efficient block IO
  436. * operations.
  437. * <p>
  438. * The caller will close the stream once complete.
  439. *
  440. * @return a stream to read from the file.
  441. * @throws IOException
  442. * the file could not be opened for reading.
  443. */
  444. public InputStream openEntryStream() throws IOException {
  445. return current().openInputStream();
  446. }
  447. /**
  448. * Determine if the current entry path is ignored by an ignore rule.
  449. *
  450. * @return true if the entry was ignored by an ignore rule file.
  451. * @throws IOException
  452. * a relevant ignore rule file exists but cannot be read.
  453. */
  454. public boolean isEntryIgnored() throws IOException {
  455. return isEntryIgnored(pathLen);
  456. }
  457. /**
  458. * Determine if the entry path is ignored by an ignore rule.
  459. *
  460. * @param pLen
  461. * the length of the path in the path buffer.
  462. * @return true if the entry is ignored by an ignore rule.
  463. * @throws IOException
  464. * a relevant ignore rule file exists but cannot be read.
  465. */
  466. protected boolean isEntryIgnored(final int pLen) throws IOException {
  467. IgnoreNode rules = getIgnoreNode();
  468. if (rules != null) {
  469. // The ignore code wants path to start with a '/' if possible.
  470. // If we have the '/' in our path buffer because we are inside
  471. // a subdirectory include it in the range we convert to string.
  472. //
  473. int pOff = pathOffset;
  474. if (0 < pOff)
  475. pOff--;
  476. String p = TreeWalk.pathOf(path, pOff, pLen);
  477. switch (rules.isIgnored(p, FileMode.TREE.equals(mode))) {
  478. case IGNORED:
  479. return true;
  480. case NOT_IGNORED:
  481. return false;
  482. case CHECK_PARENT:
  483. break;
  484. }
  485. }
  486. if (parent instanceof WorkingTreeIterator)
  487. return ((WorkingTreeIterator) parent).isEntryIgnored(pLen);
  488. return false;
  489. }
  490. private IgnoreNode getIgnoreNode() throws IOException {
  491. if (ignoreNode instanceof PerDirectoryIgnoreNode)
  492. ignoreNode = ((PerDirectoryIgnoreNode) ignoreNode).load();
  493. return ignoreNode;
  494. }
  495. private static final Comparator<Entry> ENTRY_CMP = new Comparator<Entry>() {
  496. public int compare(final Entry o1, final Entry o2) {
  497. final byte[] a = o1.encodedName;
  498. final byte[] b = o2.encodedName;
  499. final int aLen = o1.encodedNameLen;
  500. final int bLen = o2.encodedNameLen;
  501. int cPos;
  502. for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
  503. final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
  504. if (cmp != 0)
  505. return cmp;
  506. }
  507. if (cPos < aLen)
  508. return (a[cPos] & 0xff) - lastPathChar(o2);
  509. if (cPos < bLen)
  510. return lastPathChar(o1) - (b[cPos] & 0xff);
  511. return lastPathChar(o1) - lastPathChar(o2);
  512. }
  513. };
  514. static int lastPathChar(final Entry e) {
  515. return e.getMode() == FileMode.TREE ? '/' : '\0';
  516. }
  517. /**
  518. * Constructor helper.
  519. *
  520. * @param list
  521. * files in the subtree of the work tree this iterator operates
  522. * on
  523. */
  524. protected void init(final Entry[] list) {
  525. // Filter out nulls, . and .. as these are not valid tree entries,
  526. // also cache the encoded forms of the path names for efficient use
  527. // later on during sorting and iteration.
  528. //
  529. entries = list;
  530. int i, o;
  531. final CharsetEncoder nameEncoder = state.nameEncoder;
  532. for (i = 0, o = 0; i < entries.length; i++) {
  533. final Entry e = entries[i];
  534. if (e == null)
  535. continue;
  536. final String name = e.getName();
  537. if (".".equals(name) || "..".equals(name))
  538. continue;
  539. if (Constants.DOT_GIT.equals(name))
  540. continue;
  541. if (Constants.DOT_GIT_IGNORE.equals(name))
  542. ignoreNode = new PerDirectoryIgnoreNode(e);
  543. if (i != o)
  544. entries[o] = e;
  545. e.encodeName(nameEncoder);
  546. o++;
  547. }
  548. entryCnt = o;
  549. Arrays.sort(entries, 0, entryCnt, ENTRY_CMP);
  550. contentIdFromPtr = -1;
  551. ptr = 0;
  552. if (!eof())
  553. parseEntry();
  554. }
  555. /**
  556. * Obtain the current entry from this iterator.
  557. *
  558. * @return the currently selected entry.
  559. */
  560. protected Entry current() {
  561. return entries[ptr];
  562. }
  563. /**
  564. * The result of a metadata-comparison between the current entry and a
  565. * {@link DirCacheEntry}
  566. */
  567. public enum MetadataDiff {
  568. /**
  569. * The entries are equal by metaData (mode, length,
  570. * modification-timestamp) or the <code>assumeValid</code> attribute of
  571. * the index entry is set
  572. */
  573. EQUAL,
  574. /**
  575. * The entries are not equal by metaData (mode, length) or the
  576. * <code>isUpdateNeeded</code> attribute of the index entry is set
  577. */
  578. DIFFER_BY_METADATA,
  579. /** index entry is smudged - can't use that entry for comparison */
  580. SMUDGED,
  581. /**
  582. * The entries are equal by metaData (mode, length) but differ by
  583. * modification-timestamp.
  584. */
  585. DIFFER_BY_TIMESTAMP
  586. }
  587. /**
  588. * Compare the metadata (mode, length, modification-timestamp) of the
  589. * current entry and a {@link DirCacheEntry}
  590. *
  591. * @param entry
  592. * the {@link DirCacheEntry} to compare with
  593. * @return a {@link MetadataDiff} which tells whether and how the entries
  594. * metadata differ
  595. */
  596. public MetadataDiff compareMetadata(DirCacheEntry entry) {
  597. if (entry.isAssumeValid())
  598. return MetadataDiff.EQUAL;
  599. if (entry.isUpdateNeeded())
  600. return MetadataDiff.DIFFER_BY_METADATA;
  601. if (!entry.isSmudged() && (getEntryLength() != entry.getLength()))
  602. return MetadataDiff.DIFFER_BY_METADATA;
  603. // Determine difference in mode-bits of file and index-entry. In the
  604. // bitwise presentation of modeDiff we'll have a '1' when the two modes
  605. // differ at this position.
  606. int modeDiff = getEntryRawMode() ^ entry.getRawMode();
  607. // Do not rely on filemode differences in case of symbolic links
  608. if (modeDiff != 0 && !FileMode.SYMLINK.equals(entry.getRawMode())) {
  609. // Ignore the executable file bits if WorkingTreeOptions tell me to
  610. // do so. Ignoring is done by setting the bits representing a
  611. // EXECUTABLE_FILE to '0' in modeDiff
  612. if (!state.options.isFileMode())
  613. modeDiff &= ~FileMode.EXECUTABLE_FILE.getBits();
  614. if (modeDiff != 0)
  615. // Report a modification if the modes still (after potentially
  616. // ignoring EXECUTABLE_FILE bits) differ
  617. return MetadataDiff.DIFFER_BY_METADATA;
  618. }
  619. // Git under windows only stores seconds so we round the timestamp
  620. // Java gives us if it looks like the timestamp in index is seconds
  621. // only. Otherwise we compare the timestamp at millisecond precision.
  622. long cacheLastModified = entry.getLastModified();
  623. long fileLastModified = getEntryLastModified();
  624. if (cacheLastModified % 1000 == 0)
  625. fileLastModified = fileLastModified - fileLastModified % 1000;
  626. if (fileLastModified != cacheLastModified)
  627. return MetadataDiff.DIFFER_BY_TIMESTAMP;
  628. else if (!entry.isSmudged())
  629. // The file is clean when you look at timestamps.
  630. return MetadataDiff.EQUAL;
  631. else
  632. return MetadataDiff.SMUDGED;
  633. }
  634. /**
  635. * Checks whether this entry differs from a given entry from the
  636. * {@link DirCache}.
  637. *
  638. * File status information is used and if status is same we consider the
  639. * file identical to the state in the working directory. Native git uses
  640. * more stat fields than we have accessible in Java.
  641. *
  642. * @param entry
  643. * the entry from the dircache we want to compare against
  644. * @param forceContentCheck
  645. * True if the actual file content should be checked if
  646. * modification time differs.
  647. * @return true if content is most likely different.
  648. */
  649. public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) {
  650. MetadataDiff diff = compareMetadata(entry);
  651. switch (diff) {
  652. case DIFFER_BY_TIMESTAMP:
  653. if (forceContentCheck)
  654. // But we are told to look at content even though timestamps
  655. // tell us about modification
  656. return contentCheck(entry);
  657. else
  658. // We are told to assume a modification if timestamps differs
  659. return true;
  660. case SMUDGED:
  661. // The file is clean by timestamps but the entry was smudged.
  662. // Lets do a content check
  663. return contentCheck(entry);
  664. case EQUAL:
  665. return false;
  666. case DIFFER_BY_METADATA:
  667. return true;
  668. default:
  669. throw new IllegalStateException(MessageFormat.format(
  670. JGitText.get().unexpectedCompareResult, diff.name()));
  671. }
  672. }
  673. /**
  674. * Compares the entries content with the content in the filesystem.
  675. * Unsmudges the entry when it is detected that it is clean.
  676. *
  677. * @param entry
  678. * the entry to be checked
  679. * @return <code>true</code> if the content matches, <code>false</code>
  680. * otherwise
  681. */
  682. private boolean contentCheck(DirCacheEntry entry) {
  683. if (getEntryObjectId().equals(entry.getObjectId())) {
  684. // Content has not changed
  685. // We know the entry can't be racily clean because it's still clean.
  686. // Therefore we unsmudge the entry!
  687. // If by any chance we now unsmudge although we are still in the
  688. // same time-slot as the last modification to the index file the
  689. // next index write operation will smudge again.
  690. // Caution: we are unsmudging just by setting the length of the
  691. // in-memory entry object. It's the callers task to detect that we
  692. // have modified the entry and to persist the modified index.
  693. entry.setLength((int) getEntryLength());
  694. return false;
  695. } else {
  696. // Content differs: that's a real change!
  697. return true;
  698. }
  699. }
  700. private long computeLength(InputStream in) throws IOException {
  701. // Since we only care about the length, use skip. The stream
  702. // may be able to more efficiently wade through its data.
  703. //
  704. long length = 0;
  705. for (;;) {
  706. long n = in.skip(1 << 20);
  707. if (n <= 0)
  708. break;
  709. length += n;
  710. }
  711. return length;
  712. }
  713. private byte[] computeHash(InputStream in, long length) throws IOException {
  714. final MessageDigest contentDigest = state.contentDigest;
  715. final byte[] contentReadBuffer = state.contentReadBuffer;
  716. contentDigest.reset();
  717. contentDigest.update(hblob);
  718. contentDigest.update((byte) ' ');
  719. long sz = length;
  720. if (sz == 0) {
  721. contentDigest.update((byte) '0');
  722. } else {
  723. final int bufn = contentReadBuffer.length;
  724. int p = bufn;
  725. do {
  726. contentReadBuffer[--p] = digits[(int) (sz % 10)];
  727. sz /= 10;
  728. } while (sz > 0);
  729. contentDigest.update(contentReadBuffer, p, bufn - p);
  730. }
  731. contentDigest.update((byte) 0);
  732. for (;;) {
  733. final int r = in.read(contentReadBuffer);
  734. if (r <= 0)
  735. break;
  736. contentDigest.update(contentReadBuffer, 0, r);
  737. sz += r;
  738. }
  739. if (sz != length)
  740. return zeroid;
  741. return contentDigest.digest();
  742. }
  743. /** A single entry within a working directory tree. */
  744. protected static abstract class Entry {
  745. byte[] encodedName;
  746. int encodedNameLen;
  747. void encodeName(final CharsetEncoder enc) {
  748. final ByteBuffer b;
  749. try {
  750. b = enc.encode(CharBuffer.wrap(getName()));
  751. } catch (CharacterCodingException e) {
  752. // This should so never happen.
  753. throw new RuntimeException(MessageFormat.format(
  754. JGitText.get().unencodeableFile, getName()));
  755. }
  756. encodedNameLen = b.limit();
  757. if (b.hasArray() && b.arrayOffset() == 0)
  758. encodedName = b.array();
  759. else
  760. b.get(encodedName = new byte[encodedNameLen]);
  761. }
  762. public String toString() {
  763. return getMode().toString() + " " + getName();
  764. }
  765. /**
  766. * Get the type of this entry.
  767. * <p>
  768. * <b>Note: Efficient implementation required.</b>
  769. * <p>
  770. * The implementation of this method must be efficient. If a subclass
  771. * needs to compute the value they should cache the reference within an
  772. * instance member instead.
  773. *
  774. * @return a file mode constant from {@link FileMode}.
  775. */
  776. public abstract FileMode getMode();
  777. /**
  778. * Get the byte length of this entry.
  779. * <p>
  780. * <b>Note: Efficient implementation required.</b>
  781. * <p>
  782. * The implementation of this method must be efficient. If a subclass
  783. * needs to compute the value they should cache the reference within an
  784. * instance member instead.
  785. *
  786. * @return size of this file, in bytes.
  787. */
  788. public abstract long getLength();
  789. /**
  790. * Get the last modified time of this entry.
  791. * <p>
  792. * <b>Note: Efficient implementation required.</b>
  793. * <p>
  794. * The implementation of this method must be efficient. If a subclass
  795. * needs to compute the value they should cache the reference within an
  796. * instance member instead.
  797. *
  798. * @return time since the epoch (in ms) of the last change.
  799. */
  800. public abstract long getLastModified();
  801. /**
  802. * Get the name of this entry within its directory.
  803. * <p>
  804. * Efficient implementations are not required. The caller will obtain
  805. * the name only once and cache it once obtained.
  806. *
  807. * @return name of the entry.
  808. */
  809. public abstract String getName();
  810. /**
  811. * Obtain an input stream to read the file content.
  812. * <p>
  813. * Efficient implementations are not required. The caller will usually
  814. * obtain the stream only once per entry, if at all.
  815. * <p>
  816. * The input stream should not use buffering if the implementation can
  817. * avoid it. The caller will buffer as necessary to perform efficient
  818. * block IO operations.
  819. * <p>
  820. * The caller will close the stream once complete.
  821. *
  822. * @return a stream to read from the file.
  823. * @throws IOException
  824. * the file could not be opened for reading.
  825. */
  826. public abstract InputStream openInputStream() throws IOException;
  827. }
  828. /** Magic type indicating we know rules exist, but they aren't loaded. */
  829. private static class PerDirectoryIgnoreNode extends IgnoreNode {
  830. final Entry entry;
  831. PerDirectoryIgnoreNode(Entry entry) {
  832. super(Collections.<IgnoreRule> emptyList());
  833. this.entry = entry;
  834. }
  835. IgnoreNode load() throws IOException {
  836. IgnoreNode r = new IgnoreNode();
  837. InputStream in = entry.openInputStream();
  838. try {
  839. r.parse(in);
  840. } finally {
  841. in.close();
  842. }
  843. return r.getRules().isEmpty() ? null : r;
  844. }
  845. }
  846. /** Magic type indicating there may be rules for the top level. */
  847. private static class RootIgnoreNode extends PerDirectoryIgnoreNode {
  848. final Repository repository;
  849. RootIgnoreNode(Entry entry, Repository repository) {
  850. super(entry);
  851. this.repository = repository;
  852. }
  853. @Override
  854. IgnoreNode load() throws IOException {
  855. IgnoreNode r;
  856. if (entry != null) {
  857. r = super.load();
  858. if (r == null)
  859. r = new IgnoreNode();
  860. } else {
  861. r = new IgnoreNode();
  862. }
  863. FS fs = repository.getFS();
  864. String path = repository.getConfig().get(CoreConfig.KEY)
  865. .getExcludesFile();
  866. if (path != null) {
  867. File excludesfile;
  868. if (path.startsWith("~/"))
  869. excludesfile = fs.resolve(fs.userHome(), path.substring(2));
  870. else
  871. excludesfile = fs.resolve(null, path);
  872. loadRulesFromFile(r, excludesfile);
  873. }
  874. File exclude = fs
  875. .resolve(repository.getDirectory(), "info/exclude");
  876. loadRulesFromFile(r, exclude);
  877. return r.getRules().isEmpty() ? null : r;
  878. }
  879. private void loadRulesFromFile(IgnoreNode r, File exclude)
  880. throws FileNotFoundException, IOException {
  881. if (exclude.exists()) {
  882. FileInputStream in = new FileInputStream(exclude);
  883. try {
  884. r.parse(in);
  885. } finally {
  886. in.close();
  887. }
  888. }
  889. }
  890. }
  891. private static final class IteratorState {
  892. /** Options used to process the working tree. */
  893. final WorkingTreeOptions options;
  894. /** File name character encoder. */
  895. final CharsetEncoder nameEncoder;
  896. /** Digest computer for {@link #contentId} computations. */
  897. MessageDigest contentDigest;
  898. /** Buffer used to perform {@link #contentId} computations. */
  899. byte[] contentReadBuffer;
  900. /** TreeWalk with a (supposedly) matching DirCacheIterator. */
  901. TreeWalk walk;
  902. /** Position of the matching {@link DirCacheIterator}. */
  903. int dirCacheTree;
  904. IteratorState(WorkingTreeOptions options) {
  905. this.options = options;
  906. this.nameEncoder = Constants.CHARSET.newEncoder();
  907. }
  908. void initializeDigestAndReadBuffer() {
  909. if (contentDigest == null) {
  910. contentDigest = Constants.newMessageDigest();
  911. contentReadBuffer = new byte[BUFFER_SIZE];
  912. }
  913. }
  914. }
  915. }