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.util.regex.Pattern;
46  
47  import org.eclipse.jgit.lib.Constants;
48  import org.eclipse.jgit.lib.ObjectId;
49  import org.eclipse.jgit.lib.ObjectInserter;
50  import org.eclipse.jgit.lib.PersonIdent;
51  
52  /**
53   * Utilities for creating and working with Change-Id's, like the one used by
54   * Gerrit Code Review.
55   * <p>
56   * A Change-Id is a SHA-1 computed from the content of a commit, in a similar
57   * fashion to how the commit id is computed. Unlike the commit id a Change-Id is
58   * retained in the commit and subsequent revised commits in the footer of the
59   * commit text.
60   */
61  public class ChangeIdUtil {
62  
63  	static final String CHANGE_ID = "Change-Id:"; //$NON-NLS-1$
64  
65  	// package-private so the unit test can test this part only
66  	@SuppressWarnings("nls")
67  	static String clean(String msg) {
68  		return msg.//
69  				replaceAll("(?i)(?m)^Signed-off-by:.*$\n?", "").// //$NON-NLS-1$
70  				replaceAll("(?m)^#.*$\n?", "").// //$NON-NLS-1$
71  				replaceAll("(?m)\n\n\n+", "\\\n").// //$NON-NLS-1$
72  				replaceAll("\\n*$", "").// //$NON-NLS-1$
73  				replaceAll("(?s)\ndiff --git.*", "").// //$NON-NLS-1$
74  				trim();
75  	}
76  
77  	/**
78  	 * Compute a Change-Id.
79  	 *
80  	 * @param treeId
81  	 *            The id of the tree that would be committed
82  	 * @param firstParentId
83  	 *            parent id of previous commit or null
84  	 * @param author
85  	 *            the {@link org.eclipse.jgit.lib.PersonIdent} for the presumed
86  	 *            author and time
87  	 * @param committer
88  	 *            the {@link org.eclipse.jgit.lib.PersonIdent} for the presumed
89  	 *            committer and time
90  	 * @param message
91  	 *            The commit message
92  	 * @return the change id SHA1 string (without the 'I') or null if the
93  	 *         message is not complete enough
94  	 */
95  	public static ObjectId computeChangeId(final ObjectId treeId,
96  			final ObjectId firstParentId, final PersonIdent author,
97  			final PersonIdent committer, final String message) {
98  		String cleanMessage = clean(message);
99  		if (cleanMessage.length() == 0)
100 			return null;
101 		StringBuilder b = new StringBuilder();
102 		b.append("tree "); //$NON-NLS-1$
103 		b.append(ObjectId.toString(treeId));
104 		b.append("\n"); //$NON-NLS-1$
105 		if (firstParentId != null) {
106 			b.append("parent "); //$NON-NLS-1$
107 			b.append(ObjectId.toString(firstParentId));
108 			b.append("\n"); //$NON-NLS-1$
109 		}
110 		b.append("author "); //$NON-NLS-1$
111 		b.append(author.toExternalString());
112 		b.append("\n"); //$NON-NLS-1$
113 		b.append("committer "); //$NON-NLS-1$
114 		b.append(committer.toExternalString());
115 		b.append("\n\n"); //$NON-NLS-1$
116 		b.append(cleanMessage);
117 		try (ObjectInserter f = new ObjectInserter.Formatter()) {
118 			return f.idFor(Constants.OBJ_COMMIT, Constants.encode(b.toString()));
119 		}
120 	}
121 
122 	private static final Pattern issuePattern = Pattern
123 			.compile("^(Bug|Issue)[a-zA-Z0-9-]*:.*$"); //$NON-NLS-1$
124 
125 	private static final Pattern footerPattern = Pattern
126 			.compile("(^[a-zA-Z0-9-]+:(?!//).*$)"); //$NON-NLS-1$
127 
128 	private static final Pattern changeIdPattern = Pattern
129 			.compile("(^" + CHANGE_ID + " *I[a-f0-9]{40}$)"); //$NON-NLS-1$ //$NON-NLS-2$
130 
131 	private static final Pattern includeInFooterPattern = Pattern
132 			.compile("^[ \\[].*$"); //$NON-NLS-1$
133 
134 	private static final Pattern trailingWhitespace = Pattern.compile("\\s+$"); //$NON-NLS-1$
135 
136 	/**
137 	 * Find the right place to insert a Change-Id and return it.
138 	 * <p>
139 	 * The Change-Id is inserted before the first footer line but after a Bug
140 	 * line.
141 	 *
142 	 * @param message
143 	 *            a message.
144 	 * @param changeId
145 	 *            a Change-Id.
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 the first
156 	 * footer line but after a Bug line.
157 	 *
158 	 * If Change-Id is found and replaceExisting is set to false, the message is
159 	 * unchanged.
160 	 *
161 	 * If Change-Id is found and replaceExisting is set to true, the Change-Id
162 	 * is replaced with {@code changeId}.
163 	 *
164 	 * @param message
165 	 *            a message.
166 	 * @param changeId
167 	 *            a Change-Id.
168 	 * @param replaceExisting
169 	 *            a boolean.
170 	 * @return a commit message with an inserted Change-Id line
171 	 */
172 	public static String insertId(String message, ObjectId changeId,
173 			boolean replaceExisting) {
174 		int indexOfChangeId = indexOfChangeId(message, "\n"); //$NON-NLS-1$
175 		if (indexOfChangeId > 0) {
176 			if (!replaceExisting)
177 				return message;
178 			else {
179 				StringBuilder ret = new StringBuilder(message.substring(0,
180 						indexOfChangeId));
181 				ret.append(CHANGE_ID);
182 				ret.append(" I"); //$NON-NLS-1$
183 				ret.append(ObjectId.toString(changeId));
184 				int indexOfNextLineBreak = message.indexOf("\n", //$NON-NLS-1$
185 						indexOfChangeId);
186 				if (indexOfNextLineBreak > 0)
187 					ret.append(message.substring(indexOfNextLineBreak));
188 				return ret.toString();
189 			}
190 		}
191 
192 		String[] lines = message.split("\n"); //$NON-NLS-1$
193 		int footerFirstLine = indexOfFirstFooterLine(lines);
194 		int insertAfter = footerFirstLine;
195 		for (int i = footerFirstLine; i < lines.length; ++i) {
196 			if (issuePattern.matcher(lines[i]).matches()) {
197 				insertAfter = i + 1;
198 				continue;
199 			}
200 			break;
201 		}
202 		StringBuilder ret = new StringBuilder();
203 		int i = 0;
204 		for (; i < insertAfter; ++i) {
205 			ret.append(lines[i]);
206 			ret.append("\n"); //$NON-NLS-1$
207 		}
208 		if (insertAfter == lines.length && insertAfter == footerFirstLine)
209 			ret.append("\n"); //$NON-NLS-1$
210 		ret.append(CHANGE_ID);
211 		ret.append(" I"); //$NON-NLS-1$
212 		ret.append(ObjectId.toString(changeId));
213 		ret.append("\n"); //$NON-NLS-1$
214 		for (; i < lines.length; ++i) {
215 			ret.append(lines[i]);
216 			ret.append("\n"); //$NON-NLS-1$
217 		}
218 		return ret.toString();
219 	}
220 
221 	/**
222 	 * Return the index in the String {@code message} where the Change-Id entry
223 	 * in the footer begins. If there are more than one entries matching the
224 	 * pattern, return the index of the last one in the last section. Because of
225 	 * Bug: 400818 we release the constraint here that a footer must contain
226 	 * only lines matching {@code footerPattern}.
227 	 *
228 	 * @param message
229 	 *            a message.
230 	 * @param delimiter
231 	 *            the line delimiter, like "\n" or "\r\n", needed to find the
232 	 *            footer
233 	 * @return the index of the ChangeId footer in the message, or -1 if no
234 	 *         ChangeId footer available
235 	 */
236 	public static int indexOfChangeId(String message, String delimiter) {
237 		String[] lines = message.split(delimiter);
238 		if (lines.length == 0)
239 			return -1;
240 		int indexOfChangeIdLine = 0;
241 		boolean inFooter = false;
242 		for (int i = lines.length - 1; i >= 0; --i) {
243 			if (!inFooter && isEmptyLine(lines[i]))
244 				continue;
245 			inFooter = true;
246 			if (changeIdPattern.matcher(trimRight(lines[i])).matches()) {
247 				indexOfChangeIdLine = i;
248 				break;
249 			} else if (isEmptyLine(lines[i]) || i == 0)
250 				return -1;
251 		}
252 		int indexOfChangeIdLineinString = 0;
253 		for (int i = 0; i < indexOfChangeIdLine; ++i)
254 			indexOfChangeIdLineinString += lines[i].length()
255 					+ delimiter.length();
256 		return indexOfChangeIdLineinString
257 				+ lines[indexOfChangeIdLine].indexOf(CHANGE_ID);
258 	}
259 
260 	private static boolean isEmptyLine(String line) {
261 		return line.trim().length() == 0;
262 	}
263 
264 	private static String trimRight(String s) {
265 		return trailingWhitespace.matcher(s).replaceAll(""); //$NON-NLS-1$
266 	}
267 
268 	/**
269 	 * Find the index of the first line of the footer paragraph in an array of
270 	 * the lines, or lines.length if no footer is available
271 	 *
272 	 * @param lines
273 	 *            the commit message split into lines and the line delimiters
274 	 *            stripped off
275 	 * @return the index of the first line of the footer paragraph, or
276 	 *         lines.length if no footer is available
277 	 */
278 	public static int indexOfFirstFooterLine(String[] lines) {
279 		int footerFirstLine = lines.length;
280 		for (int i = lines.length - 1; i > 1; --i) {
281 			if (footerPattern.matcher(lines[i]).matches()) {
282 				footerFirstLine = i;
283 				continue;
284 			}
285 			if (footerFirstLine != lines.length && lines[i].length() == 0)
286 				break;
287 			if (footerFirstLine != lines.length
288 					&& includeInFooterPattern.matcher(lines[i]).matches()) {
289 				footerFirstLine = i + 1;
290 				continue;
291 			}
292 			footerFirstLine = lines.length;
293 			break;
294 		}
295 		return footerFirstLine;
296 	}
297 }