Skip to content

Commit bb4b8d5

Browse files
committed
feat: 缓存目录为空则移除
1 parent 4960847 commit bb4b8d5

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

dl.go

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -452,10 +452,8 @@ func (d *Downloader) multiDownload(contentLen int64) (err error) {
452452
}
453453

454454
// 删除临时目录
455-
if err = os.RemoveAll(partDir); err != nil {
456-
// 合并成功但清理失败,不应该返回错误
457-
// 只记录错误但继续执行
458-
}
455+
_ = os.RemoveAll(partDir)
456+
_ = removeIfEmpty(d.options.BaseDir)
459457

460458
if d.onDownloadFinished != nil {
461459
d.onDownloadFinished(filename)
@@ -641,3 +639,31 @@ func (d *Downloader) singleDownload() error {
641639

642640
return nil
643641
}
642+
643+
// removeIfEmpty 判断文件夹是否为空,如果是则删除
644+
func removeIfEmpty(dirPath string) error {
645+
// 1. 打开目录
646+
f, err := os.Open(dirPath)
647+
if err != nil {
648+
return fmt.Errorf("fail to open directory: %v", err)
649+
}
650+
defer f.Close()
651+
652+
// 2. 读取目录内容
653+
// Readdirnames(1) 表示只读取 1 个条目。
654+
// 如果返回 io.EOF,说明目录下没有任何文件或子目录。
655+
_, err = f.Readdirnames(1)
656+
if err == io.EOF {
657+
// 目录为空,执行删除
658+
// 必须先关闭文件句柄才能删除(尤其是 Windows 系统)
659+
f.Close()
660+
return os.Remove(dirPath)
661+
}
662+
663+
if err != nil {
664+
return fmt.Errorf("fail to read directory: %v", err)
665+
}
666+
667+
// 3. 如果能读到内容,说明文件夹不为空
668+
return nil
669+
}

0 commit comments

Comments
 (0)