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