github.com/ledgerwatch/erigon-lib@v1.0.0/common/dir/rw_dir.go (about) 1 /* 2 Copyright 2021 Erigon contributors 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 dir 18 19 import ( 20 "os" 21 "path/filepath" 22 ) 23 24 func MustExist(path string) { 25 const perm = 0764 // user rwx, group rw, other r 26 if err := os.MkdirAll(path, perm); err != nil { 27 panic(err) 28 } 29 } 30 31 func Exist(path string) bool { 32 _, err := os.Stat(path) 33 if err != nil && os.IsNotExist(err) { 34 return false 35 } 36 return true 37 } 38 39 func FileExist(path string) bool { 40 fi, err := os.Stat(path) 41 if err != nil && os.IsNotExist(err) { 42 return false 43 } 44 if !fi.Mode().IsRegular() { 45 return false 46 } 47 return true 48 } 49 50 func Recreate(dir string) { 51 if Exist(dir) { 52 _ = os.RemoveAll(dir) 53 } 54 MustExist(dir) 55 } 56 57 func HasFileOfType(dir, ext string) bool { 58 files, err := os.ReadDir(dir) 59 if err != nil { 60 return false 61 } 62 for _, f := range files { 63 if f.IsDir() { 64 continue 65 } 66 if filepath.Ext(f.Name()) == ext { 67 return true 68 } 69 } 70 return false 71 } 72 73 func DeleteFilesOfType(dir string, exts ...string) { 74 d, err := os.Open(dir) 75 if err != nil { 76 if os.IsNotExist(err) { 77 return 78 } 79 panic(err) 80 } 81 defer d.Close() 82 83 files, err := d.Readdir(-1) 84 if err != nil { 85 panic(err) 86 } 87 88 for _, file := range files { 89 if !file.Mode().IsRegular() { 90 continue 91 } 92 93 for _, ext := range exts { 94 if filepath.Ext(file.Name()) == ext { 95 _ = os.Remove(filepath.Join(dir, file.Name())) 96 } 97 } 98 } 99 }