erigon-pulse/common/dir/rw_dir.go

84 lines
1.3 KiB
Go
Raw Normal View History

package dir
import (
"os"
"path/filepath"
)
func MustExist(path string) {
const perm = 0764 // user rwx, group rw, other r
if err := os.MkdirAll(path, perm); err != nil {
panic(err)
}
}
2022-08-03 08:07:36 +00:00
func Exist(path string) bool {
_, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
2022-08-12 10:48:00 +00:00
func FileExist(path string) bool {
fi, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
return false
}
if !fi.Mode().IsRegular() {
return false
}
return true
}
2022-08-12 10:48:00 +00:00
func Recreate(dir string) {
2022-08-12 15:38:29 +00:00
if Exist(dir) {
_ = os.RemoveAll(dir)
2022-08-12 10:48:00 +00:00
}
2022-08-12 15:38:29 +00:00
MustExist(dir)
2022-08-12 10:48:00 +00:00
}
2022-09-12 03:51:50 +00:00
func HasFileOfType(dir, ext string) bool {
files, err := os.ReadDir(dir)
if err != nil {
return false
}
for _, f := range files {
if f.IsDir() {
continue
}
if filepath.Ext(f.Name()) == ext {
return true
}
}
return false
}
func DeleteFilesOfType(dir string, exts ...string) {
d, err := os.Open(dir)
if err != nil {
if os.IsNotExist(err) {
return
}
panic(err)
}
defer d.Close()
files, err := d.Readdir(-1)
if err != nil {
panic(err)
}
for _, file := range files {
if !file.Mode().IsRegular() {
continue
}
for _, ext := range exts {
if filepath.Ext(file.Name()) == ext {
2022-09-12 05:37:53 +00:00
_ = os.Remove(filepath.Join(dir, file.Name()))
2022-09-12 03:51:50 +00:00
}
}
}
}