commit 7fad5dc142e5285556ce79d15c65d864fb9c331a Author: sneak Date: Mon Mar 30 15:40:09 2020 -0700 initial diff --git a/README.md b/README.md new file mode 100644 index 0000000..349af66 --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +# sneak/goutil + +This is a bunch of little general-purpose go utility functions that I don't +feel comfortable including as-is in my normal projects as they are too +general, so I put them here. + +Suggestions are welcome. + +# License + +WTFPL (free software, no restrictions) + +# Author + +* [sneak@sneak.berlin](mailto:sneak@sneak.berlin) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..be17c67 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module git.eeqj.de/sneak/goutil + +go 1.14 + +require github.com/hako/durafmt v0.0.0-20191009132224-3f39dc1ed9f4 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..300d53f --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/hako/durafmt v0.0.0-20191009132224-3f39dc1ed9f4 h1:60gBOooTSmNtrqNaRvrDbi8VAne0REaek2agjnITKSw= +github.com/hako/durafmt v0.0.0-20191009132224-3f39dc1ed9f4/go.mod h1:5Scbynm8dF1XAPwIwkGPqzkM/shndPm79Jd1003hTjE= diff --git a/util.go b/util.go new file mode 100644 index 0000000..5d781c7 --- /dev/null +++ b/util.go @@ -0,0 +1,45 @@ +package goutil + +import ( + "errors" + "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 err + } + + return nil + } + if src.Mode().IsRegular() { + return errors.New("file already exists at path") + } + return nil +}