diff --git a/glob.go b/glob.go index 5b19579..16c1e2e 100644 --- a/glob.go +++ b/glob.go @@ -10,6 +10,11 @@ import ( "github.com/spf13/afero" ) +const ( + runeSeparator = '/' + stringSeparator = string(runeSeparator) +) + // FileSystem is meant to be used with WithFs. type FileSystem afero.Fs @@ -48,10 +53,14 @@ func QuoteMeta(pattern string) string { return glob.QuoteMeta(pattern) } +func CleanPath(path string) string { + return filepath.ToSlash(filepath.Clean(path)) +} + // Glob returns all files that match the given pattern in the current directory. func Glob(pattern string, opts ...OptFunc) ([]string, error) { return doGlob( - strings.TrimPrefix(pattern, "./"), + strings.TrimPrefix(pattern, "." + stringSeparator), compileOptions(opts), ) } @@ -60,7 +69,7 @@ func doGlob(pattern string, options *globOptions) ([]string, error) { // nolint: var fs = options.fs var matches []string - matcher, err := glob.Compile(pattern, filepath.Separator) + matcher, err := glob.Compile(pattern, runeSeparator) if err != nil { return matches, fmt.Errorf("compile glob pattern: %w", err) } @@ -76,7 +85,7 @@ func doGlob(pattern string, options *globOptions) ([]string, error) { // nolint: // glob contains no dynamic matchers so prefix is the file name that // the glob references directly. When the glob explicitly references // a single non-existing file, return an error for the user to check. - return []string{}, fmt.Errorf("matching %q: %w", prefix, os.ErrNotExist) + return []string{}, fmt.Errorf(`matching "%s": %w`, prefix, os.ErrNotExist) } return []string{}, nil @@ -100,6 +109,8 @@ func doGlob(pattern string, options *globOptions) ([]string, error) { // nolint: return err } + // The glob ast from github.com/gobwas/glob only works properly with linux paths + path = CleanPath(path) if !matcher.Match(path) { return nil } @@ -149,6 +160,7 @@ func filesInDirectory(fs afero.Fs, dir string) ([]string, error) { if info.IsDir() { return nil } + path = CleanPath(path) files = append(files, path) return nil }) diff --git a/prefix.go b/prefix.go index 6cb55b5..7e21312 100644 --- a/prefix.go +++ b/prefix.go @@ -59,11 +59,11 @@ func staticText(node *ast.Node) (text string, ok bool) { // staticPrefix returns the file path inside the pattern up // to the first path element that contains a wildcard. func staticPrefix(pattern string) (string, error) { - parts := strings.Split(pattern, string(filepath.Separator)) + parts := strings.Split(pattern, stringSeparator) prefix := "" - if len(pattern) > 0 && rune(pattern[0]) == filepath.Separator { - prefix = string(filepath.Separator) + if len(pattern) > 0 && rune(pattern[0]) == runeSeparator { + prefix = stringSeparator } for _, part := range parts { @@ -81,7 +81,8 @@ func staticPrefix(pattern string) (string, error) { break } - prefix = filepath.Join(prefix, staticPart) + // The glob ast from github.com/gobwas/glob only works properly with linux paths + prefix = filepath.ToSlash(filepath.Join(prefix, staticPart)) } if prefix == "" {