View Javadoc
1   /*
2    * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
3    * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
4    * Copyright (C) 2006-2008, 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  
46  package org.eclipse.jgit.lib;
47  
48  import java.io.Serializable;
49  import java.text.SimpleDateFormat;
50  import java.util.Date;
51  import java.util.Locale;
52  import java.util.TimeZone;
53  
54  import org.eclipse.jgit.internal.JGitText;
55  import org.eclipse.jgit.util.SystemReader;
56  import org.eclipse.jgit.util.time.ProposedTimestamp;
57  
58  /**
59   * A combination of a person identity and time in Git.
60   *
61   * Git combines Name + email + time + time zone to specify who wrote or
62   * committed something.
63   */
64  public class PersonIdent implements Serializable {
65  	private static final long serialVersionUID = 1L;
66  
67  	/**
68  	 * @param tzOffset
69  	 *            timezone offset as in {@link #getTimeZoneOffset()}.
70  	 * @return time zone object for the given offset.
71  	 * @since 4.1
72  	 */
73  	public static TimeZone getTimeZone(int tzOffset) {
74  		StringBuilder tzId = new StringBuilder(8);
75  		tzId.append("GMT"); //$NON-NLS-1$
76  		appendTimezone(tzId, tzOffset);
77  		return TimeZone.getTimeZone(tzId.toString());
78  	}
79  
80  	/**
81  	 * Format a timezone offset.
82  	 *
83  	 * @param r
84  	 *            string builder to append to.
85  	 * @param offset
86  	 *            timezone offset as in {@link #getTimeZoneOffset()}.
87  	 * @since 4.1
88  	 */
89  	public static void appendTimezone(StringBuilder r, int offset) {
90  		final char sign;
91  		final int offsetHours;
92  		final int offsetMins;
93  
94  		if (offset < 0) {
95  			sign = '-';
96  			offset = -offset;
97  		} else {
98  			sign = '+';
99  		}
100 
101 		offsetHours = offset / 60;
102 		offsetMins = offset % 60;
103 
104 		r.append(sign);
105 		if (offsetHours < 10) {
106 			r.append('0');
107 		}
108 		r.append(offsetHours);
109 		if (offsetMins < 10) {
110 			r.append('0');
111 		}
112 		r.append(offsetMins);
113 	}
114 
115 	/**
116 	 * Sanitize the given string for use in an identity and append to output.
117 	 * <p>
118 	 * Trims whitespace from both ends and special characters {@code \n < >} that
119 	 * interfere with parsing; appends all other characters to the output.
120 	 * Analogous to the C git function {@code strbuf_addstr_without_crud}.
121 	 *
122 	 * @param r
123 	 *            string builder to append to.
124 	 * @param str
125 	 *            input string.
126 	 * @since 4.4
127 	 */
128 	public static void appendSanitized(StringBuilder r, String str) {
129 		// Trim any whitespace less than \u0020 as in String#trim().
130 		int i = 0;
131 		while (i < str.length() && str.charAt(i) <= ' ') {
132 			i++;
133 		}
134 		int end = str.length();
135 		while (end > i && str.charAt(end - 1) <= ' ') {
136 			end--;
137 		}
138 
139 		for (; i < end; i++) {
140 			char c = str.charAt(i);
141 			switch (c) {
142 				case '\n':
143 				case '<':
144 				case '>':
145 					continue;
146 				default:
147 					r.append(c);
148 					break;
149 			}
150 		}
151 	}
152 
153 	private final String name;
154 
155 	private final String emailAddress;
156 
157 	private final long when;
158 
159 	private final int tzOffset;
160 
161 	/**
162 	 * Creates new PersonIdent from config info in repository, with current time.
163 	 * This new PersonIdent gets the info from the default committer as available
164 	 * from the configuration.
165 	 *
166 	 * @param repo
167 	 */
168 	public PersonIdent(final Repository repo) {
169 		this(repo.getConfig().get(UserConfig.KEY));
170 	}
171 
172 	/**
173 	 * Copy a {@link PersonIdent}.
174 	 *
175 	 * @param pi
176 	 *            Original {@link PersonIdent}
177 	 */
178 	public PersonIdent(final PersonIdent pi) {
179 		this(pi.getName(), pi.getEmailAddress());
180 	}
181 
182 	/**
183 	 * Construct a new {@link PersonIdent} with current time.
184 	 *
185 	 * @param aName
186 	 * @param aEmailAddress
187 	 */
188 	public PersonIdent(final String aName, final String aEmailAddress) {
189 		this(aName, aEmailAddress, SystemReader.getInstance().getCurrentTime());
190 	}
191 
192 	/**
193 	 * Construct a new {@link PersonIdent} with current time.
194 	 *
195 	 * @param aName
196 	 * @param aEmailAddress
197 	 * @param when
198 	 * @since 4.6
199 	 */
200 	public PersonIdent(String aName, String aEmailAddress,
201 			ProposedTimestamp when) {
202 		this(aName, aEmailAddress, when.millis());
203 	}
204 
205 	/**
206 	 * Copy a PersonIdent, but alter the clone's time stamp
207 	 *
208 	 * @param pi
209 	 *            original {@link PersonIdent}
210 	 * @param when
211 	 *            local time
212 	 * @param tz
213 	 *            time zone
214 	 */
215 	public PersonIdent(final PersonIdent pi, final Date when, final TimeZone tz) {
216 		this(pi.getName(), pi.getEmailAddress(), when, tz);
217 	}
218 
219 	/**
220 	 * Copy a {@link PersonIdent}, but alter the clone's time stamp
221 	 *
222 	 * @param pi
223 	 *            original {@link PersonIdent}
224 	 * @param aWhen
225 	 *            local time
226 	 */
227 	public PersonIdent(final PersonIdent pi, final Date aWhen) {
228 		this(pi.getName(), pi.getEmailAddress(), aWhen.getTime(), pi.tzOffset);
229 	}
230 
231 	/**
232 	 * Construct a PersonIdent from simple data
233 	 *
234 	 * @param aName
235 	 * @param aEmailAddress
236 	 * @param aWhen
237 	 *            local time stamp
238 	 * @param aTZ
239 	 *            time zone
240 	 */
241 	public PersonIdent(final String aName, final String aEmailAddress,
242 			final Date aWhen, final TimeZone aTZ) {
243 		this(aName, aEmailAddress, aWhen.getTime(), aTZ.getOffset(aWhen
244 				.getTime()) / (60 * 1000));
245 	}
246 
247 	/**
248 	 * Copy a PersonIdent, but alter the clone's time stamp
249 	 *
250 	 * @param pi
251 	 *            original {@link PersonIdent}
252 	 * @param aWhen
253 	 *            local time stamp
254 	 * @param aTZ
255 	 *            time zone
256 	 */
257 	public PersonIdent(final PersonIdent pi, final long aWhen, final int aTZ) {
258 		this(pi.getName(), pi.getEmailAddress(), aWhen, aTZ);
259 	}
260 
261 	private PersonIdent(final String aName, final String aEmailAddress,
262 			long when) {
263 		this(aName, aEmailAddress, when, SystemReader.getInstance()
264 				.getTimezone(when));
265 	}
266 
267 	private PersonIdent(final UserConfig config) {
268 		this(config.getCommitterName(), config.getCommitterEmail());
269 	}
270 
271 	/**
272 	 * Construct a {@link PersonIdent}.
273 	 * <p>
274 	 * Whitespace in the name and email is preserved for the lifetime of this
275 	 * object, but are trimmed by {@link #toExternalString()}. This means that
276 	 * parsing the result of {@link #toExternalString()} may not return an
277 	 * equivalent instance.
278 	 *
279 	 * @param aName
280 	 * @param aEmailAddress
281 	 * @param aWhen
282 	 *            local time stamp
283 	 * @param aTZ
284 	 *            time zone
285 	 */
286 	public PersonIdent(final String aName, final String aEmailAddress,
287 			final long aWhen, final int aTZ) {
288 		if (aName == null)
289 			throw new IllegalArgumentException(
290 					JGitText.get().personIdentNameNonNull);
291 		if (aEmailAddress == null)
292 			throw new IllegalArgumentException(
293 					JGitText.get().personIdentEmailNonNull);
294 		name = aName;
295 		emailAddress = aEmailAddress;
296 		when = aWhen;
297 		tzOffset = aTZ;
298 	}
299 
300 	/**
301 	 * @return Name of person
302 	 */
303 	public String getName() {
304 		return name;
305 	}
306 
307 	/**
308 	 * @return email address of person
309 	 */
310 	public String getEmailAddress() {
311 		return emailAddress;
312 	}
313 
314 	/**
315 	 * @return timestamp
316 	 */
317 	public Date getWhen() {
318 		return new Date(when);
319 	}
320 
321 	/**
322 	 * @return this person's declared time zone; null if time zone is unknown.
323 	 */
324 	public TimeZone getTimeZone() {
325 		return getTimeZone(tzOffset);
326 	}
327 
328 	/**
329 	 * @return this person's declared time zone as minutes east of UTC. If the
330 	 *         timezone is to the west of UTC it is negative.
331 	 */
332 	public int getTimeZoneOffset() {
333 		return tzOffset;
334 	}
335 
336 	/**
337 	 * Hashcode is based only on the email address and timestamp.
338 	 */
339 	@Override
340 	public int hashCode() {
341 		int hc = getEmailAddress().hashCode();
342 		hc *= 31;
343 		hc += (int) (when / 1000L);
344 		return hc;
345 	}
346 
347 	@Override
348 	public boolean equals(final Object o) {
349 		if (o instanceof PersonIdent) {
350 			final PersonIdent p = (PersonIdent) o;
351 			return getName().equals(p.getName())
352 					&& getEmailAddress().equals(p.getEmailAddress())
353 					&& when / 1000L == p.when / 1000L;
354 		}
355 		return false;
356 	}
357 
358 	/**
359 	 * Format for Git storage.
360 	 *
361 	 * @return a string in the git author format
362 	 */
363 	public String toExternalString() {
364 		final StringBuilder r = new StringBuilder();
365 		appendSanitized(r, getName());
366 		r.append(" <"); //$NON-NLS-1$
367 		appendSanitized(r, getEmailAddress());
368 		r.append("> "); //$NON-NLS-1$
369 		r.append(when / 1000);
370 		r.append(' ');
371 		appendTimezone(r, tzOffset);
372 		return r.toString();
373 	}
374 
375 	@Override
376 	@SuppressWarnings("nls")
377 	public String toString() {
378 		final StringBuilder r = new StringBuilder();
379 		final SimpleDateFormat dtfmt;
380 		dtfmt = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy Z", Locale.US);
381 		dtfmt.setTimeZone(getTimeZone());
382 
383 		r.append("PersonIdent[");
384 		r.append(getName());
385 		r.append(", ");
386 		r.append(getEmailAddress());
387 		r.append(", ");
388 		r.append(dtfmt.format(Long.valueOf(when)));
389 		r.append("]");
390 
391 		return r.toString();
392 	}
393 }
394