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