Skip to content

Commit dc061bf

Browse files
committed
Set a root path if one is not present #23
Signed-off-by: Jono Yang <jyang@nexb.com>
1 parent 3b794f1 commit dc061bf

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

src/commoncode/resource.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import posixpath
1313
import traceback
1414
import sys
15+
from pathlib import Path
1516

1617
from collections import deque
1718
from functools import partial
@@ -1530,7 +1531,7 @@ def _get_or_create_parent(self, path, parent_by_path):
15301531
Note: the root path and root Resource must already be in
15311532
`parent_by_path` or else this function does not work.
15321533
"""
1533-
parent_path = parent_directory(path).rstrip('/').rstrip('\\').lstrip("/")
1534+
parent_path = parent_directory(path).rstrip('/').rstrip('\\').lstrip('/')
15341535
existing_parent = parent_by_path.get(parent_path)
15351536
if existing_parent:
15361537
return existing_parent
@@ -1548,6 +1549,13 @@ def _get_or_create_parent(self, path, parent_by_path):
15481549
parent_by_path[parent_path] = parent_resource
15491550
return parent_resource
15501551

1552+
def _set_new_root_directory(self, resources_data, new_root_directory_path):
1553+
for resource_data in resources_data:
1554+
resource_path = Path(resource_data['path'])
1555+
new_resource_path = Path(new_root_directory_path)
1556+
new_resource_path = new_resource_path.joinpath(resource_path)
1557+
resource_data['path'] = str(new_resource_path)
1558+
15511559
def _populate(self, scan_data):
15521560
"""
15531561
Populate this codebase with Resource objects.
@@ -1642,6 +1650,21 @@ def _populate(self, scan_data):
16421650
sample_resource_path = sample_resource_data['path']
16431651
sample_resource_path = sample_resource_path.strip('/')
16441652
root_path = sample_resource_path.split('/')[0]
1653+
1654+
# Check to see if the Resources from the scan we received has a common root directory.
1655+
for resource_data in resources_data:
1656+
resource_path = resource_data.get('path')
1657+
resource_path = resource_path.strip('/')
1658+
resource_root_path = resource_path.split('/')[0]
1659+
# If not, set a common root directory for all Resources.
1660+
if resource_root_path != root_path:
1661+
self._set_new_root_directory(
1662+
resources_data=resources_data,
1663+
new_root_directory_path='virtual_root'
1664+
)
1665+
root_path = 'virtual_root'
1666+
break
1667+
16451668
root_name = root_path
16461669
root_is_file = False
16471670
root_data = self._create_empty_resource_data()

0 commit comments

Comments
 (0)