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

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