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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. try {
  360. return IO.readWholeStream(filterClean(in), n);
  361. } finally {
  362. safeClose(in);
  363. }
  364. }
  365. private InputStream filterClean(InputStream in) {
  366. return new EolCanonicalizingInputStream(in);
  367. }
  368. /**
  369. * Returns the working tree options used by this iterator.
  370. *
  371. * @return working tree options
  372. */
  373. public WorkingTreeOptions getOptions() {
  374. return state.options;
  375. }
  376. @Override
  377. public int idOffset() {
  378. return 0;
  379. }
  380. @Override
  381. public void reset() {
  382. if (!first()) {
  383. ptr = 0;
  384. if (!eof())
  385. parseEntry();
  386. }
  387. }
  388. @Override
  389. public boolean first() {
  390. return ptr == 0;
  391. }
  392. @Override
  393. public boolean eof() {
  394. return ptr == entryCnt;
  395. }
  396. @Override
  397. public void next(final int delta) throws CorruptObjectException {
  398. ptr += delta;
  399. if (!eof())
  400. parseEntry();
  401. }
  402. @Override
  403. public void back(final int delta) throws CorruptObjectException {
  404. ptr -= delta;
  405. parseEntry();
  406. }
  407. private void parseEntry() {
  408. final Entry e = entries[ptr];
  409. mode = e.getMode().getBits();
  410. final int nameLen = e.encodedNameLen;
  411. ensurePathCapacity(pathOffset + nameLen, pathOffset);
  412. System.arraycopy(e.encodedName, 0, path, pathOffset, nameLen);
  413. pathLen = pathOffset + nameLen;
  414. }
  415. /**
  416. * Get the byte length of this entry.
  417. *
  418. * @return size of this file, in bytes.
  419. */
  420. public long getEntryLength() {
  421. return current().getLength();
  422. }
  423. /**
  424. * Get the last modified time of this entry.
  425. *
  426. * @return last modified time of this file, in milliseconds since the epoch
  427. * (Jan 1, 1970 UTC).
  428. */
  429. public long getEntryLastModified() {
  430. return current().getLastModified();
  431. }
  432. /**
  433. * Obtain an input stream to read the file content.
  434. * <p>
  435. * Efficient implementations are not required. The caller will usually
  436. * obtain the stream only once per entry, if at all.
  437. * <p>
  438. * The input stream should not use buffering if the implementation can avoid
  439. * it. The caller will buffer as necessary to perform efficient block IO
  440. * operations.
  441. * <p>
  442. * The caller will close the stream once complete.
  443. *
  444. * @return a stream to read from the file.
  445. * @throws IOException
  446. * the file could not be opened for reading.
  447. */
  448. public InputStream openEntryStream() throws IOException {
  449. return current().openInputStream();
  450. }
  451. /**
  452. * Determine if the current entry path is ignored by an ignore rule.
  453. *
  454. * @return true if the entry was ignored by an ignore rule file.
  455. * @throws IOException
  456. * a relevant ignore rule file exists but cannot be read.
  457. */
  458. public boolean isEntryIgnored() throws IOException {
  459. return isEntryIgnored(pathLen);
  460. }
  461. /**
  462. * Determine if the entry path is ignored by an ignore rule.
  463. *
  464. * @param pLen
  465. * the length of the path in the path buffer.
  466. * @return true if the entry is ignored by an ignore rule.
  467. * @throws IOException
  468. * a relevant ignore rule file exists but cannot be read.
  469. */
  470. protected boolean isEntryIgnored(final int pLen) throws IOException {
  471. IgnoreNode rules = getIgnoreNode();
  472. if (rules != null) {
  473. // The ignore code wants path to start with a '/' if possible.
  474. // If we have the '/' in our path buffer because we are inside
  475. // a subdirectory include it in the range we convert to string.
  476. //
  477. int pOff = pathOffset;
  478. if (0 < pOff)
  479. pOff--;
  480. String p = TreeWalk.pathOf(path, pOff, pLen);
  481. switch (rules.isIgnored(p, FileMode.TREE.equals(mode))) {
  482. case IGNORED:
  483. return true;
  484. case NOT_IGNORED:
  485. return false;
  486. case CHECK_PARENT:
  487. break;
  488. }
  489. }
  490. if (parent instanceof WorkingTreeIterator)
  491. return ((WorkingTreeIterator) parent).isEntryIgnored(pLen);
  492. return false;
  493. }
  494. private IgnoreNode getIgnoreNode() throws IOException {
  495. if (ignoreNode instanceof PerDirectoryIgnoreNode)
  496. ignoreNode = ((PerDirectoryIgnoreNode) ignoreNode).load();
  497. return ignoreNode;
  498. }
  499. private static final Comparator<Entry> ENTRY_CMP = new Comparator<Entry>() {
  500. public int compare(final Entry o1, final Entry o2) {
  501. final byte[] a = o1.encodedName;
  502. final byte[] b = o2.encodedName;
  503. final int aLen = o1.encodedNameLen;
  504. final int bLen = o2.encodedNameLen;
  505. int cPos;
  506. for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
  507. final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
  508. if (cmp != 0)
  509. return cmp;
  510. }
  511. if (cPos < aLen)
  512. return (a[cPos] & 0xff) - lastPathChar(o2);
  513. if (cPos < bLen)
  514. return lastPathChar(o1) - (b[cPos] & 0xff);
  515. return lastPathChar(o1) - lastPathChar(o2);
  516. }
  517. };
  518. static int lastPathChar(final Entry e) {
  519. return e.getMode() == FileMode.TREE ? '/' : '\0';
  520. }
  521. /**
  522. * Constructor helper.
  523. *
  524. * @param list
  525. * files in the subtree of the work tree this iterator operates
  526. * on
  527. */
  528. protected void init(final Entry[] list) {
  529. // Filter out nulls, . and .. as these are not valid tree entries,
  530. // also cache the encoded forms of the path names for efficient use
  531. // later on during sorting and iteration.
  532. //
  533. entries = list;
  534. int i, o;
  535. final CharsetEncoder nameEncoder = state.nameEncoder;
  536. for (i = 0, o = 0; i < entries.length; i++) {
  537. final Entry e = entries[i];
  538. if (e == null)
  539. continue;
  540. final String name = e.getName();
  541. if (".".equals(name) || "..".equals(name))
  542. continue;
  543. if (Constants.DOT_GIT.equals(name))
  544. continue;
  545. if (Constants.DOT_GIT_IGNORE.equals(name))
  546. ignoreNode = new PerDirectoryIgnoreNode(e);
  547. if (i != o)
  548. entries[o] = e;
  549. e.encodeName(nameEncoder);
  550. o++;
  551. }
  552. entryCnt = o;
  553. Arrays.sort(entries, 0, entryCnt, ENTRY_CMP);
  554. contentIdFromPtr = -1;
  555. ptr = 0;
  556. if (!eof())
  557. parseEntry();
  558. }
  559. /**
  560. * Obtain the current entry from this iterator.
  561. *
  562. * @return the currently selected entry.
  563. */
  564. protected Entry current() {
  565. return entries[ptr];
  566. }
  567. /**
  568. * The result of a metadata-comparison between the current entry and a
  569. * {@link DirCacheEntry}
  570. */
  571. public enum MetadataDiff {
  572. /**
  573. * The entries are equal by metaData (mode, length,
  574. * modification-timestamp) or the <code>assumeValid</code> attribute of
  575. * the index entry is set
  576. */
  577. EQUAL,
  578. /**
  579. * The entries are not equal by metaData (mode, length) or the
  580. * <code>isUpdateNeeded</code> attribute of the index entry is set
  581. */
  582. DIFFER_BY_METADATA,
  583. /** index entry is smudged - can't use that entry for comparison */
  584. SMUDGED,
  585. /**
  586. * The entries are equal by metaData (mode, length) but differ by
  587. * modification-timestamp.
  588. */
  589. DIFFER_BY_TIMESTAMP
  590. }
  591. /**
  592. * Compare the metadata (mode, length, modification-timestamp) of the
  593. * current entry and a {@link DirCacheEntry}
  594. *
  595. * @param entry
  596. * the {@link DirCacheEntry} to compare with
  597. * @return a {@link MetadataDiff} which tells whether and how the entries
  598. * metadata differ
  599. */
  600. public MetadataDiff compareMetadata(DirCacheEntry entry) {
  601. if (entry.isAssumeValid())
  602. return MetadataDiff.EQUAL;
  603. if (entry.isUpdateNeeded())
  604. return MetadataDiff.DIFFER_BY_METADATA;
  605. if (!entry.isSmudged() && (getEntryLength() != entry.getLength()))
  606. return MetadataDiff.DIFFER_BY_METADATA;
  607. // Determine difference in mode-bits of file and index-entry. In the
  608. // bitwise presentation of modeDiff we'll have a '1' when the two modes
  609. // differ at this position.
  610. int modeDiff = getEntryRawMode() ^ entry.getRawMode();
  611. // Do not rely on filemode differences in case of symbolic links
  612. if (modeDiff != 0 && !FileMode.SYMLINK.equals(entry.getRawMode())) {
  613. // Ignore the executable file bits if WorkingTreeOptions tell me to
  614. // do so. Ignoring is done by setting the bits representing a
  615. // EXECUTABLE_FILE to '0' in modeDiff
  616. if (!state.options.isFileMode())
  617. modeDiff &= ~FileMode.EXECUTABLE_FILE.getBits();
  618. if (modeDiff != 0)
  619. // Report a modification if the modes still (after potentially
  620. // ignoring EXECUTABLE_FILE bits) differ
  621. return MetadataDiff.DIFFER_BY_METADATA;
  622. }
  623. // Git under windows only stores seconds so we round the timestamp
  624. // Java gives us if it looks like the timestamp in index is seconds
  625. // only. Otherwise we compare the timestamp at millisecond precision.
  626. long cacheLastModified = entry.getLastModified();
  627. long fileLastModified = getEntryLastModified();
  628. if (cacheLastModified % 1000 == 0)
  629. fileLastModified = fileLastModified - fileLastModified % 1000;
  630. if (fileLastModified != cacheLastModified)
  631. return MetadataDiff.DIFFER_BY_TIMESTAMP;
  632. else if (!entry.isSmudged())
  633. // The file is clean when you look at timestamps.
  634. return MetadataDiff.EQUAL;
  635. else
  636. return MetadataDiff.SMUDGED;
  637. }
  638. /**
  639. * Checks whether this entry differs from a given entry from the
  640. * {@link DirCache}.
  641. *
  642. * File status information is used and if status is same we consider the
  643. * file identical to the state in the working directory. Native git uses
  644. * more stat fields than we have accessible in Java.
  645. *
  646. * @param entry
  647. * the entry from the dircache we want to compare against
  648. * @param forceContentCheck
  649. * True if the actual file content should be checked if
  650. * modification time differs.
  651. * @return true if content is most likely different.
  652. */
  653. public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) {
  654. MetadataDiff diff = compareMetadata(entry);
  655. switch (diff) {
  656. case DIFFER_BY_TIMESTAMP:
  657. if (forceContentCheck)
  658. // But we are told to look at content even though timestamps
  659. // tell us about modification
  660. return contentCheck(entry);
  661. else
  662. // We are told to assume a modification if timestamps differs
  663. return true;
  664. case SMUDGED:
  665. // The file is clean by timestamps but the entry was smudged.
  666. // Lets do a content check
  667. return contentCheck(entry);
  668. case EQUAL:
  669. return false;
  670. case DIFFER_BY_METADATA:
  671. return true;
  672. default:
  673. throw new IllegalStateException(MessageFormat.format(
  674. JGitText.get().unexpectedCompareResult, diff.name()));
  675. }
  676. }
  677. /**
  678. * Get the file mode to use for the current entry when it is to be updated
  679. * in the index.
  680. *
  681. * @param indexIter
  682. * {@link DirCacheIterator} positioned at the same entry as this
  683. * iterator or null if no {@link DirCacheIterator} is available
  684. * at this iterator's current entry
  685. * @return index file mode
  686. */
  687. public FileMode getIndexFileMode(final DirCacheIterator indexIter) {
  688. final FileMode wtMode = getEntryFileMode();
  689. if (indexIter == null)
  690. return wtMode;
  691. if (getOptions().isFileMode())
  692. return wtMode;
  693. final FileMode iMode = indexIter.getEntryFileMode();
  694. if (FileMode.REGULAR_FILE == wtMode
  695. && FileMode.EXECUTABLE_FILE == iMode)
  696. return iMode;
  697. if (FileMode.EXECUTABLE_FILE == wtMode
  698. && FileMode.REGULAR_FILE == iMode)
  699. return iMode;
  700. return wtMode;
  701. }
  702. /**
  703. * Compares the entries content with the content in the filesystem.
  704. * Unsmudges the entry when it is detected that it is clean.
  705. *
  706. * @param entry
  707. * the entry to be checked
  708. * @return <code>true</code> if the content matches, <code>false</code>
  709. * otherwise
  710. */
  711. private boolean contentCheck(DirCacheEntry entry) {
  712. if (getEntryObjectId().equals(entry.getObjectId())) {
  713. // Content has not changed
  714. // We know the entry can't be racily clean because it's still clean.
  715. // Therefore we unsmudge the entry!
  716. // If by any chance we now unsmudge although we are still in the
  717. // same time-slot as the last modification to the index file the
  718. // next index write operation will smudge again.
  719. // Caution: we are unsmudging just by setting the length of the
  720. // in-memory entry object. It's the callers task to detect that we
  721. // have modified the entry and to persist the modified index.
  722. entry.setLength((int) getEntryLength());
  723. return false;
  724. } else {
  725. // Content differs: that's a real change!
  726. return true;
  727. }
  728. }
  729. private long computeLength(InputStream in) throws IOException {
  730. // Since we only care about the length, use skip. The stream
  731. // may be able to more efficiently wade through its data.
  732. //
  733. long length = 0;
  734. for (;;) {
  735. long n = in.skip(1 << 20);
  736. if (n <= 0)
  737. break;
  738. length += n;
  739. }
  740. return length;
  741. }
  742. private byte[] computeHash(InputStream in, long length) throws IOException {
  743. final MessageDigest contentDigest = state.contentDigest;
  744. final byte[] contentReadBuffer = state.contentReadBuffer;
  745. contentDigest.reset();
  746. contentDigest.update(hblob);
  747. contentDigest.update((byte) ' ');
  748. long sz = length;
  749. if (sz == 0) {
  750. contentDigest.update((byte) '0');
  751. } else {
  752. final int bufn = contentReadBuffer.length;
  753. int p = bufn;
  754. do {
  755. contentReadBuffer[--p] = digits[(int) (sz % 10)];
  756. sz /= 10;
  757. } while (sz > 0);
  758. contentDigest.update(contentReadBuffer, p, bufn - p);
  759. }
  760. contentDigest.update((byte) 0);
  761. for (;;) {
  762. final int r = in.read(contentReadBuffer);
  763. if (r <= 0)
  764. break;
  765. contentDigest.update(contentReadBuffer, 0, r);
  766. sz += r;
  767. }
  768. if (sz != length)
  769. return zeroid;
  770. return contentDigest.digest();
  771. }
  772. /** A single entry within a working directory tree. */
  773. protected static abstract class Entry {
  774. byte[] encodedName;
  775. int encodedNameLen;
  776. void encodeName(final CharsetEncoder enc) {
  777. final ByteBuffer b;
  778. try {
  779. b = enc.encode(CharBuffer.wrap(getName()));
  780. } catch (CharacterCodingException e) {
  781. // This should so never happen.
  782. throw new RuntimeException(MessageFormat.format(
  783. JGitText.get().unencodeableFile, getName()));
  784. }
  785. encodedNameLen = b.limit();
  786. if (b.hasArray() && b.arrayOffset() == 0)
  787. encodedName = b.array();
  788. else
  789. b.get(encodedName = new byte[encodedNameLen]);
  790. }
  791. public String toString() {
  792. return getMode().toString() + " " + getName();
  793. }
  794. /**
  795. * Get the type of this entry.
  796. * <p>
  797. * <b>Note: Efficient implementation required.</b>
  798. * <p>
  799. * The implementation of this method must be efficient. If a subclass
  800. * needs to compute the value they should cache the reference within an
  801. * instance member instead.
  802. *
  803. * @return a file mode constant from {@link FileMode}.
  804. */
  805. public abstract FileMode getMode();
  806. /**
  807. * Get the byte length of this entry.
  808. * <p>
  809. * <b>Note: Efficient implementation required.</b>
  810. * <p>
  811. * The implementation of this method must be efficient. If a subclass
  812. * needs to compute the value they should cache the reference within an
  813. * instance member instead.
  814. *
  815. * @return size of this file, in bytes.
  816. */
  817. public abstract long getLength();
  818. /**
  819. * Get the last modified time of this entry.
  820. * <p>
  821. * <b>Note: Efficient implementation required.</b>
  822. * <p>
  823. * The implementation of this method must be efficient. If a subclass
  824. * needs to compute the value they should cache the reference within an
  825. * instance member instead.
  826. *
  827. * @return time since the epoch (in ms) of the last change.
  828. */
  829. public abstract long getLastModified();
  830. /**
  831. * Get the name of this entry within its directory.
  832. * <p>
  833. * Efficient implementations are not required. The caller will obtain
  834. * the name only once and cache it once obtained.
  835. *
  836. * @return name of the entry.
  837. */
  838. public abstract String getName();
  839. /**
  840. * Obtain an input stream to read the file content.
  841. * <p>
  842. * Efficient implementations are not required. The caller will usually
  843. * obtain the stream only once per entry, if at all.
  844. * <p>
  845. * The input stream should not use buffering if the implementation can
  846. * avoid it. The caller will buffer as necessary to perform efficient
  847. * block IO operations.
  848. * <p>
  849. * The caller will close the stream once complete.
  850. *
  851. * @return a stream to read from the file.
  852. * @throws IOException
  853. * the file could not be opened for reading.
  854. */
  855. public abstract InputStream openInputStream() throws IOException;
  856. }
  857. /** Magic type indicating we know rules exist, but they aren't loaded. */
  858. private static class PerDirectoryIgnoreNode extends IgnoreNode {
  859. final Entry entry;
  860. PerDirectoryIgnoreNode(Entry entry) {
  861. super(Collections.<IgnoreRule> emptyList());
  862. this.entry = entry;
  863. }
  864. IgnoreNode load() throws IOException {
  865. IgnoreNode r = new IgnoreNode();
  866. InputStream in = entry.openInputStream();
  867. try {
  868. r.parse(in);
  869. } finally {
  870. in.close();
  871. }
  872. return r.getRules().isEmpty() ? null : r;
  873. }
  874. }
  875. /** Magic type indicating there may be rules for the top level. */
  876. private static class RootIgnoreNode extends PerDirectoryIgnoreNode {
  877. final Repository repository;
  878. RootIgnoreNode(Entry entry, Repository repository) {
  879. super(entry);
  880. this.repository = repository;
  881. }
  882. @Override
  883. IgnoreNode load() throws IOException {
  884. IgnoreNode r;
  885. if (entry != null) {
  886. r = super.load();
  887. if (r == null)
  888. r = new IgnoreNode();
  889. } else {
  890. r = new IgnoreNode();
  891. }
  892. FS fs = repository.getFS();
  893. String path = repository.getConfig().get(CoreConfig.KEY)
  894. .getExcludesFile();
  895. if (path != null) {
  896. File excludesfile;
  897. if (path.startsWith("~/"))
  898. excludesfile = fs.resolve(fs.userHome(), path.substring(2));
  899. else
  900. excludesfile = fs.resolve(null, path);
  901. loadRulesFromFile(r, excludesfile);
  902. }
  903. File exclude = fs
  904. .resolve(repository.getDirectory(), "info/exclude");
  905. loadRulesFromFile(r, exclude);
  906. return r.getRules().isEmpty() ? null : r;
  907. }
  908. private void loadRulesFromFile(IgnoreNode r, File exclude)
  909. throws FileNotFoundException, IOException {
  910. if (exclude.exists()) {
  911. FileInputStream in = new FileInputStream(exclude);
  912. try {
  913. r.parse(in);
  914. } finally {
  915. in.close();
  916. }
  917. }
  918. }
  919. }
  920. private static final class IteratorState {
  921. /** Options used to process the working tree. */
  922. final WorkingTreeOptions options;
  923. /** File name character encoder. */
  924. final CharsetEncoder nameEncoder;
  925. /** Digest computer for {@link #contentId} computations. */
  926. MessageDigest contentDigest;
  927. /** Buffer used to perform {@link #contentId} computations. */
  928. byte[] contentReadBuffer;
  929. /** TreeWalk with a (supposedly) matching DirCacheIterator. */
  930. TreeWalk walk;
  931. /** Position of the matching {@link DirCacheIterator}. */
  932. int dirCacheTree;
  933. IteratorState(WorkingTreeOptions options) {
  934. this.options = options;
  935. this.nameEncoder = Constants.CHARSET.newEncoder();
  936. }
  937. void initializeDigestAndReadBuffer() {
  938. if (contentDigest == null) {
  939. contentDigest = Constants.newMessageDigest();
  940. contentReadBuffer = new byte[BUFFER_SIZE];
  941. }
  942. }
  943. }
  944. }