CommitBuilder.java

  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. /**
  57.  * Mutable builder to construct a commit recording the state of a project.
  58.  *
  59.  * Applications should use this object when they need to manually construct a
  60.  * commit and want precise control over its fields. For a higher level interface
  61.  * see {@link org.eclipse.jgit.api.CommitCommand}.
  62.  *
  63.  * To read a commit object, construct a {@link org.eclipse.jgit.revwalk.RevWalk}
  64.  * and obtain a {@link org.eclipse.jgit.revwalk.RevCommit} instance by calling
  65.  * {@link org.eclipse.jgit.revwalk.RevWalk#parseCommit(AnyObjectId)}.
  66.  */
  67. public class CommitBuilder {
  68.     private static final ObjectId[] EMPTY_OBJECTID_LIST = new ObjectId[0];

  69.     private static final byte[] htree = Constants.encodeASCII("tree"); //$NON-NLS-1$

  70.     private static final byte[] hparent = Constants.encodeASCII("parent"); //$NON-NLS-1$

  71.     private static final byte[] hauthor = Constants.encodeASCII("author"); //$NON-NLS-1$

  72.     private static final byte[] hcommitter = Constants.encodeASCII("committer"); //$NON-NLS-1$

  73.     private static final byte[] hgpgsig = Constants.encodeASCII("gpgsig"); //$NON-NLS-1$

  74.     private static final byte[] hencoding = Constants.encodeASCII("encoding"); //$NON-NLS-1$

  75.     private ObjectId treeId;

  76.     private ObjectId[] parentIds;

  77.     private PersonIdent author;

  78.     private PersonIdent committer;

  79.     private GpgSignature gpgSignature;

  80.     private String message;

  81.     private Charset encoding;

  82.     /**
  83.      * Initialize an empty commit.
  84.      */
  85.     public CommitBuilder() {
  86.         parentIds = EMPTY_OBJECTID_LIST;
  87.         encoding = UTF_8;
  88.     }

  89.     /**
  90.      * Get id of the root tree listing this commit's snapshot.
  91.      *
  92.      * @return id of the root tree listing this commit's snapshot.
  93.      */
  94.     public ObjectId getTreeId() {
  95.         return treeId;
  96.     }

  97.     /**
  98.      * Set the tree id for this commit object.
  99.      *
  100.      * @param id
  101.      *            the tree identity.
  102.      */
  103.     public void setTreeId(AnyObjectId id) {
  104.         treeId = id.copy();
  105.     }

  106.     /**
  107.      * Get the author of this commit (who wrote it).
  108.      *
  109.      * @return the author of this commit (who wrote it).
  110.      */
  111.     public PersonIdent getAuthor() {
  112.         return author;
  113.     }

  114.     /**
  115.      * Set the author (name, email address, and date) of who wrote the commit.
  116.      *
  117.      * @param newAuthor
  118.      *            the new author. Should not be null.
  119.      */
  120.     public void setAuthor(PersonIdent newAuthor) {
  121.         author = newAuthor;
  122.     }

  123.     /**
  124.      * Get the committer and commit time for this object.
  125.      *
  126.      * @return the committer and commit time for this object.
  127.      */
  128.     public PersonIdent getCommitter() {
  129.         return committer;
  130.     }

  131.     /**
  132.      * Set the committer and commit time for this object.
  133.      *
  134.      * @param newCommitter
  135.      *            the committer information. Should not be null.
  136.      */
  137.     public void setCommitter(PersonIdent newCommitter) {
  138.         committer = newCommitter;
  139.     }

  140.     /**
  141.      * Set the GPG signature of this commit.
  142.      * <p>
  143.      * Note, the signature set here will change the payload of the commit, i.e.
  144.      * the output of {@link #build()} will include the signature. Thus, the
  145.      * typical flow will be:
  146.      * <ol>
  147.      * <li>call {@link #build()} without a signature set to obtain payload</li>
  148.      * <li>create {@link GpgSignature} from payload</li>
  149.      * <li>set {@link GpgSignature}</li>
  150.      * </ol>
  151.      * </p>
  152.      *
  153.      * @param newSignature
  154.      *            the signature to set or <code>null</code> to unset
  155.      * @since 5.3
  156.      */
  157.     public void setGpgSignature(GpgSignature newSignature) {
  158.         gpgSignature = newSignature;
  159.     }

  160.     /**
  161.      * Get the GPG signature of this commit.
  162.      *
  163.      * @return the GPG signature of this commit, maybe <code>null</code> if the
  164.      *         commit is not to be signed
  165.      * @since 5.3
  166.      */
  167.     public GpgSignature getGpgSignature() {
  168.         return gpgSignature;
  169.     }

  170.     /**
  171.      * Get the ancestors of this commit.
  172.      *
  173.      * @return the ancestors of this commit. Never null.
  174.      */
  175.     public ObjectId[] getParentIds() {
  176.         return parentIds;
  177.     }

  178.     /**
  179.      * Set the parent of this commit.
  180.      *
  181.      * @param newParent
  182.      *            the single parent for the commit.
  183.      */
  184.     public void setParentId(AnyObjectId newParent) {
  185.         parentIds = new ObjectId[] { newParent.copy() };
  186.     }

  187.     /**
  188.      * Set the parents of this commit.
  189.      *
  190.      * @param parent1
  191.      *            the first parent of this commit. Typically this is the current
  192.      *            value of the {@code HEAD} reference and is thus the current
  193.      *            branch's position in history.
  194.      * @param parent2
  195.      *            the second parent of this merge commit. Usually this is the
  196.      *            branch being merged into the current branch.
  197.      */
  198.     public void setParentIds(AnyObjectId parent1, AnyObjectId parent2) {
  199.         parentIds = new ObjectId[] { parent1.copy(), parent2.copy() };
  200.     }

  201.     /**
  202.      * Set the parents of this commit.
  203.      *
  204.      * @param newParents
  205.      *            the entire list of parents for this commit.
  206.      */
  207.     public void setParentIds(ObjectId... newParents) {
  208.         parentIds = new ObjectId[newParents.length];
  209.         for (int i = 0; i < newParents.length; i++)
  210.             parentIds[i] = newParents[i].copy();
  211.     }

  212.     /**
  213.      * Set the parents of this commit.
  214.      *
  215.      * @param newParents
  216.      *            the entire list of parents for this commit.
  217.      */
  218.     public void setParentIds(List<? extends AnyObjectId> newParents) {
  219.         parentIds = new ObjectId[newParents.size()];
  220.         for (int i = 0; i < newParents.size(); i++)
  221.             parentIds[i] = newParents.get(i).copy();
  222.     }

  223.     /**
  224.      * Add a parent onto the end of the parent list.
  225.      *
  226.      * @param additionalParent
  227.      *            new parent to add onto the end of the current parent list.
  228.      */
  229.     public void addParentId(AnyObjectId additionalParent) {
  230.         if (parentIds.length == 0) {
  231.             setParentId(additionalParent);
  232.         } else {
  233.             ObjectId[] newParents = new ObjectId[parentIds.length + 1];
  234.             System.arraycopy(parentIds, 0, newParents, 0, parentIds.length);
  235.             newParents[parentIds.length] = additionalParent.copy();
  236.             parentIds = newParents;
  237.         }
  238.     }

  239.     /**
  240.      * Get the complete commit message.
  241.      *
  242.      * @return the complete commit message.
  243.      */
  244.     public String getMessage() {
  245.         return message;
  246.     }

  247.     /**
  248.      * Set the commit message.
  249.      *
  250.      * @param newMessage
  251.      *            the commit message. Should not be null.
  252.      */
  253.     public void setMessage(String newMessage) {
  254.         message = newMessage;
  255.     }

  256.     /**
  257.      * Set the encoding for the commit information.
  258.      *
  259.      * @param encodingName
  260.      *            the encoding name. See
  261.      *            {@link java.nio.charset.Charset#forName(String)}.
  262.      * @deprecated use {@link #setEncoding(Charset)} instead.
  263.      */
  264.     @Deprecated
  265.     public void setEncoding(String encodingName) {
  266.         encoding = Charset.forName(encodingName);
  267.     }

  268.     /**
  269.      * Set the encoding for the commit information.
  270.      *
  271.      * @param enc
  272.      *            the encoding to use.
  273.      */
  274.     public void setEncoding(Charset enc) {
  275.         encoding = enc;
  276.     }

  277.     /**
  278.      * Get the encoding that should be used for the commit message text.
  279.      *
  280.      * @return the encoding that should be used for the commit message text.
  281.      */
  282.     public Charset getEncoding() {
  283.         return encoding;
  284.     }

  285.     /**
  286.      * Format this builder's state as a commit object.
  287.      *
  288.      * @return this object in the canonical commit format, suitable for storage
  289.      *         in a repository.
  290.      * @throws java.io.UnsupportedEncodingException
  291.      *             the encoding specified by {@link #getEncoding()} is not
  292.      *             supported by this Java runtime.
  293.      */
  294.     public byte[] build() throws UnsupportedEncodingException {
  295.         ByteArrayOutputStream os = new ByteArrayOutputStream();
  296.         OutputStreamWriter w = new OutputStreamWriter(os, getEncoding());
  297.         try {
  298.             os.write(htree);
  299.             os.write(' ');
  300.             getTreeId().copyTo(os);
  301.             os.write('\n');

  302.             for (ObjectId p : getParentIds()) {
  303.                 os.write(hparent);
  304.                 os.write(' ');
  305.                 p.copyTo(os);
  306.                 os.write('\n');
  307.             }

  308.             os.write(hauthor);
  309.             os.write(' ');
  310.             w.write(getAuthor().toExternalString());
  311.             w.flush();
  312.             os.write('\n');

  313.             os.write(hcommitter);
  314.             os.write(' ');
  315.             w.write(getCommitter().toExternalString());
  316.             w.flush();
  317.             os.write('\n');

  318.             if (getGpgSignature() != null) {
  319.                 os.write(hgpgsig);
  320.                 os.write(' ');
  321.                 writeGpgSignatureString(getGpgSignature().toExternalString(), os);
  322.                 os.write('\n');
  323.             }

  324.             if (getEncoding() != UTF_8) {
  325.                 os.write(hencoding);
  326.                 os.write(' ');
  327.                 os.write(Constants.encodeASCII(getEncoding().name()));
  328.                 os.write('\n');
  329.             }

  330.             os.write('\n');

  331.             if (getMessage() != null) {
  332.                 w.write(getMessage());
  333.                 w.flush();
  334.             }
  335.         } catch (IOException err) {
  336.             // This should never occur, the only way to get it above is
  337.             // for the ByteArrayOutputStream to throw, but it doesn't.
  338.             //
  339.             throw new RuntimeException(err);
  340.         }
  341.         return os.toByteArray();
  342.     }

  343.     /**
  344.      * Writes signature to output as per <a href=
  345.      * "https://github.com/git/git/blob/master/Documentation/technical/signature-format.txt#L66,L89">gpgsig
  346.      * header</a>.
  347.      * <p>
  348.      * CRLF and CR will be sanitized to LF and signature will have a hanging
  349.      * indent of one space starting with line two.
  350.      * </p>
  351.      *
  352.      * @param in
  353.      *            signature string with line breaks
  354.      * @param out
  355.      *            output stream
  356.      * @throws IOException
  357.      *             thrown by the output stream
  358.      * @throws IllegalArgumentException
  359.      *             if the signature string contains non 7-bit ASCII chars
  360.      */
  361.     static void writeGpgSignatureString(String in, OutputStream out)
  362.             throws IOException, IllegalArgumentException {
  363.         for (int i = 0; i < in.length(); ++i) {
  364.             char ch = in.charAt(i);
  365.             if (ch == '\r') {
  366.                 if (i + 1 < in.length() && in.charAt(i + 1) == '\n') {
  367.                     out.write('\n');
  368.                     out.write(' ');
  369.                     ++i;
  370.                 } else {
  371.                     out.write('\n');
  372.                     out.write(' ');
  373.                 }
  374.             } else if (ch == '\n') {
  375.                 out.write('\n');
  376.                 out.write(' ');
  377.             } else {
  378.                 // sanity check
  379.                 if (ch > 127)
  380.                     throw new IllegalArgumentException(MessageFormat
  381.                             .format(JGitText.get().notASCIIString, in));
  382.                 out.write(ch);
  383.             }
  384.         }
  385.     }

  386.     /**
  387.      * Format this builder's state as a commit object.
  388.      *
  389.      * @return this object in the canonical commit format, suitable for storage
  390.      *         in a repository.
  391.      * @throws java.io.UnsupportedEncodingException
  392.      *             the encoding specified by {@link #getEncoding()} is not
  393.      *             supported by this Java runtime.
  394.      */
  395.     public byte[] toByteArray() throws UnsupportedEncodingException {
  396.         return build();
  397.     }

  398.     /** {@inheritDoc} */
  399.     @SuppressWarnings("nls")
  400.     @Override
  401.     public String toString() {
  402.         StringBuilder r = new StringBuilder();
  403.         r.append("Commit");
  404.         r.append("={\n");

  405.         r.append("tree ");
  406.         r.append(treeId != null ? treeId.name() : "NOT_SET");
  407.         r.append("\n");

  408.         for (ObjectId p : parentIds) {
  409.             r.append("parent ");
  410.             r.append(p.name());
  411.             r.append("\n");
  412.         }

  413.         r.append("author ");
  414.         r.append(author != null ? author.toString() : "NOT_SET");
  415.         r.append("\n");

  416.         r.append("committer ");
  417.         r.append(committer != null ? committer.toString() : "NOT_SET");
  418.         r.append("\n");

  419.         r.append("gpgSignature ");
  420.         r.append(gpgSignature != null ? gpgSignature.toString() : "NOT_SET");
  421.         r.append("\n");

  422.         if (encoding != null && encoding != UTF_8) {
  423.             r.append("encoding ");
  424.             r.append(encoding.name());
  425.             r.append("\n");
  426.         }

  427.         r.append("\n");
  428.         r.append(message != null ? message : "");
  429.         r.append("}");
  430.         return r.toString();
  431.     }
  432. }