Skip to content

Commit

Permalink
fix: update parsing logic of config.Duration
Browse files Browse the repository at this point in the history
Fixes: #10734
  • Loading branch information
powersj committed Mar 10, 2022
1 parent 2c2fcc4 commit dd9d8c7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 21 deletions.
38 changes: 17 additions & 21 deletions config/types.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package config

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

"github.com/alecthomas/units"
Expand All @@ -16,40 +17,35 @@ 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)
fmt.Printf("%s -> %s\n", durStr, dur)
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

0 comments on commit dd9d8c7

Please sign in to comment.