fix: cleaning up the cache folder caused permission issues

This commit is contained in:
krau
2025-05-19 09:23:10 +08:00
parent 9ea4857cd9
commit 729e688748
3 changed files with 11 additions and 33 deletions

View File

@@ -1,31 +1,11 @@
package common
import (
"errors"
"os"
"path/filepath"
"time"
)
// 创建文件, 自动创建目录
func MkFile(path string, data []byte) error {
err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
if err != nil {
return err
}
return os.WriteFile(path, data, os.ModePerm)
}
// 删除文件, 并清理空目录. 如果文件不存在则返回 nil
func PurgeFile(path string) error {
if err := os.Remove(path); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return err
}
}
return RemoveEmptyDirectories(filepath.Dir(path))
}
func RmFileAfter(path string, td time.Duration) {
_, err := os.Stat(path)
if err != nil {
@@ -34,22 +14,23 @@ func RmFileAfter(path string, td time.Duration) {
}
Log.Debugf("Remove file after %s: %s", td, path)
time.AfterFunc(td, func() {
PurgeFile(path)
if err := os.Remove(path); err != nil {
Log.Errorf("Failed to remove file %s: %s", path, err)
}
})
}
// 递归删除目录
func RemoveEmptyDirectories(dirPath string) error {
// 删除目录下的所有内容, 但不删除目录本身
func RemoveAllInDir(dirPath string) error {
entries, err := os.ReadDir(dirPath)
if err != nil {
return err
}
if len(entries) == 0 {
err := os.Remove(dirPath)
if err != nil {
for _, entry := range entries {
entryPath := filepath.Join(dirPath, entry.Name())
if err := os.RemoveAll(entryPath); err != nil {
return err
}
return RemoveEmptyDirectories(filepath.Dir(dirPath))
}
return nil
}