You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GitDateParser.java 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. * Copyright (C) 2012 Christian Halstrick
  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. import java.text.MessageFormat;
  45. import java.text.ParseException;
  46. import java.text.SimpleDateFormat;
  47. import java.util.Calendar;
  48. import java.util.Date;
  49. import java.util.GregorianCalendar;
  50. import java.util.HashMap;
  51. import java.util.Map;
  52. import org.eclipse.jgit.internal.JGitText;
  53. /**
  54. * Parses strings with time and date specifications into {@link Date}.
  55. *
  56. * When git needs to parse strings specified by the user this parser can be
  57. * used. One example is the parsing of the config parameter gc.pruneexpire. The
  58. * parser can handle only subset of what native gits approxidate parser
  59. * understands.
  60. */
  61. public class GitDateParser {
  62. /**
  63. * The Date representing never. Though this is a concrete value, most
  64. * callers are adviced to avoid depending on the actual value.
  65. */
  66. public static final Date NEVER = new Date(Long.MAX_VALUE);
  67. // Since SimpleDateFormat instances are expensive to instantiate they should
  68. // be cached. Since they are also not threadsafe they are cached using
  69. // ThreadLocal.
  70. private static ThreadLocal<Map<ParseableSimpleDateFormat, SimpleDateFormat>> formatCache = new ThreadLocal<Map<ParseableSimpleDateFormat, SimpleDateFormat>>() {
  71. protected Map<ParseableSimpleDateFormat, SimpleDateFormat> initialValue() {
  72. return new HashMap<ParseableSimpleDateFormat, SimpleDateFormat>();
  73. }
  74. };
  75. // Gets an instance of a SimpleDateFormat. If there is not already an
  76. // appropriate instance in the (ThreadLocal) cache the create one and put in
  77. // into the cache
  78. private static SimpleDateFormat getDateFormat(ParseableSimpleDateFormat f) {
  79. Map<ParseableSimpleDateFormat, SimpleDateFormat> map = formatCache
  80. .get();
  81. SimpleDateFormat dateFormat = map.get(f);
  82. if (dateFormat != null)
  83. return dateFormat;
  84. SimpleDateFormat df = SystemReader.getInstance().getSimpleDateFormat(
  85. f.formatStr);
  86. map.put(f, df);
  87. return df;
  88. }
  89. // An enum of all those formats which this parser can parse with the help of
  90. // a SimpleDateFormat. There are other formats (e.g. the relative formats
  91. // like "yesterday" or "1 week ago") which this parser can parse but which
  92. // are not listed here because they are parsed without the help of a
  93. // SimpleDateFormat.
  94. enum ParseableSimpleDateFormat {
  95. ISO("yyyy-MM-dd HH:mm:ss Z"), // //$NON-NLS-1$
  96. RFC("EEE, dd MMM yyyy HH:mm:ss Z"), // //$NON-NLS-1$
  97. SHORT("yyyy-MM-dd"), // //$NON-NLS-1$
  98. SHORT_WITH_DOTS_REVERSE("dd.MM.yyyy"), // //$NON-NLS-1$
  99. SHORT_WITH_DOTS("yyyy.MM.dd"), // //$NON-NLS-1$
  100. SHORT_WITH_SLASH("MM/dd/yyyy"), // //$NON-NLS-1$
  101. DEFAULT("EEE MMM dd HH:mm:ss yyyy Z"), // //$NON-NLS-1$
  102. LOCAL("EEE MMM dd HH:mm:ss yyyy");
  103. String formatStr;
  104. private ParseableSimpleDateFormat(String formatStr) {
  105. this.formatStr = formatStr;
  106. }
  107. }
  108. /**
  109. * Parses a string into a {@link Date}. Since this parser also supports
  110. * relative formats (e.g. "yesterday") the caller can specify the reference
  111. * date. These types of strings can be parsed:
  112. * <ul>
  113. * <li>"never"</li>
  114. * <li>"now"</li>
  115. * <li>"yesterday"</li>
  116. * <li>"(x) years|months|weeks|days|hours|minutes|seconds ago"<br>
  117. * Multiple specs can be combined like in "2 weeks 3 days ago". Instead of
  118. * ' ' one can use '.' to seperate the words</li>
  119. * <li>"yyyy-MM-dd HH:mm:ss Z" (ISO)</li>
  120. * <li>"EEE, dd MMM yyyy HH:mm:ss Z" (RFC)</li>
  121. * <li>"yyyy-MM-dd"</li>
  122. * <li>"yyyy.MM.dd"</li>
  123. * <li>"MM/dd/yyyy",</li>
  124. * <li>"dd.MM.yyyy"</li>
  125. * <li>"EEE MMM dd HH:mm:ss yyyy Z" (DEFAULT)</li>
  126. * <li>"EEE MMM dd HH:mm:ss yyyy" (LOCAL)</li>
  127. * </ul>
  128. *
  129. * @param dateStr
  130. * the string to be parsed
  131. * @param now
  132. * the base date which is used for the calculation of relative
  133. * formats. E.g. if baseDate is "25.8.2012" then parsing of the
  134. * string "1 week ago" would result in a date corresponding to
  135. * "18.8.2012". This is used when a JGit command calls this
  136. * parser often but wants a consistent starting point for calls.<br>
  137. * If set to <code>null</code> then the current time will be used
  138. * instead.
  139. * @return the parsed {@link Date}
  140. * @throws ParseException
  141. * if the given dateStr was not recognized
  142. */
  143. public static Date parse(String dateStr, Calendar now)
  144. throws ParseException {
  145. dateStr = dateStr.trim();
  146. Date ret;
  147. if ("never".equalsIgnoreCase(dateStr)) //$NON-NLS-1$
  148. return NEVER;
  149. ret = parse_relative(dateStr, now);
  150. if (ret != null)
  151. return ret;
  152. for (ParseableSimpleDateFormat f : ParseableSimpleDateFormat.values()) {
  153. try {
  154. return parse_simple(dateStr, f);
  155. } catch (ParseException e) {
  156. // simply proceed with the next parser
  157. }
  158. }
  159. ParseableSimpleDateFormat[] values = ParseableSimpleDateFormat.values();
  160. StringBuilder allFormats = new StringBuilder("\"") //$NON-NLS-1$
  161. .append(values[0].formatStr);
  162. for (int i = 1; i < values.length; i++)
  163. allFormats.append("\", \"").append(values[i].formatStr); //$NON-NLS-1$
  164. allFormats.append("\""); //$NON-NLS-1$
  165. throw new ParseException(MessageFormat.format(
  166. JGitText.get().cannotParseDate, dateStr, allFormats.toString()), 0);
  167. }
  168. // tries to parse a string with the formats supported by SimpleDateFormat
  169. private static Date parse_simple(String dateStr, ParseableSimpleDateFormat f)
  170. throws ParseException {
  171. SimpleDateFormat dateFormat = getDateFormat(f);
  172. dateFormat.setLenient(false);
  173. return dateFormat.parse(dateStr);
  174. }
  175. // tries to parse a string with a relative time specification
  176. private static Date parse_relative(String dateStr, Calendar now) {
  177. Calendar cal;
  178. SystemReader sysRead = SystemReader.getInstance();
  179. // check for the static words "yesterday" or "now"
  180. if ("now".equals(dateStr)) { //$NON-NLS-1$
  181. return ((now == null) ? new Date(sysRead.getCurrentTime()) : now
  182. .getTime());
  183. }
  184. if (now == null) {
  185. cal = new GregorianCalendar(sysRead.getTimeZone(),
  186. sysRead.getLocale());
  187. cal.setTimeInMillis(sysRead.getCurrentTime());
  188. } else
  189. cal = (Calendar) now.clone();
  190. if ("yesterday".equals(dateStr)) { //$NON-NLS-1$
  191. cal.add(Calendar.DATE, -1);
  192. cal.set(Calendar.HOUR_OF_DAY, 0);
  193. cal.set(Calendar.MINUTE, 0);
  194. cal.set(Calendar.SECOND, 0);
  195. cal.set(Calendar.MILLISECOND, 0);
  196. cal.set(Calendar.MILLISECOND, 0);
  197. return cal.getTime();
  198. }
  199. // parse constructs like "3 days ago", "5.week.2.day.ago"
  200. String[] parts = dateStr.split("\\.| "); //$NON-NLS-1$
  201. int partsLength = parts.length;
  202. // check we have an odd number of parts (at least 3) and that the last
  203. // part is "ago"
  204. if (partsLength < 3 || (partsLength & 1) == 0
  205. || !"ago".equals(parts[parts.length - 1])) //$NON-NLS-1$
  206. return null;
  207. int number;
  208. for (int i = 0; i < parts.length - 2; i += 2) {
  209. try {
  210. number = Integer.parseInt(parts[i]);
  211. } catch (NumberFormatException e) {
  212. return null;
  213. }
  214. if ("year".equals(parts[i + 1]) || "years".equals(parts[i + 1])) //$NON-NLS-1$ //$NON-NLS-2$
  215. cal.add(Calendar.YEAR, -number);
  216. else if ("month".equals(parts[i + 1]) //$NON-NLS-1$
  217. || "months".equals(parts[i + 1])) //$NON-NLS-1$
  218. cal.add(Calendar.MONTH, -number);
  219. else if ("week".equals(parts[i + 1]) //$NON-NLS-1$
  220. || "weeks".equals(parts[i + 1])) //$NON-NLS-1$
  221. cal.add(Calendar.WEEK_OF_YEAR, -number);
  222. else if ("day".equals(parts[i + 1]) || "days".equals(parts[i + 1])) //$NON-NLS-1$ //$NON-NLS-2$
  223. cal.add(Calendar.DATE, -number);
  224. else if ("hour".equals(parts[i + 1]) //$NON-NLS-1$
  225. || "hours".equals(parts[i + 1])) //$NON-NLS-1$
  226. cal.add(Calendar.HOUR_OF_DAY, -number);
  227. else if ("minute".equals(parts[i + 1]) //$NON-NLS-1$
  228. || "minutes".equals(parts[i + 1])) //$NON-NLS-1$
  229. cal.add(Calendar.MINUTE, -number);
  230. else if ("second".equals(parts[i + 1]) //$NON-NLS-1$
  231. || "seconds".equals(parts[i + 1])) //$NON-NLS-1$
  232. cal.add(Calendar.SECOND, -number);
  233. else
  234. return null;
  235. }
  236. return cal.getTime();
  237. }
  238. }