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

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