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 PersonIdent} for the presumed author and time
86  	 * @param committer
87  	 *            the {@link PersonIdent} for the presumed committer and time
88  	 * @param message
89  	 *            The commit message
90  	 * @return the change id SHA1 string (without the 'I') or null if the
91  	 *         message is not complete enough
92  	 */
93  	public static ObjectId computeChangeId(final ObjectId treeId,
94  			final ObjectId firstParentId, final PersonIdent author,
95  			final PersonIdent committer, final String message) {
96  		String cleanMessage = clean(message);
97  		if (cleanMessage.length() == 0)
98  			return null;
99  		StringBuilder b = new StringBuilder();
100 		b.append("tree "); //$NON-NLS-1$
101 		b.append(ObjectId.toString(treeId));
102 		b.append("\n"); //$NON-NLS-1$
103 		if (firstParentId != null) {
104 			b.append("parent "); //$NON-NLS-1$
105 			b.append(ObjectId.toString(firstParentId));
106 			b.append("\n"); //$NON-NLS-1$
107 		}
108 		b.append("author "); //$NON-NLS-1$
109 		b.append(author.toExternalString());
110 		b.append("\n"); //$NON-NLS-1$
111 		b.append("committer "); //$NON-NLS-1$
112 		b.append(committer.toExternalString());
113 		b.append("\n\n"); //$NON-NLS-1$
114 		b.append(cleanMessage);
115 		try (ObjectInserter f = new ObjectInserter.Formatter()) {
116 			return f.idFor(Constants.OBJ_COMMIT, Constants.encode(b.toString()));
117 		}
118 	}
119 
120 	private static final Pattern issuePattern = Pattern
121 			.compile("^(Bug|Issue)[a-zA-Z0-9-]*:.*$"); //$NON-NLS-1$
122 
123 	private static final Pattern footerPattern = Pattern
124 			.compile("(^[a-zA-Z0-9-]+:(?!//).*$)"); //$NON-NLS-1$
125 
126 	private static final Pattern changeIdPattern = Pattern
127 			.compile("(^" + CHANGE_ID + " *I[a-f0-9]{40}$)"); //$NON-NLS-1$ //$NON-NLS-2$
128 
129 	private static final Pattern includeInFooterPattern = Pattern
130 			.compile("^[ \\[].*$"); //$NON-NLS-1$
131 
132 	private static final Pattern trailingWhitespace = Pattern.compile("\\s+$"); //$NON-NLS-1$
133 
134 	/**
135 	 * Find the right place to insert a Change-Id and return it.
136 	 * <p>
137 	 * The Change-Id is inserted before the first footer line but after a Bug
138 	 * line.
139 	 *
140 	 * @param message
141 	 * @param changeId
142 	 * @return a commit message with an inserted Change-Id line
143 	 */
144 	public static String insertId(String message, ObjectId changeId) {
145 		return insertId(message, changeId, false);
146 	}
147 
148 	/**
149 	 * Find the right place to insert a Change-Id and return it.
150 	 * <p>
151 	 * If no Change-Id is found the Change-Id is inserted before
152 	 * the first footer line but after a Bug line.
153 	 *
154 	 * If Change-Id is found and replaceExisting is set to false,
155 	 * the message is unchanged.
156 	 *
157 	 * If Change-Id is found and replaceExisting is set to true,
158 	 * the Change-Id is replaced with {@code changeId}.
159 	 *
160 	 * @param message
161 	 * @param changeId
162 	 * @param replaceExisting
163 	 * @return a commit message with an inserted Change-Id line
164 	 */
165 	public static String insertId(String message, ObjectId changeId,
166 			boolean replaceExisting) {
167 		int indexOfChangeId = indexOfChangeId(message, "\n"); //$NON-NLS-1$
168 		if (indexOfChangeId > 0) {
169 			if (!replaceExisting)
170 				return message;
171 			else {
172 				StringBuilder ret = new StringBuilder(message.substring(0,
173 						indexOfChangeId));
174 				ret.append(CHANGE_ID);
175 				ret.append(" I"); //$NON-NLS-1$
176 				ret.append(ObjectId.toString(changeId));
177 				int indexOfNextLineBreak = message.indexOf("\n", //$NON-NLS-1$
178 						indexOfChangeId);
179 				if (indexOfNextLineBreak > 0)
180 					ret.append(message.substring(indexOfNextLineBreak));
181 				return ret.toString();
182 			}
183 		}
184 
185 		String[] lines = message.split("\n"); //$NON-NLS-1$
186 		int footerFirstLine = indexOfFirstFooterLine(lines);
187 		int insertAfter = footerFirstLine;
188 		for (int i = footerFirstLine; i < lines.length; ++i) {
189 			if (issuePattern.matcher(lines[i]).matches()) {
190 				insertAfter = i + 1;
191 				continue;
192 			}
193 			break;
194 		}
195 		StringBuilder ret = new StringBuilder();
196 		int i = 0;
197 		for (; i < insertAfter; ++i) {
198 			ret.append(lines[i]);
199 			ret.append("\n"); //$NON-NLS-1$
200 		}
201 		if (insertAfter == lines.length && insertAfter == footerFirstLine)
202 			ret.append("\n"); //$NON-NLS-1$
203 		ret.append(CHANGE_ID);
204 		ret.append(" I"); //$NON-NLS-1$
205 		ret.append(ObjectId.toString(changeId));
206 		ret.append("\n"); //$NON-NLS-1$
207 		for (; i < lines.length; ++i) {
208 			ret.append(lines[i]);
209 			ret.append("\n"); //$NON-NLS-1$
210 		}
211 		return ret.toString();
212 	}
213 
214 	/**
215 	 * Return the index in the String {@code message} where the Change-Id entry
216 	 * in the footer begins. If there are more than one entries matching the
217 	 * pattern, return the index of the last one in the last section. Because of
218 	 * Bug: 400818 we release the constraint here that a footer must contain
219 	 * only lines matching {@code footerPattern}.
220 	 *
221 	 * @param message
222 	 * @param delimiter
223 	 *            the line delimiter, like "\n" or "\r\n", needed to find the
224 	 *            footer
225 	 * @return the index of the ChangeId footer in the message, or -1 if no
226 	 *         ChangeId footer available
227 	 */
228 	public static int indexOfChangeId(String message, String delimiter) {
229 		String[] lines = message.split(delimiter);
230 		if (lines.length == 0)
231 			return -1;
232 		int indexOfChangeIdLine = 0;
233 		boolean inFooter = false;
234 		for (int i = lines.length - 1; i >= 0; --i) {
235 			if (!inFooter && isEmptyLine(lines[i]))
236 				continue;
237 			inFooter = true;
238 			if (changeIdPattern.matcher(trimRight(lines[i])).matches()) {
239 				indexOfChangeIdLine = i;
240 				break;
241 			} else if (isEmptyLine(lines[i]) || i == 0)
242 				return -1;
243 		}
244 		int indexOfChangeIdLineinString = 0;
245 		for (int i = 0; i < indexOfChangeIdLine; ++i)
246 			indexOfChangeIdLineinString += lines[i].length()
247 					+ delimiter.length();
248 		return indexOfChangeIdLineinString
249 				+ lines[indexOfChangeIdLine].indexOf(CHANGE_ID);
250 	}
251 
252 	private static boolean isEmptyLine(String line) {
253 		return line.trim().length() == 0;
254 	}
255 
256 	private static String trimRight(String s) {
257 		return trailingWhitespace.matcher(s).replaceAll(""); //$NON-NLS-1$
258 	}
259 
260 	/**
261 	 * Find the index of the first line of the footer paragraph in an array of
262 	 * the lines, or lines.length if no footer is available
263 	 *
264 	 * @param lines
265 	 *            the commit message split into lines and the line delimiters
266 	 *            stripped off
267 	 * @return the index of the first line of the footer paragraph, or
268 	 *         lines.length if no footer is available
269 	 */
270 	public static int indexOfFirstFooterLine(String[] lines) {
271 		int footerFirstLine = lines.length;
272 		for (int i = lines.length - 1; i > 1; --i) {
273 			if (footerPattern.matcher(lines[i]).matches()) {
274 				footerFirstLine = i;
275 				continue;
276 			}
277 			if (footerFirstLine != lines.length && lines[i].length() == 0)
278 				break;
279 			if (footerFirstLine != lines.length
280 					&& includeInFooterPattern.matcher(lines[i]).matches()) {
281 				footerFirstLine = i + 1;
282 				continue;
283 			}
284 			footerFirstLine = lines.length;
285 			break;
286 		}
287 		return footerFirstLine;
288 	}
289 }