driftctl/pkg/iac/terraform/state/enumerator/glob.go

61 lines
1.1 KiB
Go
Raw Normal View History

package enumerator
import (
2021-05-06 08:58:45 +00:00
"io/fs"
"os"
2021-05-06 08:58:45 +00:00
"path"
"path/filepath"
"strings"
2021-05-06 08:58:45 +00:00
"github.com/bmatcuk/doublestar/v4"
)
func GlobS3(path string) (prefix string, pattern string, err error) {
if !HasMeta(path) {
return path, "", nil
}
prefix, pattern = splitDirPattern(path)
return
}
func HasMeta(path string) bool {
magicChars := `?*[]`
return strings.ContainsAny(path, magicChars)
}
func splitDirPattern(p string) (base string, pattern string) {
base = p
sep := string(os.PathSeparator)
for {
if !HasMeta(base) {
break
}
if !strings.Contains(base, sep) {
return "", base
}
base = base[:strings.LastIndex(base, sep)]
}
if len(base) == len(p) {
return p, ""
}
return base, p[len(base)+1:]
}
func Glob(pattern string) ([]string, error) {
if !strings.Contains(pattern, "**") {
return filepath.Glob(pattern)
}
2021-05-06 08:58:45 +00:00
var files []string
err := doublestar.GlobWalk(os.DirFS("."), path.Clean(pattern), func(path string, d fs.DirEntry) error {
files = append(files, path)
return nil
})
if err != nil {
return nil, err
}
return files, nil
}