diff --git a/src/scancode/cli.py b/src/scancode/cli.py index 1376c6cfee..faa3375c5c 100644 --- a/src/scancode/cli.py +++ b/src/scancode/cli.py @@ -1070,6 +1070,27 @@ def echo_func(*_args, **_kwargs): results = get_results(codebase, as_list=True, **requested_options) elif return_codebase: results = codebase + # Strip root from paths when strip_root is enabled. + # See https://github.com/aboutcode-org/scancode-toolkit/issues/2985 + if strip_root and not codebase.has_single_resource: + from commoncode.resource import strip_first_path_segment + new_resources_by_path = {} + for old_path, resource in list(codebase.resources_by_path.items()): + stripped_path = strip_first_path_segment(old_path) + resource.path = stripped_path + new_resources_by_path[stripped_path] = resource + codebase.resources_by_path = new_resources_by_path + + # Fix parent() to handle empty parent_path for direct children of root. + # commoncode's parent() uses `return path and get_resource(path)` which + # returns '' (empty string) when path is '', breaking tree traversal. + original_parent = codebase.resource_class.parent + def patched_parent(self, codebase_arg): + parent_path = self.parent_path() + if parent_path == '': + return codebase_arg.root + return original_parent(self, codebase_arg) + codebase.resource_class.parent = patched_parent finally: # remove temporary files