blob: e7a282863873e754ad0a4a4e30737c8f5333eeec [file] [log] [blame]
Dave Borowitz2b2f34b2014-04-29 16:47:20 -07001// Copyright (C) 2014 Google Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package com.google.gitiles;
16
17import com.google.common.base.Optional;
18
19import org.eclipse.jgit.lib.PersonIdent;
20import org.eclipse.jgit.util.SystemReader;
21
22import java.io.IOException;
23import java.text.DateFormat;
24import java.text.SimpleDateFormat;
25import java.util.TimeZone;
26
27/** Date formatter similar in spirit to JGit's {@code GitDateFormatter}. */
28public class DateFormatter {
29 public static enum Format {
30 // Format strings should match org.eclipse.jgit.util.GitDateFormatter except
31 // for the timezone suffix.
32 DEFAULT("EEE MMM dd HH:mm:ss yyyy"),
33 ISO("yyyy-MM-dd HH:mm:ss");
34
35 private final String fmt;
36 private final ThreadLocal<DateFormat> defaultFormat;
37 private final ThreadLocal<DateFormat> fixedTzFormat;
38
39 private Format(String fmt) {
40 this.fmt = fmt;
41 this.defaultFormat = new ThreadLocal<>();
42 this.fixedTzFormat = new ThreadLocal<>();
43 }
44
45 private DateFormat getDateFormat(Optional<TimeZone> fixedTz) {
46 DateFormat df;
47 if (fixedTz.isPresent()) {
48 df = fixedTzFormat.get();
49 if (df == null) {
50 df = new SimpleDateFormat(fmt);
51 fixedTzFormat.set(df);
52 }
53 df.setTimeZone(fixedTz.get());
54 } else {
55 df = defaultFormat.get();
56 if (df == null) {
57 df = new SimpleDateFormat(fmt + " Z");
58 defaultFormat.set(df);
59 }
60 }
61 return df;
62 }
63 }
64
65 private final Optional<TimeZone> fixedTz;
66 private final Format format;
67
68 public DateFormatter(Optional<TimeZone> fixedTz, Format format) {
69 this.fixedTz = fixedTz;
70 this.format = format;
71 }
72
73 public DateFormatter(GitilesAccess access, Format format) throws IOException {
74 this(ConfigUtil.getTimeZone(access.getConfig(), "gitiles", null, "fixedTimeZone"), format);
75 }
76
77 public String format(PersonIdent ident) {
78 DateFormat df = format.getDateFormat(fixedTz);
79 if (!fixedTz.isPresent()) {
80 TimeZone tz = ident.getTimeZone();
81 if (tz == null) {
82 tz = SystemReader.getInstance().getTimeZone();
83 }
84 df.setTimeZone(tz);
85 }
86 return df.format(ident.getWhen());
87 }
88}