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

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