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

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