github.heygears.com/openimsdk/tools@v0.0.49/field/file.go (about) 1 // Copyright © 2024 OpenIM open source community. All rights reserved. 2 // 3 // 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 at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 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. 14 15 package field 16 17 import ( 18 "os" 19 20 "github.com/openimsdk/tools/errs" 21 ) 22 23 // LinkTreatment is the base type for constants used by Exists that indicate 24 // how symlinks are treated for existence checks. 25 type LinkTreatment int 26 27 const ( 28 // CheckFollowSymlink follows the symlink and verifies that the target of 29 // the symlink exists. 30 CheckFollowSymlink LinkTreatment = iota 31 32 // CheckSymlinkOnly does not follow the symlink and verifies only that they 33 // symlink itself exists. 34 CheckSymlinkOnly 35 ) 36 37 // ErrInvalidLinkTreatment indicates that the link treatment behavior requested 38 // is not a valid behavior. 39 var ErrInvalidLinkTreatment = errs.New("unknown link behavior") 40 41 // Exists checks if specified file, directory, or symlink exists. The behavior 42 // of the test depends on the linkBehaviour argument. See LinkTreatment for 43 // more details. 44 func Exists(linkBehavior LinkTreatment, filename string) (bool, error) { 45 var err error 46 47 if linkBehavior == CheckFollowSymlink { 48 _, err = os.Stat(filename) 49 } else if linkBehavior == CheckSymlinkOnly { 50 _, err = os.Lstat(filename) 51 } else { 52 return false, errs.Wrap(ErrInvalidLinkTreatment) 53 } 54 55 if os.IsNotExist(err) { 56 return false, nil 57 } else if err != nil { 58 return false, errs.WrapMsg(err, "failed to check if file exists", "file", filename) 59 } 60 return true, nil 61 } 62 63 // ReadDirNoStat returns a string of files/directories contained 64 // in dirname without calling lstat on them. 65 func ReadDirNoStat(dirname string) ([]string, error) { 66 if dirname == "" { 67 dirname = "." 68 } 69 70 f, err := os.Open(dirname) 71 if err != nil { 72 return nil, errs.WrapMsg(err, "failed to open directory", "dir", dirname) 73 } 74 defer f.Close() 75 76 return f.Readdirnames(-1) 77 }