Skip to content

Commit

Permalink
Merge pull request #188 from projectdiscovery/improve-parse-duration
Browse files Browse the repository at this point in the history
support days unit while parsing time string
  • Loading branch information
Mzack9999 authored Jun 27, 2023
2 parents 531b9d6 + b1fa41c commit eaf3001
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion permission/permission_win.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func checkCurrentUserRoot() (bool, error) {
return false, err
}

defer windows.FreeSid(sid)
defer func() { _ = windows.FreeSid(sid) }()

// This appears to cast a null pointer so I'm not sure why this
// works, but this guy says it does and it Works for Me™:
Expand Down
19 changes: 19 additions & 0 deletions time/timeutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package timeutil
import (
"fmt"
"strconv"
"strings"
"time"
)

Expand Down Expand Up @@ -55,3 +56,21 @@ func ParseUnixTimestamp(s string) (time.Time, error) {
}
return time.Unix(i, 0), nil
}

// ParseDuration is similar to time.ParseDuration but also supports days unit
// if the unit is omitted, it defaults to seconds
func ParseDuration(s string) (time.Duration, error) {
s = strings.ToLower(s)
// default to sec
if _, err := strconv.Atoi(s); err == nil {
s = s + "s"
}
// parse days unit as hours
if strings.HasSuffix(s, "d") {
s = strings.TrimSuffix(s, "d")
if days, err := strconv.Atoi(s); err == nil {
s = strconv.Itoa(days*24) + "h"
}
}
return time.ParseDuration(s)
}
10 changes: 10 additions & 0 deletions time/timeutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,13 @@ func TestMsToTime(t *testing.T) {
func TestSToTime(t *testing.T) {
// TBD in chaos + bbsh
}

func TestParseDuration(t *testing.T) {
tt, err := ParseDuration("2d")
require.Nil(t, err, "couldn't parse duration")
require.Equal(t, time.Hour*24*2, tt, "times don't match")

tt, err = ParseDuration("2")
require.Nil(t, err, "couldn't parse duration")
require.Equal(t, time.Second*2, tt, "times don't match")
}

0 comments on commit eaf3001

Please sign in to comment.