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.

DirCache.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * Copyright (C) 2011, 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.dircache;
  46. import java.io.BufferedInputStream;
  47. import java.io.EOFException;
  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.io.OutputStream;
  54. import java.io.UnsupportedEncodingException;
  55. import java.security.DigestOutputStream;
  56. import java.security.MessageDigest;
  57. import java.text.MessageFormat;
  58. import java.util.Arrays;
  59. import java.util.Comparator;
  60. import org.eclipse.jgit.errors.CorruptObjectException;
  61. import org.eclipse.jgit.errors.LockFailedException;
  62. import org.eclipse.jgit.errors.UnmergedPathException;
  63. import org.eclipse.jgit.events.IndexChangedEvent;
  64. import org.eclipse.jgit.events.IndexChangedListener;
  65. import org.eclipse.jgit.internal.JGitText;
  66. import org.eclipse.jgit.lib.Constants;
  67. import org.eclipse.jgit.lib.ObjectId;
  68. import org.eclipse.jgit.lib.ObjectInserter;
  69. import org.eclipse.jgit.storage.file.FileSnapshot;
  70. import org.eclipse.jgit.storage.file.LockFile;
  71. import org.eclipse.jgit.util.FS;
  72. import org.eclipse.jgit.util.IO;
  73. import org.eclipse.jgit.util.MutableInteger;
  74. import org.eclipse.jgit.util.NB;
  75. import org.eclipse.jgit.util.TemporaryBuffer;
  76. import org.eclipse.jgit.util.io.SafeBufferedOutputStream;
  77. /**
  78. * Support for the Git dircache (aka index file).
  79. * <p>
  80. * The index file keeps track of which objects are currently checked out in the
  81. * working directory, and the last modified time of those working files. Changes
  82. * in the working directory can be detected by comparing the modification times
  83. * to the cached modification time within the index file.
  84. * <p>
  85. * Index files are also used during merges, where the merge happens within the
  86. * index file first, and the working directory is updated as a post-merge step.
  87. * Conflicts are stored in the index file to allow tool (and human) based
  88. * resolutions to be easily performed.
  89. */
  90. public class DirCache {
  91. private static final byte[] SIG_DIRC = { 'D', 'I', 'R', 'C' };
  92. private static final int EXT_TREE = 0x54524545 /* 'TREE' */;
  93. private static final DirCacheEntry[] NO_ENTRIES = {};
  94. private static final byte[] NO_CHECKSUM = {};
  95. static final Comparator<DirCacheEntry> ENT_CMP = new Comparator<DirCacheEntry>() {
  96. public int compare(final DirCacheEntry o1, final DirCacheEntry o2) {
  97. final int cr = cmp(o1, o2);
  98. if (cr != 0)
  99. return cr;
  100. return o1.getStage() - o2.getStage();
  101. }
  102. };
  103. static int cmp(final DirCacheEntry a, final DirCacheEntry b) {
  104. return cmp(a.path, a.path.length, b);
  105. }
  106. static int cmp(final byte[] aPath, final int aLen, final DirCacheEntry b) {
  107. return cmp(aPath, aLen, b.path, b.path.length);
  108. }
  109. static int cmp(final byte[] aPath, final int aLen, final byte[] bPath,
  110. final int bLen) {
  111. for (int cPos = 0; cPos < aLen && cPos < bLen; cPos++) {
  112. final int cmp = (aPath[cPos] & 0xff) - (bPath[cPos] & 0xff);
  113. if (cmp != 0)
  114. return cmp;
  115. }
  116. return aLen - bLen;
  117. }
  118. /**
  119. * Create a new empty index which is never stored on disk.
  120. *
  121. * @return an empty cache which has no backing store file. The cache may not
  122. * be read or written, but it may be queried and updated (in
  123. * memory).
  124. */
  125. public static DirCache newInCore() {
  126. return new DirCache(null, null);
  127. }
  128. /**
  129. * Create a new in-core index representation and read an index from disk.
  130. * <p>
  131. * The new index will be read before it is returned to the caller. Read
  132. * failures are reported as exceptions and therefore prevent the method from
  133. * returning a partially populated index.
  134. *
  135. * @param indexLocation
  136. * location of the index file on disk.
  137. * @param fs
  138. * the file system abstraction which will be necessary to perform
  139. * certain file system operations.
  140. * @return a cache representing the contents of the specified index file (if
  141. * it exists) or an empty cache if the file does not exist.
  142. * @throws IOException
  143. * the index file is present but could not be read.
  144. * @throws CorruptObjectException
  145. * the index file is using a format or extension that this
  146. * library does not support.
  147. */
  148. public static DirCache read(final File indexLocation, final FS fs)
  149. throws CorruptObjectException, IOException {
  150. final DirCache c = new DirCache(indexLocation, fs);
  151. c.read();
  152. return c;
  153. }
  154. /**
  155. * Create a new in-core index representation, lock it, and read from disk.
  156. * <p>
  157. * The new index will be locked and then read before it is returned to the
  158. * caller. Read failures are reported as exceptions and therefore prevent
  159. * the method from returning a partially populated index. On read failure,
  160. * the lock is released.
  161. *
  162. * @param indexLocation
  163. * location of the index file on disk.
  164. * @param fs
  165. * the file system abstraction which will be necessary to perform
  166. * certain file system operations.
  167. * @return a cache representing the contents of the specified index file (if
  168. * it exists) or an empty cache if the file does not exist.
  169. * @throws IOException
  170. * the index file is present but could not be read, or the lock
  171. * could not be obtained.
  172. * @throws CorruptObjectException
  173. * the index file is using a format or extension that this
  174. * library does not support.
  175. */
  176. public static DirCache lock(final File indexLocation, final FS fs)
  177. throws CorruptObjectException, IOException {
  178. final DirCache c = new DirCache(indexLocation, fs);
  179. if (!c.lock())
  180. throw new LockFailedException(indexLocation);
  181. try {
  182. c.read();
  183. } catch (IOException e) {
  184. c.unlock();
  185. throw e;
  186. } catch (RuntimeException e) {
  187. c.unlock();
  188. throw e;
  189. } catch (Error e) {
  190. c.unlock();
  191. throw e;
  192. }
  193. return c;
  194. }
  195. /**
  196. * Create a new in-core index representation, lock it, and read from disk.
  197. * <p>
  198. * The new index will be locked and then read before it is returned to the
  199. * caller. Read failures are reported as exceptions and therefore prevent
  200. * the method from returning a partially populated index. On read failure,
  201. * the lock is released.
  202. *
  203. * @param indexLocation
  204. * location of the index file on disk.
  205. * @param fs
  206. * the file system abstraction which will be necessary to perform
  207. * certain file system operations.
  208. * @param indexChangedListener
  209. * listener to be informed when DirCache is committed
  210. * @return a cache representing the contents of the specified index file (if
  211. * it exists) or an empty cache if the file does not exist.
  212. * @throws IOException
  213. * the index file is present but could not be read, or the lock
  214. * could not be obtained.
  215. * @throws CorruptObjectException
  216. * the index file is using a format or extension that this
  217. * library does not support.
  218. */
  219. public static DirCache lock(final File indexLocation, final FS fs,
  220. IndexChangedListener indexChangedListener)
  221. throws CorruptObjectException,
  222. IOException {
  223. DirCache c = lock(indexLocation, fs);
  224. c.registerIndexChangedListener(indexChangedListener);
  225. return c;
  226. }
  227. /** Location of the current version of the index file. */
  228. private final File liveFile;
  229. /** Individual file index entries, sorted by path name. */
  230. private DirCacheEntry[] sortedEntries;
  231. /** Number of positions within {@link #sortedEntries} that are valid. */
  232. private int entryCnt;
  233. /** Cache tree for this index; null if the cache tree is not available. */
  234. private DirCacheTree tree;
  235. /** Our active lock (if we hold it); null if we don't have it locked. */
  236. private LockFile myLock;
  237. /** file system abstraction **/
  238. private final FS fs;
  239. /** Keep track of whether the index has changed or not */
  240. private FileSnapshot snapshot;
  241. /** index checksum when index was read from disk */
  242. private byte[] readIndexChecksum;
  243. /** index checksum when index was written to disk */
  244. private byte[] writeIndexChecksum;
  245. /** listener to be informed on commit */
  246. private IndexChangedListener indexChangedListener;
  247. /**
  248. * Create a new in-core index representation.
  249. * <p>
  250. * The new index will be empty. Callers may wish to read from the on disk
  251. * file first with {@link #read()}.
  252. *
  253. * @param indexLocation
  254. * location of the index file on disk.
  255. * @param fs
  256. * the file system abstraction which will be necessary to perform
  257. * certain file system operations.
  258. */
  259. public DirCache(final File indexLocation, final FS fs) {
  260. liveFile = indexLocation;
  261. this.fs = fs;
  262. clear();
  263. }
  264. /**
  265. * Create a new builder to update this cache.
  266. * <p>
  267. * Callers should add all entries to the builder, then use
  268. * {@link DirCacheBuilder#finish()} to update this instance.
  269. *
  270. * @return a new builder instance for this cache.
  271. */
  272. public DirCacheBuilder builder() {
  273. return new DirCacheBuilder(this, entryCnt + 16);
  274. }
  275. /**
  276. * Create a new editor to recreate this cache.
  277. * <p>
  278. * Callers should add commands to the editor, then use
  279. * {@link DirCacheEditor#finish()} to update this instance.
  280. *
  281. * @return a new builder instance for this cache.
  282. */
  283. public DirCacheEditor editor() {
  284. return new DirCacheEditor(this, entryCnt + 16);
  285. }
  286. void replace(final DirCacheEntry[] e, final int cnt) {
  287. sortedEntries = e;
  288. entryCnt = cnt;
  289. tree = null;
  290. }
  291. /**
  292. * Read the index from disk, if it has changed on disk.
  293. * <p>
  294. * This method tries to avoid loading the index if it has not changed since
  295. * the last time we consulted it. A missing index file will be treated as
  296. * though it were present but had no file entries in it.
  297. *
  298. * @throws IOException
  299. * the index file is present but could not be read. This
  300. * DirCache instance may not be populated correctly.
  301. * @throws CorruptObjectException
  302. * the index file is using a format or extension that this
  303. * library does not support.
  304. */
  305. public void read() throws IOException, CorruptObjectException {
  306. if (liveFile == null)
  307. throw new IOException(JGitText.get().dirCacheDoesNotHaveABackingFile);
  308. if (!liveFile.exists())
  309. clear();
  310. else if (snapshot == null || snapshot.isModified(liveFile)) {
  311. try {
  312. final FileInputStream inStream = new FileInputStream(liveFile);
  313. try {
  314. clear();
  315. readFrom(inStream);
  316. } finally {
  317. try {
  318. inStream.close();
  319. } catch (IOException err2) {
  320. // Ignore any close failures.
  321. }
  322. }
  323. } catch (FileNotFoundException fnfe) {
  324. // Someone must have deleted it between our exists test
  325. // and actually opening the path. That's fine, its empty.
  326. //
  327. clear();
  328. }
  329. snapshot = FileSnapshot.save(liveFile);
  330. }
  331. }
  332. /**
  333. * @return true if the memory state differs from the index file
  334. * @throws IOException
  335. */
  336. public boolean isOutdated() throws IOException {
  337. if (liveFile == null || !liveFile.exists())
  338. return false;
  339. return snapshot == null || snapshot.isModified(liveFile);
  340. }
  341. /** Empty this index, removing all entries. */
  342. public void clear() {
  343. snapshot = null;
  344. sortedEntries = NO_ENTRIES;
  345. entryCnt = 0;
  346. tree = null;
  347. readIndexChecksum = NO_CHECKSUM;
  348. }
  349. private void readFrom(final InputStream inStream) throws IOException,
  350. CorruptObjectException {
  351. final BufferedInputStream in = new BufferedInputStream(inStream);
  352. final MessageDigest md = Constants.newMessageDigest();
  353. // Read the index header and verify we understand it.
  354. //
  355. final byte[] hdr = new byte[20];
  356. IO.readFully(in, hdr, 0, 12);
  357. md.update(hdr, 0, 12);
  358. if (!is_DIRC(hdr))
  359. throw new CorruptObjectException(JGitText.get().notADIRCFile);
  360. final int ver = NB.decodeInt32(hdr, 4);
  361. boolean extended = false;
  362. if (ver == 3)
  363. extended = true;
  364. else if (ver != 2)
  365. throw new CorruptObjectException(MessageFormat.format(
  366. JGitText.get().unknownDIRCVersion, Integer.valueOf(ver)));
  367. entryCnt = NB.decodeInt32(hdr, 8);
  368. if (entryCnt < 0)
  369. throw new CorruptObjectException(JGitText.get().DIRCHasTooManyEntries);
  370. snapshot = FileSnapshot.save(liveFile);
  371. int smudge_s = (int) (snapshot.lastModified() / 1000);
  372. int smudge_ns = ((int) (snapshot.lastModified() % 1000)) * 1000000;
  373. // Load the individual file entries.
  374. //
  375. final int infoLength = DirCacheEntry.getMaximumInfoLength(extended);
  376. final byte[] infos = new byte[infoLength * entryCnt];
  377. sortedEntries = new DirCacheEntry[entryCnt];
  378. final MutableInteger infoAt = new MutableInteger();
  379. for (int i = 0; i < entryCnt; i++)
  380. sortedEntries[i] = new DirCacheEntry(infos, infoAt, in, md, smudge_s, smudge_ns);
  381. // After the file entries are index extensions, and then a footer.
  382. //
  383. for (;;) {
  384. in.mark(21);
  385. IO.readFully(in, hdr, 0, 20);
  386. if (in.read() < 0) {
  387. // No extensions present; the file ended where we expected.
  388. //
  389. break;
  390. }
  391. in.reset();
  392. md.update(hdr, 0, 8);
  393. IO.skipFully(in, 8);
  394. long sz = NB.decodeUInt32(hdr, 4);
  395. switch (NB.decodeInt32(hdr, 0)) {
  396. case EXT_TREE: {
  397. if (Integer.MAX_VALUE < sz) {
  398. throw new CorruptObjectException(MessageFormat.format(
  399. JGitText.get().DIRCExtensionIsTooLargeAt,
  400. formatExtensionName(hdr), Long.valueOf(sz)));
  401. }
  402. final byte[] raw = new byte[(int) sz];
  403. IO.readFully(in, raw, 0, raw.length);
  404. md.update(raw, 0, raw.length);
  405. tree = new DirCacheTree(raw, new MutableInteger(), null);
  406. break;
  407. }
  408. default:
  409. if (hdr[0] >= 'A' && hdr[0] <= 'Z') {
  410. // The extension is optional and is here only as
  411. // a performance optimization. Since we do not
  412. // understand it, we can safely skip past it, after
  413. // we include its data in our checksum.
  414. //
  415. skipOptionalExtension(in, md, hdr, sz);
  416. } else {
  417. // The extension is not an optimization and is
  418. // _required_ to understand this index format.
  419. // Since we did not trap it above we must abort.
  420. //
  421. throw new CorruptObjectException(MessageFormat.format(JGitText.get().DIRCExtensionNotSupportedByThisVersion
  422. , formatExtensionName(hdr)));
  423. }
  424. }
  425. }
  426. readIndexChecksum = md.digest();
  427. if (!Arrays.equals(readIndexChecksum, hdr)) {
  428. throw new CorruptObjectException(JGitText.get().DIRCChecksumMismatch);
  429. }
  430. }
  431. private void skipOptionalExtension(final InputStream in,
  432. final MessageDigest md, final byte[] hdr, long sz)
  433. throws IOException {
  434. final byte[] b = new byte[4096];
  435. while (0 < sz) {
  436. int n = in.read(b, 0, (int) Math.min(b.length, sz));
  437. if (n < 0) {
  438. throw new EOFException(
  439. MessageFormat.format(
  440. JGitText.get().shortReadOfOptionalDIRCExtensionExpectedAnotherBytes,
  441. formatExtensionName(hdr), Long.valueOf(sz)));
  442. }
  443. md.update(b, 0, n);
  444. sz -= n;
  445. }
  446. }
  447. private static String formatExtensionName(final byte[] hdr)
  448. throws UnsupportedEncodingException {
  449. return "'" + new String(hdr, 0, 4, "ISO-8859-1") + "'";
  450. }
  451. private static boolean is_DIRC(final byte[] hdr) {
  452. if (hdr.length < SIG_DIRC.length)
  453. return false;
  454. for (int i = 0; i < SIG_DIRC.length; i++)
  455. if (hdr[i] != SIG_DIRC[i])
  456. return false;
  457. return true;
  458. }
  459. /**
  460. * Try to establish an update lock on the cache file.
  461. *
  462. * @return true if the lock is now held by the caller; false if it is held
  463. * by someone else.
  464. * @throws IOException
  465. * the output file could not be created. The caller does not
  466. * hold the lock.
  467. */
  468. public boolean lock() throws IOException {
  469. if (liveFile == null)
  470. throw new IOException(JGitText.get().dirCacheDoesNotHaveABackingFile);
  471. final LockFile tmp = new LockFile(liveFile, fs);
  472. if (tmp.lock()) {
  473. tmp.setNeedStatInformation(true);
  474. myLock = tmp;
  475. return true;
  476. }
  477. return false;
  478. }
  479. /**
  480. * Write the entry records from memory to disk.
  481. * <p>
  482. * The cache must be locked first by calling {@link #lock()} and receiving
  483. * true as the return value. Applications are encouraged to lock the index,
  484. * then invoke {@link #read()} to ensure the in-memory data is current,
  485. * prior to updating the in-memory entries.
  486. * <p>
  487. * Once written the lock is closed and must be either committed with
  488. * {@link #commit()} or rolled back with {@link #unlock()}.
  489. *
  490. * @throws IOException
  491. * the output file could not be created. The caller no longer
  492. * holds the lock.
  493. */
  494. public void write() throws IOException {
  495. final LockFile tmp = myLock;
  496. requireLocked(tmp);
  497. try {
  498. writeTo(new SafeBufferedOutputStream(tmp.getOutputStream()));
  499. } catch (IOException err) {
  500. tmp.unlock();
  501. throw err;
  502. } catch (RuntimeException err) {
  503. tmp.unlock();
  504. throw err;
  505. } catch (Error err) {
  506. tmp.unlock();
  507. throw err;
  508. }
  509. }
  510. void writeTo(final OutputStream os) throws IOException {
  511. final MessageDigest foot = Constants.newMessageDigest();
  512. final DigestOutputStream dos = new DigestOutputStream(os, foot);
  513. boolean extended = false;
  514. for (int i = 0; i < entryCnt; i++)
  515. extended |= sortedEntries[i].isExtended();
  516. // Write the header.
  517. //
  518. final byte[] tmp = new byte[128];
  519. System.arraycopy(SIG_DIRC, 0, tmp, 0, SIG_DIRC.length);
  520. NB.encodeInt32(tmp, 4, extended ? 3 : 2);
  521. NB.encodeInt32(tmp, 8, entryCnt);
  522. dos.write(tmp, 0, 12);
  523. // Write the individual file entries.
  524. final int smudge_s;
  525. final int smudge_ns;
  526. if (myLock != null) {
  527. // For new files we need to smudge the index entry
  528. // if they have been modified "now". Ideally we'd
  529. // want the timestamp when we're done writing the index,
  530. // so we use the current timestamp as a approximation.
  531. myLock.createCommitSnapshot();
  532. snapshot = myLock.getCommitSnapshot();
  533. smudge_s = (int) (snapshot.lastModified() / 1000);
  534. smudge_ns = ((int) (snapshot.lastModified() % 1000)) * 1000000;
  535. } else {
  536. // Used in unit tests only
  537. smudge_ns = 0;
  538. smudge_s = 0;
  539. }
  540. for (int i = 0; i < entryCnt; i++) {
  541. final DirCacheEntry e = sortedEntries[i];
  542. if (e.mightBeRacilyClean(smudge_s, smudge_ns))
  543. e.smudgeRacilyClean();
  544. e.write(dos);
  545. }
  546. if (tree != null) {
  547. final TemporaryBuffer bb = new TemporaryBuffer.LocalFile();
  548. tree.write(tmp, bb);
  549. bb.close();
  550. NB.encodeInt32(tmp, 0, EXT_TREE);
  551. NB.encodeInt32(tmp, 4, (int) bb.length());
  552. dos.write(tmp, 0, 8);
  553. bb.writeTo(dos, null);
  554. }
  555. writeIndexChecksum = foot.digest();
  556. os.write(writeIndexChecksum);
  557. os.close();
  558. }
  559. /**
  560. * Commit this change and release the lock.
  561. * <p>
  562. * If this method fails (returns false) the lock is still released.
  563. *
  564. * @return true if the commit was successful and the file contains the new
  565. * data; false if the commit failed and the file remains with the
  566. * old data.
  567. * @throws IllegalStateException
  568. * the lock is not held.
  569. */
  570. public boolean commit() {
  571. final LockFile tmp = myLock;
  572. requireLocked(tmp);
  573. myLock = null;
  574. if (!tmp.commit())
  575. return false;
  576. snapshot = tmp.getCommitSnapshot();
  577. if (indexChangedListener != null
  578. && !Arrays.equals(readIndexChecksum, writeIndexChecksum))
  579. indexChangedListener.onIndexChanged(new IndexChangedEvent());
  580. return true;
  581. }
  582. private void requireLocked(final LockFile tmp) {
  583. if (liveFile == null)
  584. throw new IllegalStateException(JGitText.get().dirCacheIsNotLocked);
  585. if (tmp == null)
  586. throw new IllegalStateException(MessageFormat.format(JGitText.get().dirCacheFileIsNotLocked
  587. , liveFile.getAbsolutePath()));
  588. }
  589. /**
  590. * Unlock this file and abort this change.
  591. * <p>
  592. * The temporary file (if created) is deleted before returning.
  593. */
  594. public void unlock() {
  595. final LockFile tmp = myLock;
  596. if (tmp != null) {
  597. myLock = null;
  598. tmp.unlock();
  599. }
  600. }
  601. /**
  602. * Locate the position a path's entry is at in the index.
  603. * <p>
  604. * If there is at least one entry in the index for this path the position of
  605. * the lowest stage is returned. Subsequent stages can be identified by
  606. * testing consecutive entries until the path differs.
  607. * <p>
  608. * If no path matches the entry -(position+1) is returned, where position is
  609. * the location it would have gone within the index.
  610. *
  611. * @param path
  612. * the path to search for.
  613. * @return if >= 0 then the return value is the position of the entry in the
  614. * index; pass to {@link #getEntry(int)} to obtain the entry
  615. * information. If < 0 the entry does not exist in the index.
  616. */
  617. public int findEntry(final String path) {
  618. final byte[] p = Constants.encode(path);
  619. return findEntry(p, p.length);
  620. }
  621. int findEntry(final byte[] p, final int pLen) {
  622. int low = 0;
  623. int high = entryCnt;
  624. while (low < high) {
  625. int mid = (low + high) >>> 1;
  626. final int cmp = cmp(p, pLen, sortedEntries[mid]);
  627. if (cmp < 0)
  628. high = mid;
  629. else if (cmp == 0) {
  630. while (mid > 0 && cmp(p, pLen, sortedEntries[mid - 1]) == 0)
  631. mid--;
  632. return mid;
  633. } else
  634. low = mid + 1;
  635. }
  636. return -(low + 1);
  637. }
  638. /**
  639. * Determine the next index position past all entries with the same name.
  640. * <p>
  641. * As index entries are sorted by path name, then stage number, this method
  642. * advances the supplied position to the first position in the index whose
  643. * path name does not match the path name of the supplied position's entry.
  644. *
  645. * @param position
  646. * entry position of the path that should be skipped.
  647. * @return position of the next entry whose path is after the input.
  648. */
  649. public int nextEntry(final int position) {
  650. DirCacheEntry last = sortedEntries[position];
  651. int nextIdx = position + 1;
  652. while (nextIdx < entryCnt) {
  653. final DirCacheEntry next = sortedEntries[nextIdx];
  654. if (cmp(last, next) != 0)
  655. break;
  656. last = next;
  657. nextIdx++;
  658. }
  659. return nextIdx;
  660. }
  661. int nextEntry(final byte[] p, final int pLen, int nextIdx) {
  662. while (nextIdx < entryCnt) {
  663. final DirCacheEntry next = sortedEntries[nextIdx];
  664. if (!DirCacheTree.peq(p, next.path, pLen))
  665. break;
  666. nextIdx++;
  667. }
  668. return nextIdx;
  669. }
  670. /**
  671. * Total number of file entries stored in the index.
  672. * <p>
  673. * This count includes unmerged stages for a file entry if the file is
  674. * currently conflicted in a merge. This means the total number of entries
  675. * in the index may be up to 3 times larger than the number of files in the
  676. * working directory.
  677. * <p>
  678. * Note that this value counts only <i>files</i>.
  679. *
  680. * @return number of entries available.
  681. * @see #getEntry(int)
  682. */
  683. public int getEntryCount() {
  684. return entryCnt;
  685. }
  686. /**
  687. * Get a specific entry.
  688. *
  689. * @param i
  690. * position of the entry to get.
  691. * @return the entry at position <code>i</code>.
  692. */
  693. public DirCacheEntry getEntry(final int i) {
  694. return sortedEntries[i];
  695. }
  696. /**
  697. * Get a specific entry.
  698. *
  699. * @param path
  700. * the path to search for.
  701. * @return the entry for the given <code>path</code>.
  702. */
  703. public DirCacheEntry getEntry(final String path) {
  704. final int i = findEntry(path);
  705. return i < 0 ? null : sortedEntries[i];
  706. }
  707. /**
  708. * Recursively get all entries within a subtree.
  709. *
  710. * @param path
  711. * the subtree path to get all entries within.
  712. * @return all entries recursively contained within the subtree.
  713. */
  714. public DirCacheEntry[] getEntriesWithin(String path) {
  715. if (path.length() == 0) {
  716. final DirCacheEntry[] r = new DirCacheEntry[sortedEntries.length];
  717. System.arraycopy(sortedEntries, 0, r, 0, sortedEntries.length);
  718. return r;
  719. }
  720. if (!path.endsWith("/"))
  721. path += "/";
  722. final byte[] p = Constants.encode(path);
  723. final int pLen = p.length;
  724. int eIdx = findEntry(p, pLen);
  725. if (eIdx < 0)
  726. eIdx = -(eIdx + 1);
  727. final int lastIdx = nextEntry(p, pLen, eIdx);
  728. final DirCacheEntry[] r = new DirCacheEntry[lastIdx - eIdx];
  729. System.arraycopy(sortedEntries, eIdx, r, 0, r.length);
  730. return r;
  731. }
  732. void toArray(final int i, final DirCacheEntry[] dst, final int off,
  733. final int cnt) {
  734. System.arraycopy(sortedEntries, i, dst, off, cnt);
  735. }
  736. /**
  737. * Obtain (or build) the current cache tree structure.
  738. * <p>
  739. * This method can optionally recreate the cache tree, without flushing the
  740. * tree objects themselves to disk.
  741. *
  742. * @param build
  743. * if true and the cache tree is not present in the index it will
  744. * be generated and returned to the caller.
  745. * @return the cache tree; null if there is no current cache tree available
  746. * and <code>build</code> was false.
  747. */
  748. public DirCacheTree getCacheTree(final boolean build) {
  749. if (build) {
  750. if (tree == null)
  751. tree = new DirCacheTree();
  752. tree.validate(sortedEntries, entryCnt, 0, 0);
  753. }
  754. return tree;
  755. }
  756. /**
  757. * Write all index trees to the object store, returning the root tree.
  758. *
  759. * @param ow
  760. * the writer to use when serializing to the store. The caller is
  761. * responsible for flushing the inserter before trying to use the
  762. * returned tree identity.
  763. * @return identity for the root tree.
  764. * @throws UnmergedPathException
  765. * one or more paths contain higher-order stages (stage > 0),
  766. * which cannot be stored in a tree object.
  767. * @throws IllegalStateException
  768. * one or more paths contain an invalid mode which should never
  769. * appear in a tree object.
  770. * @throws IOException
  771. * an unexpected error occurred writing to the object store.
  772. */
  773. public ObjectId writeTree(final ObjectInserter ow)
  774. throws UnmergedPathException, IOException {
  775. return getCacheTree(true).writeTree(sortedEntries, 0, 0, ow);
  776. }
  777. /**
  778. * Tells whether this index contains unmerged paths.
  779. *
  780. * @return {@code true} if this index contains unmerged paths. Means: at
  781. * least one entry is of a stage different from 0. {@code false}
  782. * will be returned if all entries are of stage 0.
  783. */
  784. public boolean hasUnmergedPaths() {
  785. for (int i = 0; i < entryCnt; i++) {
  786. if (sortedEntries[i].getStage() > 0) {
  787. return true;
  788. }
  789. }
  790. return false;
  791. }
  792. private void registerIndexChangedListener(IndexChangedListener listener) {
  793. this.indexChangedListener = listener;
  794. }
  795. }