CLI date/time related options - allow different time formats (#21867)

This commit is contained in:
Winfried Plappert authored and GitHub committed 2026-11-22 18:12:38 +00:00
1 parent 1d80020e28
commit 8f4873d5d7
7 files changed
+154 -30

No files matched your search

+32 -1
View File
@@ -3,7 +3,6 @@ package ui
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math/bits"
"strconv"
@@ -11,6 +10,8 @@ import (
"unicode"
"golang.org/x/text/width"
"github.com/restic/restic/internal/errors"
)
func FormatBytes(c uint64) string {
@@ -185,3 +186,33 @@ func wideRune(s string) (wide bool, utfsize uint) {
wide = kind != width.Neutral && kind != width.EastAsianNarrow
return wide, uint(size)
}
// allowed formats for ParseTime
var timeFormats = []string{
// y-m-d variations
"2006-1-2",
"2006-1-2 15:04",
"2006-1-2 15:04:05",
"2006-1-2 15:04:05 -0700",
"2006-1-2 15:04:05 MST",
// d.m.y variations
"2.1.2006",
"2.1.2006 15:04",
"2.1.2006 15:04:05",
"2.1.2006 15:04:05 -0700",
"2.1.2006 15:04:05 MST",
// *nix style date/time
"Mon Jan 2 15:04:05 -0700 MST 2006",
}
func ParseTime(str string) (time.Time, error) {
for _, fmt := range timeFormats {
if t, err := time.ParseInLocation(fmt, str, time.Local); err == nil {
return t, nil
}
}
return time.Time{}, errors.Fatalf("unable to parse time: %q", str)
}
+88
View File
@@ -162,6 +162,94 @@ func TestTruncate(t *testing.T) {
}
}
func testParseTimeMayFail(t *testing.T, s string, expectError bool) error {
t.Helper()
_, err := ParseTime(s)
if expectError == (err != nil) {
return nil
}
return err
}
func TestParseTime(t *testing.T) {
tests := []struct {
time string
err bool
}{
{
time: "2026-11-1",
},
{
time: "2026-11-11 25:00:00",
err: true,
},
{
time: "2026-11-11 23:00:00 GMT",
},
{
time: "2026-11-11 23:00:00 UTC",
},
{
time: "2026-11-11 23:00:00 +0200",
},
{
time: "2026-13-1",
err: true,
},
{
time: "2026-11-31",
err: true,
},
{
time: "1.3.2026",
},
{
time: "32-3-2026",
err: true,
},
{
time: "1.3.2026 01:02",
},
{
time: "1.3.2026 11:22:33",
},
{
time: "1.3.2026 11:22:333",
err: true,
},
{
time: "01.3.2026 01:02:03 GMT",
},
{
time: "01.7.2026 01:02:03 IST",
},
{
time: "01.3.2026 01:02:03 CET",
},
{
time: "01.3.2026 01:02:03 CST",
err: true,
},
{
time: "01.08.2026 12:00:01 +0200",
},
{
time: "29.02.2027",
err: true,
},
{
time: "29.02.2028",
},
}
for _, tt := range tests {
t.Run(tt.time, func(t *testing.T) {
rtest.OK(t, testParseTimeMayFail(t, tt.time, tt.err))
})
}
}
func benchmarkTruncate(b *testing.B, s string, w int) {
for i := 0; i < b.N; i++ {
Truncate(s, w)