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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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.IgnoreNode;
  71. import org.eclipse.jgit.ignore.IgnoreRule;
  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 boolean isBinary(byte[] content, int sz) {
  366. return RawText.isBinary(content, sz);
  367. }
  368. private 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 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 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. IgnoreNode rules = getIgnoreNode();
  520. if (rules != null) {
  521. // The ignore code wants path to start with a '/' if possible.
  522. // If we have the '/' in our path buffer because we are inside
  523. // a subdirectory include it in the range we convert to string.
  524. //
  525. int pOff = pathOffset;
  526. if (0 < pOff)
  527. pOff--;
  528. String p = TreeWalk.pathOf(path, pOff, pLen);
  529. switch (rules.isIgnored(p, FileMode.TREE.equals(mode))) {
  530. case IGNORED:
  531. return true;
  532. case NOT_IGNORED:
  533. return false;
  534. case CHECK_PARENT:
  535. break;
  536. }
  537. }
  538. if (parent instanceof WorkingTreeIterator)
  539. return ((WorkingTreeIterator) parent).isEntryIgnored(pLen);
  540. return false;
  541. }
  542. private IgnoreNode getIgnoreNode() throws IOException {
  543. if (ignoreNode instanceof PerDirectoryIgnoreNode)
  544. ignoreNode = ((PerDirectoryIgnoreNode) ignoreNode).load();
  545. return ignoreNode;
  546. }
  547. private static final Comparator<Entry> ENTRY_CMP = new Comparator<Entry>() {
  548. public int compare(final Entry o1, final Entry o2) {
  549. final byte[] a = o1.encodedName;
  550. final byte[] b = o2.encodedName;
  551. final int aLen = o1.encodedNameLen;
  552. final int bLen = o2.encodedNameLen;
  553. int cPos;
  554. for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
  555. final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
  556. if (cmp != 0)
  557. return cmp;
  558. }
  559. if (cPos < aLen)
  560. return (a[cPos] & 0xff) - lastPathChar(o2);
  561. if (cPos < bLen)
  562. return lastPathChar(o1) - (b[cPos] & 0xff);
  563. return lastPathChar(o1) - lastPathChar(o2);
  564. }
  565. };
  566. static int lastPathChar(final Entry e) {
  567. return e.getMode() == FileMode.TREE ? '/' : '\0';
  568. }
  569. /**
  570. * Constructor helper.
  571. *
  572. * @param list
  573. * files in the subtree of the work tree this iterator operates
  574. * on
  575. */
  576. protected void init(final Entry[] list) {
  577. // Filter out nulls, . and .. as these are not valid tree entries,
  578. // also cache the encoded forms of the path names for efficient use
  579. // later on during sorting and iteration.
  580. //
  581. entries = list;
  582. int i, o;
  583. final CharsetEncoder nameEncoder = state.nameEncoder;
  584. for (i = 0, o = 0; i < entries.length; i++) {
  585. final Entry e = entries[i];
  586. if (e == null)
  587. continue;
  588. final String name = e.getName();
  589. if (".".equals(name) || "..".equals(name)) //$NON-NLS-1$ //$NON-NLS-2$
  590. continue;
  591. if (Constants.DOT_GIT.equals(name))
  592. continue;
  593. if (Constants.DOT_GIT_IGNORE.equals(name))
  594. ignoreNode = new PerDirectoryIgnoreNode(e);
  595. if (i != o)
  596. entries[o] = e;
  597. e.encodeName(nameEncoder);
  598. o++;
  599. }
  600. entryCnt = o;
  601. Arrays.sort(entries, 0, entryCnt, ENTRY_CMP);
  602. contentIdFromPtr = -1;
  603. ptr = 0;
  604. if (!eof())
  605. parseEntry();
  606. }
  607. /**
  608. * Obtain the current entry from this iterator.
  609. *
  610. * @return the currently selected entry.
  611. */
  612. protected Entry current() {
  613. return entries[ptr];
  614. }
  615. /**
  616. * The result of a metadata-comparison between the current entry and a
  617. * {@link DirCacheEntry}
  618. */
  619. public enum MetadataDiff {
  620. /**
  621. * The entries are equal by metaData (mode, length,
  622. * modification-timestamp) or the <code>assumeValid</code> attribute of
  623. * the index entry is set
  624. */
  625. EQUAL,
  626. /**
  627. * The entries are not equal by metaData (mode, length) or the
  628. * <code>isUpdateNeeded</code> attribute of the index entry is set
  629. */
  630. DIFFER_BY_METADATA,
  631. /** index entry is smudged - can't use that entry for comparison */
  632. SMUDGED,
  633. /**
  634. * The entries are equal by metaData (mode, length) but differ by
  635. * modification-timestamp.
  636. */
  637. DIFFER_BY_TIMESTAMP
  638. }
  639. /**
  640. * Is the file mode of the current entry different than the given raw mode?
  641. *
  642. * @param rawMode
  643. * @return true if different, false otherwise
  644. */
  645. public boolean isModeDifferent(final int rawMode) {
  646. // Determine difference in mode-bits of file and index-entry. In the
  647. // bitwise presentation of modeDiff we'll have a '1' when the two modes
  648. // differ at this position.
  649. int modeDiff = getEntryRawMode() ^ rawMode;
  650. if (modeDiff == 0)
  651. return false;
  652. // Do not rely on filemode differences in case of symbolic links
  653. if (getOptions().getSymLinks() == SymLinks.FALSE)
  654. if (FileMode.SYMLINK.equals(rawMode))
  655. return false;
  656. // Ignore the executable file bits if WorkingTreeOptions tell me to
  657. // do so. Ignoring is done by setting the bits representing a
  658. // EXECUTABLE_FILE to '0' in modeDiff
  659. if (!state.options.isFileMode())
  660. modeDiff &= ~FileMode.EXECUTABLE_FILE.getBits();
  661. return modeDiff != 0;
  662. }
  663. /**
  664. * Compare the metadata (mode, length, modification-timestamp) of the
  665. * current entry and a {@link DirCacheEntry}
  666. *
  667. * @param entry
  668. * the {@link DirCacheEntry} to compare with
  669. * @return a {@link MetadataDiff} which tells whether and how the entries
  670. * metadata differ
  671. */
  672. public MetadataDiff compareMetadata(DirCacheEntry entry) {
  673. if (entry.isAssumeValid())
  674. return MetadataDiff.EQUAL;
  675. if (entry.isUpdateNeeded())
  676. return MetadataDiff.DIFFER_BY_METADATA;
  677. if (!entry.isSmudged() && entry.getLength() != (int) getEntryLength())
  678. return MetadataDiff.DIFFER_BY_METADATA;
  679. if (isModeDifferent(entry.getRawMode()))
  680. return MetadataDiff.DIFFER_BY_METADATA;
  681. // Git under windows only stores seconds so we round the timestamp
  682. // Java gives us if it looks like the timestamp in index is seconds
  683. // only. Otherwise we compare the timestamp at millisecond precision,
  684. // unless core.checkstat is set to "minimal", in which case we only
  685. // compare the whole second part.
  686. long cacheLastModified = entry.getLastModified();
  687. long fileLastModified = getEntryLastModified();
  688. long lastModifiedMillis = fileLastModified % 1000;
  689. long cacheMillis = cacheLastModified % 1000;
  690. if (getOptions().getCheckStat() == CheckStat.MINIMAL) {
  691. fileLastModified = fileLastModified - lastModifiedMillis;
  692. cacheLastModified = cacheLastModified - cacheMillis;
  693. } else if (cacheMillis == 0)
  694. fileLastModified = fileLastModified - lastModifiedMillis;
  695. // Some Java version on Linux return whole seconds only even when
  696. // the file systems supports more precision.
  697. else if (lastModifiedMillis == 0)
  698. cacheLastModified = cacheLastModified - cacheMillis;
  699. if (fileLastModified != cacheLastModified)
  700. return MetadataDiff.DIFFER_BY_TIMESTAMP;
  701. else if (!entry.isSmudged())
  702. // The file is clean when you look at timestamps.
  703. return MetadataDiff.EQUAL;
  704. else
  705. return MetadataDiff.SMUDGED;
  706. }
  707. /**
  708. * Checks whether this entry differs from a given entry from the
  709. * {@link DirCache}.
  710. *
  711. * File status information is used and if status is same we consider the
  712. * file identical to the state in the working directory. Native git uses
  713. * more stat fields than we have accessible in Java.
  714. *
  715. * @param entry
  716. * the entry from the dircache we want to compare against
  717. * @param forceContentCheck
  718. * True if the actual file content should be checked if
  719. * modification time differs.
  720. * @return true if content is most likely different.
  721. * @deprecated Use {@link #isModified(DirCacheEntry, boolean, ObjectReader)}
  722. */
  723. public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) {
  724. try {
  725. return isModified(entry, forceContentCheck, null);
  726. } catch (IOException e) {
  727. throw new JGitInternalException(e.getMessage(), e);
  728. }
  729. }
  730. /**
  731. * Checks whether this entry differs from a given entry from the
  732. * {@link DirCache}.
  733. *
  734. * File status information is used and if status is same we consider the
  735. * file identical to the state in the working directory. Native git uses
  736. * more stat fields than we have accessible in Java.
  737. *
  738. * @param entry
  739. * the entry from the dircache we want to compare against
  740. * @param forceContentCheck
  741. * True if the actual file content should be checked if
  742. * modification time differs.
  743. * @param reader
  744. * access to repository objects if necessary. Should not be null.
  745. * @return true if content is most likely different.
  746. * @throws IOException
  747. * @since 3.3
  748. */
  749. public boolean isModified(DirCacheEntry entry, boolean forceContentCheck,
  750. ObjectReader reader) throws IOException {
  751. MetadataDiff diff = compareMetadata(entry);
  752. switch (diff) {
  753. case DIFFER_BY_TIMESTAMP:
  754. if (forceContentCheck)
  755. // But we are told to look at content even though timestamps
  756. // tell us about modification
  757. return contentCheck(entry, reader);
  758. else
  759. // We are told to assume a modification if timestamps differs
  760. return true;
  761. case SMUDGED:
  762. // The file is clean by timestamps but the entry was smudged.
  763. // Lets do a content check
  764. return contentCheck(entry, reader);
  765. case EQUAL:
  766. return false;
  767. case DIFFER_BY_METADATA:
  768. if (mode == FileMode.SYMLINK.getBits())
  769. return contentCheck(entry, reader);
  770. return true;
  771. default:
  772. throw new IllegalStateException(MessageFormat.format(
  773. JGitText.get().unexpectedCompareResult, diff.name()));
  774. }
  775. }
  776. /**
  777. * Get the file mode to use for the current entry when it is to be updated
  778. * in the index.
  779. *
  780. * @param indexIter
  781. * {@link DirCacheIterator} positioned at the same entry as this
  782. * iterator or null if no {@link DirCacheIterator} is available
  783. * at this iterator's current entry
  784. * @return index file mode
  785. */
  786. public FileMode getIndexFileMode(final DirCacheIterator indexIter) {
  787. final FileMode wtMode = getEntryFileMode();
  788. if (indexIter == null)
  789. return wtMode;
  790. if (getOptions().isFileMode())
  791. return wtMode;
  792. final FileMode iMode = indexIter.getEntryFileMode();
  793. if (FileMode.REGULAR_FILE == wtMode
  794. && FileMode.EXECUTABLE_FILE == iMode)
  795. return iMode;
  796. if (FileMode.EXECUTABLE_FILE == wtMode
  797. && FileMode.REGULAR_FILE == iMode)
  798. return iMode;
  799. return wtMode;
  800. }
  801. /**
  802. * Compares the entries content with the content in the filesystem.
  803. * Unsmudges the entry when it is detected that it is clean.
  804. *
  805. * @param entry
  806. * the entry to be checked
  807. * @param reader
  808. * acccess to repository data if necessary
  809. * @return <code>true</code> if the content doesn't match,
  810. * <code>false</code> if it matches
  811. * @throws IOException
  812. */
  813. private boolean contentCheck(DirCacheEntry entry, ObjectReader reader)
  814. throws IOException {
  815. if (getEntryObjectId().equals(entry.getObjectId())) {
  816. // Content has not changed
  817. // We know the entry can't be racily clean because it's still clean.
  818. // Therefore we unsmudge the entry!
  819. // If by any chance we now unsmudge although we are still in the
  820. // same time-slot as the last modification to the index file the
  821. // next index write operation will smudge again.
  822. // Caution: we are unsmudging just by setting the length of the
  823. // in-memory entry object. It's the callers task to detect that we
  824. // have modified the entry and to persist the modified index.
  825. entry.setLength((int) getEntryLength());
  826. return false;
  827. } else {
  828. if (mode == FileMode.SYMLINK.getBits())
  829. return !new File(readContentAsNormalizedString(current()))
  830. .equals(new File((readContentAsNormalizedString(entry,
  831. reader))));
  832. // Content differs: that's a real change, perhaps
  833. if (reader == null) // deprecated use, do no further checks
  834. return true;
  835. switch (getOptions().getAutoCRLF()) {
  836. case INPUT:
  837. case TRUE:
  838. InputStream dcIn = null;
  839. try {
  840. ObjectLoader loader = reader.open(entry.getObjectId());
  841. if (loader == null)
  842. return true;
  843. // We need to compute the length, but only if it is not
  844. // a binary stream.
  845. dcIn = new EolCanonicalizingInputStream(
  846. loader.openStream(), true, true /* abort if binary */);
  847. long dcInLen;
  848. try {
  849. dcInLen = computeLength(dcIn);
  850. } catch (EolCanonicalizingInputStream.IsBinaryException e) {
  851. return true;
  852. } finally {
  853. dcIn.close();
  854. }
  855. dcIn = new EolCanonicalizingInputStream(
  856. loader.openStream(), true);
  857. byte[] autoCrLfHash = computeHash(dcIn, dcInLen);
  858. boolean changed = getEntryObjectId().compareTo(
  859. autoCrLfHash, 0) != 0;
  860. return changed;
  861. } catch (IOException e) {
  862. return true;
  863. } finally {
  864. if (dcIn != null)
  865. try {
  866. dcIn.close();
  867. } catch (IOException e) {
  868. // empty
  869. }
  870. }
  871. case FALSE:
  872. break;
  873. }
  874. return true;
  875. }
  876. }
  877. private static String readContentAsNormalizedString(DirCacheEntry entry,
  878. ObjectReader reader) throws MissingObjectException, IOException {
  879. ObjectLoader open = reader.open(entry.getObjectId());
  880. byte[] cachedBytes = open.getCachedBytes();
  881. return FS.detect().normalize(RawParseUtils.decode(cachedBytes));
  882. }
  883. private static String readContentAsNormalizedString(Entry entry) throws IOException {
  884. long length = entry.getLength();
  885. byte[] content = new byte[(int) length];
  886. InputStream is = entry.openInputStream();
  887. IO.readFully(is, content, 0, (int) length);
  888. return FS.detect().normalize(RawParseUtils.decode(content));
  889. }
  890. private long computeLength(InputStream in) throws IOException {
  891. // Since we only care about the length, use skip. The stream
  892. // may be able to more efficiently wade through its data.
  893. //
  894. long length = 0;
  895. for (;;) {
  896. long n = in.skip(1 << 20);
  897. if (n <= 0)
  898. break;
  899. length += n;
  900. }
  901. return length;
  902. }
  903. private byte[] computeHash(InputStream in, long length) throws IOException {
  904. final MessageDigest contentDigest = state.contentDigest;
  905. final byte[] contentReadBuffer = state.contentReadBuffer;
  906. contentDigest.reset();
  907. contentDigest.update(hblob);
  908. contentDigest.update((byte) ' ');
  909. long sz = length;
  910. if (sz == 0) {
  911. contentDigest.update((byte) '0');
  912. } else {
  913. final int bufn = contentReadBuffer.length;
  914. int p = bufn;
  915. do {
  916. contentReadBuffer[--p] = digits[(int) (sz % 10)];
  917. sz /= 10;
  918. } while (sz > 0);
  919. contentDigest.update(contentReadBuffer, p, bufn - p);
  920. }
  921. contentDigest.update((byte) 0);
  922. for (;;) {
  923. final int r = in.read(contentReadBuffer);
  924. if (r <= 0)
  925. break;
  926. contentDigest.update(contentReadBuffer, 0, r);
  927. sz += r;
  928. }
  929. if (sz != length)
  930. return zeroid;
  931. return contentDigest.digest();
  932. }
  933. /** A single entry within a working directory tree. */
  934. protected static abstract class Entry {
  935. byte[] encodedName;
  936. int encodedNameLen;
  937. void encodeName(final CharsetEncoder enc) {
  938. final ByteBuffer b;
  939. try {
  940. b = enc.encode(CharBuffer.wrap(getName()));
  941. } catch (CharacterCodingException e) {
  942. // This should so never happen.
  943. throw new RuntimeException(MessageFormat.format(
  944. JGitText.get().unencodeableFile, getName()));
  945. }
  946. encodedNameLen = b.limit();
  947. if (b.hasArray() && b.arrayOffset() == 0)
  948. encodedName = b.array();
  949. else
  950. b.get(encodedName = new byte[encodedNameLen]);
  951. }
  952. public String toString() {
  953. return getMode().toString() + " " + getName(); //$NON-NLS-1$
  954. }
  955. /**
  956. * Get the type of this entry.
  957. * <p>
  958. * <b>Note: Efficient implementation required.</b>
  959. * <p>
  960. * The implementation of this method must be efficient. If a subclass
  961. * needs to compute the value they should cache the reference within an
  962. * instance member instead.
  963. *
  964. * @return a file mode constant from {@link FileMode}.
  965. */
  966. public abstract FileMode getMode();
  967. /**
  968. * Get the byte length of this entry.
  969. * <p>
  970. * <b>Note: Efficient implementation required.</b>
  971. * <p>
  972. * The implementation of this method must be efficient. If a subclass
  973. * needs to compute the value they should cache the reference within an
  974. * instance member instead.
  975. *
  976. * @return size of this file, in bytes.
  977. */
  978. public abstract long getLength();
  979. /**
  980. * Get the last modified time of this entry.
  981. * <p>
  982. * <b>Note: Efficient implementation required.</b>
  983. * <p>
  984. * The implementation of this method must be efficient. If a subclass
  985. * needs to compute the value they should cache the reference within an
  986. * instance member instead.
  987. *
  988. * @return time since the epoch (in ms) of the last change.
  989. */
  990. public abstract long getLastModified();
  991. /**
  992. * Get the name of this entry within its directory.
  993. * <p>
  994. * Efficient implementations are not required. The caller will obtain
  995. * the name only once and cache it once obtained.
  996. *
  997. * @return name of the entry.
  998. */
  999. public abstract String getName();
  1000. /**
  1001. * Obtain an input stream to read the file content.
  1002. * <p>
  1003. * Efficient implementations are not required. The caller will usually
  1004. * obtain the stream only once per entry, if at all.
  1005. * <p>
  1006. * The input stream should not use buffering if the implementation can
  1007. * avoid it. The caller will buffer as necessary to perform efficient
  1008. * block IO operations.
  1009. * <p>
  1010. * The caller will close the stream once complete.
  1011. *
  1012. * @return a stream to read from the file.
  1013. * @throws IOException
  1014. * the file could not be opened for reading.
  1015. */
  1016. public abstract InputStream openInputStream() throws IOException;
  1017. }
  1018. /** Magic type indicating we know rules exist, but they aren't loaded. */
  1019. private static class PerDirectoryIgnoreNode extends IgnoreNode {
  1020. final Entry entry;
  1021. PerDirectoryIgnoreNode(Entry entry) {
  1022. super(Collections.<IgnoreRule> emptyList());
  1023. this.entry = entry;
  1024. }
  1025. IgnoreNode load() throws IOException {
  1026. IgnoreNode r = new IgnoreNode();
  1027. InputStream in = entry.openInputStream();
  1028. try {
  1029. r.parse(in);
  1030. } finally {
  1031. in.close();
  1032. }
  1033. return r.getRules().isEmpty() ? null : r;
  1034. }
  1035. }
  1036. /** Magic type indicating there may be rules for the top level. */
  1037. private static class RootIgnoreNode extends PerDirectoryIgnoreNode {
  1038. final Repository repository;
  1039. RootIgnoreNode(Entry entry, Repository repository) {
  1040. super(entry);
  1041. this.repository = repository;
  1042. }
  1043. @Override
  1044. IgnoreNode load() throws IOException {
  1045. IgnoreNode r;
  1046. if (entry != null) {
  1047. r = super.load();
  1048. if (r == null)
  1049. r = new IgnoreNode();
  1050. } else {
  1051. r = new IgnoreNode();
  1052. }
  1053. FS fs = repository.getFS();
  1054. String path = repository.getConfig().get(CoreConfig.KEY)
  1055. .getExcludesFile();
  1056. if (path != null) {
  1057. File excludesfile;
  1058. if (path.startsWith("~/")) //$NON-NLS-1$
  1059. excludesfile = fs.resolve(fs.userHome(), path.substring(2));
  1060. else
  1061. excludesfile = fs.resolve(null, path);
  1062. loadRulesFromFile(r, excludesfile);
  1063. }
  1064. File exclude = fs.resolve(repository.getDirectory(),
  1065. Constants.INFO_EXCLUDE);
  1066. loadRulesFromFile(r, exclude);
  1067. return r.getRules().isEmpty() ? null : r;
  1068. }
  1069. private void loadRulesFromFile(IgnoreNode r, File exclude)
  1070. throws FileNotFoundException, IOException {
  1071. if (FS.DETECTED.exists(exclude)) {
  1072. FileInputStream in = new FileInputStream(exclude);
  1073. try {
  1074. r.parse(in);
  1075. } finally {
  1076. in.close();
  1077. }
  1078. }
  1079. }
  1080. }
  1081. private static final class IteratorState {
  1082. /** Options used to process the working tree. */
  1083. final WorkingTreeOptions options;
  1084. /** File name character encoder. */
  1085. final CharsetEncoder nameEncoder;
  1086. /** Digest computer for {@link #contentId} computations. */
  1087. MessageDigest contentDigest;
  1088. /** Buffer used to perform {@link #contentId} computations. */
  1089. byte[] contentReadBuffer;
  1090. /** TreeWalk with a (supposedly) matching DirCacheIterator. */
  1091. TreeWalk walk;
  1092. /** Position of the matching {@link DirCacheIterator}. */
  1093. int dirCacheTree;
  1094. IteratorState(WorkingTreeOptions options) {
  1095. this.options = options;
  1096. this.nameEncoder = Constants.CHARSET.newEncoder();
  1097. }
  1098. void initializeDigestAndReadBuffer() {
  1099. if (contentDigest == null) {
  1100. contentDigest = Constants.newMessageDigest();
  1101. contentReadBuffer = new byte[BUFFER_SIZE];
  1102. }
  1103. }
  1104. }
  1105. }