refactor: replace util with go generics

This commit is contained in:
ᴍᴏᴏɴD4ʀᴋ
2022-04-17 16:35:40 +08:00
parent a0eeee8604
commit 806c5bf2ee
14 changed files with 83 additions and 113 deletions
+2 -6
View File
@@ -45,11 +45,11 @@ func ReadFile(filename string) (string, error) {
// CopyItemToLocal copies the file from the provided path to the local path
func CopyItemToLocal(itemPaths map[item.Item]string) error {
for i, path := range itemPaths {
for i, p := range itemPaths {
// var dstFilename = item.TempName()
var filename = i.String()
// TODO: Handle read file error
d, err := ioutil.ReadFile(path)
d, err := ioutil.ReadFile(p)
if err != nil {
fmt.Println(err.Error())
}
@@ -113,7 +113,3 @@ func CompressDir(dir string) error {
log.Debugf("Compress success, zip filename is %s", filename)
return nil
}
// func CleanProfilePath(p string) string {
//
// }
+35
View File
@@ -1,5 +1,11 @@
package typeutil
import (
"time"
"golang.org/x/exp/constraints"
)
// Keys returns a slice of the keys of the map. based with go 1.18 generics
func Keys[K comparable, V any](m map[K]V) []K {
r := make([]K, 0, len(m))
@@ -8,3 +14,32 @@ func Keys[K comparable, V any](m map[K]V) []K {
}
return r
}
func IntToBool[T constraints.Signed](a T) bool {
switch a {
case 0, -1:
return false
}
return true
}
func TimeStamp(stamp int64) time.Time {
s := time.Unix(stamp, 0)
if s.Local().Year() > 9999 {
return time.Date(9999, 12, 13, 23, 59, 59, 0, time.Local)
}
return s
}
func TimeEpoch(epoch int64) time.Time {
maxTime := int64(99633311740000000)
if epoch > maxTime {
return time.Date(2049, 1, 1, 1, 1, 1, 1, time.Local)
}
t := time.Date(1601, 1, 1, 0, 0, 0, 0, time.Local)
d := time.Duration(epoch)
for i := 0; i < 1000; i++ {
t = t.Add(d)
}
return t
}
-69
View File
@@ -1,69 +0,0 @@
package utils
import (
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"time"
)
func IntToBool(a int) bool {
switch a {
case 0, -1:
return false
}
return true
}
func BookmarkType(a int64) string {
switch a {
case 1:
return "url"
default:
return "folder"
}
}
func TimeStampFormat(stamp int64) time.Time {
s1 := time.Unix(stamp, 0)
if s1.Local().Year() > 9999 {
return time.Date(9999, 12, 13, 23, 59, 59, 0, time.Local)
}
return s1
}
func TimeEpochFormat(epoch int64) time.Time {
maxTime := int64(99633311740000000)
if epoch > maxTime {
return time.Date(2049, 1, 1, 1, 1, 1, 1, time.Local)
}
t := time.Date(1601, 1, 1, 0, 0, 0, 0, time.UTC)
d := time.Duration(epoch)
for i := 0; i < 1000; i++ {
t = t.Add(d)
}
return t
}
func WriteFile(filename string, data []byte) error {
err := ioutil.WriteFile(filename, data, 0644)
if err != nil {
return nil
}
return err
}
func FormatFilename(dir, browser, filename, format string) string {
r := strings.Replace(strings.TrimSpace(strings.ToLower(browser)), " ", "_", -1)
p := path.Join(dir, fmt.Sprintf("%s_%s.%s", r, filename, format))
return p
}
func MakeDir(dirName string) error {
if _, err := os.Stat(dirName); os.IsNotExist(err) {
return os.Mkdir(dirName, 0700)
}
return nil
}