generateUniqueFileName 生成唯一文件名,类似浏览器的下载文件重命名逻辑、类似 windows 的回收站 修改:将序号插入到倒数第二个字符位置,如 "1721205308914.pdf.md" -> "1721205308914(1).pdf.md"
(eid, libraryID int64, originalPath string)
| 576 | // generateUniqueFileName 生成唯一文件名,类似浏览器的下载文件重命名逻辑、类似 windows 的回收站 |
| 577 | // 修改:将序号插入到倒数第二个字符位置,如 "1721205308914.pdf.md" -> "1721205308914(1).pdf.md" |
| 578 | func (dm *DirectoryManager) generateUniqueFileName(eid, libraryID int64, originalPath string) (string, error) { |
| 579 | // 检查原始路径是否已存在 |
| 580 | existingFile, err := model.GetFileByPathAndLibraryNotDeleted(eid, libraryID, originalPath) |
| 581 | if err != nil || existingFile == nil { |
| 582 | // 文件不存在,可以使用原始路径 |
| 583 | return originalPath, nil |
| 584 | } |
| 585 | |
| 586 | // 如果文件已被删除,也可以使用原始路径 |
| 587 | // if existingFile.IsDeleted { |
| 588 | // return originalPath, nil |
| 589 | // } |
| 590 | |
| 591 | // 文件已存在,开始生成重命名 |
| 592 | dir := filepath.Dir(originalPath) |
| 593 | filename := filepath.Base(originalPath) |
| 594 | |
| 595 | // 解析文件名和扩展名(支持多重扩展名) |
| 596 | baseName, extensions := dm.parseFileNameAndExtensions(filename) |
| 597 | |
| 598 | // 从(1)开始尝试 |
| 599 | for i := 1; i <= 1000; i++ { // 设置上限避免无限循环 |
| 600 | // 将序号插入到baseName和extensions之间 |
| 601 | newName := fmt.Sprintf("%s(%d)%s", baseName, i, extensions) |
| 602 | newPath := filepath.Join(dir, newName) |
| 603 | |
| 604 | // 确保路径以 / 开头 |
| 605 | if !strings.HasPrefix(newPath, "/") { |
| 606 | newPath = "/" + newPath |
| 607 | } |
| 608 | |
| 609 | // 检查新路径是否已存在 |
| 610 | existingFile, err := model.GetFileByPathAndLibrary(eid, libraryID, newPath) |
| 611 | if err != nil && existingFile == nil { |
| 612 | // 找到可用路径 |
| 613 | return newPath, nil |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | return "", fmt.Errorf("无法生成唯一文件名,已尝试1000次") |
| 618 | } |
no test coverage detected