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.

ObjectWriter.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
  3. * Copyright (C) 2006-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.lib;
  45. import java.io.ByteArrayInputStream;
  46. import java.io.ByteArrayOutputStream;
  47. import java.io.File;
  48. import java.io.FileInputStream;
  49. import java.io.FileOutputStream;
  50. import java.io.IOException;
  51. import java.io.InputStream;
  52. import java.io.OutputStreamWriter;
  53. import java.security.MessageDigest;
  54. import java.util.zip.Deflater;
  55. import java.util.zip.DeflaterOutputStream;
  56. import org.eclipse.jgit.errors.ObjectWritingException;
  57. /**
  58. * A class for writing loose objects.
  59. */
  60. public class ObjectWriter {
  61. private static final byte[] htree = Constants.encodeASCII("tree");
  62. private static final byte[] hparent = Constants.encodeASCII("parent");
  63. private static final byte[] hauthor = Constants.encodeASCII("author");
  64. private static final byte[] hcommitter = Constants.encodeASCII("committer");
  65. private static final byte[] hencoding = Constants.encodeASCII("encoding");
  66. private final Repository r;
  67. private final byte[] buf;
  68. private final MessageDigest md;
  69. /**
  70. * Construct an Object writer for the specified repository
  71. * @param d
  72. */
  73. public ObjectWriter(final Repository d) {
  74. r = d;
  75. buf = new byte[8192];
  76. md = Constants.newMessageDigest();
  77. }
  78. /**
  79. * Write a blob with the specified data
  80. *
  81. * @param b bytes of the blob
  82. * @return SHA-1 of the blob
  83. * @throws IOException
  84. */
  85. public ObjectId writeBlob(final byte[] b) throws IOException {
  86. return writeBlob(b.length, new ByteArrayInputStream(b));
  87. }
  88. /**
  89. * Write a blob with the data in the specified file
  90. *
  91. * @param f
  92. * a file containing blob data
  93. * @return SHA-1 of the blob
  94. * @throws IOException
  95. */
  96. public ObjectId writeBlob(final File f) throws IOException {
  97. final FileInputStream is = new FileInputStream(f);
  98. try {
  99. return writeBlob(f.length(), is);
  100. } finally {
  101. is.close();
  102. }
  103. }
  104. /**
  105. * Write a blob with data from a stream
  106. *
  107. * @param len
  108. * number of bytes to consume from the stream
  109. * @param is
  110. * stream with blob data
  111. * @return SHA-1 of the blob
  112. * @throws IOException
  113. */
  114. public ObjectId writeBlob(final long len, final InputStream is)
  115. throws IOException {
  116. return writeObject(Constants.OBJ_BLOB, len, is, true);
  117. }
  118. /**
  119. * Write a Tree to the object database.
  120. *
  121. * @param t
  122. * Tree
  123. * @return SHA-1 of the tree
  124. * @throws IOException
  125. */
  126. public ObjectId writeTree(final Tree t) throws IOException {
  127. final ByteArrayOutputStream o = new ByteArrayOutputStream();
  128. final TreeEntry[] items = t.members();
  129. for (int k = 0; k < items.length; k++) {
  130. final TreeEntry e = items[k];
  131. final ObjectId id = e.getId();
  132. if (id == null)
  133. throw new ObjectWritingException("Object at path \""
  134. + e.getFullName() + "\" does not have an id assigned."
  135. + " All object ids must be assigned prior"
  136. + " to writing a tree.");
  137. e.getMode().copyTo(o);
  138. o.write(' ');
  139. o.write(e.getNameUTF8());
  140. o.write(0);
  141. id.copyRawTo(o);
  142. }
  143. return writeCanonicalTree(o.toByteArray());
  144. }
  145. /**
  146. * Write a canonical tree to the object database.
  147. *
  148. * @param b
  149. * the canonical encoding of the tree object.
  150. * @return SHA-1 of the tree
  151. * @throws IOException
  152. */
  153. public ObjectId writeCanonicalTree(final byte[] b) throws IOException {
  154. return writeTree(b.length, new ByteArrayInputStream(b));
  155. }
  156. private ObjectId writeTree(final long len, final InputStream is)
  157. throws IOException {
  158. return writeObject(Constants.OBJ_TREE, len, is, true);
  159. }
  160. /**
  161. * Write a Commit to the object database
  162. *
  163. * @param c
  164. * Commit to store
  165. * @return SHA-1 of the commit
  166. * @throws IOException
  167. */
  168. public ObjectId writeCommit(final Commit c) throws IOException {
  169. final ByteArrayOutputStream os = new ByteArrayOutputStream();
  170. String encoding = c.getEncoding();
  171. if (encoding == null)
  172. encoding = Constants.CHARACTER_ENCODING;
  173. final OutputStreamWriter w = new OutputStreamWriter(os, encoding);
  174. os.write(htree);
  175. os.write(' ');
  176. c.getTreeId().copyTo(os);
  177. os.write('\n');
  178. ObjectId[] ps = c.getParentIds();
  179. for (int i=0; i<ps.length; ++i) {
  180. os.write(hparent);
  181. os.write(' ');
  182. ps[i].copyTo(os);
  183. os.write('\n');
  184. }
  185. os.write(hauthor);
  186. os.write(' ');
  187. w.write(c.getAuthor().toExternalString());
  188. w.flush();
  189. os.write('\n');
  190. os.write(hcommitter);
  191. os.write(' ');
  192. w.write(c.getCommitter().toExternalString());
  193. w.flush();
  194. os.write('\n');
  195. if (!encoding.equals(Constants.CHARACTER_ENCODING)) {
  196. os.write(hencoding);
  197. os.write(' ');
  198. os.write(Constants.encodeASCII(encoding));
  199. os.write('\n');
  200. }
  201. os.write('\n');
  202. w.write(c.getMessage());
  203. w.flush();
  204. return writeCommit(os.toByteArray());
  205. }
  206. private ObjectId writeTag(final byte[] b) throws IOException {
  207. return writeTag(b.length, new ByteArrayInputStream(b));
  208. }
  209. /**
  210. * Write an annotated Tag to the object database
  211. *
  212. * @param c
  213. * Tag
  214. * @return SHA-1 of the tag
  215. * @throws IOException
  216. */
  217. public ObjectId writeTag(final Tag c) throws IOException {
  218. final ByteArrayOutputStream os = new ByteArrayOutputStream();
  219. final OutputStreamWriter w = new OutputStreamWriter(os,
  220. Constants.CHARSET);
  221. w.write("object ");
  222. c.getObjId().copyTo(w);
  223. w.write('\n');
  224. w.write("type ");
  225. w.write(c.getType());
  226. w.write("\n");
  227. w.write("tag ");
  228. w.write(c.getTag());
  229. w.write("\n");
  230. w.write("tagger ");
  231. w.write(c.getAuthor().toExternalString());
  232. w.write('\n');
  233. w.write('\n');
  234. w.write(c.getMessage());
  235. w.close();
  236. return writeTag(os.toByteArray());
  237. }
  238. private ObjectId writeCommit(final byte[] b) throws IOException {
  239. return writeCommit(b.length, new ByteArrayInputStream(b));
  240. }
  241. private ObjectId writeCommit(final long len, final InputStream is)
  242. throws IOException {
  243. return writeObject(Constants.OBJ_COMMIT, len, is, true);
  244. }
  245. private ObjectId writeTag(final long len, final InputStream is)
  246. throws IOException {
  247. return writeObject(Constants.OBJ_TAG, len, is, true);
  248. }
  249. /**
  250. * Compute the SHA-1 of a blob without creating an object. This is for
  251. * figuring out if we already have a blob or not.
  252. *
  253. * @param len number of bytes to consume
  254. * @param is stream for read blob data from
  255. * @return SHA-1 of a looked for blob
  256. * @throws IOException
  257. */
  258. public ObjectId computeBlobSha1(final long len, final InputStream is)
  259. throws IOException {
  260. return writeObject(Constants.OBJ_BLOB, len, is, false);
  261. }
  262. ObjectId writeObject(final int type, long len, final InputStream is,
  263. boolean store) throws IOException {
  264. final File t;
  265. final DeflaterOutputStream deflateStream;
  266. final FileOutputStream fileStream;
  267. ObjectId id = null;
  268. Deflater def = null;
  269. if (store) {
  270. t = File.createTempFile("noz", null, r.getObjectsDirectory());
  271. fileStream = new FileOutputStream(t);
  272. } else {
  273. t = null;
  274. fileStream = null;
  275. }
  276. md.reset();
  277. if (store) {
  278. def = new Deflater(r.getConfig().getCore().getCompression());
  279. deflateStream = new DeflaterOutputStream(fileStream, def);
  280. } else
  281. deflateStream = null;
  282. try {
  283. byte[] header;
  284. int n;
  285. header = Constants.encodedTypeString(type);
  286. md.update(header);
  287. if (deflateStream != null)
  288. deflateStream.write(header);
  289. md.update((byte) ' ');
  290. if (deflateStream != null)
  291. deflateStream.write((byte) ' ');
  292. header = Constants.encodeASCII(len);
  293. md.update(header);
  294. if (deflateStream != null)
  295. deflateStream.write(header);
  296. md.update((byte) 0);
  297. if (deflateStream != null)
  298. deflateStream.write((byte) 0);
  299. while (len > 0
  300. && (n = is.read(buf, 0, (int) Math.min(len, buf.length))) > 0) {
  301. md.update(buf, 0, n);
  302. if (deflateStream != null)
  303. deflateStream.write(buf, 0, n);
  304. len -= n;
  305. }
  306. if (len != 0)
  307. throw new IOException("Input did not match supplied length. "
  308. + len + " bytes are missing.");
  309. if (deflateStream != null ) {
  310. deflateStream.close();
  311. if (t != null)
  312. t.setReadOnly();
  313. }
  314. id = ObjectId.fromRaw(md.digest());
  315. } finally {
  316. if (id == null && deflateStream != null) {
  317. try {
  318. deflateStream.close();
  319. } finally {
  320. t.delete();
  321. }
  322. }
  323. if (def != null) {
  324. def.end();
  325. }
  326. }
  327. if (t == null)
  328. return id;
  329. if (r.hasObject(id)) {
  330. // Object is already in the repository so remove
  331. // the temporary file.
  332. //
  333. t.delete();
  334. } else {
  335. final File o = r.toFile(id);
  336. if (!t.renameTo(o)) {
  337. // Maybe the directory doesn't exist yet as the object
  338. // directories are always lazily created. Note that we
  339. // try the rename first as the directory likely does exist.
  340. //
  341. o.getParentFile().mkdir();
  342. if (!t.renameTo(o)) {
  343. if (!r.hasObject(id)) {
  344. // The object failed to be renamed into its proper
  345. // location and it doesn't exist in the repository
  346. // either. We really don't know what went wrong, so
  347. // fail.
  348. //
  349. t.delete();
  350. throw new ObjectWritingException("Unable to"
  351. + " create new object: " + o);
  352. }
  353. }
  354. }
  355. }
  356. return id;
  357. }
  358. }