util/util.go

98 lines
2.3 KiB
Go
Raw Normal View History

2024-06-01 22:35:40 +00:00
package util
2020-03-30 22:40:09 +00:00
import (
"errors"
2020-09-21 21:53:35 +00:00
"io"
2020-03-30 22:40:09 +00:00
"math"
"os"
"regexp"
"time"
"github.com/hako/durafmt"
)
func FilterToAlnum(input string) string {
re := regexp.MustCompile("[^a-zA-Z0-9]+")
return re.ReplaceAllString(input, "")
}
func TimeDiffHuman(first time.Time, second time.Time) string {
if first.Before(second) {
return durafmt.ParseShort(second.Sub(first)).String()
} else {
return durafmt.ParseShort(first.Sub(second)).String()
}
}
// Does anyone else use uints for things that are always >=0 like counts and
func TimeDiffAbsSeconds(first time.Time, second time.Time) uint {
return uint(math.Abs(first.Sub(second).Truncate(time.Second).Seconds()))
}
func Mkdirp(p string) error {
src, err := os.Stat(p)
if os.IsNotExist(err) {
errDir := os.MkdirAll(p, 0755)
if errDir != nil {
return errDir
2020-03-30 22:40:09 +00:00
}
return nil
}
if src.Mode().IsRegular() {
return errors.New("file already exists at path")
}
return nil
}
2020-09-21 21:53:35 +00:00
// straight outta stackoverflow
// https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
func CopyFile(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
cerr := out.Close()
if err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}
2020-09-22 00:18:04 +00:00
const milliInSecond int64 = 1000
const microInSecond int64 = 1000000
const nsInSecond int64 = 1000000000
func TimeFromUnixMilli(input int64) time.Time {
var wholeSeconds int64 = input / milliInSecond
var remainderMillis int64 = input - (wholeSeconds * milliInSecond)
var remainderNano int64 = remainderMillis * 1000000
return time.Unix(wholeSeconds, remainderNano)
}
2020-09-22 00:18:04 +00:00
func TimeFromUnixMicro(input int64) time.Time {
var wholeSeconds int64 = input / microInSecond
var remainderMicros int64 = input - (wholeSeconds * microInSecond)
var remainderNano int64 = remainderMicros * 1000
return time.Unix(wholeSeconds, remainderNano)
}
func TimeFromWebKit(input int64) time.Time {
// webkit time is stupid and uses 1601-01-01 for epoch
// it's 11644473600 seconds behind unix 1970-01-01 epoch
// it's also in microseconds
unixMicrosCorrected := input - (11644473600 * 1000000)
return TimeFromUnixMicro(unixMicrosCorrected)
}