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 12KB

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