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.

PackInserter.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. /*
  2. * Copyright (C) 2017, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.storage.file;
  44. import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;
  45. import static org.eclipse.jgit.lib.Constants.OBJECT_ID_LENGTH;
  46. import static org.eclipse.jgit.lib.Constants.OBJ_OFS_DELTA;
  47. import static org.eclipse.jgit.lib.Constants.OBJ_REF_DELTA;
  48. import java.io.BufferedInputStream;
  49. import java.io.EOFException;
  50. import java.io.File;
  51. import java.io.FileOutputStream;
  52. import java.io.FilterInputStream;
  53. import java.io.IOException;
  54. import java.io.InputStream;
  55. import java.io.OutputStream;
  56. import java.io.RandomAccessFile;
  57. import java.nio.channels.Channels;
  58. import java.text.MessageFormat;
  59. import java.util.Collection;
  60. import java.util.Collections;
  61. import java.util.HashSet;
  62. import java.util.List;
  63. import java.util.Set;
  64. import java.util.zip.CRC32;
  65. import java.util.zip.DataFormatException;
  66. import java.util.zip.Deflater;
  67. import java.util.zip.DeflaterOutputStream;
  68. import java.util.zip.Inflater;
  69. import java.util.zip.InflaterInputStream;
  70. import org.eclipse.jgit.errors.CorruptObjectException;
  71. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  72. import org.eclipse.jgit.errors.LargeObjectException;
  73. import org.eclipse.jgit.errors.MissingObjectException;
  74. import org.eclipse.jgit.internal.JGitText;
  75. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  76. import org.eclipse.jgit.lib.AnyObjectId;
  77. import org.eclipse.jgit.lib.Constants;
  78. import org.eclipse.jgit.lib.InflaterCache;
  79. import org.eclipse.jgit.lib.ObjectId;
  80. import org.eclipse.jgit.lib.ObjectIdOwnerMap;
  81. import org.eclipse.jgit.lib.ObjectInserter;
  82. import org.eclipse.jgit.lib.ObjectLoader;
  83. import org.eclipse.jgit.lib.ObjectReader;
  84. import org.eclipse.jgit.lib.ObjectStream;
  85. import org.eclipse.jgit.storage.pack.PackConfig;
  86. import org.eclipse.jgit.transport.PackParser;
  87. import org.eclipse.jgit.transport.PackedObjectInfo;
  88. import org.eclipse.jgit.util.BlockList;
  89. import org.eclipse.jgit.util.FileUtils;
  90. import org.eclipse.jgit.util.IO;
  91. import org.eclipse.jgit.util.NB;
  92. import org.eclipse.jgit.util.io.CountingOutputStream;
  93. import org.eclipse.jgit.util.sha1.SHA1;
  94. /**
  95. * Object inserter that inserts one pack per call to {@link #flush()}, and never
  96. * inserts loose objects.
  97. */
  98. public class PackInserter extends ObjectInserter {
  99. /** Always produce version 2 indexes, to get CRC data. */
  100. private static final int INDEX_VERSION = 2;
  101. private final ObjectDirectory db;
  102. private List<PackedObjectInfo> objectList;
  103. private ObjectIdOwnerMap<PackedObjectInfo> objectMap;
  104. private boolean rollback;
  105. private boolean checkExisting = true;
  106. private int compression = Deflater.BEST_COMPRESSION;
  107. private File tmpPack;
  108. private PackStream packOut;
  109. private Inflater cachedInflater;
  110. private PackConfig pconfig;
  111. PackInserter(ObjectDirectory db) {
  112. this.db = db;
  113. this.pconfig = new PackConfig(db.getConfig());
  114. }
  115. /**
  116. * Whether to check if objects exist in the repo
  117. *
  118. * @param check
  119. * if {@code false}, will write out possibly-duplicate objects
  120. * without first checking whether they exist in the repo; default
  121. * is true.
  122. */
  123. public void checkExisting(boolean check) {
  124. checkExisting = check;
  125. }
  126. /**
  127. * Set compression level for zlib deflater.
  128. *
  129. * @param compression
  130. * compression level for zlib deflater.
  131. */
  132. public void setCompressionLevel(int compression) {
  133. this.compression = compression;
  134. }
  135. int getBufferSize() {
  136. return buffer().length;
  137. }
  138. /** {@inheritDoc} */
  139. @Override
  140. public ObjectId insert(int type, byte[] data, int off, int len)
  141. throws IOException {
  142. ObjectId id = idFor(type, data, off, len);
  143. if (objectMap != null && objectMap.contains(id)) {
  144. return id;
  145. }
  146. // Ignore loose objects, which are potentially unreachable.
  147. if (checkExisting && db.hasPackedObject(id)) {
  148. return id;
  149. }
  150. long offset = beginObject(type, len);
  151. packOut.compress.write(data, off, len);
  152. packOut.compress.finish();
  153. return endObject(id, offset);
  154. }
  155. /** {@inheritDoc} */
  156. @Override
  157. public ObjectId insert(int type, long len, InputStream in)
  158. throws IOException {
  159. byte[] buf = buffer();
  160. if (len <= buf.length) {
  161. IO.readFully(in, buf, 0, (int) len);
  162. return insert(type, buf, 0, (int) len);
  163. }
  164. long offset = beginObject(type, len);
  165. SHA1 md = digest();
  166. md.update(Constants.encodedTypeString(type));
  167. md.update((byte) ' ');
  168. md.update(Constants.encodeASCII(len));
  169. md.update((byte) 0);
  170. while (0 < len) {
  171. int n = in.read(buf, 0, (int) Math.min(buf.length, len));
  172. if (n <= 0) {
  173. throw new EOFException();
  174. }
  175. md.update(buf, 0, n);
  176. packOut.compress.write(buf, 0, n);
  177. len -= n;
  178. }
  179. packOut.compress.finish();
  180. return endObject(md.toObjectId(), offset);
  181. }
  182. private long beginObject(int type, long len) throws IOException {
  183. if (packOut == null) {
  184. beginPack();
  185. }
  186. long offset = packOut.getOffset();
  187. packOut.beginObject(type, len);
  188. return offset;
  189. }
  190. private ObjectId endObject(ObjectId id, long offset) {
  191. PackedObjectInfo obj = new PackedObjectInfo(id);
  192. obj.setOffset(offset);
  193. obj.setCRC((int) packOut.crc32.getValue());
  194. objectList.add(obj);
  195. objectMap.addIfAbsent(obj);
  196. return id;
  197. }
  198. private static File idxFor(File packFile) {
  199. String p = packFile.getName();
  200. return new File(
  201. packFile.getParentFile(),
  202. p.substring(0, p.lastIndexOf('.')) + ".idx"); //$NON-NLS-1$
  203. }
  204. private void beginPack() throws IOException {
  205. objectList = new BlockList<>();
  206. objectMap = new ObjectIdOwnerMap<>();
  207. rollback = true;
  208. tmpPack = File.createTempFile("insert_", ".pack", db.getDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
  209. packOut = new PackStream(tmpPack);
  210. // Write the header as though it were a single object pack.
  211. packOut.write(packOut.hdrBuf, 0, writePackHeader(packOut.hdrBuf, 1));
  212. }
  213. private static int writePackHeader(byte[] buf, int objectCount) {
  214. System.arraycopy(Constants.PACK_SIGNATURE, 0, buf, 0, 4);
  215. NB.encodeInt32(buf, 4, 2); // Always use pack version 2.
  216. NB.encodeInt32(buf, 8, objectCount);
  217. return 12;
  218. }
  219. /** {@inheritDoc} */
  220. @Override
  221. public PackParser newPackParser(InputStream in) {
  222. throw new UnsupportedOperationException();
  223. }
  224. /** {@inheritDoc} */
  225. @Override
  226. public ObjectReader newReader() {
  227. return new Reader();
  228. }
  229. /** {@inheritDoc} */
  230. @Override
  231. public void flush() throws IOException {
  232. if (tmpPack == null) {
  233. return;
  234. }
  235. if (packOut == null) {
  236. throw new IOException();
  237. }
  238. byte[] packHash;
  239. try {
  240. packHash = packOut.finishPack();
  241. } finally {
  242. packOut = null;
  243. }
  244. Collections.sort(objectList);
  245. File tmpIdx = idxFor(tmpPack);
  246. writePackIndex(tmpIdx, packHash, objectList);
  247. File realPack = new File(db.getPackDirectory(),
  248. "pack-" + computeName(objectList).name() + ".pack"); //$NON-NLS-1$ //$NON-NLS-2$
  249. db.closeAllPackHandles(realPack);
  250. tmpPack.setReadOnly();
  251. FileUtils.rename(tmpPack, realPack, ATOMIC_MOVE);
  252. File realIdx = idxFor(realPack);
  253. tmpIdx.setReadOnly();
  254. try {
  255. FileUtils.rename(tmpIdx, realIdx, ATOMIC_MOVE);
  256. } catch (IOException e) {
  257. File newIdx = new File(
  258. realIdx.getParentFile(), realIdx.getName() + ".new"); //$NON-NLS-1$
  259. try {
  260. FileUtils.rename(tmpIdx, newIdx, ATOMIC_MOVE);
  261. } catch (IOException e2) {
  262. newIdx = tmpIdx;
  263. e = e2;
  264. }
  265. throw new IOException(MessageFormat.format(
  266. JGitText.get().panicCantRenameIndexFile, newIdx,
  267. realIdx), e);
  268. }
  269. boolean interrupted = false;
  270. try {
  271. FileSnapshot snapshot = FileSnapshot.save(realPack);
  272. if (pconfig.doWaitPreventRacyPack(snapshot.size())) {
  273. snapshot.waitUntilNotRacy();
  274. }
  275. } catch (InterruptedException e) {
  276. interrupted = true;
  277. }
  278. try {
  279. db.openPack(realPack);
  280. rollback = false;
  281. } finally {
  282. clear();
  283. if (interrupted) {
  284. // Re-set interrupted flag
  285. Thread.currentThread().interrupt();
  286. }
  287. }
  288. }
  289. private static void writePackIndex(File idx, byte[] packHash,
  290. List<PackedObjectInfo> list) throws IOException {
  291. try (OutputStream os = new FileOutputStream(idx)) {
  292. PackIndexWriter w = PackIndexWriter.createVersion(os, INDEX_VERSION);
  293. w.write(list, packHash);
  294. }
  295. }
  296. private ObjectId computeName(List<PackedObjectInfo> list) {
  297. SHA1 md = digest().reset();
  298. byte[] buf = buffer();
  299. for (PackedObjectInfo otp : list) {
  300. otp.copyRawTo(buf, 0);
  301. md.update(buf, 0, OBJECT_ID_LENGTH);
  302. }
  303. return ObjectId.fromRaw(md.digest());
  304. }
  305. /** {@inheritDoc} */
  306. @Override
  307. public void close() {
  308. try {
  309. if (packOut != null) {
  310. try {
  311. packOut.close();
  312. } catch (IOException err) {
  313. // Ignore a close failure, the pack should be removed.
  314. }
  315. }
  316. if (rollback && tmpPack != null) {
  317. try {
  318. FileUtils.delete(tmpPack);
  319. } catch (IOException e) {
  320. // Still delete idx.
  321. }
  322. try {
  323. FileUtils.delete(idxFor(tmpPack));
  324. } catch (IOException e) {
  325. // Ignore error deleting temp idx.
  326. }
  327. rollback = false;
  328. }
  329. } finally {
  330. clear();
  331. try {
  332. InflaterCache.release(cachedInflater);
  333. } finally {
  334. cachedInflater = null;
  335. }
  336. }
  337. }
  338. private void clear() {
  339. objectList = null;
  340. objectMap = null;
  341. tmpPack = null;
  342. packOut = null;
  343. }
  344. private Inflater inflater() {
  345. if (cachedInflater == null) {
  346. cachedInflater = InflaterCache.get();
  347. } else {
  348. cachedInflater.reset();
  349. }
  350. return cachedInflater;
  351. }
  352. /**
  353. * Stream that writes to a pack file.
  354. * <p>
  355. * Backed by two views of the same open file descriptor: a random-access file,
  356. * and an output stream. Seeking in the file causes subsequent writes to the
  357. * output stream to occur wherever the file pointer is pointing, so we need to
  358. * take care to always seek to the end of the file before writing a new
  359. * object.
  360. * <p>
  361. * Callers should always use {@link #seek(long)} to seek, rather than reaching
  362. * into the file member. As long as this contract is followed, calls to {@link
  363. * #write(byte[], int, int)} are guaranteed to write at the end of the file,
  364. * even if there have been intermediate seeks.
  365. */
  366. private class PackStream extends OutputStream {
  367. final byte[] hdrBuf;
  368. final CRC32 crc32;
  369. final DeflaterOutputStream compress;
  370. private final RandomAccessFile file;
  371. private final CountingOutputStream out;
  372. private final Deflater deflater;
  373. private boolean atEnd;
  374. PackStream(File pack) throws IOException {
  375. file = new RandomAccessFile(pack, "rw"); //$NON-NLS-1$
  376. out = new CountingOutputStream(new FileOutputStream(file.getFD()));
  377. deflater = new Deflater(compression);
  378. compress = new DeflaterOutputStream(this, deflater, 8192);
  379. hdrBuf = new byte[32];
  380. crc32 = new CRC32();
  381. atEnd = true;
  382. }
  383. long getOffset() {
  384. // This value is accurate as long as we only ever write to the end of the
  385. // file, and don't seek back to overwrite any previous segments. Although
  386. // this is subtle, storing the stream counter this way is still preferable
  387. // to returning file.length() here, as it avoids a syscall and possible
  388. // IOException.
  389. return out.getCount();
  390. }
  391. void seek(long offset) throws IOException {
  392. file.seek(offset);
  393. atEnd = false;
  394. }
  395. void beginObject(int objectType, long length) throws IOException {
  396. crc32.reset();
  397. deflater.reset();
  398. write(hdrBuf, 0, encodeTypeSize(objectType, length));
  399. }
  400. private int encodeTypeSize(int type, long rawLength) {
  401. long nextLength = rawLength >>> 4;
  402. hdrBuf[0] = (byte) ((nextLength > 0 ? 0x80 : 0x00) | (type << 4) | (rawLength & 0x0F));
  403. rawLength = nextLength;
  404. int n = 1;
  405. while (rawLength > 0) {
  406. nextLength >>>= 7;
  407. hdrBuf[n++] = (byte) ((nextLength > 0 ? 0x80 : 0x00) | (rawLength & 0x7F));
  408. rawLength = nextLength;
  409. }
  410. return n;
  411. }
  412. @Override
  413. public void write(int b) throws IOException {
  414. hdrBuf[0] = (byte) b;
  415. write(hdrBuf, 0, 1);
  416. }
  417. @Override
  418. public void write(byte[] data, int off, int len) throws IOException {
  419. crc32.update(data, off, len);
  420. if (!atEnd) {
  421. file.seek(file.length());
  422. atEnd = true;
  423. }
  424. out.write(data, off, len);
  425. }
  426. byte[] finishPack() throws IOException {
  427. // Overwrite placeholder header with actual object count, then hash. This
  428. // method intentionally uses direct seek/write calls rather than the
  429. // wrappers which keep track of atEnd. This leaves atEnd, the file
  430. // pointer, and out's counter in an inconsistent state; that's ok, since
  431. // this method closes the file anyway.
  432. try {
  433. file.seek(0);
  434. out.write(hdrBuf, 0, writePackHeader(hdrBuf, objectList.size()));
  435. byte[] buf = buffer();
  436. SHA1 md = digest().reset();
  437. file.seek(0);
  438. while (true) {
  439. int r = file.read(buf);
  440. if (r < 0) {
  441. break;
  442. }
  443. md.update(buf, 0, r);
  444. }
  445. byte[] packHash = md.digest();
  446. out.write(packHash, 0, packHash.length);
  447. return packHash;
  448. } finally {
  449. close();
  450. }
  451. }
  452. @Override
  453. public void close() throws IOException {
  454. deflater.end();
  455. try {
  456. out.close();
  457. } finally {
  458. file.close();
  459. }
  460. }
  461. byte[] inflate(long filePos, int len) throws IOException, DataFormatException {
  462. byte[] dstbuf;
  463. try {
  464. dstbuf = new byte[len];
  465. } catch (OutOfMemoryError noMemory) {
  466. return null; // Caller will switch to large object streaming.
  467. }
  468. byte[] srcbuf = buffer();
  469. Inflater inf = inflater();
  470. filePos += setInput(filePos, inf, srcbuf);
  471. for (int dstoff = 0;;) {
  472. int n = inf.inflate(dstbuf, dstoff, dstbuf.length - dstoff);
  473. dstoff += n;
  474. if (inf.finished()) {
  475. return dstbuf;
  476. }
  477. if (inf.needsInput()) {
  478. filePos += setInput(filePos, inf, srcbuf);
  479. } else if (n == 0) {
  480. throw new DataFormatException();
  481. }
  482. }
  483. }
  484. private int setInput(long filePos, Inflater inf, byte[] buf)
  485. throws IOException {
  486. if (file.getFilePointer() != filePos) {
  487. seek(filePos);
  488. }
  489. int n = file.read(buf);
  490. if (n < 0) {
  491. throw new EOFException(JGitText.get().unexpectedEofInPack);
  492. }
  493. inf.setInput(buf, 0, n);
  494. return n;
  495. }
  496. }
  497. private class Reader extends ObjectReader {
  498. private final ObjectReader ctx;
  499. private Reader() {
  500. ctx = db.newReader();
  501. setStreamFileThreshold(ctx.getStreamFileThreshold());
  502. }
  503. @Override
  504. public ObjectReader newReader() {
  505. return db.newReader();
  506. }
  507. @Override
  508. public ObjectInserter getCreatedFromInserter() {
  509. return PackInserter.this;
  510. }
  511. @Override
  512. public Collection<ObjectId> resolve(AbbreviatedObjectId id)
  513. throws IOException {
  514. Collection<ObjectId> stored = ctx.resolve(id);
  515. if (objectList == null) {
  516. return stored;
  517. }
  518. Set<ObjectId> r = new HashSet<>(stored.size() + 2);
  519. r.addAll(stored);
  520. for (PackedObjectInfo obj : objectList) {
  521. if (id.prefixCompare(obj) == 0) {
  522. r.add(obj.copy());
  523. }
  524. }
  525. return r;
  526. }
  527. @Override
  528. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  529. throws MissingObjectException, IncorrectObjectTypeException,
  530. IOException {
  531. if (objectMap == null) {
  532. return ctx.open(objectId, typeHint);
  533. }
  534. PackedObjectInfo obj = objectMap.get(objectId);
  535. if (obj == null) {
  536. return ctx.open(objectId, typeHint);
  537. }
  538. byte[] buf = buffer();
  539. packOut.seek(obj.getOffset());
  540. int cnt = packOut.file.read(buf, 0, 20);
  541. if (cnt <= 0) {
  542. throw new EOFException(JGitText.get().unexpectedEofInPack);
  543. }
  544. int c = buf[0] & 0xff;
  545. int type = (c >> 4) & 7;
  546. if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
  547. throw new IOException(MessageFormat.format(
  548. JGitText.get().cannotReadBackDelta, Integer.toString(type)));
  549. }
  550. if (typeHint != OBJ_ANY && type != typeHint) {
  551. throw new IncorrectObjectTypeException(objectId.copy(), typeHint);
  552. }
  553. long sz = c & 0x0f;
  554. int ptr = 1;
  555. int shift = 4;
  556. while ((c & 0x80) != 0) {
  557. if (ptr >= cnt) {
  558. throw new EOFException(JGitText.get().unexpectedEofInPack);
  559. }
  560. c = buf[ptr++] & 0xff;
  561. sz += ((long) (c & 0x7f)) << shift;
  562. shift += 7;
  563. }
  564. long zpos = obj.getOffset() + ptr;
  565. if (sz < getStreamFileThreshold()) {
  566. byte[] data = inflate(obj, zpos, (int) sz);
  567. if (data != null) {
  568. return new ObjectLoader.SmallObject(type, data);
  569. }
  570. }
  571. return new StreamLoader(type, sz, zpos);
  572. }
  573. private byte[] inflate(PackedObjectInfo obj, long zpos, int sz)
  574. throws IOException, CorruptObjectException {
  575. try {
  576. return packOut.inflate(zpos, sz);
  577. } catch (DataFormatException dfe) {
  578. throw new CorruptObjectException(
  579. MessageFormat.format(
  580. JGitText.get().objectAtHasBadZlibStream,
  581. Long.valueOf(obj.getOffset()),
  582. tmpPack.getAbsolutePath()),
  583. dfe);
  584. }
  585. }
  586. @Override
  587. public Set<ObjectId> getShallowCommits() throws IOException {
  588. return ctx.getShallowCommits();
  589. }
  590. @Override
  591. public void close() {
  592. ctx.close();
  593. }
  594. private class StreamLoader extends ObjectLoader {
  595. private final int type;
  596. private final long size;
  597. private final long pos;
  598. StreamLoader(int type, long size, long pos) {
  599. this.type = type;
  600. this.size = size;
  601. this.pos = pos;
  602. }
  603. @Override
  604. public ObjectStream openStream()
  605. throws MissingObjectException, IOException {
  606. int bufsz = buffer().length;
  607. packOut.seek(pos);
  608. InputStream fileStream = new FilterInputStream(
  609. Channels.newInputStream(packOut.file.getChannel())) {
  610. // atEnd was already set to false by the previous seek, but it's
  611. // technically possible for a caller to call insert on the
  612. // inserter in the middle of reading from this stream. Behavior is
  613. // undefined in this case, so it would arguably be ok to ignore,
  614. // but it's not hard to at least make an attempt to not corrupt
  615. // the data.
  616. @Override
  617. public int read() throws IOException {
  618. packOut.atEnd = false;
  619. return super.read();
  620. }
  621. @Override
  622. public int read(byte[] b) throws IOException {
  623. packOut.atEnd = false;
  624. return super.read(b);
  625. }
  626. @Override
  627. public int read(byte[] b, int off, int len) throws IOException {
  628. packOut.atEnd = false;
  629. return super.read(b,off,len);
  630. }
  631. @Override
  632. public void close() {
  633. // Never close underlying RandomAccessFile, which lasts the
  634. // lifetime of the enclosing PackStream.
  635. }
  636. };
  637. return new ObjectStream.Filter(
  638. type, size,
  639. new BufferedInputStream(
  640. new InflaterInputStream(fileStream, inflater(), bufsz), bufsz));
  641. }
  642. @Override
  643. public int getType() {
  644. return type;
  645. }
  646. @Override
  647. public long getSize() {
  648. return size;
  649. }
  650. @Override
  651. public byte[] getCachedBytes() throws LargeObjectException {
  652. throw new LargeObjectException.ExceedsLimit(
  653. getStreamFileThreshold(), size);
  654. }
  655. }
  656. }
  657. }