2021-09-23 18:53:46 +00:00
|
|
|
package util
|
2021-04-22 16:34:00 +00:00
|
|
|
|
|
|
|
import (
|
2021-08-23 20:09:24 +00:00
|
|
|
"os"
|
2021-04-22 16:34:00 +00:00
|
|
|
"path"
|
|
|
|
|
|
|
|
"github.com/bazelbuild/rules_go/go/tools/bazel"
|
2021-08-17 21:23:38 +00:00
|
|
|
"github.com/pkg/errors"
|
2021-04-22 16:34:00 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// BazelDirectoryNonEmpty returns true if directory exists and is not empty.
|
|
|
|
func BazelDirectoryNonEmpty(filePath string) (bool, error) {
|
2021-08-23 20:09:24 +00:00
|
|
|
fs, err := bazelReadDir(filePath)
|
2021-04-22 16:34:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return len(fs) > 0, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// BazelFileBytes returns the byte array of the bazel file path given.
|
|
|
|
func BazelFileBytes(filePaths ...string) ([]byte, error) {
|
|
|
|
filepath, err := bazel.Runfile(path.Join(filePaths...))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-04-18 20:42:07 +00:00
|
|
|
fileBytes, err := os.ReadFile(filepath) // #nosec G304
|
2021-04-22 16:34:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-08-17 21:23:38 +00:00
|
|
|
if len(fileBytes) == 0 {
|
|
|
|
return nil, errors.New("empty file")
|
|
|
|
}
|
2021-04-22 16:34:00 +00:00
|
|
|
return fileBytes, nil
|
|
|
|
}
|
2021-08-23 20:09:24 +00:00
|
|
|
|
|
|
|
// BazelListFiles lists all of the file names in a given directory. Excludes directories. Returns
|
|
|
|
// an error when no non-directory files exist.
|
|
|
|
func BazelListFiles(filepath string) ([]string, error) {
|
|
|
|
d, err := bazelReadDir(filepath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ret := make([]string, 0, len(d))
|
|
|
|
|
|
|
|
for _, f := range d {
|
|
|
|
if f.IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
ret = append(ret, f.Name())
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(ret) == 0 {
|
|
|
|
return nil, errors.New("no files found")
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// BazelListDirectories lists all of the directories in the given directory. Excludes regular files.
|
|
|
|
// Returns error when no directories exist.
|
|
|
|
func BazelListDirectories(filepath string) ([]string, error) {
|
|
|
|
d, err := bazelReadDir(filepath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ret := make([]string, 0)
|
|
|
|
for _, f := range d {
|
|
|
|
if f.IsDir() {
|
|
|
|
ret = append(ret, f.Name())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(ret) == 0 {
|
|
|
|
return nil, errors.New("no directories found")
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret, nil
|
|
|
|
}
|
|
|
|
|
2022-04-18 20:42:07 +00:00
|
|
|
func bazelReadDir(filepath string) ([]os.DirEntry, error) {
|
2021-08-23 20:09:24 +00:00
|
|
|
p, err := bazel.Runfile(filepath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-04-18 20:42:07 +00:00
|
|
|
return os.ReadDir(p)
|
2021-08-23 20:09:24 +00:00
|
|
|
}
|