Skip to content

Commit a3be1fb

Browse files
feat: Adding ancestors method to the CodebaseResource Model with testing
Signed-off-by: AbanoubAziz <[email protected]>
1 parent 16ed5c4 commit a3be1fb

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

scanpipe/models.py

+19
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import shutil
2828
import uuid
2929
from collections import Counter
30+
from collections import deque
3031
from collections import defaultdict
3132
from contextlib import suppress
3233
from itertools import groupby
@@ -2875,6 +2876,24 @@ def descendants(self):
28752876
"""
28762877
return self.project.codebaseresources.filter(path__startswith=f"{self.path}/")
28772878

2879+
def ancestors(self):
2880+
"""
2881+
Return a QuerySet of ancestors CodebaseResource objects using a database query
2882+
on the current CodebaseResource `path`. The current CodebaseResource is not included
2883+
"""
2884+
2885+
if not self.has_parent():
2886+
return []
2887+
anscesotrs = deque()
2888+
current = self.parent()
2889+
anscesotrs_appendleft = anscesotrs.appendleft
2890+
2891+
while current:
2892+
anscesotrs_appendleft(current)
2893+
current = current.parent()
2894+
2895+
return list(anscesotrs)
2896+
28782897
def children(self, codebase=None):
28792898
"""
28802899
Return a QuerySet of direct children CodebaseResource objects using a

scanpipe/tests/test_models.py

+12
Original file line numberDiff line numberDiff line change
@@ -1905,6 +1905,18 @@ def test_scanpipe_codebase_resource_descendants(self):
19051905
"asgiref-3.3.0-py3-none-any.whl-extract/asgiref/wsgi.py",
19061906
]
19071907
self.assertEqual(expected, sorted([resource.path for resource in descendants]))
1908+
1909+
def test_scanpipe_codebase_resource_ancestors(self):
1910+
path = "asgiref-3.3.0-py3-none-any.whl-extract/asgiref/__init__.py"
1911+
resource = self.project_asgiref.codebaseresources.get(path=path)
1912+
ancestors = list(resource.ancestors())
1913+
self.assertEqual(2, len(ancestors))
1914+
self.assertNotIn(resource.path, ancestors)
1915+
expected = [
1916+
"asgiref-3.3.0-py3-none-any.whl-extract",
1917+
"asgiref-3.3.0-py3-none-any.whl-extract/asgiref",
1918+
]
1919+
self.assertEqual(expected, [resource.path for resource in ancestors])
19081920

19091921
def test_scanpipe_codebase_resource_children(self):
19101922
path = "asgiref-3.3.0-py3-none-any.whl-extract"

0 commit comments

Comments
 (0)