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

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