|
1
|
|
|
package files |
|
2
|
|
|
|
|
3
|
|
|
import ( |
|
4
|
|
|
"fmt" |
|
5
|
|
|
"os" |
|
6
|
|
|
"path/filepath" |
|
7
|
|
|
"strings" |
|
8
|
|
|
) |
|
9
|
|
|
|
|
10
|
|
|
// FileExists validates that the specified path exists. |
|
11
|
|
|
// Path may be a directory or file. |
|
12
|
|
|
func FileExists(path string) (bool, error) { |
|
13
|
|
|
if _, err := os.Stat(path); err == nil { |
|
14
|
|
|
return true, nil |
|
15
|
|
|
} else if os.IsNotExist(err) { |
|
16
|
|
|
return false, nil |
|
17
|
|
|
} else { |
|
18
|
|
|
return false, err |
|
19
|
|
|
} |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
// GetOrCreateFile gets a pointer to the file at the path specified. |
|
23
|
|
|
// If the path does not exist, it is created. |
|
24
|
|
|
// If the parent directory or directories don't exist, they are also created. |
|
25
|
|
|
func GetOrCreateFile(path string) (*os.File, error) { |
|
26
|
|
|
parent := filepath.Dir(path) |
|
27
|
|
|
if exists, _ := FileExists(parent); !exists { |
|
28
|
|
|
err := os.MkdirAll(parent, 0644) |
|
29
|
|
|
if err != nil { |
|
30
|
|
|
return nil, err |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
if exists, _ := FileExists(path); !exists { |
|
34
|
|
|
return os.Create(path) |
|
35
|
|
|
} |
|
36
|
|
|
return os.Open(path) |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
func Parent(path string) string { |
|
40
|
|
|
return strings.ReplaceAll(filepath.Dir(path), "\\", "/") |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
func Join(path, file string) string { |
|
44
|
|
|
return strings.ReplaceAll(filepath.Join(path, file), "\\", "/") |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
func FormatBytes(size uint64) string { |
|
48
|
|
|
const unit = 1024 |
|
49
|
|
|
if size < unit { |
|
50
|
|
|
return fmt.Sprintf("%d B", size) |
|
51
|
|
|
} |
|
52
|
|
|
div, exp := uint64(unit), 0 |
|
53
|
|
|
for n := size / unit; n >= unit; n /= unit { |
|
54
|
|
|
div *= unit |
|
55
|
|
|
exp++ |
|
56
|
|
|
} |
|
57
|
|
|
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp]) |
|
58
|
|
|
} |
|
59
|
|
|
|