github.com/lzy4123/fabric@v2.1.1+incompatible/common/ledger/util/ioutil.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package util 8 9 import ( 10 "io" 11 "io/ioutil" 12 "os" 13 "path" 14 "strings" 15 16 "github.com/hyperledger/fabric/common/flogging" 17 "github.com/pkg/errors" 18 ) 19 20 var logger = flogging.MustGetLogger("kvledger.util") 21 22 // CreateDirIfMissing creates a dir for dirPath if not already exists. If the dir is empty it returns true 23 func CreateDirIfMissing(dirPath string) (bool, error) { 24 // if dirPath does not end with a path separator, it leaves out the last segment while creating directories 25 if !strings.HasSuffix(dirPath, "/") { 26 dirPath = dirPath + "/" 27 } 28 logger.Debugf("CreateDirIfMissing [%s]", dirPath) 29 logDirStatus("Before creating dir", dirPath) 30 err := os.MkdirAll(path.Dir(dirPath), 0755) 31 if err != nil { 32 logger.Debugf("Error creating dir [%s]", dirPath) 33 return false, errors.Wrapf(err, "error creating dir [%s]", dirPath) 34 } 35 logDirStatus("After creating dir", dirPath) 36 return DirEmpty(dirPath) 37 } 38 39 // DirEmpty returns true if the dir at dirPath is empty 40 func DirEmpty(dirPath string) (bool, error) { 41 f, err := os.Open(dirPath) 42 if err != nil { 43 logger.Debugf("Error opening dir [%s]: %+v", dirPath, err) 44 return false, errors.Wrapf(err, "error opening dir [%s]", dirPath) 45 } 46 defer f.Close() 47 48 _, err = f.Readdir(1) 49 if err == io.EOF { 50 return true, nil 51 } 52 err = errors.Wrapf(err, "error checking if dir [%s] is empty", dirPath) 53 return false, err 54 } 55 56 // FileExists checks whether the given file exists. 57 // If the file exists, this method also returns the size of the file. 58 func FileExists(filePath string) (bool, int64, error) { 59 fileInfo, err := os.Stat(filePath) 60 if os.IsNotExist(err) { 61 return false, 0, nil 62 } 63 if err != nil { 64 return false, 0, errors.Wrapf(err, "error checking if file [%s] exists", filePath) 65 } 66 return true, fileInfo.Size(), nil 67 } 68 69 // ListSubdirs returns the subdirectories 70 func ListSubdirs(dirPath string) ([]string, error) { 71 subdirs := []string{} 72 files, err := ioutil.ReadDir(dirPath) 73 if err != nil { 74 return nil, errors.Wrapf(err, "error reading dir %s", dirPath) 75 } 76 for _, f := range files { 77 if f.IsDir() { 78 subdirs = append(subdirs, f.Name()) 79 } 80 } 81 return subdirs, nil 82 } 83 84 func logDirStatus(msg string, dirPath string) { 85 exists, _, err := FileExists(dirPath) 86 if err != nil { 87 logger.Errorf("Error checking for dir existence") 88 } 89 if exists { 90 logger.Debugf("%s - [%s] exists", msg, dirPath) 91 } else { 92 logger.Debugf("%s - [%s] does not exist", msg, dirPath) 93 } 94 }