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

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