podman
1// Copyright ©2015 The Go Authors
2// Copyright ©2015 Steve Francia <spf@spf13.com>
3//
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//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16package afero17
18import (19"os"20"path/filepath"21"sort"22)
23
24// readDirNames reads the directory named by dirname and returns
25// a sorted list of directory entries.
26// adapted from https://golang.org/src/path/filepath/path.go
27func readDirNames(fs Fs, dirname string) ([]string, error) {28f, err := fs.Open(dirname)29if err != nil {30return nil, err31}32names, err := f.Readdirnames(-1)33f.Close()34if err != nil {35return nil, err36}37sort.Strings(names)38return names, nil39}
40
41// walk recursively descends path, calling walkFn
42// adapted from https://golang.org/src/path/filepath/path.go
43func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error {44err := walkFn(path, info, nil)45if err != nil {46if info.IsDir() && err == filepath.SkipDir {47return nil48}49return err50}51
52if !info.IsDir() {53return nil54}55
56names, err := readDirNames(fs, path)57if err != nil {58return walkFn(path, info, err)59}60
61for _, name := range names {62filename := filepath.Join(path, name)63fileInfo, err := lstatIfPossible(fs, filename)64if err != nil {65if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {66return err67}68} else {69err = walk(fs, filename, fileInfo, walkFn)70if err != nil {71if !fileInfo.IsDir() || err != filepath.SkipDir {72return err73}74}75}76}77return nil78}
79
80// if the filesystem supports it, use Lstat, else use fs.Stat
81func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) {82if lfs, ok := fs.(Lstater); ok {83fi, _, err := lfs.LstatIfPossible(path)84return fi, err85}86return fs.Stat(path)87}
88
89// Walk walks the file tree rooted at root, calling walkFn for each file or
90// directory in the tree, including root. All errors that arise visiting files
91// and directories are filtered by walkFn. The files are walked in lexical
92// order, which makes the output deterministic but means that for very
93// large directories Walk can be inefficient.
94// Walk does not follow symbolic links.
95
96func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error {97return Walk(a.Fs, root, walkFn)98}
99
100func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error {101info, err := lstatIfPossible(fs, root)102if err != nil {103return walkFn(root, nil, err)104}105return walk(fs, root, info, walkFn)106}
107