View Javadoc
1   /*
2    * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
3    * Copyright (C) 2006-2007, Robin Rosenberg <robin.rosenberg@dewire.com>
4    * Copyright (C) 2006-2007, Shawn O. Pearce <spearce@spearce.org>
5    * and other copyright owners as documented in the project's IP log.
6    *
7    * This program and the accompanying materials are made available
8    * under the terms of the Eclipse Distribution License v1.0 which
9    * accompanies this distribution, is reproduced below, and is
10   * available at http://www.eclipse.org/org/documents/edl-v10.php
11   *
12   * All rights reserved.
13   *
14   * Redistribution and use in source and binary forms, with or
15   * without modification, are permitted provided that the following
16   * conditions are met:
17   *
18   * - Redistributions of source code must retain the above copyright
19   *   notice, this list of conditions and the following disclaimer.
20   *
21   * - Redistributions in binary form must reproduce the above
22   *   copyright notice, this list of conditions and the following
23   *   disclaimer in the documentation and/or other materials provided
24   *   with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the
27   *   names of its contributors may be used to endorse or promote
28   *   products derived from this software without specific prior
29   *   written permission.
30   *
31   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44   */
45  
46  package org.eclipse.jgit.lib;
47  
48  import java.io.ByteArrayOutputStream;
49  import java.io.IOException;
50  import java.io.OutputStreamWriter;
51  import java.io.UnsupportedEncodingException;
52  import java.nio.charset.Charset;
53  import java.util.List;
54  
55  /**
56   * Mutable builder to construct a commit recording the state of a project.
57   *
58   * Applications should use this object when they need to manually construct a
59   * commit and want precise control over its fields. For a higher level interface
60   * see {@link org.eclipse.jgit.api.CommitCommand}.
61   *
62   * To read a commit object, construct a {@link org.eclipse.jgit.revwalk.RevWalk}
63   * and obtain a {@link org.eclipse.jgit.revwalk.RevCommit} instance by calling
64   * {@link org.eclipse.jgit.revwalk.RevWalk#parseCommit(AnyObjectId)}.
65   */
66  public class CommitBuilder {
67  	private static final ObjectId[] EMPTY_OBJECTID_LIST = new ObjectId[0];
68  
69  	private static final byte[] htree = Constants.encodeASCII("tree"); //$NON-NLS-1$
70  
71  	private static final byte[] hparent = Constants.encodeASCII("parent"); //$NON-NLS-1$
72  
73  	private static final byte[] hauthor = Constants.encodeASCII("author"); //$NON-NLS-1$
74  
75  	private static final byte[] hcommitter = Constants.encodeASCII("committer"); //$NON-NLS-1$
76  
77  	private static final byte[] hencoding = Constants.encodeASCII("encoding"); //$NON-NLS-1$
78  
79  	private ObjectId treeId;
80  
81  	private ObjectId[] parentIds;
82  
83  	private PersonIdent author;
84  
85  	private PersonIdent committer;
86  
87  	private String message;
88  
89  	private Charset encoding;
90  
91  	/**
92  	 * Initialize an empty commit.
93  	 */
94  	public CommitBuilder() {
95  		parentIds = EMPTY_OBJECTID_LIST;
96  		encoding = Constants.CHARSET;
97  	}
98  
99  	/**
100 	 * Get id of the root tree listing this commit's snapshot.
101 	 *
102 	 * @return id of the root tree listing this commit's snapshot.
103 	 */
104 	public ObjectId getTreeId() {
105 		return treeId;
106 	}
107 
108 	/**
109 	 * Set the tree id for this commit object
110 	 *
111 	 * @param id
112 	 *            the tree identity.
113 	 */
114 	public void setTreeId(AnyObjectId id) {
115 		treeId = id.copy();
116 	}
117 
118 	/**
119 	 * Get the author of this commit (who wrote it).
120 	 *
121 	 * @return the author of this commit (who wrote it).
122 	 */
123 	public PersonIdent getAuthor() {
124 		return author;
125 	}
126 
127 	/**
128 	 * Set the author (name, email address, and date) of who wrote the commit.
129 	 *
130 	 * @param newAuthor
131 	 *            the new author. Should not be null.
132 	 */
133 	public void setAuthor(PersonIdent newAuthor) {
134 		author = newAuthor;
135 	}
136 
137 	/**
138 	 * Get the committer and commit time for this object.
139 	 *
140 	 * @return the committer and commit time for this object.
141 	 */
142 	public PersonIdent getCommitter() {
143 		return committer;
144 	}
145 
146 	/**
147 	 * Set the committer and commit time for this object
148 	 *
149 	 * @param newCommitter
150 	 *            the committer information. Should not be null.
151 	 */
152 	public void setCommitter(PersonIdent newCommitter) {
153 		committer = newCommitter;
154 	}
155 
156 	/**
157 	 * Get the ancestors of this commit.
158 	 *
159 	 * @return the ancestors of this commit. Never null.
160 	 */
161 	public ObjectId[] getParentIds() {
162 		return parentIds;
163 	}
164 
165 	/**
166 	 * Set the parent of this commit.
167 	 *
168 	 * @param newParent
169 	 *            the single parent for the commit.
170 	 */
171 	public void setParentId(AnyObjectId newParent) {
172 		parentIds = new ObjectId[] { newParent.copy() };
173 	}
174 
175 	/**
176 	 * Set the parents of this commit.
177 	 *
178 	 * @param parent1
179 	 *            the first parent of this commit. Typically this is the current
180 	 *            value of the {@code HEAD} reference and is thus the current
181 	 *            branch's position in history.
182 	 * @param parent2
183 	 *            the second parent of this merge commit. Usually this is the
184 	 *            branch being merged into the current branch.
185 	 */
186 	public void setParentIds(AnyObjectId parent1, AnyObjectId parent2) {
187 		parentIds = new ObjectId[] { parent1.copy(), parent2.copy() };
188 	}
189 
190 	/**
191 	 * Set the parents of this commit.
192 	 *
193 	 * @param newParents
194 	 *            the entire list of parents for this commit.
195 	 */
196 	public void setParentIds(ObjectId... newParents) {
197 		parentIds = new ObjectId[newParents.length];
198 		for (int i = 0; i < newParents.length; i++)
199 			parentIds[i] = newParents[i].copy();
200 	}
201 
202 	/**
203 	 * Set the parents of this commit.
204 	 *
205 	 * @param newParents
206 	 *            the entire list of parents for this commit.
207 	 */
208 	public void setParentIds(List<? extends AnyObjectId> newParents) {
209 		parentIds = new ObjectId[newParents.size()];
210 		for (int i = 0; i < newParents.size(); i++)
211 			parentIds[i] = newParents.get(i).copy();
212 	}
213 
214 	/**
215 	 * Add a parent onto the end of the parent list.
216 	 *
217 	 * @param additionalParent
218 	 *            new parent to add onto the end of the current parent list.
219 	 */
220 	public void addParentId(AnyObjectId additionalParent) {
221 		if (parentIds.length == 0) {
222 			setParentId(additionalParent);
223 		} else {
224 			ObjectId[] newParents = new ObjectId[parentIds.length + 1];
225 			System.arraycopy(parentIds, 0, newParents, 0, parentIds.length);
226 			newParents[parentIds.length] = additionalParent.copy();
227 			parentIds = newParents;
228 		}
229 	}
230 
231 	/**
232 	 * Get the complete commit message.
233 	 *
234 	 * @return the complete commit message.
235 	 */
236 	public String getMessage() {
237 		return message;
238 	}
239 
240 	/**
241 	 * Set the commit message.
242 	 *
243 	 * @param newMessage
244 	 *            the commit message. Should not be null.
245 	 */
246 	public void setMessage(String newMessage) {
247 		message = newMessage;
248 	}
249 
250 	/**
251 	 * Set the encoding for the commit information
252 	 *
253 	 * @param encodingName
254 	 *            the encoding name. See
255 	 *            {@link java.nio.charset.Charset#forName(String)}.
256 	 */
257 	public void setEncoding(String encodingName) {
258 		encoding = Charset.forName(encodingName);
259 	}
260 
261 	/**
262 	 * Set the encoding for the commit information
263 	 *
264 	 * @param enc
265 	 *            the encoding to use.
266 	 */
267 	public void setEncoding(Charset enc) {
268 		encoding = enc;
269 	}
270 
271 	/**
272 	 * Get the encoding that should be used for the commit message text.
273 	 *
274 	 * @return the encoding that should be used for the commit message text.
275 	 */
276 	public Charset getEncoding() {
277 		return encoding;
278 	}
279 
280 	/**
281 	 * Format this builder's state as a commit object.
282 	 *
283 	 * @return this object in the canonical commit format, suitable for storage
284 	 *         in a repository.
285 	 * @throws java.io.UnsupportedEncodingException
286 	 *             the encoding specified by {@link #getEncoding()} is not
287 	 *             supported by this Java runtime.
288 	 */
289 	public byte[] build() throws UnsupportedEncodingException {
290 		ByteArrayOutputStream os = new ByteArrayOutputStream();
291 		OutputStreamWriter w = new OutputStreamWriter(os, getEncoding());
292 		try {
293 			os.write(htree);
294 			os.write(' ');
295 			getTreeId().copyTo(os);
296 			os.write('\n');
297 
298 			for (ObjectId p : getParentIds()) {
299 				os.write(hparent);
300 				os.write(' ');
301 				p.copyTo(os);
302 				os.write('\n');
303 			}
304 
305 			os.write(hauthor);
306 			os.write(' ');
307 			w.write(getAuthor().toExternalString());
308 			w.flush();
309 			os.write('\n');
310 
311 			os.write(hcommitter);
312 			os.write(' ');
313 			w.write(getCommitter().toExternalString());
314 			w.flush();
315 			os.write('\n');
316 
317 			if (getEncoding() != Constants.CHARSET) {
318 				os.write(hencoding);
319 				os.write(' ');
320 				os.write(Constants.encodeASCII(getEncoding().name()));
321 				os.write('\n');
322 			}
323 
324 			os.write('\n');
325 
326 			if (getMessage() != null) {
327 				w.write(getMessage());
328 				w.flush();
329 			}
330 		} catch (IOException err) {
331 			// This should never occur, the only way to get it above is
332 			// for the ByteArrayOutputStream to throw, but it doesn't.
333 			//
334 			throw new RuntimeException(err);
335 		}
336 		return os.toByteArray();
337 	}
338 
339 	/**
340 	 * Format this builder's state as a commit object.
341 	 *
342 	 * @return this object in the canonical commit format, suitable for storage
343 	 *         in a repository.
344 	 * @throws java.io.UnsupportedEncodingException
345 	 *             the encoding specified by {@link #getEncoding()} is not
346 	 *             supported by this Java runtime.
347 	 */
348 	public byte[] toByteArray() throws UnsupportedEncodingException {
349 		return build();
350 	}
351 
352 	/** {@inheritDoc} */
353 	@SuppressWarnings("nls")
354 	@Override
355 	public String toString() {
356 		StringBuilder r = new StringBuilder();
357 		r.append("Commit");
358 		r.append("={\n");
359 
360 		r.append("tree ");
361 		r.append(treeId != null ? treeId.name() : "NOT_SET");
362 		r.append("\n");
363 
364 		for (ObjectId p : parentIds) {
365 			r.append("parent ");
366 			r.append(p.name());
367 			r.append("\n");
368 		}
369 
370 		r.append("author ");
371 		r.append(author != null ? author.toString() : "NOT_SET");
372 		r.append("\n");
373 
374 		r.append("committer ");
375 		r.append(committer != null ? committer.toString() : "NOT_SET");
376 		r.append("\n");
377 
378 		if (encoding != null && encoding != Constants.CHARSET) {
379 			r.append("encoding ");
380 			r.append(encoding.name());
381 			r.append("\n");
382 		}
383 
384 		r.append("\n");
385 		r.append(message != null ? message : "");
386 		r.append("}");
387 		return r.toString();
388 	}
389 }