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.

PackIndex.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.internal.storage.file;
  45. import java.io.File;
  46. import java.io.FileInputStream;
  47. import java.io.FileNotFoundException;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.text.MessageFormat;
  51. import java.util.Iterator;
  52. import java.util.Set;
  53. import org.eclipse.jgit.errors.CorruptObjectException;
  54. import org.eclipse.jgit.errors.MissingObjectException;
  55. import org.eclipse.jgit.internal.JGitText;
  56. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  57. import org.eclipse.jgit.lib.AnyObjectId;
  58. import org.eclipse.jgit.lib.MutableObjectId;
  59. import org.eclipse.jgit.lib.ObjectId;
  60. import org.eclipse.jgit.lib.ObjectIdSet;
  61. import org.eclipse.jgit.util.IO;
  62. import org.eclipse.jgit.util.NB;
  63. /**
  64. * Access path to locate objects by {@link ObjectId} in a {@link PackFile}.
  65. * <p>
  66. * Indexes are strictly redundant information in that we can rebuild all of the
  67. * data held in the index file from the on disk representation of the pack file
  68. * itself, but it is faster to access for random requests because data is stored
  69. * by ObjectId.
  70. * </p>
  71. */
  72. public abstract class PackIndex
  73. implements Iterable<PackIndex.MutableEntry>, ObjectIdSet {
  74. /**
  75. * Open an existing pack <code>.idx</code> file for reading.
  76. * <p>
  77. * The format of the file will be automatically detected and a proper access
  78. * implementation for that format will be constructed and returned to the
  79. * caller. The file may or may not be held open by the returned instance.
  80. * </p>
  81. *
  82. * @param idxFile
  83. * existing pack .idx to read.
  84. * @return access implementation for the requested file.
  85. * @throws FileNotFoundException
  86. * the file does not exist.
  87. * @throws IOException
  88. * the file exists but could not be read due to security errors,
  89. * unrecognized data version, or unexpected data corruption.
  90. */
  91. public static PackIndex open(final File idxFile) throws IOException {
  92. final FileInputStream fd = new FileInputStream(idxFile);
  93. try {
  94. return read(fd);
  95. } catch (IOException ioe) {
  96. final String path = idxFile.getAbsolutePath();
  97. final IOException err;
  98. err = new IOException(MessageFormat.format(JGitText.get().unreadablePackIndex, path));
  99. err.initCause(ioe);
  100. throw err;
  101. } finally {
  102. try {
  103. fd.close();
  104. } catch (IOException err2) {
  105. // ignore
  106. }
  107. }
  108. }
  109. /**
  110. * Read an existing pack index file from a buffered stream.
  111. * <p>
  112. * The format of the file will be automatically detected and a proper access
  113. * implementation for that format will be constructed and returned to the
  114. * caller. The file may or may not be held open by the returned instance.
  115. *
  116. * @param fd
  117. * stream to read the index file from. The stream must be
  118. * buffered as some small IOs are performed against the stream.
  119. * The caller is responsible for closing the stream.
  120. * @return a copy of the index in-memory.
  121. * @throws IOException
  122. * the stream cannot be read.
  123. * @throws CorruptObjectException
  124. * the stream does not contain a valid pack index.
  125. */
  126. public static PackIndex read(InputStream fd) throws IOException,
  127. CorruptObjectException {
  128. final byte[] hdr = new byte[8];
  129. IO.readFully(fd, hdr, 0, hdr.length);
  130. if (isTOC(hdr)) {
  131. final int v = NB.decodeInt32(hdr, 4);
  132. switch (v) {
  133. case 2:
  134. return new PackIndexV2(fd);
  135. default:
  136. throw new IOException(MessageFormat.format(
  137. JGitText.get().unsupportedPackIndexVersion,
  138. Integer.valueOf(v)));
  139. }
  140. }
  141. return new PackIndexV1(fd, hdr);
  142. }
  143. private static boolean isTOC(final byte[] h) {
  144. final byte[] toc = PackIndexWriter.TOC;
  145. for (int i = 0; i < toc.length; i++)
  146. if (h[i] != toc[i])
  147. return false;
  148. return true;
  149. }
  150. /** Footer checksum applied on the bottom of the pack file. */
  151. protected byte[] packChecksum;
  152. /**
  153. * Determine if an object is contained within the pack file.
  154. *
  155. * @param id
  156. * the object to look for. Must not be null.
  157. * @return true if the object is listed in this index; false otherwise.
  158. */
  159. public boolean hasObject(final AnyObjectId id) {
  160. return findOffset(id) != -1;
  161. }
  162. @Override
  163. public boolean contains(AnyObjectId id) {
  164. return findOffset(id) != -1;
  165. }
  166. /**
  167. * Provide iterator that gives access to index entries. Note, that iterator
  168. * returns reference to mutable object, the same reference in each call -
  169. * for performance reason. If client needs immutable objects, it must copy
  170. * returned object on its own.
  171. * <p>
  172. * Iterator returns objects in SHA-1 lexicographical order.
  173. * </p>
  174. *
  175. * @return iterator over pack index entries
  176. */
  177. public abstract Iterator<MutableEntry> iterator();
  178. /**
  179. * Obtain the total number of objects described by this index.
  180. *
  181. * @return number of objects in this index, and likewise in the associated
  182. * pack that this index was generated from.
  183. */
  184. public abstract long getObjectCount();
  185. /**
  186. * Obtain the total number of objects needing 64 bit offsets.
  187. *
  188. * @return number of objects in this index using a 64 bit offset; that is an
  189. * object positioned after the 2 GB position within the file.
  190. */
  191. public abstract long getOffset64Count();
  192. /**
  193. * Get ObjectId for the n-th object entry returned by {@link #iterator()}.
  194. * <p>
  195. * This method is a constant-time replacement for the following loop:
  196. *
  197. * <pre>
  198. * Iterator&lt;MutableEntry&gt; eItr = index.iterator();
  199. * int curPosition = 0;
  200. * while (eItr.hasNext() &amp;&amp; curPosition++ &lt; nthPosition)
  201. * eItr.next();
  202. * ObjectId result = eItr.next().toObjectId();
  203. * </pre>
  204. *
  205. * @param nthPosition
  206. * position within the traversal of {@link #iterator()} that the
  207. * caller needs the object for. The first returned
  208. * {@link MutableEntry} is 0, the second is 1, etc.
  209. * @return the ObjectId for the corresponding entry.
  210. */
  211. public abstract ObjectId getObjectId(long nthPosition);
  212. /**
  213. * Get ObjectId for the n-th object entry returned by {@link #iterator()}.
  214. * <p>
  215. * This method is a constant-time replacement for the following loop:
  216. *
  217. * <pre>
  218. * Iterator&lt;MutableEntry&gt; eItr = index.iterator();
  219. * int curPosition = 0;
  220. * while (eItr.hasNext() &amp;&amp; curPosition++ &lt; nthPosition)
  221. * eItr.next();
  222. * ObjectId result = eItr.next().toObjectId();
  223. * </pre>
  224. *
  225. * @param nthPosition
  226. * unsigned 32 bit position within the traversal of
  227. * {@link #iterator()} that the caller needs the object for. The
  228. * first returned {@link MutableEntry} is 0, the second is 1,
  229. * etc. Positions past 2**31-1 are negative, but still valid.
  230. * @return the ObjectId for the corresponding entry.
  231. */
  232. public final ObjectId getObjectId(final int nthPosition) {
  233. if (nthPosition >= 0)
  234. return getObjectId((long) nthPosition);
  235. final int u31 = nthPosition >>> 1;
  236. final int one = nthPosition & 1;
  237. return getObjectId(((long) u31) << 1 | one);
  238. }
  239. /**
  240. * Get offset in a pack for the n-th object entry returned by
  241. * {@link #iterator()}.
  242. *
  243. * @param nthPosition
  244. * unsigned 32 bit position within the traversal of
  245. * {@link #iterator()} for which the caller needs the offset. The
  246. * first returned {@link MutableEntry} is 0, the second is 1,
  247. * etc. Positions past 2**31-1 are negative, but still valid.
  248. * @return the offset in a pack for the corresponding entry.
  249. */
  250. abstract long getOffset(long nthPosition);
  251. /**
  252. * Locate the file offset position for the requested object.
  253. *
  254. * @param objId
  255. * name of the object to locate within the pack.
  256. * @return offset of the object's header and compressed content; -1 if the
  257. * object does not exist in this index and is thus not stored in the
  258. * associated pack.
  259. */
  260. public abstract long findOffset(AnyObjectId objId);
  261. /**
  262. * Retrieve stored CRC32 checksum of the requested object raw-data
  263. * (including header).
  264. *
  265. * @param objId
  266. * id of object to look for
  267. * @return CRC32 checksum of specified object (at 32 less significant bits)
  268. * @throws MissingObjectException
  269. * when requested ObjectId was not found in this index
  270. * @throws UnsupportedOperationException
  271. * when this index doesn't support CRC32 checksum
  272. */
  273. public abstract long findCRC32(AnyObjectId objId)
  274. throws MissingObjectException, UnsupportedOperationException;
  275. /**
  276. * Check whether this index supports (has) CRC32 checksums for objects.
  277. *
  278. * @return true if CRC32 is stored, false otherwise
  279. */
  280. public abstract boolean hasCRC32Support();
  281. /**
  282. * Find objects matching the prefix abbreviation.
  283. *
  284. * @param matches
  285. * set to add any located ObjectIds to. This is an output
  286. * parameter.
  287. * @param id
  288. * prefix to search for.
  289. * @param matchLimit
  290. * maximum number of results to return. At most this many
  291. * ObjectIds should be added to matches before returning.
  292. * @throws IOException
  293. * the index cannot be read.
  294. */
  295. public abstract void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
  296. int matchLimit) throws IOException;
  297. /**
  298. * Represent mutable entry of pack index consisting of object id and offset
  299. * in pack (both mutable).
  300. *
  301. */
  302. public static class MutableEntry {
  303. final MutableObjectId idBuffer = new MutableObjectId();
  304. long offset;
  305. /**
  306. * Returns offset for this index object entry
  307. *
  308. * @return offset of this object in a pack file
  309. */
  310. public long getOffset() {
  311. return offset;
  312. }
  313. /** @return hex string describing the object id of this entry. */
  314. public String name() {
  315. ensureId();
  316. return idBuffer.name();
  317. }
  318. /** @return a copy of the object id. */
  319. public ObjectId toObjectId() {
  320. ensureId();
  321. return idBuffer.toObjectId();
  322. }
  323. /** @return a complete copy of this entry, that won't modify */
  324. public MutableEntry cloneEntry() {
  325. final MutableEntry r = new MutableEntry();
  326. ensureId();
  327. r.idBuffer.fromObjectId(idBuffer);
  328. r.offset = offset;
  329. return r;
  330. }
  331. void ensureId() {
  332. // Override in implementations.
  333. }
  334. }
  335. abstract class EntriesIterator implements Iterator<MutableEntry> {
  336. protected final MutableEntry entry = initEntry();
  337. protected long returnedNumber = 0;
  338. protected abstract MutableEntry initEntry();
  339. public boolean hasNext() {
  340. return returnedNumber < getObjectCount();
  341. }
  342. /**
  343. * Implementation must update {@link #returnedNumber} before returning
  344. * element.
  345. */
  346. public abstract MutableEntry next();
  347. public void remove() {
  348. throw new UnsupportedOperationException();
  349. }
  350. }
  351. }