-
Notifications
You must be signed in to change notification settings - Fork 17
/
tools.go
71 lines (61 loc) · 1.58 KB
/
tools.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
package main
import (
"encoding/json"
"fmt"
"os"
"gopkg.in/yaml.v3"
)
func isDirectory(path string) (bool, error) {
info, err := os.Stat(path)
if err != nil {
return false, err
}
return info.IsDir(), nil
}
// exists checks whether a file or directory exists.
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
// file does not exist
return false, nil
}
// other error
return false, err
}
// isFile checks whether a path is a file.
func isFile(path string) (bool, error) {
info, err := os.Stat(path)
if err != nil {
return false, err
}
return !info.IsDir(), nil
}
// isJSONFile checks whether a path is a JSON file.
func isJSONFile(filepath string) bool {
return filepath[len(filepath)-5:] == ".json"
}
// isYAMLFile checks whether a path is a YAML file.
func isYAMLFile(filepath string) bool {
return filepath[len(filepath)-5:] == ".yaml" || filepath[len(filepath)-4:] == ".yml"
}
// loadFromJSON loads a JSON file into dst (which must be a pointer).
func loadFromJSON(configFilepath string, dst any) error {
file, err := os.Open(configFilepath)
if err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}
defer file.Close()
return json.NewDecoder(file).Decode(dst)
}
// loadFromYAML loads a YAML file into dst (which must be a pointer).
func loadFromYAML(configFilepath string, dst any) error {
file, err := os.Open(configFilepath)
if err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}
defer file.Close()
return yaml.NewDecoder(file).Decode(dst)
}