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

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