Add retries to file moving func

This commit is contained in:
2025-07-21 11:07:23 +03:00
parent 87188deda5
commit 4b5c4a577a

46
main.go
View File

@@ -2,7 +2,9 @@ package main
import (
"context"
"errors"
"fmt"
"io/fs"
"log"
"os"
"os/signal"
@@ -52,7 +54,7 @@ func main() {
log.Println("Worker stopped")
return
}
processFile(file, destDir, &counter)
processFile(file, destDir, counterFile, &counter)
case <-ctx.Done():
// Получен сигнал завершения
saveCounter(counterFile, counter)
@@ -123,7 +125,7 @@ mainLoop:
log.Println("Shutdown complete")
}
func processFile(filePath, destDir string, counter *int) {
func processFile(filePath, destDir, counterPath string, counter *int) {
// Проверка что это файл
info, err := os.Stat(filePath)
if err != nil {
@@ -137,18 +139,42 @@ func processFile(filePath, destDir string, counter *int) {
// Ожидание завершения записи
time.Sleep(500 * time.Millisecond)
// Копирование
newName := fmt.Sprintf("%03d", *counter)
destPath := filepath.Join(destDir, newName)
if err := os.Rename(filePath, destPath); err != nil {
log.Printf("Moving failed: %v", err)
return
moveAttempt := 0
for {
if moveAttempt > 100 {
log.Printf("Moving failed after %d attempts, see messages", moveAttempt)
break
}
// Обновление счетчика
*counter++
saveCounter(destDir, *counter)
saveCounter(counterPath, *counter)
newName := fmt.Sprintf("%05d", *counter)
destPath := filepath.Join(destDir, newName)
_, err := os.Stat(destPath)
if err == nil {
log.Printf("Moving failed, file already exists: %s", destPath)
moveAttempt++
continue
}
if !errors.Is(err, fs.ErrNotExist) {
log.Printf("Moving failed: %v", err)
moveAttempt++
continue
}
if err := os.Rename(filePath, destPath); err != nil {
log.Printf("Moving failed: %v", err)
moveAttempt++
continue
}
log.Printf("Moved: %s -> %s", filePath, destPath)
break
}
}
func loadCounter(counterPath string) int {