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

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