You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CommitBuilder.java 11KB

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