/
files.go
100 lines (86 loc) · 2.1 KB
/
files.go
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
90
91
92
93
94
95
96
97
98
99
100
package common
import (
"github.com/dustin/go-humanize"
"io"
"io/ioutil"
"os"
"path/filepath"
)
func GetTempFile() (f *os.File, err error) {
return ioutil.TempFile("", "archon")
}
// WriteTempFile writes from the reader to a temp file and returns the path of the file
// or an empty string on error
func WriteTempFile(r io.Reader) string {
tempFile, err := GetTempFile()
if err != nil {return ""}
defer tempFile.Close()
_, err = io.Copy(tempFile, r)
if err != nil {return ""}
return tempFile.Name()
}
func IsFullPath( path string ) bool {
l := len(path)
if l == 0 {
return false
}
if path[0] == '/' || path[0] == '\\' {
return true
}
if l >= 2 && path[1] == ':' {
// Windows
return true
}
return false
}
func Join(dir, subpath string) string {
if IsFullPath(subpath) {return subpath}
return filepath.Join(dir, subpath)
}
// Default to executable returns full path. If input path is relative, it will considered relative to the
// the folder of the executable
func DefaultToExecutable(path string) string {
ex, _ := os.Executable()
return Join(filepath.Dir(ex),path)
}
func CreateFile(fullPath string) (*os.File, error) {
err := os.MkdirAll(filepath.Dir(fullPath), os.ModeDir|os.ModePerm)
if err != nil {return nil, err}
file, err := os.Create(fullPath)
return file, err
}
func FileExists( path string ) bool {
_, err := os.Stat(path)
return err == nil || !os.IsNotExist(err)
}
func FileSize( path string ) int64 {
fi, err := os.Stat(path);
if err != nil {
return 0
}
return fi.Size()
}
func FileSizeString(fullPath string) string {
return humanize.Bytes(uint64(FileSize(fullPath)))
}
func MakeFolders(folders []string) (err error) {
for _, folder := range folders {
err = os.MkdirAll(folder, os.ModeDir|os.ModePerm)
if err != nil {break}
}
return
}
// DirSize returns the size the files in a folder and subfolders in bytes
func DirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}