diff --git a/main.go b/main.go index 85688a3..461e7eb 100644 --- a/main.go +++ b/main.go @@ -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 - // Обновление счетчика - *counter++ - saveCounter(destDir, *counter) - log.Printf("Moved: %s -> %s", filePath, destPath) + for { + if moveAttempt > 100 { + log.Printf("Moving failed after %d attempts, see messages", moveAttempt) + break + } + + *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 {