diff --git a/scanpipe/pipes/input.py b/scanpipe/pipes/input.py index 58ec2e5c96..363809adbd 100644 --- a/scanpipe/pipes/input.py +++ b/scanpipe/pipes/input.py @@ -66,6 +66,12 @@ def copy_inputs(input_locations, dest_path): def move_input(input_location, dest_path): """Move the provided ``input_location`` to the ``dest_path``.""" destination = dest_path / Path(input_location).name + i = 2 + while destination.exists(): + input_path = Path(input_location) + destination = dest_path / f"{input_path.stem}_{i}{input_path.suffix}" + i += 1 + return shutil.move(input_location, destination) diff --git a/scanpipe/tests/test_models.py b/scanpipe/tests/test_models.py index 0251e7b729..91964e857a 100644 --- a/scanpipe/tests/test_models.py +++ b/scanpipe/tests/test_models.py @@ -22,6 +22,7 @@ import io import json +import os import shutil import sys import tempfile @@ -411,6 +412,27 @@ def test_scanpipe_project_model_move_input_from(self): self.assertEqual([input_filename], self.project1.input_files) self.assertFalse(Path(input_location).exists()) + def test_move_input_handles_duplicate_filenames(self): + # Create first file + fd1, path1 = tempfile.mkstemp(suffix=".txt") + os.close(fd1) + Path(path1).write_text("one") + + # Create second file with same name in same directory + temp_dir = Path(path1).parent + path2 = temp_dir / Path(path1).name + Path(path2).write_text("two") + + # Move both into project input + dest1 = self.project1.move_input_from(path1) + dest2 = self.project1.move_input_from(path2) + + # Ensure both files exist + self.assertTrue(Path(dest1).exists()) + self.assertTrue(Path(dest2).exists()) + # Ensure filenames are different + self.assertNotEqual(Path(dest1).name, Path(dest2).name) + def test_scanpipe_project_model_get_inputs_with_source(self): self.assertEqual([], self.project1.get_inputs_with_source())