2017-04-25 20:05:59 +08:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2017-06-02 16:08:14 +08:00
|
|
|
"io"
|
2017-06-09 18:14:55 +08:00
|
|
|
"math"
|
2018-01-26 17:17:38 +08:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2017-04-25 20:05:59 +08:00
|
|
|
)
|
|
|
|
|
2018-01-26 17:17:38 +08:00
|
|
|
func AbsolutePath(p string) (string, error) {
|
2017-04-25 20:05:59 +08:00
|
|
|
|
|
|
|
if strings.HasPrefix(p, "~") {
|
|
|
|
home := os.Getenv("HOME")
|
|
|
|
if home == "" {
|
|
|
|
panic(fmt.Sprintf("can not found HOME in envs, '%s' AbsPh Failed!", p))
|
|
|
|
}
|
|
|
|
p = fmt.Sprint(home, string(p[1:]))
|
|
|
|
}
|
|
|
|
s, err := filepath.Abs(p)
|
|
|
|
|
|
|
|
if nil != err {
|
2018-01-26 17:17:38 +08:00
|
|
|
return "", err
|
2017-04-25 20:05:59 +08:00
|
|
|
}
|
2018-01-26 17:17:38 +08:00
|
|
|
return s, nil
|
2017-04-25 20:05:59 +08:00
|
|
|
}
|
2017-06-02 09:27:13 +08:00
|
|
|
|
|
|
|
// FileExists reports whether the named file or directory exists.
|
|
|
|
func FileExists(name string) bool {
|
|
|
|
if _, err := os.Stat(name); err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
2017-06-02 16:08:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func CopyFile(dstName, srcName string) (written int64, err error) {
|
|
|
|
src, err := os.Open(srcName)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer src.Close()
|
|
|
|
dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer dst.Close()
|
|
|
|
return io.Copy(dst, src)
|
|
|
|
}
|
|
|
|
|
2017-06-09 18:14:55 +08:00
|
|
|
func FormatBytes(size int64) string {
|
|
|
|
units := []string{" B", " KB", " MB", " GB", " TB"}
|
|
|
|
|
|
|
|
s := float64(size)
|
|
|
|
|
|
|
|
i := 0
|
|
|
|
|
2018-01-26 17:17:38 +08:00
|
|
|
for ; s >= 1024 && i < 4; i++ {
|
2017-06-09 18:14:55 +08:00
|
|
|
s /= 1024
|
|
|
|
}
|
|
|
|
|
2018-01-26 17:17:38 +08:00
|
|
|
return fmt.Sprintf("%.2f%s", s, units[i])
|
2017-06-09 18:14:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func Round(val float64, places int) float64 {
|
|
|
|
var t float64
|
|
|
|
f := math.Pow10(places)
|
|
|
|
x := val * f
|
|
|
|
if math.IsInf(x, 0) || math.IsNaN(x) {
|
|
|
|
return val
|
|
|
|
}
|
|
|
|
if x >= 0.0 {
|
|
|
|
t = math.Ceil(x)
|
|
|
|
if (t - x) > 0.50000000001 {
|
|
|
|
t -= 1.0
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
t = math.Ceil(-x)
|
|
|
|
if (t + x) > 0.50000000001 {
|
|
|
|
t -= 1.0
|
|
|
|
}
|
|
|
|
t = -t
|
|
|
|
}
|
|
|
|
x = t / f
|
|
|
|
|
|
|
|
if !math.IsInf(x, 0) {
|
|
|
|
return x
|
|
|
|
}
|
|
|
|
|
|
|
|
return t
|
|
|
|
}
|