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 13KB

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