-
Notifications
You must be signed in to change notification settings - Fork 667
/
storage_common.go
71 lines (65 loc) · 1.71 KB
/
storage_common.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
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package storage
import (
"errors"
"fmt"
"os"
"path/filepath"
)
// fileExists checks if a file exists before we
// try using it to prevent further errors.
func FileExists(filePath string) (bool, error) {
info, err := os.Stat(filePath)
if err == nil {
return !info.IsDir(), nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
// ReadFileWithName reads a single file with name fileNameWithoutExt without specifying any extension.
// it errors when there are more than 1 file with the given fileName
func ReadFileWithName(parentDir string, fileNameNoExt string) ([]byte, error) {
filePath := filepath.Join(parentDir, fileNameNoExt)
files, err := filepath.Glob(filePath + ".*") // all possible extensions
switch {
case err != nil:
return nil, err
case len(files) > 1:
return nil, fmt.Errorf(`too many files matched "%s.*" in %s`, fileNameNoExt, parentDir)
case len(files) == 0:
// no file found, return nothing
return nil, nil
default:
return os.ReadFile(files[0])
}
}
// folderExists checks if a folder exists before we
// try using it to prevent further errors.
func FolderExists(filePath string) (bool, error) {
info, err := os.Stat(filePath)
switch {
case errors.Is(err, os.ErrNotExist):
return false, nil
case err != nil:
return false, err
default:
return info.IsDir(), nil
}
}
func DirSize(path string) (uint64, 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 nil
})
return uint64(size), err
}