diff --git a/scanpipe/pipes/__init__.py b/scanpipe/pipes/__init__.py index 953036ed6c..a27bb2e01c 100644 --- a/scanpipe/pipes/__init__.py +++ b/scanpipe/pipes/__init__.py @@ -46,6 +46,10 @@ logger = logging.getLogger("scanpipe.pipes") +class CodebaseResourcesExistError(Exception): + """The project already has codebase resources.""" + + def make_codebase_resource(project, location, save=True, **extra_fields): """ Create a CodebaseResource instance in the database for the given ``project``. @@ -138,7 +142,15 @@ def collect_and_create_codebase_resources(project, batch_size=5000): The default ``batch_size`` can be overridden, although the benefits of a value greater than 5000 objects are usually not significant. + + Raise a ``CodebaseResourcesExistError`` if the project already has resources. """ + if project.codebaseresources.exists(): + raise CodebaseResourcesExistError( + "Codebase resources already exist for this project. " + "Reset the project before running this pipeline again." + ) + model_class = CodebaseResource objs = yield_resources_from_codebase(project) diff --git a/scanpipe/tests/pipes/test_d2d.py b/scanpipe/tests/pipes/test_d2d.py index 7a527f1e34..5493249349 100644 --- a/scanpipe/tests/pipes/test_d2d.py +++ b/scanpipe/tests/pipes/test_d2d.py @@ -858,6 +858,7 @@ def test_scanpipe_pipes_d2d_map_jvm_to_class_source_file_attribute(self): # The `Tasks.class` is from lombok-1.18.42.jar # Ref: https://github.com/aboutcode-org/scancode.io/issues/1993 copy_input(self.data / "jvm" / "Tasks.class", to_dir) + pipes.collect_and_create_codebase_resources(self.project1) from1 = make_resource_file( self.project1, @@ -865,7 +866,6 @@ def test_scanpipe_pipes_d2d_map_jvm_to_class_source_file_attribute(self): extra_data={"java_package": "lombok.delombok.ant"}, ) - pipes.collect_and_create_codebase_resources(self.project1) to1 = self.project1.codebaseresources.get( path="to/lombok/delombok/ant/Tasks.class" ) diff --git a/scanpipe/tests/pipes/test_pipes.py b/scanpipe/tests/pipes/test_pipes.py index 9d48547b40..f62119ec27 100644 --- a/scanpipe/tests/pipes/test_pipes.py +++ b/scanpipe/tests/pipes/test_pipes.py @@ -642,3 +642,17 @@ def test_scanpipe_pipes_collect_and_create_codebase_resources(self): self.assertEqual("from", from_resource.tag) to_resource = p1.codebaseresources.get(path="to/a.txt") self.assertEqual("to", to_resource.tag) + + def test_scanpipe_pipes_collect_and_create_codebase_resources_existing(self): + p1 = Project.objects.create(name="Analysis") + input_location = self.data / "codebase" / "a.txt" + copy_input(input_location, p1.codebase_path) + pipes.collect_and_create_codebase_resources(p1) + + expected = ( + "Codebase resources already exist for this project. " + "Reset the project before running this pipeline again." + ) + with self.assertRaisesMessage(pipes.CodebaseResourcesExistError, expected): + pipes.collect_and_create_codebase_resources(p1) + self.assertEqual(1, p1.codebaseresources.count())