-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathio.go
71 lines (60 loc) · 1.53 KB
/
io.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 2023 Volvo Car Corporation
// SPDX-License-Identifier: Apache-2.0
package kubeutil
import (
"errors"
"fmt"
"os"
"path/filepath"
"golang.org/x/exp/slices"
)
// ListGoFiles returns a list of all go files in the root directory and
// its children directories
func ListGoFiles(root string) ([]string, error) {
return listFiles(root, []string{".go"})
}
// ListYAMLFiles returns a list of all yaml files in the root directory and
// its children directories
func ListYAMLFiles(root string) ([]string, error) {
return listFiles(root, []string{".yaml", ".yml"})
}
// ListJSONFiles returns a list of all json files in the root directory and
// its children directories
func ListJSONFiles(root string) ([]string, error) {
return listFiles(root, []string{".json"})
}
func listFiles(root string, extensions []string) ([]string, error) {
var files []string
fi, err := os.Stat(root)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, errors.New("root is not a directory")
}
err = filepath.Walk(
root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("walk %q %q, %w", path, info.Name(), err)
}
if !info.IsDir() && slices.Contains(
extensions,
filepath.Ext(filepath.Base(path)),
) {
files = append(files, path)
}
return nil
},
)
if err != nil {
return nil, fmt.Errorf("walk: %w", err)
}
return files, nil
}
func FileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}