fix: prevent overwrite when document has multiple files
This commit is contained in:
1 parent
5e88eaea97
commit
cf391172a1
2 files changed
+79
-4
No files matched your search
@@ -323,10 +323,16 @@ func handleExistingFile(ctx context.Context, client *DocspellClient, cfg config,
|
||||
return fmt.Errorf("create directory: %w", err)
|
||||
}
|
||||
|
||||
subfolder := fmt.Sprintf("%s %s - %s.%s", date.Format("20060102"), corr, itemName, extension)
|
||||
newPath := filepath.Join(curDir, subfolder)
|
||||
|
||||
if err := MoveFile(fileExistsResponse.File, newPath); err != nil {
|
||||
baseName := fmt.Sprintf("%s %s - %s", date.Format("20060102"), corr, itemName)
|
||||
newPath, alreadyArchived, err := archiveDestination(curDir, baseName, extension, len(itemDetails.Attachments), fileExistsResponse.File)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if alreadyArchived {
|
||||
if err := os.Remove(fileExistsResponse.File); err != nil {
|
||||
return fmt.Errorf("remove duplicate source file: %w", err)
|
||||
}
|
||||
} else if err := MoveFile(fileExistsResponse.File, newPath); err != nil {
|
||||
return fmt.Errorf("move file: %w", err)
|
||||
}
|
||||
|
||||
@@ -334,6 +340,37 @@ func handleExistingFile(ctx context.Context, client *DocspellClient, cfg config,
|
||||
return nil
|
||||
}
|
||||
|
||||
func archiveDestination(directory, baseName, extension string, attachmentCount int, sourcePath string) (string, bool, error) {
|
||||
if attachmentCount < 1 {
|
||||
attachmentCount = 1
|
||||
}
|
||||
for index := 1; ; index++ {
|
||||
suffix := ""
|
||||
if attachmentCount > 1 || index > 1 {
|
||||
suffix = fmt.Sprintf(".%d", index)
|
||||
}
|
||||
destination := filepath.Join(directory, baseName+suffix+"."+extension)
|
||||
_, err := os.Stat(destination)
|
||||
if os.IsNotExist(err) {
|
||||
return destination, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("inspect archive destination: %w", err)
|
||||
}
|
||||
sourceHash, err := fileSHA256(sourcePath)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("hash source file: %w", err)
|
||||
}
|
||||
destinationHash, err := fileSHA256(destination)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("hash archive destination: %w", err)
|
||||
}
|
||||
if sourceHash == destinationHash {
|
||||
return destination, true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateConfig(cfg config) {
|
||||
if len(cfg.ImportDirectories) == 0 || cfg.ArchiveDirectory == "" {
|
||||
fmt.Println("FATAL Parameter missing")
|
||||
|
||||
Reference in new issue
Block a user