Compare commits

...

11 Commits

25 changed files with 849 additions and 39 deletions

View File

@@ -3,5 +3,6 @@ BFB goext library
A collection of general & useful library methods
Every subfolder is a seperate dependency and can be imported individually
This should not have any heavy dependencies (gin, mongo, etc) and add missing basic language features...
Potentially needs `export GOPRIVATE="gogs.mikescher.com"`

View File

@@ -1,7 +1,7 @@
package dataext
import (
"go.mongodb.org/mongo-driver/bson/primitive"
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"math/rand"
"strconv"
"testing"
@@ -251,18 +251,21 @@ func randomKey() string {
}
func randomVal() LRUData {
v := primitive.NewObjectID()
v, err := langext.NewHexUUID()
if err != nil {
panic(err)
}
return &v
}
func eq(a LRUData, b LRUData) bool {
v1, ok1 := a.(*primitive.ObjectID)
v2, ok2 := b.(*primitive.ObjectID)
v1, ok1 := a.(*string)
v2, ok2 := b.(*string)
if ok1 && ok2 {
if v1 == nil || v2 == nil {
return false
}
return v1.Hex() == v2.Hex()
return v1 == v2
}
return false

8
go.mod
View File

@@ -1,3 +1,9 @@
module blackforestbytes.com/goext/lang
module gogs.mikescher.com/BlackForestBytes/goext
go 1.19
require (
golang.org/x/term v0.1.0
)
require golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // indirect

43
go.sum Normal file
View File

@@ -0,0 +1,43 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g=
github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
go.mongodb.org/mongo-driver v1.10.3 h1:XDQEvmh6z1EUsXuIkXE9TaVeqHw6SwS1uf93jFs0HBA=
go.mongodb.org/mongo-driver v1.10.3/go.mod h1:z4XpeoU6w+9Vht+jAFyLgVrD+jGSQQe0+CBWFHNiHt8=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.1.0 h1:g6Z6vPFA9dYBAF7DWcH6sCcOntplXsDKcliusYijMlw=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -4,6 +4,24 @@ import (
"reflect"
)
func BoolCount(arr ...bool) int {
c := 0
for _, v := range arr {
if v {
c++
}
}
return c
}
func Range[T IntegerConstraint](start T, end T) []T {
r := make([]T, 0, end-start)
for i := start; i < end; i++ {
r = append(r, i)
}
return r
}
func ForceArray[T any](v []T) []T {
if v == nil {
return make([]T, 0)
@@ -124,6 +142,27 @@ func ArrAnyErr(arr interface{}, fn func(int) (bool, error)) (bool, error) {
return false, nil
}
func ArrFirst[T comparable](arr []T, comp func(v T) bool) (T, bool) {
for _, v := range arr {
if comp(v) {
return v, true
}
}
return *new(T), false
}
func ArrLast[T comparable](arr []T, comp func(v T) bool) (T, bool) {
found := false
result := *new(T)
for _, v := range arr {
if comp(v) {
found = true
result = v
}
}
return result, found
}
func AddToSet[T comparable](set []T, add T) []T {
for _, v := range set {
if v == add {

74
langext/base62.go Normal file
View File

@@ -0,0 +1,74 @@
package langext
import (
"crypto/rand"
"errors"
"math"
"math/big"
"strings"
)
var (
base62Base = uint64(62)
base62CharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)
func RandBase62(rlen int) string {
bi52 := big.NewInt(int64(len(base62CharacterSet)))
randMax := big.NewInt(math.MaxInt64)
r := ""
for i := 0; i < rlen; i++ {
v, err := rand.Int(rand.Reader, randMax)
if err != nil {
panic(err)
}
r += string(base62CharacterSet[v.Mod(v, bi52).Int64()])
}
return r
}
func EncodeBase62(num uint64) string {
if num == 0 {
return "0"
}
b := make([]byte, 0)
// loop as long the num is bigger than zero
for num > 0 {
r := num % base62Base
num -= r
num /= base62Base
b = append([]byte{base62CharacterSet[int(r)]}, b...)
}
return string(b)
}
func DecodeBase62(str string) (uint64, error) {
if str == "" {
return 0, errors.New("empty string")
}
result := uint64(0)
for _, v := range str {
result *= base62Base
pos := strings.IndexRune(base62CharacterSet, v)
if pos == -1 {
return 0, errors.New("invalid character: " + string(v))
}
result += uint64(pos)
}
return result, nil
}

9
langext/bool.go Normal file
View File

@@ -0,0 +1,9 @@
package langext
func FormatBool(v bool, strTrue string, strFalse string) string {
if v {
return strTrue
} else {
return strFalse
}
}

View File

@@ -1,6 +1,9 @@
package langext
import "fmt"
import (
"errors"
"fmt"
)
func FormatBytesToSI(b uint64) string {
const unit = 1000
@@ -14,3 +17,30 @@ func FormatBytesToSI(b uint64) string {
}
return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp])
}
func BytesXOR(a []byte, b []byte) ([]byte, error) {
if len(a) != len(b) {
return nil, errors.New("length mismatch")
}
r := make([]byte, len(a))
for i := 0; i < len(a); i++ {
r[i] = a[i] ^ b[i]
}
return r, nil
}
func FormatBytes(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}

View File

@@ -30,3 +30,34 @@ func CompareIntArr(arr1 []int, arr2 []int) bool {
return false
}
func CompareArr[T OrderedConstraint](arr1 []T, arr2 []T) bool {
for i := 0; i < len(arr1) || i < len(arr2); i++ {
if i < len(arr1) && i < len(arr2) {
if arr1[i] < arr2[i] {
return true
} else if arr1[i] > arr2[i] {
return false
} else {
continue
}
}
if i < len(arr1) {
return true
} else { // if i < len(arr2)
return false
}
}
return false
}

21
langext/coords.go Normal file
View File

@@ -0,0 +1,21 @@
package langext
import "math"
func DegToRad(deg float64) float64 {
return deg * (math.Pi / 180.0)
}
func RadToDeg(rad float64) float64 {
return rad / (math.Pi * 180.0)
}
func GeoDistance(lon1 float64, lat1 float64, lon2 float64, lat2 float64) float64 {
var d1 = DegToRad(lat1)
var num1 = DegToRad(lon1)
var d2 = DegToRad(lat2)
var num2 = DegToRad(lon2) - num1
var d3 = math.Pow(math.Sin((d2-d1)/2.0), 2.0) + math.Cos(d1)*math.Cos(d2)*math.Pow(math.Sin(num2/2.0), 2.0)
return 6376500.0 * (2.0 * math.Atan2(math.Sqrt(d3), math.Sqrt(1.0-d3)))
}

33
langext/generics.go Normal file
View File

@@ -0,0 +1,33 @@
package langext
type IntConstraint interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}
type SignedConstraint interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type UnsignedConstraint interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
type IntegerConstraint interface {
SignedConstraint | UnsignedConstraint
}
type FloatConstraint interface {
~float32 | ~float64
}
type ComplexConstraint interface {
~complex64 | ~complex128
}
type OrderedConstraint interface {
IntegerConstraint | FloatConstraint | ~string
}
type NumberConstraint interface {
IntegerConstraint | FloatConstraint
}

65
langext/json.go Normal file
View File

@@ -0,0 +1,65 @@
package langext
import (
"bytes"
"encoding/json"
"fmt"
)
type H map[string]any
type A []any
func TryPrettyPrintJson(str string) string {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
return str
}
return prettyJSON.String()
}
func PrettyPrintJson(str string) (string, bool) {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
return str, false
}
return prettyJSON.String(), true
}
func PatchJson[JV string | []byte](rawjson JV, key string, value any) (JV, error) {
var err error
var jsonpayload map[string]any
err = json.Unmarshal([]byte(rawjson), &jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to unmarshal payload: %w", err)
}
jsonpayload[key] = value
newjson, err := json.Marshal(jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to re-marshal payload: %w", err)
}
return JV(newjson), nil
}
func PatchRemJson[JV string | []byte](rawjson JV, key string) (JV, error) {
var err error
var jsonpayload map[string]any
err = json.Unmarshal([]byte(rawjson), &jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to unmarshal payload: %w", err)
}
delete(jsonpayload, key)
newjson, err := json.Marshal(jsonpayload)
if err != nil {
return *new(JV), fmt.Errorf("failed to re-marshal payload: %w", err)
}
return JV(newjson), nil
}

9
langext/maps.go Normal file
View File

@@ -0,0 +1,9 @@
package langext
func MapKeyArr[T comparable, V any](v map[T]V) []T {
result := make([]T, 0, len(v))
for k := range v {
result = append(result, k)
}
return result
}

11
langext/os.go Normal file
View File

@@ -0,0 +1,11 @@
package langext
import "os"
func FileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}

15
langext/rand.go Normal file
View File

@@ -0,0 +1,15 @@
package langext
import (
"crypto/rand"
"io"
)
func RandBytes(size int) []byte {
b := make([]byte, size)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
panic(err)
}
return b
}

View File

@@ -61,3 +61,49 @@ func ConvertStringerArray[T fmt.Stringer](inarr []T) []string {
}
return result
}
func StrRunePadLeft(str string, pad string, padlen int) string {
if pad == "" {
pad = " "
}
if len([]rune(str)) >= padlen {
return str
}
return strings.Repeat(pad, padlen-len([]rune(str)))[0:(padlen-len([]rune(str)))] + str
}
func StrRunePadRight(str string, pad string, padlen int) string {
if pad == "" {
pad = " "
}
if len([]rune(str)) >= padlen {
return str
}
return str + strings.Repeat(pad, padlen-len([]rune(str)))[0:(padlen-len([]rune(str)))]
}
func Indent(str string, pad string) string {
eonl := strings.HasSuffix(str, "\n")
r := ""
for _, v := range strings.Split(str, "\n") {
r += pad + v + "\n"
}
if eonl {
r = r[0 : len(r)-1]
}
return r
}
func NumToStringOpt[V IntConstraint](v *V, fallback string) string {
if v == nil {
return fallback
} else {
return fmt.Sprintf("%d", v)
}
}

134
langext/uuid.go Normal file
View File

@@ -0,0 +1,134 @@
package langext
import (
"crypto/rand"
"encoding/hex"
"io"
"strings"
)
func NewUUID() ([16]byte, error) {
var uuid [16]byte
_, err := io.ReadFull(rand.Reader, uuid[:])
if err != nil {
return [16]byte{}, err
}
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
return uuid, nil
}
func NewHexUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
var dst = make([]byte, 36)
hex.Encode(dst, uuid[:4])
dst[8] = '-'
hex.Encode(dst[9:13], uuid[4:6])
dst[13] = '-'
hex.Encode(dst[14:18], uuid[6:8])
dst[18] = '-'
hex.Encode(dst[19:23], uuid[8:10])
dst[23] = '-'
hex.Encode(dst[24:], uuid[10:])
return string(dst), nil
}
func NewUpperHexUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
var dst = make([]byte, 36)
hex.Encode(dst, uuid[:4])
dst[8] = '-'
hex.Encode(dst[9:13], uuid[4:6])
dst[13] = '-'
hex.Encode(dst[14:18], uuid[6:8])
dst[18] = '-'
hex.Encode(dst[19:23], uuid[8:10])
dst[23] = '-'
hex.Encode(dst[24:], uuid[10:])
return strings.ToUpper(string(dst)), nil
}
func NewRawHexUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
var dst = make([]byte, 32)
hex.Encode(dst, uuid[:4])
hex.Encode(dst[8:12], uuid[4:6])
hex.Encode(dst[12:16], uuid[6:8])
hex.Encode(dst[16:20], uuid[8:10])
hex.Encode(dst[20:], uuid[10:])
return strings.ToUpper(string(dst)), nil
}
func NewBracesUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}
var dst = make([]byte, 38)
dst[0] = '{'
hex.Encode(dst, uuid[:5])
dst[9] = '-'
hex.Encode(dst[10:14], uuid[4:6])
dst[14] = '-'
hex.Encode(dst[15:19], uuid[6:8])
dst[19] = '-'
hex.Encode(dst[20:24], uuid[8:10])
dst[24] = '-'
hex.Encode(dst[25:], uuid[10:])
dst[37] = '}'
return strings.ToUpper(string(dst)), nil
}
func NewParensUUID() (string, error) {
uuid, err := NewUUID()
if err != nil {
return "", err
}
// Result: (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)
var dst = make([]byte, 38)
dst[0] = '('
hex.Encode(dst, uuid[:5])
dst[9] = '-'
hex.Encode(dst[10:14], uuid[4:6])
dst[14] = '-'
hex.Encode(dst[15:19], uuid[6:8])
dst[19] = '-'
hex.Encode(dst[20:24], uuid[8:10])
dst[24] = '-'
hex.Encode(dst[25:], uuid[10:])
dst[37] = ')'
return strings.ToUpper(string(dst)), nil
}

View File

@@ -1,5 +1,7 @@
package mathext
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
func AvgFloat64(arr []float64) float64 {
return SumFloat64(arr) / float64(len(arr))
}
@@ -11,3 +13,19 @@ func SumFloat64(arr []float64) float64 {
}
return sum
}
func Max[T langext.OrderedConstraint](v1 T, v2 T) T {
if v1 > v2 {
return v1
} else {
return v2
}
}
func Min[T langext.OrderedConstraint](v1 T, v2 T) T {
if v1 < v2 {
return v1
} else {
return v2
}
}

View File

@@ -1,26 +1,28 @@
package mathext
func Sum(v []float64) float64 {
total := float64(0)
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
func Sum[T langext.NumberConstraint](v []T) T {
total := T(0)
for _, v := range v {
total += v
}
return total
}
func Mean(v []float64) float64 {
return Sum(v) / float64(len(v))
func Mean[T langext.FloatConstraint](v []T) T {
return Sum(v) / T(len(v))
}
func Median(v []float64) float64 {
func Median[T langext.FloatConstraint](v []T) T {
if len(v)%2 == 1 {
return v[len(v)/2]
} else {
return (v[len(v)/2-1] + v[len(v)/2]) / float64(2)
return (v[len(v)/2-1] + v[len(v)/2]) / T(2)
}
}
func Min(v []float64) float64 {
func ArrMin[T langext.OrderedConstraint](v []T) T {
r := v[0]
for _, val := range v {
if val < r {
@@ -30,7 +32,7 @@ func Min(v []float64) float64 {
return r
}
func Max(v []float64) float64 {
func ArrMax[T langext.OrderedConstraint](v []T) T {
r := v[0]
for _, val := range v {
if val > r {

61
termext/colors.go Normal file
View File

@@ -0,0 +1,61 @@
package termext
import "strings"
const (
colorReset = "\033[0m"
colorRed = "\033[31m"
colorGreen = "\033[32m"
colorYellow = "\033[33m"
colorBlue = "\033[34m"
colorPurple = "\033[35m"
colorCyan = "\033[36m"
colorGray = "\033[37m"
colorWhite = "\033[97m"
)
func Red(v string) string {
return colorRed + v + colorReset
}
func Green(v string) string {
return colorGreen + v + colorReset
}
func Yellow(v string) string {
return colorYellow + v + colorReset
}
func Blue(v string) string {
return colorBlue + v + colorReset
}
func Purple(v string) string {
return colorPurple + v + colorReset
}
func Cyan(v string) string {
return colorCyan + v + colorReset
}
func Gray(v string) string {
return colorGray + v + colorReset
}
func White(v string) string {
return colorWhite + v + colorReset
}
func CleanString(v string) string {
v = strings.ReplaceAll(v, colorReset, "")
v = strings.ReplaceAll(v, colorRed, "")
v = strings.ReplaceAll(v, colorGreen, "")
v = strings.ReplaceAll(v, colorYellow, "")
v = strings.ReplaceAll(v, colorBlue, "")
v = strings.ReplaceAll(v, colorPurple, "")
v = strings.ReplaceAll(v, colorCyan, "")
v = strings.ReplaceAll(v, colorGray, "")
v = strings.ReplaceAll(v, colorWhite, "")
return v
}

5
termext/osutil.go Normal file
View File

@@ -0,0 +1,5 @@
package termext
func enableColor() bool {
return true
}

24
termext/osutil_windows.go Normal file
View File

@@ -0,0 +1,24 @@
package termext
func enableColor() bool {
handle, err := windows.GetStdHandle(windows.STD_OUTPUT_HANDLE)
if err != nil {
return false
}
var mode uint32
err = windows.GetConsoleMode(handle, &mode)
if err != nil {
return false
}
if mode&windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING {
mode = mode | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
err = windows.SetConsoleMode(handle, mode)
if err != nil {
return false
}
}
return true
}

90
termext/termcolor.go Normal file
View File

@@ -0,0 +1,90 @@
package termext
import (
"golang.org/x/term"
"os"
"regexp"
"strconv"
"strings"
)
// -> partly copied from [ https://github.com/jwalton/go-supportscolor/tree/master ]
func SupportsColors() bool {
if isatty := term.IsTerminal(int(os.Stdout.Fd())); !isatty {
return false
}
termenv := os.Getenv("TERM")
if termenv == "dumb" {
return false
}
if osColorEnabled := enableColor(); !osColorEnabled {
return false
}
if _, ci := os.LookupEnv("CI"); ci {
var ciEnvNames = []string{"TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"}
for _, ciEnvName := range ciEnvNames {
_, exists := os.LookupEnv(ciEnvName)
if exists {
return true
}
}
if os.Getenv("CI_NAME") == "codeship" {
return true
}
return false
}
if teamCityVersion, isTeamCity := os.LookupEnv("TEAMCITY_VERSION"); isTeamCity {
versionRegex := regexp.MustCompile(`^(9\.(0*[1-9]\d*)\.|\d{2,}\.)`)
if versionRegex.MatchString(teamCityVersion) {
return true
}
return false
}
if os.Getenv("COLORTERM") == "truecolor" {
return true
}
if termProgram, termProgramPreset := os.LookupEnv("TERM_PROGRAM"); termProgramPreset {
switch termProgram {
case "iTerm.app":
termProgramVersion := strings.Split(os.Getenv("TERM_PROGRAM_VERSION"), ".")
version, err := strconv.ParseInt(termProgramVersion[0], 10, 64)
if err == nil && version >= 3 {
return true
}
return true
case "Apple_Terminal":
return true
default:
// No default
}
}
var term256Regex = regexp.MustCompile("(?i)-256(color)?$")
if term256Regex.MatchString(termenv) {
return true
}
var termBasicRegex = regexp.MustCompile("(?i)^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux")
if termBasicRegex.MatchString(termenv) {
return true
}
if _, colorTerm := os.LookupEnv("COLORTERM"); colorTerm {
return true
}
return false
}

View File

@@ -1,6 +1,9 @@
package timeext
import "time"
import (
"fmt"
"time"
)
func FromSeconds(v int) time.Duration {
return time.Duration(int64(v) * int64(time.Second))
@@ -53,3 +56,36 @@ func FromMilliseconds(v int) time.Duration {
func FromMillisecondsFloat(v float64) time.Duration {
return time.Duration(int64(v * float64(time.Millisecond)))
}
func FormatNaturalDurationEnglish(iv time.Duration) string {
if sec := int64(iv.Seconds()); sec < 180 {
if sec == 1 {
return "1 second ago"
} else {
return fmt.Sprintf("%d seconds ago", sec)
}
}
if min := int64(iv.Minutes()); min < 180 {
return fmt.Sprintf("%d minutes ago", min)
}
if hours := int64(iv.Hours()); hours < 72 {
return fmt.Sprintf("%d hours ago", hours)
}
if days := int64(iv.Hours() / 24.0); days < 21 {
return fmt.Sprintf("%d days ago", days)
}
if weeks := int64(iv.Hours() / 24.0 / 7.0); weeks < 12 {
return fmt.Sprintf("%d weeks ago", weeks)
}
if months := int64(iv.Hours() / 24.0 / 7.0 / 30); months < 36 {
return fmt.Sprintf("%d months ago", months)
}
years := int64(iv.Hours() / 24.0 / 7.0 / 365)
return fmt.Sprintf("%d years ago", years)
}

View File

@@ -17,14 +17,14 @@ func init() {
}
// TimeToDatePart returns a timestamp at the start of the day which contains t (= 00:00:00)
func TimeToDatePart(t time.Time) time.Time {
t = t.In(TimezoneBerlin)
func TimeToDatePart(t time.Time, tz *time.Location) time.Time {
t = t.In(tz)
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
// TimeToWeekStart returns a timestamp at the start of the week which contains t (= Monday 00:00:00)
func TimeToWeekStart(t time.Time) time.Time {
t = TimeToDatePart(t)
func TimeToWeekStart(t time.Time, tz *time.Location) time.Time {
t = TimeToDatePart(t, tz)
delta := time.Duration(((int64(t.Weekday()) + 6) % 7) * 24 * int64(time.Hour))
t = t.Add(-1 * delta)
@@ -33,32 +33,32 @@ func TimeToWeekStart(t time.Time) time.Time {
}
// TimeToMonthStart returns a timestamp at the start of the month which contains t (= yyyy-MM-00 00:00:00)
func TimeToMonthStart(t time.Time) time.Time {
t = t.In(TimezoneBerlin)
func TimeToMonthStart(t time.Time, tz *time.Location) time.Time {
t = t.In(tz)
return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
}
// TimeToMonthEnd returns a timestamp at the end of the month which contains t (= yyyy-MM-31 23:59:59.999999999)
func TimeToMonthEnd(t time.Time) time.Time {
return TimeToMonthStart(t).AddDate(0, 1, 0).Add(-1)
func TimeToMonthEnd(t time.Time, tz *time.Location) time.Time {
return TimeToMonthStart(t, tz).AddDate(0, 1, 0).Add(-1)
}
// TimeToYearStart returns a timestamp at the start of the year which contains t (= yyyy-01-01 00:00:00)
func TimeToYearStart(t time.Time) time.Time {
t = t.In(TimezoneBerlin)
func TimeToYearStart(t time.Time, tz *time.Location) time.Time {
t = t.In(tz)
return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location())
}
// TimeToYearEnd returns a timestamp at the end of the month which contains t (= yyyy-12-31 23:59:59.999999999)
func TimeToYearEnd(t time.Time) time.Time {
return TimeToYearStart(t).AddDate(1, 0, 0).Add(-1)
func TimeToYearEnd(t time.Time, tz *time.Location) time.Time {
return TimeToYearStart(t, tz).AddDate(1, 0, 0).Add(-1)
}
// IsSameDayIncludingDateBoundaries returns true if t1 and t2 are part of the same day (TZ/Berlin), the boundaries of the day are
// inclusive, this means 2021-09-15T00:00:00 is still part of the day 2021-09-14
func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time) bool {
dp1 := TimeToDatePart(t1)
dp2 := TimeToDatePart(t2)
func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time, tz *time.Location) bool {
dp1 := TimeToDatePart(t1, tz)
dp2 := TimeToDatePart(t2, tz)
if dp1.Equal(dp2) {
return true
@@ -72,9 +72,9 @@ func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time) bool {
}
// IsDatePartEqual returns true if a and b have the same date part (`yyyy`, `MM` and `dd`)
func IsDatePartEqual(a time.Time, b time.Time) bool {
yy1, mm1, dd1 := a.In(TimezoneBerlin).Date()
yy2, mm2, dd2 := b.In(TimezoneBerlin).Date()
func IsDatePartEqual(a time.Time, b time.Time, tz *time.Location) bool {
yy1, mm1, dd1 := a.In(tz).Date()
yy2, mm2, dd2 := b.In(tz).Date()
return yy1 == yy2 && mm1 == mm2 && dd1 == dd2
}
@@ -82,7 +82,7 @@ func IsDatePartEqual(a time.Time, b time.Time) bool {
// WithTimePart returns a timestamp with the date-part (`yyyy`, `MM`, `dd`) from base
// and the time (`HH`, `mm`, `ss`) from the parameter
func WithTimePart(base time.Time, hour, minute, second int) time.Time {
datepart := TimeToDatePart(base)
datepart := TimeToDatePart(base, base.Location())
delta := time.Duration(hour*int(time.Hour) + minute*int(time.Minute) + second*int(time.Second))
@@ -92,7 +92,7 @@ func WithTimePart(base time.Time, hour, minute, second int) time.Time {
// CombineDateAndTime returns a timestamp with the date-part (`yyyy`, `MM`, `dd`) from the d parameter
// and the time (`HH`, `mm`, `ss`) from the t parameter
func CombineDateAndTime(d time.Time, t time.Time) time.Time {
datepart := TimeToDatePart(d)
datepart := TimeToDatePart(d, d.Location())
delta := time.Duration(t.Hour()*int(time.Hour) + t.Minute()*int(time.Minute) + t.Second()*int(time.Second) + t.Nanosecond()*int(time.Nanosecond))
@@ -100,8 +100,8 @@ func CombineDateAndTime(d time.Time, t time.Time) time.Time {
}
// IsSunday returns true if t is a sunday (in TZ/Berlin)
func IsSunday(t time.Time) bool {
if t.In(TimezoneBerlin).Weekday() == time.Sunday {
func IsSunday(t time.Time, tz *time.Location) bool {
if t.In(tz).Weekday() == time.Sunday {
return true
}
return false
@@ -131,3 +131,7 @@ func UnixFloatSeconds(v float64) time.Time {
sec, dec := math.Modf(v)
return time.Unix(int64(sec), int64(dec*(1e9)))
}
func FloorTime(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}