View Javadoc
1   /*
2    * Copyright (C) 2010, Robin Rosenberg
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.util;
44  
45  import java.io.IOException;
46  import java.util.regex.Pattern;
47  
48  import org.eclipse.jgit.lib.Constants;
49  import org.eclipse.jgit.lib.ObjectInserter;
50  import org.eclipse.jgit.lib.ObjectId;
51  import org.eclipse.jgit.lib.PersonIdent;
52  
53  /**
54   * Utilities for creating and working with Change-Id's, like the one used by
55   * Gerrit Code Review.
56   * <p>
57   * A Change-Id is a SHA-1 computed from the content of a commit, in a similar
58   * fashion to how the commit id is computed. Unlike the commit id a Change-Id is
59   * retained in the commit and subsequent revised commits in the footer of the
60   * commit text.
61   */
62  public class ChangeIdUtil {
63  
64  	static final String CHANGE_ID = "Change-Id:"; //$NON-NLS-1$
65  
66  	// package-private so the unit test can test this part only
67  	@SuppressWarnings("nls")
68  	static String clean(String msg) {
69  		return msg.//
70  				replaceAll("(?i)(?m)^Signed-off-by:.*$\n?", "").// //$NON-NLS-1$
71  				replaceAll("(?m)^#.*$\n?", "").// //$NON-NLS-1$
72  				replaceAll("(?m)\n\n\n+", "\\\n").// //$NON-NLS-1$
73  				replaceAll("\\n*$", "").// //$NON-NLS-1$
74  				replaceAll("(?s)\ndiff --git.*", "").// //$NON-NLS-1$
75  				trim();
76  	}
77  
78  	/**
79  	 * Compute a Change-Id.
80  	 *
81  	 * @param treeId
82  	 *            The id of the tree that would be committed
83  	 * @param firstParentId
84  	 *            parent id of previous commit or null
85  	 * @param author
86  	 *            the {@link PersonIdent} for the presumed author and time
87  	 * @param committer
88  	 *            the {@link PersonIdent} for the presumed committer and time
89  	 * @param message
90  	 *            The commit message
91  	 * @return the change id SHA1 string (without the 'I') or null if the
92  	 *         message is not complete enough
93  	 * @throws IOException
94  	 */
95  	public static ObjectId computeChangeId(final ObjectId treeId,
96  			final ObjectId firstParentId, final PersonIdent author,
97  			final PersonIdent committer, final String message)
98  			throws IOException {
99  		String cleanMessage = clean(message);
100 		if (cleanMessage.length() == 0)
101 			return null;
102 		StringBuilder b = new StringBuilder();
103 		b.append("tree "); //$NON-NLS-1$
104 		b.append(ObjectId.toString(treeId));
105 		b.append("\n"); //$NON-NLS-1$
106 		if (firstParentId != null) {
107 			b.append("parent "); //$NON-NLS-1$
108 			b.append(ObjectId.toString(firstParentId));
109 			b.append("\n"); //$NON-NLS-1$
110 		}
111 		b.append("author "); //$NON-NLS-1$
112 		b.append(author.toExternalString());
113 		b.append("\n"); //$NON-NLS-1$
114 		b.append("committer "); //$NON-NLS-1$
115 		b.append(committer.toExternalString());
116 		b.append("\n\n"); //$NON-NLS-1$
117 		b.append(cleanMessage);
118 		try (ObjectInserter f = new ObjectInserter.Formatter()) {
119 			return f.idFor(Constants.OBJ_COMMIT, //
120 					b.toString().getBytes(Constants.CHARACTER_ENCODING));
121 		}
122 	}
123 
124 	private static final Pattern issuePattern = Pattern
125 			.compile("^(Bug|Issue)[a-zA-Z0-9-]*:.*$"); //$NON-NLS-1$
126 
127 	private static final Pattern footerPattern = Pattern
128 			.compile("(^[a-zA-Z0-9-]+:(?!//).*$)"); //$NON-NLS-1$
129 
130 	private static final Pattern changeIdPattern = Pattern
131 			.compile("(^" + CHANGE_ID + " *I[a-f0-9]{40}$)"); //$NON-NLS-1$ //$NON-NLS-2$
132 
133 	private static final Pattern includeInFooterPattern = Pattern
134 			.compile("^[ \\[].*$"); //$NON-NLS-1$
135 
136 	private static final Pattern trailingWhitespace = Pattern.compile("\\s+$"); //$NON-NLS-1$
137 
138 	/**
139 	 * Find the right place to insert a Change-Id and return it.
140 	 * <p>
141 	 * The Change-Id is inserted before the first footer line but after a Bug
142 	 * line.
143 	 *
144 	 * @param message
145 	 * @param changeId
146 	 * @return a commit message with an inserted Change-Id line
147 	 */
148 	public static String insertId(String message, ObjectId changeId) {
149 		return insertId(message, changeId, false);
150 	}
151 
152 	/**
153 	 * Find the right place to insert a Change-Id and return it.
154 	 * <p>
155 	 * If no Change-Id is found the Change-Id is inserted before
156 	 * the first footer line but after a Bug line.
157 	 *
158 	 * If Change-Id is found and replaceExisting is set to false,
159 	 * the message is unchanged.
160 	 *
161 	 * If Change-Id is found and replaceExisting is set to true,
162 	 * the Change-Id is replaced with {@code changeId}.
163 	 *
164 	 * @param message
165 	 * @param changeId
166 	 * @param replaceExisting
167 	 * @return a commit message with an inserted Change-Id line
168 	 */
169 	public static String insertId(String message, ObjectId changeId,
170 			boolean replaceExisting) {
171 		int indexOfChangeId = indexOfChangeId(message, "\n"); //$NON-NLS-1$
172 		if (indexOfChangeId > 0) {
173 			if (!replaceExisting)
174 				return message;
175 			else {
176 				StringBuilder ret = new StringBuilder(message.substring(0,
177 						indexOfChangeId));
178 				ret.append(CHANGE_ID);
179 				ret.append(" I"); //$NON-NLS-1$
180 				ret.append(ObjectId.toString(changeId));
181 				int indexOfNextLineBreak = message.indexOf("\n", //$NON-NLS-1$
182 						indexOfChangeId);
183 				if (indexOfNextLineBreak > 0)
184 					ret.append(message.substring(indexOfNextLineBreak));
185 				return ret.toString();
186 			}
187 		}
188 
189 		String[] lines = message.split("\n"); //$NON-NLS-1$
190 		int footerFirstLine = indexOfFirstFooterLine(lines);
191 		int insertAfter = footerFirstLine;
192 		for (int i = footerFirstLine; i < lines.length; ++i) {
193 			if (issuePattern.matcher(lines[i]).matches()) {
194 				insertAfter = i + 1;
195 				continue;
196 			}
197 			break;
198 		}
199 		StringBuilder ret = new StringBuilder();
200 		int i = 0;
201 		for (; i < insertAfter; ++i) {
202 			ret.append(lines[i]);
203 			ret.append("\n"); //$NON-NLS-1$
204 		}
205 		if (insertAfter == lines.length && insertAfter == footerFirstLine)
206 			ret.append("\n"); //$NON-NLS-1$
207 		ret.append(CHANGE_ID);
208 		ret.append(" I"); //$NON-NLS-1$
209 		ret.append(ObjectId.toString(changeId));
210 		ret.append("\n"); //$NON-NLS-1$
211 		for (; i < lines.length; ++i) {
212 			ret.append(lines[i]);
213 			ret.append("\n"); //$NON-NLS-1$
214 		}
215 		return ret.toString();
216 	}
217 
218 	/**
219 	 * Return the index in the String {@code message} where the Change-Id entry
220 	 * in the footer begins. If there are more than one entries matching the
221 	 * pattern, return the index of the last one in the last section. Because of
222 	 * Bug: 400818 we release the constraint here that a footer must contain
223 	 * only lines matching {@code footerPattern}.
224 	 *
225 	 * @param message
226 	 * @param delimiter
227 	 *            the line delimiter, like "\n" or "\r\n", needed to find the
228 	 *            footer
229 	 * @return the index of the ChangeId footer in the message, or -1 if no
230 	 *         ChangeId footer available
231 	 */
232 	public static int indexOfChangeId(String message, String delimiter) {
233 		String[] lines = message.split(delimiter);
234 		if (lines.length == 0)
235 			return -1;
236 		int indexOfChangeIdLine = 0;
237 		boolean inFooter = false;
238 		for (int i = lines.length - 1; i >= 0; --i) {
239 			if (!inFooter && isEmptyLine(lines[i]))
240 				continue;
241 			inFooter = true;
242 			if (changeIdPattern.matcher(trimRight(lines[i])).matches()) {
243 				indexOfChangeIdLine = i;
244 				break;
245 			} else if (isEmptyLine(lines[i]) || i == 0)
246 				return -1;
247 		}
248 		int indexOfChangeIdLineinString = 0;
249 		for (int i = 0; i < indexOfChangeIdLine; ++i)
250 			indexOfChangeIdLineinString += lines[i].length()
251 					+ delimiter.length();
252 		return indexOfChangeIdLineinString
253 				+ lines[indexOfChangeIdLine].indexOf(CHANGE_ID);
254 	}
255 
256 	private static boolean isEmptyLine(String line) {
257 		return line.trim().length() == 0;
258 	}
259 
260 	private static String trimRight(String s) {
261 		return trailingWhitespace.matcher(s).replaceAll(""); //$NON-NLS-1$
262 	}
263 
264 	/**
265 	 * Find the index of the first line of the footer paragraph in an array of
266 	 * the lines, or lines.length if no footer is available
267 	 *
268 	 * @param lines
269 	 *            the commit message split into lines and the line delimiters
270 	 *            stripped off
271 	 * @return the index of the first line of the footer paragraph, or
272 	 *         lines.length if no footer is available
273 	 */
274 	public static int indexOfFirstFooterLine(String[] lines) {
275 		int footerFirstLine = lines.length;
276 		for (int i = lines.length - 1; i > 1; --i) {
277 			if (footerPattern.matcher(lines[i]).matches()) {
278 				footerFirstLine = i;
279 				continue;
280 			}
281 			if (footerFirstLine != lines.length && lines[i].length() == 0)
282 				break;
283 			if (footerFirstLine != lines.length
284 					&& includeInFooterPattern.matcher(lines[i]).matches()) {
285 				footerFirstLine = i + 1;
286 				continue;
287 			}
288 			footerFirstLine = lines.length;
289 			break;
290 		}
291 		return footerFirstLine;
292 	}
293 }