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

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