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 static java.nio.charset.StandardCharsets.UTF_8;
49  
50  import java.io.ByteArrayOutputStream;
51  import java.io.IOException;
52  import java.io.OutputStream;
53  import java.io.OutputStreamWriter;
54  import java.io.UnsupportedEncodingException;
55  import java.nio.charset.Charset;
56  import java.text.MessageFormat;
57  import java.util.List;
58  
59  import org.eclipse.jgit.internal.JGitText;
60  import org.eclipse.jgit.util.References;
61  
62  /**
63   * Mutable builder to construct a commit recording the state of a project.
64   *
65   * Applications should use this object when they need to manually construct a
66   * commit and want precise control over its fields. For a higher level interface
67   * see {@link org.eclipse.jgit.api.CommitCommand}.
68   *
69   * To read a commit object, construct a {@link org.eclipse.jgit.revwalk.RevWalk}
70   * and obtain a {@link org.eclipse.jgit.revwalk.RevCommit} instance by calling
71   * {@link org.eclipse.jgit.revwalk.RevWalk#parseCommit(AnyObjectId)}.
72   */
73  public class CommitBuilder {
74  	private static final ObjectIdObjectId[] EMPTY_OBJECTID_LIST = new ObjectId[0];
75  
76  	private static final byte[] htree = Constants.encodeASCII("tree"); //$NON-NLS-1$
77  
78  	private static final byte[] hparent = Constants.encodeASCII("parent"); //$NON-NLS-1$
79  
80  	private static final byte[] hauthor = Constants.encodeASCII("author"); //$NON-NLS-1$
81  
82  	private static final byte[] hcommitter = Constants.encodeASCII("committer"); //$NON-NLS-1$
83  
84  	private static final byte[] hgpgsig = Constants.encodeASCII("gpgsig"); //$NON-NLS-1$
85  
86  	private static final byte[] hencoding = Constants.encodeASCII("encoding"); //$NON-NLS-1$
87  
88  	private ObjectId treeId;
89  
90  	private ObjectId[] parentIds;
91  
92  	private PersonIdent author;
93  
94  	private PersonIdent committer;
95  
96  	private GpgSignature gpgSignature;
97  
98  	private String message;
99  
100 	private Charset encoding;
101 
102 	/**
103 	 * Initialize an empty commit.
104 	 */
105 	public CommitBuilder() {
106 		parentIds = EMPTY_OBJECTID_LIST;
107 		encoding = UTF_8;
108 	}
109 
110 	/**
111 	 * Get id of the root tree listing this commit's snapshot.
112 	 *
113 	 * @return id of the root tree listing this commit's snapshot.
114 	 */
115 	public ObjectId getTreeId() {
116 		return treeId;
117 	}
118 
119 	/**
120 	 * Set the tree id for this commit object.
121 	 *
122 	 * @param id
123 	 *            the tree identity.
124 	 */
125 	public void setTreeId(AnyObjectId id) {
126 		treeId = id.copy();
127 	}
128 
129 	/**
130 	 * Get the author of this commit (who wrote it).
131 	 *
132 	 * @return the author of this commit (who wrote it).
133 	 */
134 	public PersonIdent getAuthor() {
135 		return author;
136 	}
137 
138 	/**
139 	 * Set the author (name, email address, and date) of who wrote the commit.
140 	 *
141 	 * @param newAuthor
142 	 *            the new author. Should not be null.
143 	 */
144 	public void setAuthor(PersonIdent newAuthor) {
145 		author = newAuthor;
146 	}
147 
148 	/**
149 	 * Get the committer and commit time for this object.
150 	 *
151 	 * @return the committer and commit time for this object.
152 	 */
153 	public PersonIdent getCommitter() {
154 		return committer;
155 	}
156 
157 	/**
158 	 * Set the committer and commit time for this object.
159 	 *
160 	 * @param newCommitter
161 	 *            the committer information. Should not be null.
162 	 */
163 	public void setCommitter(PersonIdent newCommitter) {
164 		committer = newCommitter;
165 	}
166 
167 	/**
168 	 * Set the GPG signature of this commit.
169 	 * <p>
170 	 * Note, the signature set here will change the payload of the commit, i.e.
171 	 * the output of {@link #build()} will include the signature. Thus, the
172 	 * typical flow will be:
173 	 * <ol>
174 	 * <li>call {@link #build()} without a signature set to obtain payload</li>
175 	 * <li>create {@link GpgSignature} from payload</li>
176 	 * <li>set {@link GpgSignature}</li>
177 	 * </ol>
178 	 * </p>
179 	 *
180 	 * @param newSignature
181 	 *            the signature to set or <code>null</code> to unset
182 	 * @since 5.3
183 	 */
184 	public void setGpgSignature(GpgSignature newSignature) {
185 		gpgSignature = newSignature;
186 	}
187 
188 	/**
189 	 * Get the GPG signature of this commit.
190 	 *
191 	 * @return the GPG signature of this commit, maybe <code>null</code> if the
192 	 *         commit is not to be signed
193 	 * @since 5.3
194 	 */
195 	public GpgSignature getGpgSignature() {
196 		return gpgSignature;
197 	}
198 
199 	/**
200 	 * Get the ancestors of this commit.
201 	 *
202 	 * @return the ancestors of this commit. Never null.
203 	 */
204 	public ObjectId[] getParentIds() {
205 		return parentIds;
206 	}
207 
208 	/**
209 	 * Set the parent of this commit.
210 	 *
211 	 * @param newParent
212 	 *            the single parent for the commit.
213 	 */
214 	public void setParentId(AnyObjectId newParent) {
215 		parentIds = new ObjectId[] { newParent.copy() };
216 	}
217 
218 	/**
219 	 * Set the parents of this commit.
220 	 *
221 	 * @param parent1
222 	 *            the first parent of this commit. Typically this is the current
223 	 *            value of the {@code HEAD} reference and is thus the current
224 	 *            branch's position in history.
225 	 * @param parent2
226 	 *            the second parent of this merge commit. Usually this is the
227 	 *            branch being merged into the current branch.
228 	 */
229 	public void setParentIds(AnyObjectId./../../org/eclipse/jgit/lib/AnyObjectId.html#AnyObjectId">AnyObjectId parent1, AnyObjectId parent2) {
230 		parentIds = new ObjectId[] { parent1.copy(), parent2.copy() };
231 	}
232 
233 	/**
234 	 * Set the parents of this commit.
235 	 *
236 	 * @param newParents
237 	 *            the entire list of parents for this commit.
238 	 */
239 	public void setParentIds(ObjectId... newParents) {
240 		parentIds = new ObjectId[newParents.length];
241 		for (int i = 0; i < newParents.length; i++)
242 			parentIds[i] = newParents[i].copy();
243 	}
244 
245 	/**
246 	 * Set the parents of this commit.
247 	 *
248 	 * @param newParents
249 	 *            the entire list of parents for this commit.
250 	 */
251 	public void setParentIds(List<? extends AnyObjectId> newParents) {
252 		parentIds = new ObjectId[newParents.size()];
253 		for (int i = 0; i < newParents.size(); i++)
254 			parentIds[i] = newParents.get(i).copy();
255 	}
256 
257 	/**
258 	 * Add a parent onto the end of the parent list.
259 	 *
260 	 * @param additionalParent
261 	 *            new parent to add onto the end of the current parent list.
262 	 */
263 	public void addParentId(AnyObjectId additionalParent) {
264 		if (parentIds.length == 0) {
265 			setParentId(additionalParent);
266 		} else {
267 			ObjectId[] newParents = new ObjectId[parentIds.length + 1];
268 			System.arraycopy(parentIds, 0, newParents, 0, parentIds.length);
269 			newParents[parentIds.length] = additionalParent.copy();
270 			parentIds = newParents;
271 		}
272 	}
273 
274 	/**
275 	 * Get the complete commit message.
276 	 *
277 	 * @return the complete commit message.
278 	 */
279 	public String getMessage() {
280 		return message;
281 	}
282 
283 	/**
284 	 * Set the commit message.
285 	 *
286 	 * @param newMessage
287 	 *            the commit message. Should not be null.
288 	 */
289 	public void setMessage(String newMessage) {
290 		message = newMessage;
291 	}
292 
293 	/**
294 	 * Set the encoding for the commit information.
295 	 *
296 	 * @param encodingName
297 	 *            the encoding name. See
298 	 *            {@link java.nio.charset.Charset#forName(String)}.
299 	 * @deprecated use {@link #setEncoding(Charset)} instead.
300 	 */
301 	@Deprecated
302 	public void setEncoding(String encodingName) {
303 		encoding = Charset.forName(encodingName);
304 	}
305 
306 	/**
307 	 * Set the encoding for the commit information.
308 	 *
309 	 * @param enc
310 	 *            the encoding to use.
311 	 */
312 	public void setEncoding(Charset enc) {
313 		encoding = enc;
314 	}
315 
316 	/**
317 	 * Get the encoding that should be used for the commit message text.
318 	 *
319 	 * @return the encoding that should be used for the commit message text.
320 	 */
321 	public Charset getEncoding() {
322 		return encoding;
323 	}
324 
325 	/**
326 	 * Format this builder's state as a commit object.
327 	 *
328 	 * @return this object in the canonical commit format, suitable for storage
329 	 *         in a repository.
330 	 * @throws java.io.UnsupportedEncodingException
331 	 *             the encoding specified by {@link #getEncoding()} is not
332 	 *             supported by this Java runtime.
333 	 */
334 	public byte[] build() throws UnsupportedEncodingException {
335 		ByteArrayOutputStream os = new ByteArrayOutputStream();
336 		OutputStreamWriter w = new OutputStreamWriter(os, getEncoding());
337 		try {
338 			os.write(htree);
339 			os.write(' ');
340 			getTreeId().copyTo(os);
341 			os.write('\n');
342 
343 			for (ObjectId p : getParentIds()) {
344 				os.write(hparent);
345 				os.write(' ');
346 				p.copyTo(os);
347 				os.write('\n');
348 			}
349 
350 			os.write(hauthor);
351 			os.write(' ');
352 			w.write(getAuthor().toExternalString());
353 			w.flush();
354 			os.write('\n');
355 
356 			os.write(hcommitter);
357 			os.write(' ');
358 			w.write(getCommitter().toExternalString());
359 			w.flush();
360 			os.write('\n');
361 
362 			if (getGpgSignature() != null) {
363 				os.write(hgpgsig);
364 				os.write(' ');
365 				writeGpgSignatureString(getGpgSignature().toExternalString(), os);
366 				os.write('\n');
367 			}
368 
369 			if (!References.isSameObject(getEncoding(), UTF_8)) {
370 				os.write(hencoding);
371 				os.write(' ');
372 				os.write(Constants.encodeASCII(getEncoding().name()));
373 				os.write('\n');
374 			}
375 
376 			os.write('\n');
377 
378 			if (getMessage() != null) {
379 				w.write(getMessage());
380 				w.flush();
381 			}
382 		} catch (IOException err) {
383 			// This should never occur, the only way to get it above is
384 			// for the ByteArrayOutputStream to throw, but it doesn't.
385 			//
386 			throw new RuntimeException(err);
387 		}
388 		return os.toByteArray();
389 	}
390 
391 	/**
392 	 * Writes signature to output as per <a href=
393 	 * "https://github.com/git/git/blob/master/Documentation/technical/signature-format.txt#L66,L89">gpgsig
394 	 * header</a>.
395 	 * <p>
396 	 * CRLF and CR will be sanitized to LF and signature will have a hanging
397 	 * indent of one space starting with line two.
398 	 * </p>
399 	 *
400 	 * @param in
401 	 *            signature string with line breaks
402 	 * @param out
403 	 *            output stream
404 	 * @throws IOException
405 	 *             thrown by the output stream
406 	 * @throws IllegalArgumentException
407 	 *             if the signature string contains non 7-bit ASCII chars
408 	 */
409 	static void writeGpgSignatureString(String in, OutputStream out)
410 			throws IOException, IllegalArgumentException {
411 		for (int i = 0; i < in.length(); ++i) {
412 			char ch = in.charAt(i);
413 			if (ch == '\r') {
414 				if (i + 1 < in.length() && in.charAt(i + 1) == '\n') {
415 					out.write('\n');
416 					out.write(' ');
417 					++i;
418 				} else {
419 					out.write('\n');
420 					out.write(' ');
421 				}
422 			} else if (ch == '\n') {
423 				out.write('\n');
424 				out.write(' ');
425 			} else {
426 				// sanity check
427 				if (ch > 127)
428 					throw new IllegalArgumentException(MessageFormat
429 							.format(JGitText.get().notASCIIString, in));
430 				out.write(ch);
431 			}
432 		}
433 	}
434 
435 	/**
436 	 * Format this builder's state as a commit object.
437 	 *
438 	 * @return this object in the canonical commit format, suitable for storage
439 	 *         in a repository.
440 	 * @throws java.io.UnsupportedEncodingException
441 	 *             the encoding specified by {@link #getEncoding()} is not
442 	 *             supported by this Java runtime.
443 	 */
444 	public byte[] toByteArray() throws UnsupportedEncodingException {
445 		return build();
446 	}
447 
448 	/** {@inheritDoc} */
449 	@SuppressWarnings("nls")
450 	@Override
451 	public String toString() {
452 		StringBuilder r = new StringBuilder();
453 		r.append("Commit");
454 		r.append("={\n");
455 
456 		r.append("tree ");
457 		r.append(treeId != null ? treeId.name() : "NOT_SET");
458 		r.append("\n");
459 
460 		for (ObjectId p : parentIds) {
461 			r.append("parent ");
462 			r.append(p.name());
463 			r.append("\n");
464 		}
465 
466 		r.append("author ");
467 		r.append(author != null ? author.toString() : "NOT_SET");
468 		r.append("\n");
469 
470 		r.append("committer ");
471 		r.append(committer != null ? committer.toString() : "NOT_SET");
472 		r.append("\n");
473 
474 		r.append("gpgSignature ");
475 		r.append(gpgSignature != null ? gpgSignature.toString() : "NOT_SET");
476 		r.append("\n");
477 
478 		if (encoding != null && !References.isSameObject(encoding, UTF_8)) {
479 			r.append("encoding ");
480 			r.append(encoding.name());
481 			r.append("\n");
482 		}
483 
484 		r.append("\n");
485 		r.append(message != null ? message : "");
486 		r.append("}");
487 		return r.toString();
488 	}
489 }