diff options
| author | Oliver Kuckertz <[email protected]> | 2025-07-24 17:52:43 +0200 |
|---|---|---|
| committer | Oliver Kuckertz <[email protected]> | 2025-07-24 17:54:07 +0200 |
| commit | 1b52f7648f880d6ef6aaa19e45b102edadd6c50a (patch) | |
| tree | 878a2dedc3c9386172ee78fe799e24b6a22c9166 | |
| parent | c78f730fb023e4012c4097b24408867cd5c5bdde (diff) | |
Omit zero time.Time default from usage line
This was missed in #348, there previously was no way to omit the
default value. Treating zero timestamp values as canary for absence
of a default is in line with other flag types, e.g. zero ints.
| -rw-r--r-- | time.go | 8 | ||||
| -rw-r--r-- | time_test.go | 28 |
2 files changed, 34 insertions, 2 deletions
@@ -48,7 +48,13 @@ func (d *timeValue) Type() string { return "time" } -func (d *timeValue) String() string { return d.Time.Format(time.RFC3339Nano) } +func (d *timeValue) String() string { + if d.Time.IsZero() { + return "" + } else { + return d.Time.Format(time.RFC3339Nano) + } +} // GetTime return the time value of a flag with the given name func (f *FlagSet) GetTime(name string) (time.Time, error) { diff --git a/time_test.go b/time_test.go index 46a5ada..62d9a79 100644 --- a/time_test.go +++ b/time_test.go @@ -2,13 +2,14 @@ package pflag import ( "fmt" + "strings" "testing" "time" ) func setUpTimeVar(t *time.Time, formats []string) *FlagSet { f := NewFlagSet("test", ContinueOnError) - f.TimeVar(t, "time", time.Time{}, formats, "Time") + f.TimeVar(t, "time", *t, formats, "Time") return f } @@ -60,3 +61,28 @@ func TestTime(t *testing.T) { } } } + +func usageForTimeFlagSet(t *testing.T, timeVar time.Time) string { + t.Helper() + formats := []string{time.RFC3339Nano, time.RFC1123Z} + f := setUpTimeVar(&timeVar, formats) + if err := f.Parse([]string{}); err != nil { + t.Fatalf("expected success, got %q", err) + } + return f.FlagUsages() +} + +func TestTimeDefaultZero(t *testing.T) { + usage := usageForTimeFlagSet(t, time.Time{}) + if strings.Contains(usage, "default") { + t.Errorf("expected no default value in usage, got %q", usage) + } +} + +func TestTimeDefaultNonZero(t *testing.T) { + timeVar := time.Date(2025, 1, 1, 1, 1, 1, 0, time.UTC) + usage := usageForTimeFlagSet(t, timeVar) + if !strings.Contains(usage, "default") || !strings.Contains(usage, "2025") { + t.Errorf("expected default value in usage, got %q", usage) + } +} |
