Skip to content

Commit

Permalink
Merge pull request #5 from ieee0824/fix-duration
Browse files Browse the repository at this point in the history
time.ParseDuration使う
  • Loading branch information
ieee0824 authored Aug 18, 2017
2 parents 8f1e0ab + 1f5397f commit c67c7aa
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 84 deletions.
65 changes: 3 additions & 62 deletions duration.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
package getenv

import (
"regexp"
"time"
"strconv"
"os"
)

var (
reAlp = regexp.MustCompile(`[a-zA-Z]+`)
reNum = regexp.MustCompile(`[0-9]+`)
)

func Duration(key string, def ...interface{}) time.Duration {
var d time.Duration
if len(def) != 0 {
Expand All @@ -20,69 +13,17 @@ func Duration(key string, def ...interface{}) time.Duration {
} else if dr, ok := def[0].(time.Duration); ok {
d = dr
} else if s, ok := def[0].(string); ok {
d = parseDuration(s)
d, _ = time.ParseDuration(s)
}
}

v := os.Getenv(key)
if v == "" {
return d
}
return parseDuration(v)
}
d, _ = time.ParseDuration(v)

func trimArray(a []string) []string {
ret := []string{}

for _, e := range a {
if len(e) != 0 {
ret = append(ret, e)
}
}
return ret
return d
}

func parseDuration(s string) time.Duration {
alp := reAlp.Copy()
num := reNum.Copy()

numNodes := trimArray(alp.Split(s, -1))
alpNodes := trimArray(num.Split(s, -1))

if len(alpNodes) == 0 {
if len(numNodes) == 0 {
return 0
}

s, err := strconv.Atoi(numNodes[0])
if err != nil {
return 0
}
return time.Duration(int64(s)) * time.Second
}

if len(alpNodes) != len(numNodes) {
return 0
}

var ret time.Duration
for i, n := range numNodes {
t, err := strconv.Atoi(n)
if err != nil {
return 0
}
d := time.Duration(int64(t))
switch alpNodes[i] {
case "h":
ret += d * time.Hour
case "m":
ret += d * time.Minute
case "s":
ret += d * time.Second
default:
return 0
}
}
return ret
}

22 changes: 0 additions & 22 deletions duration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,6 @@ import (
"os"
)

func TestParseDuration(t *testing.T) {
tests := []struct {
input string
want time.Duration
}{
{"1h0m0s", 1*time.Hour},
{"1h30m20s", 1*time.Hour + 30*time.Minute + 20*time.Second},
{"60", 60*time.Second},
{"", 0},
{"a", 0},
{"00af00", 0},
{"0h30m", 30*time.Minute},
{"20s", 20*time.Second},
}

for _, test := range tests {
if test.want != parseDuration(test.input) {
t.Fatalf("want %v, but %v:", test.want, parseDuration(test.input))
}
}
}

func TestDuration(t *testing.T) {
tests := []struct {
input string
Expand Down

0 comments on commit c67c7aa

Please sign in to comment.