github.com/avfs/avfs@v0.33.1-0.20240303173310-c6ba67c33eb7/vfs_aferoutils.go (about) 1 // 2 // Copyright 2020 The AVFS authors 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 // 16 17 package avfs 18 19 import ( 20 "errors" 21 "fmt" 22 "io/fs" 23 "os" 24 ) 25 26 // DirExists checks if a path exists and is a directory. 27 func DirExists(vfs VFSBase, path string) (bool, error) { 28 fi, err := vfs.Stat(path) 29 if err == nil && fi.IsDir() { 30 return true, nil 31 } 32 33 if errors.Is(err, fs.ErrNotExist) { 34 return false, nil 35 } 36 37 return false, err 38 } 39 40 // Exists Check if a file or directory exists. 41 func Exists(vfs VFSBase, path string) (bool, error) { 42 _, err := vfs.Stat(path) 43 if err == nil { 44 return true, nil 45 } 46 47 if errors.Is(err, fs.ErrNotExist) { 48 return false, nil 49 } 50 51 return false, err 52 } 53 54 // IsDir checks if a given path is a directory. 55 func IsDir(vfs VFSBase, path string) (bool, error) { 56 fi, err := vfs.Stat(path) 57 if err != nil { 58 return false, err 59 } 60 61 return fi.IsDir(), nil 62 } 63 64 // IsEmpty checks if a given file or directory is empty. 65 func IsEmpty(vfs VFSBase, path string) (bool, error) { 66 if b, _ := Exists(vfs, path); !b { 67 return false, fmt.Errorf("%q path does not exist", path) 68 } 69 70 fi, err := vfs.Stat(path) 71 if err != nil { 72 return false, err 73 } 74 75 if fi.IsDir() { 76 f, err := vfs.OpenFile(path, os.O_RDONLY, 0) 77 if err != nil { 78 return false, err 79 } 80 81 defer f.Close() 82 83 list, err := f.ReadDir(-1) 84 if err != nil { 85 return false, err 86 } 87 88 return len(list) == 0, nil 89 } 90 91 return fi.Size() == 0, nil 92 }