View Javadoc
1   /*
2    * Copyright (C) 2010, 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  
44  package org.eclipse.jgit.lib;
45  
46  import static org.eclipse.jgit.lib.Constants.OBJECT_ID_LENGTH;
47  import static org.eclipse.jgit.lib.Constants.OBJ_TREE;
48  import static org.eclipse.jgit.lib.Constants.encode;
49  import static org.eclipse.jgit.lib.FileMode.GITLINK;
50  import static org.eclipse.jgit.lib.FileMode.REGULAR_FILE;
51  import static org.eclipse.jgit.lib.FileMode.TREE;
52  
53  import java.io.IOException;
54  
55  import org.eclipse.jgit.errors.CorruptObjectException;
56  import org.eclipse.jgit.revwalk.RevBlob;
57  import org.eclipse.jgit.revwalk.RevCommit;
58  import org.eclipse.jgit.revwalk.RevTree;
59  import org.eclipse.jgit.treewalk.CanonicalTreeParser;
60  import org.eclipse.jgit.util.TemporaryBuffer;
61  
62  /**
63   * Mutable formatter to construct a single tree object.
64   *
65   * This formatter does not process subtrees. Callers must handle creating each
66   * subtree on their own.
67   *
68   * To maintain good performance for bulk operations, this formatter does not
69   * validate its input. Callers are responsible for ensuring the resulting tree
70   * object is correctly well formed by writing entries in the correct order.
71   */
72  public class TreeFormatter {
73  	/**
74  	 * Compute the size of a tree entry record.
75  	 *
76  	 * This method can be used to estimate the correct size of a tree prior to
77  	 * allocating a formatter. Getting the size correct at allocation time
78  	 * ensures the internal buffer is sized correctly, reducing copying.
79  	 *
80  	 * @param mode
81  	 *            the mode the entry will have.
82  	 * @param nameLen
83  	 *            the length of the name, in bytes.
84  	 * @return the length of the record.
85  	 */
86  	public static int entrySize(FileMode mode, int nameLen) {
87  		return mode.copyToLength() + nameLen + OBJECT_ID_LENGTH + 2;
88  	}
89  
90  	private byte[] buf;
91  
92  	private int ptr;
93  
94  	private TemporaryBuffer.Heap overflowBuffer;
95  
96  	/** Create an empty formatter with a default buffer size. */
97  	public TreeFormatter() {
98  		this(8192);
99  	}
100 
101 	/**
102 	 * Create an empty formatter with the specified buffer size.
103 	 *
104 	 * @param size
105 	 *            estimated size of the tree, in bytes. Callers can use
106 	 *            {@link #entrySize(FileMode, int)} to estimate the size of each
107 	 *            entry in advance of allocating the formatter.
108 	 */
109 	public TreeFormatter(int size) {
110 		buf = new byte[size];
111 	}
112 
113 	/**
114 	 * Add a link to a submodule commit, mode is {@link FileMode#GITLINK}.
115 	 *
116 	 * @param name
117 	 *            name of the entry.
118 	 * @param commit
119 	 *            the ObjectId to store in this entry.
120 	 */
121 	public void append(String name, RevCommit commit) {
122 		append(name, GITLINK, commit);
123 	}
124 
125 	/**
126 	 * Add a subtree, mode is {@link FileMode#TREE}.
127 	 *
128 	 * @param name
129 	 *            name of the entry.
130 	 * @param tree
131 	 *            the ObjectId to store in this entry.
132 	 */
133 	public void append(String name, RevTree tree) {
134 		append(name, TREE, tree);
135 	}
136 
137 	/**
138 	 * Add a regular file, mode is {@link FileMode#REGULAR_FILE}.
139 	 *
140 	 * @param name
141 	 *            name of the entry.
142 	 * @param blob
143 	 *            the ObjectId to store in this entry.
144 	 */
145 	public void append(String name, RevBlob blob) {
146 		append(name, REGULAR_FILE, blob);
147 	}
148 
149 	/**
150 	 * Append any entry to the tree.
151 	 *
152 	 * @param name
153 	 *            name of the entry.
154 	 * @param mode
155 	 *            mode describing the treatment of {@code id}.
156 	 * @param id
157 	 *            the ObjectId to store in this entry.
158 	 */
159 	public void append(String name, FileMode mode, AnyObjectId id) {
160 		append(encode(name), mode, id);
161 	}
162 
163 	/**
164 	 * Append any entry to the tree.
165 	 *
166 	 * @param name
167 	 *            name of the entry. The name should be UTF-8 encoded, but file
168 	 *            name encoding is not a well defined concept in Git.
169 	 * @param mode
170 	 *            mode describing the treatment of {@code id}.
171 	 * @param id
172 	 *            the ObjectId to store in this entry.
173 	 */
174 	public void append(byte[] name, FileMode mode, AnyObjectId id) {
175 		append(name, 0, name.length, mode, id);
176 	}
177 
178 	/**
179 	 * Append any entry to the tree.
180 	 *
181 	 * @param nameBuf
182 	 *            buffer holding the name of the entry. The name should be UTF-8
183 	 *            encoded, but file name encoding is not a well defined concept
184 	 *            in Git.
185 	 * @param namePos
186 	 *            first position within {@code nameBuf} of the name data.
187 	 * @param nameLen
188 	 *            number of bytes from {@code nameBuf} to use as the name.
189 	 * @param mode
190 	 *            mode describing the treatment of {@code id}.
191 	 * @param id
192 	 *            the ObjectId to store in this entry.
193 	 */
194 	public void append(byte[] nameBuf, int namePos, int nameLen, FileMode mode,
195 			AnyObjectId id) {
196 		if (fmtBuf(nameBuf, namePos, nameLen, mode)) {
197 			id.copyRawTo(buf, ptr);
198 			ptr += OBJECT_ID_LENGTH;
199 
200 		} else {
201 			try {
202 				fmtOverflowBuffer(nameBuf, namePos, nameLen, mode);
203 				id.copyRawTo(overflowBuffer);
204 			} catch (IOException badBuffer) {
205 				// This should never occur.
206 				throw new RuntimeException(badBuffer);
207 			}
208 		}
209 	}
210 
211 	/**
212 	 * Append any entry to the tree.
213 	 *
214 	 * @param nameBuf
215 	 *            buffer holding the name of the entry. The name should be UTF-8
216 	 *            encoded, but file name encoding is not a well defined concept
217 	 *            in Git.
218 	 * @param namePos
219 	 *            first position within {@code nameBuf} of the name data.
220 	 * @param nameLen
221 	 *            number of bytes from {@code nameBuf} to use as the name.
222 	 * @param mode
223 	 *            mode describing the treatment of {@code id}.
224 	 * @param idBuf
225 	 *            buffer holding the raw ObjectId of the entry.
226 	 * @param idPos
227 	 *            first position within {@code idBuf} to copy the id from.
228 	 */
229 	public void append(byte[] nameBuf, int namePos, int nameLen, FileMode mode,
230 			byte[] idBuf, int idPos) {
231 		if (fmtBuf(nameBuf, namePos, nameLen, mode)) {
232 			System.arraycopy(idBuf, idPos, buf, ptr, OBJECT_ID_LENGTH);
233 			ptr += OBJECT_ID_LENGTH;
234 
235 		} else {
236 			try {
237 				fmtOverflowBuffer(nameBuf, namePos, nameLen, mode);
238 				overflowBuffer.write(idBuf, idPos, OBJECT_ID_LENGTH);
239 			} catch (IOException badBuffer) {
240 				// This should never occur.
241 				throw new RuntimeException(badBuffer);
242 			}
243 		}
244 	}
245 
246 	private boolean fmtBuf(byte[] nameBuf, int namePos, int nameLen,
247 			FileMode mode) {
248 		if (buf == null || buf.length < ptr + entrySize(mode, nameLen))
249 			return false;
250 
251 		mode.copyTo(buf, ptr);
252 		ptr += mode.copyToLength();
253 		buf[ptr++] = ' ';
254 
255 		System.arraycopy(nameBuf, namePos, buf, ptr, nameLen);
256 		ptr += nameLen;
257 		buf[ptr++] = 0;
258 		return true;
259 	}
260 
261 	private void fmtOverflowBuffer(byte[] nameBuf, int namePos, int nameLen,
262 			FileMode mode) throws IOException {
263 		if (buf != null) {
264 			overflowBuffer = new TemporaryBuffer.Heap(Integer.MAX_VALUE);
265 			overflowBuffer.write(buf, 0, ptr);
266 			buf = null;
267 		}
268 
269 		mode.copyTo(overflowBuffer);
270 		overflowBuffer.write((byte) ' ');
271 		overflowBuffer.write(nameBuf, namePos, nameLen);
272 		overflowBuffer.write((byte) 0);
273 	}
274 
275 	/**
276 	 * Insert this tree and obtain its ObjectId.
277 	 *
278 	 * @param ins
279 	 *            the inserter to store the tree.
280 	 * @return computed ObjectId of the tree
281 	 * @throws IOException
282 	 *             the tree could not be stored.
283 	 */
284 	public ObjectId insertTo(ObjectInserter ins) throws IOException {
285 		if (buf != null)
286 			return ins.insert(OBJ_TREE, buf, 0, ptr);
287 
288 		final long len = overflowBuffer.length();
289 		return ins.insert(OBJ_TREE, len, overflowBuffer.openInputStream());
290 	}
291 
292 	/**
293 	 * Compute the ObjectId for this tree
294 	 *
295 	 * @param ins
296 	 * @return ObjectId for this tree
297 	 */
298 	public ObjectId computeId(ObjectInserter ins) {
299 		if (buf != null)
300 			return ins.idFor(OBJ_TREE, buf, 0, ptr);
301 
302 		final long len = overflowBuffer.length();
303 		try {
304 			return ins.idFor(OBJ_TREE, len, overflowBuffer.openInputStream());
305 		} catch (IOException e) {
306 			// this should never happen
307 			throw new RuntimeException(e);
308 		}
309 	}
310 
311 	/**
312 	 * Copy this formatter's buffer into a byte array.
313 	 *
314 	 * This method is not efficient, as it needs to create a copy of the
315 	 * internal buffer in order to supply an array of the correct size to the
316 	 * caller. If the buffer is just to pass to an ObjectInserter, consider
317 	 * using {@link ObjectInserter#insert(TreeFormatter)} instead.
318 	 *
319 	 * @return a copy of this formatter's buffer.
320 	 */
321 	public byte[] toByteArray() {
322 		if (buf != null) {
323 			byte[] r = new byte[ptr];
324 			System.arraycopy(buf, 0, r, 0, ptr);
325 			return r;
326 		}
327 
328 		try {
329 			return overflowBuffer.toByteArray();
330 		} catch (IOException err) {
331 			// This should never happen, its read failure on a byte array.
332 			throw new RuntimeException(err);
333 		}
334 	}
335 
336 	@SuppressWarnings("nls")
337 	@Override
338 	public String toString() {
339 		byte[] raw = toByteArray();
340 
341 		CanonicalTreeParser p = new CanonicalTreeParser();
342 		p.reset(raw);
343 
344 		StringBuilder r = new StringBuilder();
345 		r.append("Tree={");
346 		if (!p.eof()) {
347 			r.append('\n');
348 			try {
349 				new ObjectChecker().checkTree(raw);
350 			} catch (CorruptObjectException error) {
351 				r.append("*** ERROR: ").append(error.getMessage()).append("\n");
352 				r.append('\n');
353 			}
354 		}
355 		while (!p.eof()) {
356 			final FileMode mode = p.getEntryFileMode();
357 			r.append(mode);
358 			r.append(' ');
359 			r.append(Constants.typeString(mode.getObjectType()));
360 			r.append(' ');
361 			r.append(p.getEntryObjectId().name());
362 			r.append(' ');
363 			r.append(p.getEntryPathString());
364 			r.append('\n');
365 			p.next();
366 		}
367 		r.append("}");
368 		return r.toString();
369 	}
370 }