1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-11 16:22:26 +08:00

feat: add RemoveDir

This commit is contained in:
dudaodong
2025-03-28 11:06:52 +08:00
parent e74126a0bd
commit 169f280c9c
4 changed files with 148 additions and 9 deletions

View File

@@ -172,10 +172,54 @@ func IsDir(path string) bool {
// RemoveFile remove the path file.
// Play: https://go.dev/play/p/P2y0XW8a1SH
func RemoveFile(path string) error {
func RemoveFile(path string, onDelete ...func(path string)) error {
info, err := os.Stat(path)
if err != nil {
return err
}
if info.IsDir() {
return fmt.Errorf("%s is a directory", path)
}
if len(onDelete) > 0 && onDelete[0] != nil {
onDelete[0](path)
}
return os.Remove(path)
}
// RemoveDir remove the path directory.
// Play: todo
func RemoveDir(path string, onDelete ...func(path string)) error {
info, err := os.Stat(path)
if err != nil {
return err
}
if !info.IsDir() {
return fmt.Errorf("%s is not a directory", path)
}
var callback func(string)
if len(onDelete) > 0 {
callback = onDelete[0]
}
err = filepath.Walk(path, func(p string, info os.FileInfo, err error) error {
if err == nil && callback != nil {
callback(p)
}
return nil
})
if err != nil {
return err
}
return os.RemoveAll(path)
}
// CopyFile copy src file to dest file.
// Play: https://go.dev/play/p/Jg9AMJMLrJi
func CopyFile(srcPath string, dstPath string) error {

View File

@@ -85,14 +85,37 @@ func TestIsDir(t *testing.T) {
func TestRemoveFile(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestRemoveFile")
f := "./text.txt"
if !IsExist(f) {
CreateFile(f)
err := RemoveFile(f)
assert.IsNil(err)
CreateFile(f)
err := RemoveFile(f)
assert.IsNil(err)
}
func TestRemoveDir(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestRemoveDir")
err := os.MkdirAll("./tempdir/a/b", 0755)
if err != nil {
t.Error(err)
t.FailNow()
}
var deletedPaths []string
err = RemoveDir("./tempdir", func(p string) {
deletedPaths = append(deletedPaths, p)
})
if err != nil {
t.Error(err)
t.FailNow()
}
assert.Equal([]string{"./tempdir", "tempdir/a", "tempdir/a/b"}, deletedPaths)
assert.Equal(false, IsExist("./tempdir"))
}
func TestCopyFile(t *testing.T) {