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, 2020, 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.OutputStreamWriter;
20  import java.io.UnsupportedEncodingException;
21  import java.nio.charset.Charset;
22  import java.util.List;
23  
24  import org.eclipse.jgit.util.References;
25  
26  /**
27   * Mutable builder to construct a commit recording the state of a project.
28   *
29   * Applications should use this object when they need to manually construct a
30   * commit and want precise control over its fields. For a higher level interface
31   * see {@link org.eclipse.jgit.api.CommitCommand}.
32   *
33   * To read a commit object, construct a {@link org.eclipse.jgit.revwalk.RevWalk}
34   * and obtain a {@link org.eclipse.jgit.revwalk.RevCommit} instance by calling
35   * {@link org.eclipse.jgit.revwalk.RevWalk#parseCommit(AnyObjectId)}.
36   */
37  public class CommitBuilder extends ObjectBuilder {
38  	private static final ObjectId[] EMPTY_OBJECTID_LIST = new ObjectId[0];
39  
40  	private static final byte[] htree = Constants.encodeASCII("tree"); //$NON-NLS-1$
41  
42  	private static final byte[] hparent = Constants.encodeASCII("parent"); //$NON-NLS-1$
43  
44  	private static final byte[] hauthor = Constants.encodeASCII("author"); //$NON-NLS-1$
45  
46  	private static final byte[] hcommitter = Constants.encodeASCII("committer"); //$NON-NLS-1$
47  
48  	private static final byte[] hgpgsig = Constants.encodeASCII("gpgsig"); //$NON-NLS-1$
49  
50  	private ObjectId treeId;
51  
52  	private ObjectId[] parentIds;
53  
54  	private PersonIdent committer;
55  
56  	/**
57  	 * Initialize an empty commit.
58  	 */
59  	public CommitBuilder() {
60  		parentIds = EMPTY_OBJECTID_LIST;
61  	}
62  
63  	/**
64  	 * Get id of the root tree listing this commit's snapshot.
65  	 *
66  	 * @return id of the root tree listing this commit's snapshot.
67  	 */
68  	public ObjectId getTreeId() {
69  		return treeId;
70  	}
71  
72  	/**
73  	 * Set the tree id for this commit object.
74  	 *
75  	 * @param id
76  	 *            the tree identity.
77  	 */
78  	public void setTreeId(AnyObjectId id) {
79  		treeId = id.copy();
80  	}
81  
82  	/**
83  	 * Get the author of this commit (who wrote it).
84  	 *
85  	 * @return the author of this commit (who wrote it).
86  	 */
87  	@Override
88  	public PersonIdent getAuthor() {
89  		return super.getAuthor();
90  	}
91  
92  	/**
93  	 * Set the author (name, email address, and date) of who wrote the commit.
94  	 *
95  	 * @param newAuthor
96  	 *            the new author. Should not be null.
97  	 */
98  	@Override
99  	public void setAuthor(PersonIdent newAuthor) {
100 		super.setAuthor(newAuthor);
101 	}
102 
103 	/**
104 	 * Get the committer and commit time for this object.
105 	 *
106 	 * @return the committer and commit time for this object.
107 	 */
108 	public PersonIdent getCommitter() {
109 		return committer;
110 	}
111 
112 	/**
113 	 * Set the committer and commit time for this object.
114 	 *
115 	 * @param newCommitter
116 	 *            the committer information. Should not be null.
117 	 */
118 	public void setCommitter(PersonIdent newCommitter) {
119 		committer = newCommitter;
120 	}
121 
122 	/**
123 	 * Get the ancestors of this commit.
124 	 *
125 	 * @return the ancestors of this commit. Never null.
126 	 */
127 	public ObjectId[] getParentIds() {
128 		return parentIds;
129 	}
130 
131 	/**
132 	 * Set the parent of this commit.
133 	 *
134 	 * @param newParent
135 	 *            the single parent for the commit.
136 	 */
137 	public void setParentId(AnyObjectId newParent) {
138 		parentIds = new ObjectId[] { newParent.copy() };
139 	}
140 
141 	/**
142 	 * Set the parents of this commit.
143 	 *
144 	 * @param parent1
145 	 *            the first parent of this commit. Typically this is the current
146 	 *            value of the {@code HEAD} reference and is thus the current
147 	 *            branch's position in history.
148 	 * @param parent2
149 	 *            the second parent of this merge commit. Usually this is the
150 	 *            branch being merged into the current branch.
151 	 */
152 	public void setParentIds(AnyObjectId parent1, AnyObjectId parent2) {
153 		parentIds = new ObjectId[] { parent1.copy(), parent2.copy() };
154 	}
155 
156 	/**
157 	 * Set the parents of this commit.
158 	 *
159 	 * @param newParents
160 	 *            the entire list of parents for this commit.
161 	 */
162 	public void setParentIds(ObjectId... newParents) {
163 		parentIds = new ObjectId[newParents.length];
164 		for (int i = 0; i < newParents.length; i++)
165 			parentIds[i] = newParents[i].copy();
166 	}
167 
168 	/**
169 	 * Set the parents of this commit.
170 	 *
171 	 * @param newParents
172 	 *            the entire list of parents for this commit.
173 	 */
174 	public void setParentIds(List<? extends AnyObjectId> newParents) {
175 		parentIds = new ObjectId[newParents.size()];
176 		for (int i = 0; i < newParents.size(); i++)
177 			parentIds[i] = newParents.get(i).copy();
178 	}
179 
180 	/**
181 	 * Add a parent onto the end of the parent list.
182 	 *
183 	 * @param additionalParent
184 	 *            new parent to add onto the end of the current parent list.
185 	 */
186 	public void addParentId(AnyObjectId additionalParent) {
187 		if (parentIds.length == 0) {
188 			setParentId(additionalParent);
189 		} else {
190 			ObjectId[] newParents = new ObjectId[parentIds.length + 1];
191 			System.arraycopy(parentIds, 0, newParents, 0, parentIds.length);
192 			newParents[parentIds.length] = additionalParent.copy();
193 			parentIds = newParents;
194 		}
195 	}
196 
197 	/**
198 	 * Set the encoding for the commit information.
199 	 *
200 	 * @param encodingName
201 	 *            the encoding name. See
202 	 *            {@link java.nio.charset.Charset#forName(String)}.
203 	 * @deprecated use {@link #setEncoding(Charset)} instead.
204 	 */
205 	@Deprecated
206 	public void setEncoding(String encodingName) {
207 		setEncoding(Charset.forName(encodingName));
208 	}
209 
210 	@Override
211 	public byte[] build() throws UnsupportedEncodingException {
212 		ByteArrayOutputStream os = new ByteArrayOutputStream();
213 		OutputStreamWriter w = new OutputStreamWriter(os, getEncoding());
214 		try {
215 			os.write(htree);
216 			os.write(' ');
217 			getTreeId().copyTo(os);
218 			os.write('\n');
219 
220 			for (ObjectId p : getParentIds()) {
221 				os.write(hparent);
222 				os.write(' ');
223 				p.copyTo(os);
224 				os.write('\n');
225 			}
226 
227 			os.write(hauthor);
228 			os.write(' ');
229 			w.write(getAuthor().toExternalString());
230 			w.flush();
231 			os.write('\n');
232 
233 			os.write(hcommitter);
234 			os.write(' ');
235 			w.write(getCommitter().toExternalString());
236 			w.flush();
237 			os.write('\n');
238 
239 			GpgSignature signature = getGpgSignature();
240 			if (signature != null) {
241 				os.write(hgpgsig);
242 				os.write(' ');
243 				writeMultiLineHeader(signature.toExternalString(), os,
244 						true);
245 				os.write('\n');
246 			}
247 
248 			writeEncoding(getEncoding(), os);
249 
250 			os.write('\n');
251 
252 			if (getMessage() != null) {
253 				w.write(getMessage());
254 				w.flush();
255 			}
256 		} catch (IOException err) {
257 			// This should never occur, the only way to get it above is
258 			// for the ByteArrayOutputStream to throw, but it doesn't.
259 			//
260 			throw new RuntimeException(err);
261 		}
262 		return os.toByteArray();
263 	}
264 
265 	/**
266 	 * Format this builder's state as a commit object.
267 	 *
268 	 * @return this object in the canonical commit format, suitable for storage
269 	 *         in a repository.
270 	 * @throws java.io.UnsupportedEncodingException
271 	 *             the encoding specified by {@link #getEncoding()} is not
272 	 *             supported by this Java runtime.
273 	 */
274 	public byte[] toByteArray() throws UnsupportedEncodingException {
275 		return build();
276 	}
277 
278 	/** {@inheritDoc} */
279 	@SuppressWarnings("nls")
280 	@Override
281 	public String toString() {
282 		StringBuilder r = new StringBuilder();
283 		r.append("Commit");
284 		r.append("={\n");
285 
286 		r.append("tree ");
287 		r.append(treeId != null ? treeId.name() : "NOT_SET");
288 		r.append("\n");
289 
290 		for (ObjectId p : parentIds) {
291 			r.append("parent ");
292 			r.append(p.name());
293 			r.append("\n");
294 		}
295 
296 		r.append("author ");
297 		r.append(getAuthor() != null ? getAuthor().toString() : "NOT_SET");
298 		r.append("\n");
299 
300 		r.append("committer ");
301 		r.append(committer != null ? committer.toString() : "NOT_SET");
302 		r.append("\n");
303 
304 		r.append("gpgSignature ");
305 		GpgSignature signature = getGpgSignature();
306 		r.append(signature != null ? signature.toString()
307 				: "NOT_SET");
308 		r.append("\n");
309 
310 		Charset encoding = getEncoding();
311 		if (!References.isSameObject(encoding, UTF_8)) {
312 			r.append("encoding ");
313 			r.append(encoding.name());
314 			r.append("\n");
315 		}
316 
317 		r.append("\n");
318 		r.append(getMessage() != null ? getMessage() : "");
319 		r.append("}");
320 		return r.toString();
321 	}
322 }