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