aboutsummaryrefslogtreecommitdiffsponsor
path: root/filesystem.go
blob: f744714dbea15fae920e8989d60f1be3f744754d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package pkgtools

import (
	"io/fs"
	"math"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

const maxLockWait = 10 * time.Second

func CopyFile(dst string, src string) error {
	return ErrNotImplemented
}

func HumanReadableSize(size int64) string {
	suffixes := []string{
		"B",
		"K",
		"M",
		"G",
		"T",
	}

	base := math.Log(float64(size)) / math.Log(1024)
	newSize := math.Ceil(math.Pow(1024, base-math.Floor(base))*10) / 10
	newSuffix := suffixes[int(math.Floor(base))]
	ret := strconv.FormatFloat(newSize, 'f', -1, 64) + newSuffix
	return ret
}

func IsExist(path string) (bool, error) {
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
		return false, nil
	}
	if err != nil {
		return false, err
	}
	return true, nil
}

func IsFile(path string) (bool, error) {
	info, err := os.Stat(path)
	if err != nil {
		return false, err
	}
	return info.Mode().IsRegular(), nil
}

func IsDir(path string) (bool, error) {
	info, err := os.Stat(path)
	if err != nil {
		return false, err
	}
	return info.IsDir(), nil
}

func IsParentDir(parent, sub string) (bool, error) {
	up := ".." + string(os.PathSeparator)

	rel, err := filepath.Rel(parent, sub)
	if err != nil {
		return false, err
	}
	if !strings.HasPrefix(rel, up) && rel != ".." {
		return true, nil
	}
	return false, nil
}

func IsSymlink(path string) (bool, error) {
	info, err := os.Stat(path)
	if err != nil {
		return false, err
	}
	return info.Mode() == fs.ModeSymlink, nil
}

func FileSize(fp string) (int64, error) {
	info, err := os.Stat(fp)
	if err != nil {
		return 0, err
	}
	return info.Size(), nil
}