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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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.util.IO;
  61. import org.eclipse.jgit.util.NB;
  62. /**
  63. * Access path to locate objects by {@link ObjectId} in a {@link PackFile}.
  64. * <p>
  65. * Indexes are strictly redundant information in that we can rebuild all of the
  66. * data held in the index file from the on disk representation of the pack file
  67. * itself, but it is faster to access for random requests because data is stored
  68. * by ObjectId.
  69. * </p>
  70. */
  71. public abstract class PackIndex implements Iterable<PackIndex.MutableEntry> {
  72. /**
  73. * Open an existing pack <code>.idx</code> file for reading.
  74. * <p>
  75. * The format of the file will be automatically detected and a proper access
  76. * implementation for that format will be constructed and returned to the
  77. * caller. The file may or may not be held open by the returned instance.
  78. * </p>
  79. *
  80. * @param idxFile
  81. * existing pack .idx to read.
  82. * @return access implementation for the requested file.
  83. * @throws FileNotFoundException
  84. * the file does not exist.
  85. * @throws IOException
  86. * the file exists but could not be read due to security errors,
  87. * unrecognized data version, or unexpected data corruption.
  88. */
  89. public static PackIndex open(final File idxFile) throws IOException {
  90. final FileInputStream fd = new FileInputStream(idxFile);
  91. try {
  92. return read(fd);
  93. } catch (IOException ioe) {
  94. final String path = idxFile.getAbsolutePath();
  95. final IOException err;
  96. err = new IOException(MessageFormat.format(JGitText.get().unreadablePackIndex, path));
  97. err.initCause(ioe);
  98. throw err;
  99. } finally {
  100. try {
  101. fd.close();
  102. } catch (IOException err2) {
  103. // ignore
  104. }
  105. }
  106. }
  107. /**
  108. * Read an existing pack index file from a buffered stream.
  109. * <p>
  110. * The format of the file will be automatically detected and a proper access
  111. * implementation for that format will be constructed and returned to the
  112. * caller. The file may or may not be held open by the returned instance.
  113. *
  114. * @param fd
  115. * stream to read the index file from. The stream must be
  116. * buffered as some small IOs are performed against the stream.
  117. * The caller is responsible for closing the stream.
  118. * @return a copy of the index in-memory.
  119. * @throws IOException
  120. * the stream cannot be read.
  121. * @throws CorruptObjectException
  122. * the stream does not contain a valid pack index.
  123. */
  124. public static PackIndex read(InputStream fd) throws IOException,
  125. CorruptObjectException {
  126. final byte[] hdr = new byte[8];
  127. IO.readFully(fd, hdr, 0, hdr.length);
  128. if (isTOC(hdr)) {
  129. final int v = NB.decodeInt32(hdr, 4);
  130. switch (v) {
  131. case 2:
  132. return new PackIndexV2(fd);
  133. default:
  134. throw new IOException(MessageFormat.format(
  135. JGitText.get().unsupportedPackIndexVersion,
  136. Integer.valueOf(v)));
  137. }
  138. }
  139. return new PackIndexV1(fd, hdr);
  140. }
  141. private static boolean isTOC(final byte[] h) {
  142. final byte[] toc = PackIndexWriter.TOC;
  143. for (int i = 0; i < toc.length; i++)
  144. if (h[i] != toc[i])
  145. return false;
  146. return true;
  147. }
  148. /** Footer checksum applied on the bottom of the pack file. */
  149. protected byte[] packChecksum;
  150. /**
  151. * Determine if an object is contained within the pack file.
  152. *
  153. * @param id
  154. * the object to look for. Must not be null.
  155. * @return true if the object is listed in this index; false otherwise.
  156. */
  157. public boolean hasObject(final AnyObjectId id) {
  158. return findOffset(id) != -1;
  159. }
  160. /**
  161. * Provide iterator that gives access to index entries. Note, that iterator
  162. * returns reference to mutable object, the same reference in each call -
  163. * for performance reason. If client needs immutable objects, it must copy
  164. * returned object on its own.
  165. * <p>
  166. * Iterator returns objects in SHA-1 lexicographical order.
  167. * </p>
  168. *
  169. * @return iterator over pack index entries
  170. */
  171. public abstract Iterator<MutableEntry> iterator();
  172. /**
  173. * Obtain the total number of objects described by this index.
  174. *
  175. * @return number of objects in this index, and likewise in the associated
  176. * pack that this index was generated from.
  177. */
  178. public abstract long getObjectCount();
  179. /**
  180. * Obtain the total number of objects needing 64 bit offsets.
  181. *
  182. * @return number of objects in this index using a 64 bit offset; that is an
  183. * object positioned after the 2 GB position within the file.
  184. */
  185. public abstract long getOffset64Count();
  186. /**
  187. * Get ObjectId for the n-th object entry returned by {@link #iterator()}.
  188. * <p>
  189. * This method is a constant-time replacement for the following loop:
  190. *
  191. * <pre>
  192. * Iterator&lt;MutableEntry&gt; eItr = index.iterator();
  193. * int curPosition = 0;
  194. * while (eItr.hasNext() &amp;&amp; curPosition++ &lt; nthPosition)
  195. * eItr.next();
  196. * ObjectId result = eItr.next().toObjectId();
  197. * </pre>
  198. *
  199. * @param nthPosition
  200. * position within the traversal of {@link #iterator()} that the
  201. * caller needs the object for. The first returned
  202. * {@link MutableEntry} is 0, the second is 1, etc.
  203. * @return the ObjectId for the corresponding entry.
  204. */
  205. public abstract ObjectId getObjectId(long nthPosition);
  206. /**
  207. * Get ObjectId for the n-th object entry returned by {@link #iterator()}.
  208. * <p>
  209. * This method is a constant-time replacement for the following loop:
  210. *
  211. * <pre>
  212. * Iterator&lt;MutableEntry&gt; eItr = index.iterator();
  213. * int curPosition = 0;
  214. * while (eItr.hasNext() &amp;&amp; curPosition++ &lt; nthPosition)
  215. * eItr.next();
  216. * ObjectId result = eItr.next().toObjectId();
  217. * </pre>
  218. *
  219. * @param nthPosition
  220. * unsigned 32 bit position within the traversal of
  221. * {@link #iterator()} that the caller needs the object for. The
  222. * first returned {@link MutableEntry} is 0, the second is 1,
  223. * etc. Positions past 2**31-1 are negative, but still valid.
  224. * @return the ObjectId for the corresponding entry.
  225. */
  226. public final ObjectId getObjectId(final int nthPosition) {
  227. if (nthPosition >= 0)
  228. return getObjectId((long) nthPosition);
  229. final int u31 = nthPosition >>> 1;
  230. final int one = nthPosition & 1;
  231. return getObjectId(((long) u31) << 1 | one);
  232. }
  233. /**
  234. * Get offset in a pack for the n-th object entry returned by
  235. * {@link #iterator()}.
  236. *
  237. * @param nthPosition
  238. * unsigned 32 bit position within the traversal of
  239. * {@link #iterator()} for which the caller needs the offset. The
  240. * first returned {@link MutableEntry} is 0, the second is 1,
  241. * etc. Positions past 2**31-1 are negative, but still valid.
  242. * @return the offset in a pack for the corresponding entry.
  243. */
  244. abstract long getOffset(long nthPosition);
  245. /**
  246. * Locate the file offset position for the requested object.
  247. *
  248. * @param objId
  249. * name of the object to locate within the pack.
  250. * @return offset of the object's header and compressed content; -1 if the
  251. * object does not exist in this index and is thus not stored in the
  252. * associated pack.
  253. */
  254. public abstract long findOffset(AnyObjectId objId);
  255. /**
  256. * Retrieve stored CRC32 checksum of the requested object raw-data
  257. * (including header).
  258. *
  259. * @param objId
  260. * id of object to look for
  261. * @return CRC32 checksum of specified object (at 32 less significant bits)
  262. * @throws MissingObjectException
  263. * when requested ObjectId was not found in this index
  264. * @throws UnsupportedOperationException
  265. * when this index doesn't support CRC32 checksum
  266. */
  267. public abstract long findCRC32(AnyObjectId objId)
  268. throws MissingObjectException, UnsupportedOperationException;
  269. /**
  270. * Check whether this index supports (has) CRC32 checksums for objects.
  271. *
  272. * @return true if CRC32 is stored, false otherwise
  273. */
  274. public abstract boolean hasCRC32Support();
  275. /**
  276. * Find objects matching the prefix abbreviation.
  277. *
  278. * @param matches
  279. * set to add any located ObjectIds to. This is an output
  280. * parameter.
  281. * @param id
  282. * prefix to search for.
  283. * @param matchLimit
  284. * maximum number of results to return. At most this many
  285. * ObjectIds should be added to matches before returning.
  286. * @throws IOException
  287. * the index cannot be read.
  288. */
  289. public abstract void resolve(Set<ObjectId> matches, AbbreviatedObjectId id,
  290. int matchLimit) throws IOException;
  291. /**
  292. * Represent mutable entry of pack index consisting of object id and offset
  293. * in pack (both mutable).
  294. *
  295. */
  296. public static class MutableEntry {
  297. final MutableObjectId idBuffer = new MutableObjectId();
  298. long offset;
  299. /**
  300. * Returns offset for this index object entry
  301. *
  302. * @return offset of this object in a pack file
  303. */
  304. public long getOffset() {
  305. return offset;
  306. }
  307. /** @return hex string describing the object id of this entry. */
  308. public String name() {
  309. ensureId();
  310. return idBuffer.name();
  311. }
  312. /** @return a copy of the object id. */
  313. public ObjectId toObjectId() {
  314. ensureId();
  315. return idBuffer.toObjectId();
  316. }
  317. /** @return a complete copy of this entry, that won't modify */
  318. public MutableEntry cloneEntry() {
  319. final MutableEntry r = new MutableEntry();
  320. ensureId();
  321. r.idBuffer.fromObjectId(idBuffer);
  322. r.offset = offset;
  323. return r;
  324. }
  325. void ensureId() {
  326. // Override in implementations.
  327. }
  328. }
  329. abstract class EntriesIterator implements Iterator<MutableEntry> {
  330. protected final MutableEntry entry = initEntry();
  331. protected long returnedNumber = 0;
  332. protected abstract MutableEntry initEntry();
  333. public boolean hasNext() {
  334. return returnedNumber < getObjectCount();
  335. }
  336. /**
  337. * Implementation must update {@link #returnedNumber} before returning
  338. * element.
  339. */
  340. public abstract MutableEntry next();
  341. public void remove() {
  342. throw new UnsupportedOperationException();
  343. }
  344. }
  345. }