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