Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: update parsing logic of config.Duration #10803

Merged
merged 2 commits into from
Mar 11, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix: update parsing logic of config.Duration
Fixes: #10734
  • Loading branch information
powersj committed Mar 10, 2022
commit e0e9a41f2af64877f5f9f7b638c8a50ff69aff13
36 changes: 15 additions & 21 deletions config/types.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package config

import (
"bytes"
"strconv"
"strings"
"time"

"github.com/alecthomas/units"
Expand All @@ -16,40 +16,34 @@ type Size int64

// UnmarshalTOML parses the duration from the TOML config file
func (d *Duration) UnmarshalTOML(b []byte) error {
var err error
b = bytes.Trim(b, `'`)

// see if we can directly convert it
dur, err := time.ParseDuration(string(b))
if err == nil {
*d = Duration(dur)
return nil
}

// Parse string duration, ie, "1s"
if uq, err := strconv.Unquote(string(b)); err == nil && len(uq) > 0 {
dur, err := time.ParseDuration(uq)
if err == nil {
*d = Duration(dur)
return nil
}
}
// convert to string
durStr := string(b)

// Value is a TOML number (e.g. 3, 10, 3.5)
// First try parsing as integer seconds
sI, err := strconv.ParseInt(string(b), 10, 64)
sI, err := strconv.ParseInt(durStr, 10, 64)
if err == nil {
dur := time.Second * time.Duration(sI)
*d = Duration(dur)
return nil
}
// Second try parsing as float seconds
sF, err := strconv.ParseFloat(string(b), 64)
sF, err := strconv.ParseFloat(durStr, 64)
if err == nil {
dur := time.Second * time.Duration(sF)
*d = Duration(dur)
return nil
}

// Finally, try value is a TOML string (e.g. "3s", 3s) or literal (e.g. '3s')
durStr = strings.ReplaceAll(durStr, "'", "")
durStr = strings.ReplaceAll(durStr, "\"", "")
dur, err := time.ParseDuration(durStr)
if err != nil {
return err
}

*d = Duration(dur)
return nil
}

Expand Down
3 changes: 3 additions & 0 deletions config/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ func TestDuration(t *testing.T) {
d = config.Duration(0)
require.NoError(t, d.UnmarshalTOML([]byte(`1.5`)))
require.Equal(t, time.Second, time.Duration(d))

require.Error(t, d.UnmarshalTOML([]byte(`"1"`))) // string missing unit
require.Error(t, d.UnmarshalTOML([]byte(`'2'`))) // string missing unit
}

func TestSize(t *testing.T) {
Expand Down