Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

WorkingTreeIterator.java 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. * and other copyright owners as documented in the project's IP log.
  6. *
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Distribution License v1.0 which
  9. * accompanies this distribution, is reproduced below, and is
  10. * available at http://www.eclipse.org/org/documents/edl-v10.php
  11. *
  12. * All rights reserved.
  13. *
  14. * Redistribution and use in source and binary forms, with or
  15. * without modification, are permitted provided that the following
  16. * conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above
  22. * copyright notice, this list of conditions and the following
  23. * disclaimer in the documentation and/or other materials provided
  24. * with the distribution.
  25. *
  26. * - Neither the name of the Eclipse Foundation, Inc. nor the
  27. * names of its contributors may be used to endorse or promote
  28. * products derived from this software without specific prior
  29. * written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  32. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  33. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  34. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  36. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  38. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  39. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  41. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  42. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  43. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44. */
  45. package org.eclipse.jgit.treewalk;
  46. import java.io.ByteArrayInputStream;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.nio.ByteBuffer;
  52. import java.nio.CharBuffer;
  53. import java.nio.charset.CharacterCodingException;
  54. import java.nio.charset.CharsetEncoder;
  55. import java.security.MessageDigest;
  56. import java.text.MessageFormat;
  57. import java.util.Arrays;
  58. import java.util.Collections;
  59. import java.util.Comparator;
  60. import org.eclipse.jgit.JGitText;
  61. import org.eclipse.jgit.diff.RawText;
  62. import org.eclipse.jgit.dircache.DirCache;
  63. import org.eclipse.jgit.dircache.DirCacheEntry;
  64. import org.eclipse.jgit.errors.CorruptObjectException;
  65. import org.eclipse.jgit.ignore.IgnoreNode;
  66. import org.eclipse.jgit.ignore.IgnoreRule;
  67. import org.eclipse.jgit.lib.Constants;
  68. import org.eclipse.jgit.lib.FileMode;
  69. import org.eclipse.jgit.lib.Repository;
  70. import org.eclipse.jgit.util.FS;
  71. import org.eclipse.jgit.util.IO;
  72. import org.eclipse.jgit.util.io.EolCanonicalizingInputStream;
  73. /**
  74. * Walks a working directory tree as part of a {@link TreeWalk}.
  75. * <p>
  76. * Most applications will want to use the standard implementation of this
  77. * iterator, {@link FileTreeIterator}, as that does all IO through the standard
  78. * <code>java.io</code> package. Plugins for a Java based IDE may however wish
  79. * to create their own implementations of this class to allow traversal of the
  80. * IDE's project space, as well as benefit from any caching the IDE may have.
  81. *
  82. * @see FileTreeIterator
  83. */
  84. public abstract class WorkingTreeIterator extends AbstractTreeIterator {
  85. /** An empty entry array, suitable for {@link #init(Entry[])}. */
  86. protected static final Entry[] EOF = {};
  87. /** Size we perform file IO in if we have to read and hash a file. */
  88. private static final int BUFFER_SIZE = 2048;
  89. /**
  90. * Maximum size of files which may be read fully into memory for performance
  91. * reasons.
  92. */
  93. private static final long MAXIMUM_FILE_SIZE_TO_READ_FULLY = 65536;
  94. /** The {@link #idBuffer()} for the current entry. */
  95. private byte[] contentId;
  96. /** Index within {@link #entries} that {@link #contentId} came from. */
  97. private int contentIdFromPtr;
  98. /** Buffer used to perform {@link #contentId} computations. */
  99. private byte[] contentReadBuffer;
  100. /** Digest computer for {@link #contentId} computations. */
  101. private MessageDigest contentDigest;
  102. /** File name character encoder. */
  103. private final CharsetEncoder nameEncoder;
  104. /** List of entries obtained from the subclass. */
  105. private Entry[] entries;
  106. /** Total number of entries in {@link #entries} that are valid. */
  107. private int entryCnt;
  108. /** Current position within {@link #entries}. */
  109. private int ptr;
  110. /** If there is a .gitignore file present, the parsed rules from it. */
  111. private IgnoreNode ignoreNode;
  112. /** Options used to process the working tree. */
  113. private final WorkingTreeOptions options;
  114. /**
  115. * Create a new iterator with no parent.
  116. *
  117. * @param options
  118. * working tree options to be used
  119. */
  120. protected WorkingTreeIterator(WorkingTreeOptions options) {
  121. super();
  122. nameEncoder = Constants.CHARSET.newEncoder();
  123. this.options = options;
  124. }
  125. /**
  126. * Create a new iterator with no parent and a prefix.
  127. * <p>
  128. * The prefix path supplied is inserted in front of all paths generated by
  129. * this iterator. It is intended to be used when an iterator is being
  130. * created for a subsection of an overall repository and needs to be
  131. * combined with other iterators that are created to run over the entire
  132. * repository namespace.
  133. *
  134. * @param prefix
  135. * position of this iterator in the repository tree. The value
  136. * may be null or the empty string to indicate the prefix is the
  137. * root of the repository. A trailing slash ('/') is
  138. * automatically appended if the prefix does not end in '/'.
  139. * @param options
  140. * working tree options to be used
  141. */
  142. protected WorkingTreeIterator(final String prefix,
  143. WorkingTreeOptions options) {
  144. super(prefix);
  145. nameEncoder = Constants.CHARSET.newEncoder();
  146. this.options = options;
  147. }
  148. /**
  149. * Create an iterator for a subtree of an existing iterator.
  150. *
  151. * @param p
  152. * parent tree iterator.
  153. */
  154. protected WorkingTreeIterator(final WorkingTreeIterator p) {
  155. super(p);
  156. nameEncoder = p.nameEncoder;
  157. options = p.options;
  158. }
  159. /**
  160. * Initialize this iterator for the root level of a repository.
  161. * <p>
  162. * This method should only be invoked after calling {@link #init(Entry[])},
  163. * and only for the root iterator.
  164. *
  165. * @param repo
  166. * the repository.
  167. */
  168. protected void initRootIterator(Repository repo) {
  169. Entry entry;
  170. if (ignoreNode instanceof PerDirectoryIgnoreNode)
  171. entry = ((PerDirectoryIgnoreNode) ignoreNode).entry;
  172. else
  173. entry = null;
  174. ignoreNode = new RootIgnoreNode(entry, repo);
  175. }
  176. @Override
  177. public byte[] idBuffer() {
  178. if (contentIdFromPtr == ptr)
  179. return contentId;
  180. switch (mode & FileMode.TYPE_MASK) {
  181. case FileMode.TYPE_FILE:
  182. contentIdFromPtr = ptr;
  183. return contentId = idBufferBlob(entries[ptr]);
  184. case FileMode.TYPE_SYMLINK:
  185. // Java does not support symbolic links, so we should not
  186. // have reached this particular part of the walk code.
  187. //
  188. return zeroid;
  189. case FileMode.TYPE_GITLINK:
  190. // TODO: Support obtaining current HEAD SHA-1 from nested repository
  191. //
  192. return zeroid;
  193. }
  194. return zeroid;
  195. }
  196. private void initializeDigestAndReadBuffer() {
  197. if (contentDigest != null)
  198. return;
  199. if (parent == null) {
  200. contentReadBuffer = new byte[BUFFER_SIZE];
  201. contentDigest = Constants.newMessageDigest();
  202. } else {
  203. final WorkingTreeIterator p = (WorkingTreeIterator) parent;
  204. p.initializeDigestAndReadBuffer();
  205. contentReadBuffer = p.contentReadBuffer;
  206. contentDigest = p.contentDigest;
  207. }
  208. }
  209. private static final byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
  210. '7', '8', '9' };
  211. private static final byte[] hblob = Constants
  212. .encodedTypeString(Constants.OBJ_BLOB);
  213. private byte[] idBufferBlob(final Entry e) {
  214. try {
  215. final InputStream is = e.openInputStream();
  216. if (is == null)
  217. return zeroid;
  218. try {
  219. initializeDigestAndReadBuffer();
  220. final long len = e.getLength();
  221. if (!mightNeedCleaning(e))
  222. return computeHash(is, len);
  223. if (len <= MAXIMUM_FILE_SIZE_TO_READ_FULLY) {
  224. ByteBuffer rawbuf = IO.readWholeStream(is, (int) len);
  225. byte[] raw = rawbuf.array();
  226. int n = rawbuf.limit();
  227. if (!isBinary(e, raw, n)) {
  228. rawbuf = filterClean(e, raw, n);
  229. raw = rawbuf.array();
  230. n = rawbuf.limit();
  231. }
  232. return computeHash(new ByteArrayInputStream(raw, 0, n), n);
  233. }
  234. if (isBinary(e))
  235. return computeHash(is, len);
  236. final long canonLen;
  237. final InputStream lenIs = filterClean(e, e.openInputStream());
  238. try {
  239. canonLen = computeLength(lenIs);
  240. } finally {
  241. safeClose(lenIs);
  242. }
  243. return computeHash(filterClean(e, is), canonLen);
  244. } finally {
  245. safeClose(is);
  246. }
  247. } catch (IOException err) {
  248. // Can't read the file? Don't report the failure either.
  249. return zeroid;
  250. }
  251. }
  252. private static void safeClose(final InputStream in) {
  253. try {
  254. in.close();
  255. } catch (IOException err2) {
  256. // Suppress any error related to closing an input
  257. // stream. We don't care, we should not have any
  258. // outstanding data to flush or anything like that.
  259. }
  260. }
  261. private boolean mightNeedCleaning(Entry entry) {
  262. return options.isAutoCRLF();
  263. }
  264. private boolean isBinary(Entry entry, byte[] content, int sz) {
  265. return RawText.isBinary(content, sz);
  266. }
  267. private boolean isBinary(Entry entry) throws IOException {
  268. InputStream in = entry.openInputStream();
  269. try {
  270. return RawText.isBinary(in);
  271. } finally {
  272. safeClose(in);
  273. }
  274. }
  275. private ByteBuffer filterClean(Entry entry, byte[] src, int n)
  276. throws IOException {
  277. InputStream in = new ByteArrayInputStream(src);
  278. return IO.readWholeStream(filterClean(entry, in), n);
  279. }
  280. private InputStream filterClean(Entry entry, InputStream in) {
  281. return new EolCanonicalizingInputStream(in);
  282. }
  283. /**
  284. * Returns the working tree options used by this iterator.
  285. *
  286. * @return working tree options
  287. */
  288. public WorkingTreeOptions getOptions() {
  289. return options;
  290. }
  291. @Override
  292. public int idOffset() {
  293. return 0;
  294. }
  295. @Override
  296. public void reset() {
  297. if (!first()) {
  298. ptr = 0;
  299. if (!eof())
  300. parseEntry();
  301. }
  302. }
  303. @Override
  304. public boolean first() {
  305. return ptr == 0;
  306. }
  307. @Override
  308. public boolean eof() {
  309. return ptr == entryCnt;
  310. }
  311. @Override
  312. public void next(final int delta) throws CorruptObjectException {
  313. ptr += delta;
  314. if (!eof())
  315. parseEntry();
  316. }
  317. @Override
  318. public void back(final int delta) throws CorruptObjectException {
  319. ptr -= delta;
  320. parseEntry();
  321. }
  322. private void parseEntry() {
  323. final Entry e = entries[ptr];
  324. mode = e.getMode().getBits();
  325. final int nameLen = e.encodedNameLen;
  326. ensurePathCapacity(pathOffset + nameLen, pathOffset);
  327. System.arraycopy(e.encodedName, 0, path, pathOffset, nameLen);
  328. pathLen = pathOffset + nameLen;
  329. }
  330. /**
  331. * Get the byte length of this entry.
  332. *
  333. * @return size of this file, in bytes.
  334. */
  335. public long getEntryLength() {
  336. return current().getLength();
  337. }
  338. /**
  339. * Get the last modified time of this entry.
  340. *
  341. * @return last modified time of this file, in milliseconds since the epoch
  342. * (Jan 1, 1970 UTC).
  343. */
  344. public long getEntryLastModified() {
  345. return current().getLastModified();
  346. }
  347. /**
  348. * Obtain an input stream to read the file content.
  349. * <p>
  350. * Efficient implementations are not required. The caller will usually
  351. * obtain the stream only once per entry, if at all.
  352. * <p>
  353. * The input stream should not use buffering if the implementation can avoid
  354. * it. The caller will buffer as necessary to perform efficient block IO
  355. * operations.
  356. * <p>
  357. * The caller will close the stream once complete.
  358. *
  359. * @return a stream to read from the file.
  360. * @throws IOException
  361. * the file could not be opened for reading.
  362. */
  363. public InputStream openEntryStream() throws IOException {
  364. return current().openInputStream();
  365. }
  366. /**
  367. * Determine if the current entry path is ignored by an ignore rule.
  368. *
  369. * @return true if the entry was ignored by an ignore rule file.
  370. * @throws IOException
  371. * a relevant ignore rule file exists but cannot be read.
  372. */
  373. public boolean isEntryIgnored() throws IOException {
  374. return isEntryIgnored(pathLen);
  375. }
  376. /**
  377. * Determine if the entry path is ignored by an ignore rule.
  378. *
  379. * @param pLen
  380. * the length of the path in the path buffer.
  381. * @return true if the entry is ignored by an ignore rule.
  382. * @throws IOException
  383. * a relevant ignore rule file exists but cannot be read.
  384. */
  385. protected boolean isEntryIgnored(final int pLen) throws IOException {
  386. IgnoreNode rules = getIgnoreNode();
  387. if (rules != null) {
  388. // The ignore code wants path to start with a '/' if possible.
  389. // If we have the '/' in our path buffer because we are inside
  390. // a subdirectory include it in the range we convert to string.
  391. //
  392. int pOff = pathOffset;
  393. if (0 < pOff)
  394. pOff--;
  395. String p = TreeWalk.pathOf(path, pOff, pLen);
  396. switch (rules.isIgnored(p, FileMode.TREE.equals(mode))) {
  397. case IGNORED:
  398. return true;
  399. case NOT_IGNORED:
  400. return false;
  401. case CHECK_PARENT:
  402. break;
  403. }
  404. }
  405. if (parent instanceof WorkingTreeIterator)
  406. return ((WorkingTreeIterator) parent).isEntryIgnored(pLen);
  407. return false;
  408. }
  409. private IgnoreNode getIgnoreNode() throws IOException {
  410. if (ignoreNode instanceof PerDirectoryIgnoreNode)
  411. ignoreNode = ((PerDirectoryIgnoreNode) ignoreNode).load();
  412. return ignoreNode;
  413. }
  414. private static final Comparator<Entry> ENTRY_CMP = new Comparator<Entry>() {
  415. public int compare(final Entry o1, final Entry o2) {
  416. final byte[] a = o1.encodedName;
  417. final byte[] b = o2.encodedName;
  418. final int aLen = o1.encodedNameLen;
  419. final int bLen = o2.encodedNameLen;
  420. int cPos;
  421. for (cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
  422. final int cmp = (a[cPos] & 0xff) - (b[cPos] & 0xff);
  423. if (cmp != 0)
  424. return cmp;
  425. }
  426. if (cPos < aLen)
  427. return (a[cPos] & 0xff) - lastPathChar(o2);
  428. if (cPos < bLen)
  429. return lastPathChar(o1) - (b[cPos] & 0xff);
  430. return lastPathChar(o1) - lastPathChar(o2);
  431. }
  432. };
  433. static int lastPathChar(final Entry e) {
  434. return e.getMode() == FileMode.TREE ? '/' : '\0';
  435. }
  436. /**
  437. * Constructor helper.
  438. *
  439. * @param list
  440. * files in the subtree of the work tree this iterator operates
  441. * on
  442. */
  443. protected void init(final Entry[] list) {
  444. // Filter out nulls, . and .. as these are not valid tree entries,
  445. // also cache the encoded forms of the path names for efficient use
  446. // later on during sorting and iteration.
  447. //
  448. entries = list;
  449. int i, o;
  450. for (i = 0, o = 0; i < entries.length; i++) {
  451. final Entry e = entries[i];
  452. if (e == null)
  453. continue;
  454. final String name = e.getName();
  455. if (".".equals(name) || "..".equals(name))
  456. continue;
  457. if (Constants.DOT_GIT.equals(name))
  458. continue;
  459. if (Constants.DOT_GIT_IGNORE.equals(name))
  460. ignoreNode = new PerDirectoryIgnoreNode(e);
  461. if (i != o)
  462. entries[o] = e;
  463. e.encodeName(nameEncoder);
  464. o++;
  465. }
  466. entryCnt = o;
  467. Arrays.sort(entries, 0, entryCnt, ENTRY_CMP);
  468. contentIdFromPtr = -1;
  469. ptr = 0;
  470. if (!eof())
  471. parseEntry();
  472. }
  473. /**
  474. * Obtain the current entry from this iterator.
  475. *
  476. * @return the currently selected entry.
  477. */
  478. protected Entry current() {
  479. return entries[ptr];
  480. }
  481. /**
  482. * Checks whether this entry differs from a given entry from the
  483. * {@link DirCache}.
  484. *
  485. * File status information is used and if status is same we consider the
  486. * file identical to the state in the working directory. Native git uses
  487. * more stat fields than we have accessible in Java.
  488. *
  489. * @param entry
  490. * the entry from the dircache we want to compare against
  491. * @param forceContentCheck
  492. * True if the actual file content should be checked if
  493. * modification time differs.
  494. * @param checkFilemode
  495. * whether the executable-bit in the filemode should be checked
  496. * to detect modifications
  497. * @param fs
  498. * The filesystem this repo uses. Needed to find out whether the
  499. * executable-bits are supported
  500. *
  501. * @return true if content is most likely different.
  502. */
  503. public boolean isModified(DirCacheEntry entry, boolean forceContentCheck,
  504. boolean checkFilemode, FS fs) {
  505. if (entry.isAssumeValid())
  506. return false;
  507. if (entry.isUpdateNeeded())
  508. return true;
  509. if (!entry.isSmudged() && (getEntryLength() != entry.getLength()))
  510. return true;
  511. // Determine difference in mode-bits of file and index-entry. In the
  512. // bitwise presentation of modeDiff we'll have a '1' when the two modes
  513. // differ at this position.
  514. int modeDiff = getEntryRawMode() ^ entry.getRawMode();
  515. // Ignore the executable file bits if checkFilemode tells me to do so.
  516. // Ignoring is done by setting the bits representing a EXECUTABLE_FILE
  517. // to '0' in modeDiff
  518. if (!checkFilemode)
  519. modeDiff &= ~FileMode.EXECUTABLE_FILE.getBits();
  520. if (modeDiff != 0)
  521. // Report a modification if the modes still (after potentially
  522. // ignoring EXECUTABLE_FILE bits) differ
  523. return true;
  524. // Git under windows only stores seconds so we round the timestamp
  525. // Java gives us if it looks like the timestamp in index is seconds
  526. // only. Otherwise we compare the timestamp at millisecond precision.
  527. long cacheLastModified = entry.getLastModified();
  528. long fileLastModified = getEntryLastModified();
  529. if (cacheLastModified % 1000 == 0)
  530. fileLastModified = fileLastModified - fileLastModified % 1000;
  531. if (fileLastModified != cacheLastModified) {
  532. // The file is dirty by timestamps
  533. if (forceContentCheck) {
  534. // But we are told to look at content even though timestamps
  535. // tell us about modification
  536. return contentCheck(entry);
  537. } else {
  538. // We are told to assume a modification if timestamps differs
  539. return true;
  540. }
  541. } else {
  542. // The file is clean when you look at timestamps.
  543. if (entry.isSmudged()) {
  544. // The file is clean by timestamps but the entry was smudged.
  545. // Lets do a content check
  546. return contentCheck(entry);
  547. } else {
  548. // The file is clean by timestamps and the entry is not
  549. // smudged: Can't get any cleaner!
  550. return false;
  551. }
  552. }
  553. }
  554. /**
  555. * Compares the entries content with the content in the filesystem.
  556. * Unsmudges the entry when it is detected that it is clean.
  557. *
  558. * @param entry
  559. * the entry to be checked
  560. * @return <code>true</code> if the content matches, <code>false</code>
  561. * otherwise
  562. */
  563. private boolean contentCheck(DirCacheEntry entry) {
  564. if (getEntryObjectId().equals(entry.getObjectId())) {
  565. // Content has not changed
  566. // We know the entry can't be racily clean because it's still clean.
  567. // Therefore we unsmudge the entry!
  568. // If by any chance we now unsmudge although we are still in the
  569. // same time-slot as the last modification to the index file the
  570. // next index write operation will smudge again.
  571. // Caution: we are unsmudging just by setting the length of the
  572. // in-memory entry object. It's the callers task to detect that we
  573. // have modified the entry and to persist the modified index.
  574. entry.setLength((int) getEntryLength());
  575. return false;
  576. } else {
  577. // Content differs: that's a real change!
  578. return true;
  579. }
  580. }
  581. private long computeLength(InputStream in) throws IOException {
  582. // Since we only care about the length, use skip. The stream
  583. // may be able to more efficiently wade through its data.
  584. //
  585. long length = 0;
  586. for (;;) {
  587. long n = in.skip(1 << 20);
  588. if (n <= 0)
  589. break;
  590. length += n;
  591. }
  592. return length;
  593. }
  594. private byte[] computeHash(InputStream in, long length) throws IOException {
  595. contentDigest.reset();
  596. contentDigest.update(hblob);
  597. contentDigest.update((byte) ' ');
  598. long sz = length;
  599. if (sz == 0) {
  600. contentDigest.update((byte) '0');
  601. } else {
  602. final int bufn = contentReadBuffer.length;
  603. int p = bufn;
  604. do {
  605. contentReadBuffer[--p] = digits[(int) (sz % 10)];
  606. sz /= 10;
  607. } while (sz > 0);
  608. contentDigest.update(contentReadBuffer, p, bufn - p);
  609. }
  610. contentDigest.update((byte) 0);
  611. for (;;) {
  612. final int r = in.read(contentReadBuffer);
  613. if (r <= 0)
  614. break;
  615. contentDigest.update(contentReadBuffer, 0, r);
  616. sz += r;
  617. }
  618. if (sz != length)
  619. return zeroid;
  620. return contentDigest.digest();
  621. }
  622. /** A single entry within a working directory tree. */
  623. protected static abstract class Entry {
  624. byte[] encodedName;
  625. int encodedNameLen;
  626. void encodeName(final CharsetEncoder enc) {
  627. final ByteBuffer b;
  628. try {
  629. b = enc.encode(CharBuffer.wrap(getName()));
  630. } catch (CharacterCodingException e) {
  631. // This should so never happen.
  632. throw new RuntimeException(MessageFormat.format(
  633. JGitText.get().unencodeableFile, getName()));
  634. }
  635. encodedNameLen = b.limit();
  636. if (b.hasArray() && b.arrayOffset() == 0)
  637. encodedName = b.array();
  638. else
  639. b.get(encodedName = new byte[encodedNameLen]);
  640. }
  641. public String toString() {
  642. return getMode().toString() + " " + getName();
  643. }
  644. /**
  645. * Get the type of this entry.
  646. * <p>
  647. * <b>Note: Efficient implementation required.</b>
  648. * <p>
  649. * The implementation of this method must be efficient. If a subclass
  650. * needs to compute the value they should cache the reference within an
  651. * instance member instead.
  652. *
  653. * @return a file mode constant from {@link FileMode}.
  654. */
  655. public abstract FileMode getMode();
  656. /**
  657. * Get the byte length of this entry.
  658. * <p>
  659. * <b>Note: Efficient implementation required.</b>
  660. * <p>
  661. * The implementation of this method must be efficient. If a subclass
  662. * needs to compute the value they should cache the reference within an
  663. * instance member instead.
  664. *
  665. * @return size of this file, in bytes.
  666. */
  667. public abstract long getLength();
  668. /**
  669. * Get the last modified time of this entry.
  670. * <p>
  671. * <b>Note: Efficient implementation required.</b>
  672. * <p>
  673. * The implementation of this method must be efficient. If a subclass
  674. * needs to compute the value they should cache the reference within an
  675. * instance member instead.
  676. *
  677. * @return time since the epoch (in ms) of the last change.
  678. */
  679. public abstract long getLastModified();
  680. /**
  681. * Get the name of this entry within its directory.
  682. * <p>
  683. * Efficient implementations are not required. The caller will obtain
  684. * the name only once and cache it once obtained.
  685. *
  686. * @return name of the entry.
  687. */
  688. public abstract String getName();
  689. /**
  690. * Obtain an input stream to read the file content.
  691. * <p>
  692. * Efficient implementations are not required. The caller will usually
  693. * obtain the stream only once per entry, if at all.
  694. * <p>
  695. * The input stream should not use buffering if the implementation can
  696. * avoid it. The caller will buffer as necessary to perform efficient
  697. * block IO operations.
  698. * <p>
  699. * The caller will close the stream once complete.
  700. *
  701. * @return a stream to read from the file.
  702. * @throws IOException
  703. * the file could not be opened for reading.
  704. */
  705. public abstract InputStream openInputStream() throws IOException;
  706. }
  707. /** Magic type indicating we know rules exist, but they aren't loaded. */
  708. private static class PerDirectoryIgnoreNode extends IgnoreNode {
  709. final Entry entry;
  710. PerDirectoryIgnoreNode(Entry entry) {
  711. super(Collections.<IgnoreRule> emptyList());
  712. this.entry = entry;
  713. }
  714. IgnoreNode load() throws IOException {
  715. IgnoreNode r = new IgnoreNode();
  716. InputStream in = entry.openInputStream();
  717. try {
  718. r.parse(in);
  719. } finally {
  720. in.close();
  721. }
  722. return r.getRules().isEmpty() ? null : r;
  723. }
  724. }
  725. /** Magic type indicating there may be rules for the top level. */
  726. private static class RootIgnoreNode extends PerDirectoryIgnoreNode {
  727. final Repository repository;
  728. RootIgnoreNode(Entry entry, Repository repository) {
  729. super(entry);
  730. this.repository = repository;
  731. }
  732. @Override
  733. IgnoreNode load() throws IOException {
  734. IgnoreNode r;
  735. if (entry != null) {
  736. r = super.load();
  737. if (r == null)
  738. r = new IgnoreNode();
  739. } else {
  740. r = new IgnoreNode();
  741. }
  742. File exclude = new File(repository.getDirectory(), "info/exclude");
  743. if (exclude.exists()) {
  744. FileInputStream in = new FileInputStream(exclude);
  745. try {
  746. r.parse(in);
  747. } finally {
  748. in.close();
  749. }
  750. }
  751. return r.getRules().isEmpty() ? null : r;
  752. }
  753. }
  754. }