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