Path: blob/main/vendor/github.com/spf13/afero/match.go
2875 views
// Copyright © 2014 Steve Francia <[email protected]>.1// Copyright 2009 The Go Authors. All rights reserved.23// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package afero1516import (17"path/filepath"18"sort"19"strings"20)2122// Glob returns the names of all files matching pattern or nil23// if there is no matching file. The syntax of patterns is the same24// as in Match. The pattern may describe hierarchical names such as25// /usr/*/bin/ed (assuming the Separator is '/').26//27// Glob ignores file system errors such as I/O errors reading directories.28// The only possible returned error is ErrBadPattern, when pattern29// is malformed.30//31// This was adapted from (http://golang.org/pkg/path/filepath) and uses several32// built-ins from that package.33func Glob(fs Fs, pattern string) (matches []string, err error) {34if !hasMeta(pattern) {35// Lstat not supported by a ll filesystems.36if _, err = lstatIfPossible(fs, pattern); err != nil {37return nil, nil38}39return []string{pattern}, nil40}4142dir, file := filepath.Split(pattern)43switch dir {44case "":45dir = "."46case string(filepath.Separator):47// nothing48default:49dir = dir[0 : len(dir)-1] // chop off trailing separator50}5152if !hasMeta(dir) {53return glob(fs, dir, file, nil)54}5556var m []string57m, err = Glob(fs, dir)58if err != nil {59return60}61for _, d := range m {62matches, err = glob(fs, d, file, matches)63if err != nil {64return65}66}67return68}6970// glob searches for files matching pattern in the directory dir71// and appends them to matches. If the directory cannot be72// opened, it returns the existing matches. New matches are73// added in lexicographical order.74func glob(fs Fs, dir, pattern string, matches []string) (m []string, e error) {75m = matches76fi, err := fs.Stat(dir)77if err != nil {78return79}80if !fi.IsDir() {81return82}83d, err := fs.Open(dir)84if err != nil {85return86}87defer d.Close()8889names, _ := d.Readdirnames(-1)90sort.Strings(names)9192for _, n := range names {93matched, err := filepath.Match(pattern, n)94if err != nil {95return m, err96}97if matched {98m = append(m, filepath.Join(dir, n))99}100}101return102}103104// hasMeta reports whether path contains any of the magic characters105// recognized by Match.106func hasMeta(path string) bool {107// TODO(niemeyer): Should other magic characters be added here?108return strings.ContainsAny(path, "*?[")109}110111112