1 // Copyright © 2014 Steve Francia <spf@spf13.com>.
2 // Copyright 2009 The Go Authors. All rights reserved.
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
23 // Glob returns the names of all files matching pattern or nil
24 // if there is no matching file. The syntax of patterns is the same
25 // as in Match. The pattern may describe hierarchical names such as
26 // /usr/*/bin/ed (assuming the Separator is '/').
28 // Glob ignores file system errors such as I/O errors reading directories.
29 // The only possible returned error is ErrBadPattern, when pattern
32 // This was adapted from (http://golang.org/pkg/path/filepath) and uses several
33 // built-ins from that package.
34 func Glob(fs Fs, pattern string) (matches []string, err error) {
35 if !hasMeta(pattern) {
36 // afero does not support Lstat directly.
37 if _, err = lstatIfOs(fs, pattern); err != nil {
40 return []string{pattern}, nil
43 dir, file := filepath.Split(pattern)
47 case string(filepath.Separator):
50 dir = dir[0 : len(dir)-1] // chop off trailing separator
54 return glob(fs, dir, file, nil)
58 m, err = Glob(fs, dir)
63 matches, err = glob(fs, d, file, matches)
71 // glob searches for files matching pattern in the directory dir
72 // and appends them to matches. If the directory cannot be
73 // opened, it returns the existing matches. New matches are
74 // added in lexicographical order.
75 func glob(fs Fs, dir, pattern string, matches []string) (m []string, e error) {
77 fi, err := fs.Stat(dir)
84 d, err := fs.Open(dir)
90 names, _ := d.Readdirnames(-1)
93 for _, n := range names {
94 matched, err := filepath.Match(pattern, n)
99 m = append(m, filepath.Join(dir, n))
105 // hasMeta reports whether path contains any of the magic characters
106 // recognized by Match.
107 func hasMeta(path string) bool {
108 // TODO(niemeyer): Should other magic characters be added here?
109 return strings.IndexAny(path, "*?[") >= 0