|
13 | 13 | __all__ = ['ResourcePath'] |
14 | 14 |
|
15 | 15 |
|
16 | | -def _abs_parts(path: Path) -> Tuple[str, ...]: |
17 | | - return (path.drive, path.root) + path.parts[1:] |
18 | | - |
19 | | - |
20 | | -def _file_relative_to(path: Path, base: Path) -> Optional[Tuple[str, ...]]: |
21 | | - """ |
22 | | - Like Path.relative_to, except: |
23 | | -
|
24 | | - - Both paths must be relative. |
25 | | - - `base` must be a single Path object. |
26 | | - - The error message is blank. |
27 | | - - Only a tuple of parts is returned. |
28 | | -
|
29 | | - Surprisingly, this is much, much faster. |
30 | | - """ |
31 | | - child_parts = _abs_parts(path) |
32 | | - base_parts = _abs_parts(base) |
33 | | - |
34 | | - n = len(base_parts) |
35 | | - cf = path._flavour.casefold_parts # type: ignore |
36 | | - |
37 | | - if cf(child_parts[:n]) != cf(base_parts): |
38 | | - return None |
39 | | - |
40 | | - return child_parts[n:] |
41 | | - |
42 | | - |
43 | 16 | class ResourceRoot(metaclass=ABCMeta): |
44 | 17 | """ |
45 | 18 | Represents a directory containing packages. |
@@ -76,13 +49,15 @@ def file_to_resource_path(self, file_path: Union[Path, str]) -> Optional['Resour |
76 | 49 | if not file_path.is_absolute(): |
77 | 50 | raise ValueError("Cannot convert a relative file path to a resource path.") |
78 | 51 |
|
79 | | - parts = _file_relative_to(file_path, self.file_root) |
80 | | - if parts is None: |
| 52 | + try: |
| 53 | + relpath = file_path.relative_to(self.file_root) |
| 54 | + except ValueError: |
81 | 55 | return None |
82 | | - elif parts == (): |
| 56 | + |
| 57 | + if not relpath.parts: |
83 | 58 | return self.resource_root |
84 | | - else: |
85 | | - return self._package_resource_path(*parts) |
| 59 | + |
| 60 | + return self._package_resource_path(*relpath.parts) |
86 | 61 |
|
87 | 62 | @abstractmethod |
88 | 63 | def _package_file_path( |
|
0 commit comments