Navigate current directory tree, returning node matching path or creating a new one, if missing. - path: path of the node to search - create_if_missing: create nodes if not exist. Defaults to False. - leaf_cls: expected type of leaf node. Defaults to None.
(self, path, create_if_missing=False, leaf_cls=None, check_exists=True)
| 91 | self._initialize_times() |
| 92 | |
| 93 | def resolve(self, path, create_if_missing=False, leaf_cls=None, check_exists=True): |
| 94 | """ |
| 95 | Navigate current directory tree, returning node matching path or |
| 96 | creating a new one, if missing. |
| 97 | - path: path of the node to search |
| 98 | - create_if_missing: create nodes if not exist. Defaults to False. |
| 99 | - leaf_cls: expected type of leaf node. Defaults to None. |
| 100 | - check_exists: if True and the leaf node does not exist, raise a |
| 101 | FileNotFoundError. Defaults to True. |
| 102 | """ |
| 103 | path_segments = list(pathlib.Path(path).parts) |
| 104 | current_node = self |
| 105 | |
| 106 | while path_segments: |
| 107 | path_segment = path_segments.pop(0) |
| 108 | # If current node is a file node and there are unprocessed |
| 109 | # segments, raise an error. |
| 110 | if isinstance(current_node, InMemoryFileNode): |
| 111 | path_segments = os.path.split(path) |
| 112 | current_path = "/".join( |
| 113 | path_segments[: path_segments.index(path_segment)] |
| 114 | ) |
| 115 | raise NotADirectoryError( |
| 116 | errno.ENOTDIR, os.strerror(errno.ENOTDIR), current_path |
| 117 | ) |
| 118 | current_node = current_node._resolve_child( |
| 119 | path_segment, |
| 120 | create_if_missing, |
| 121 | leaf_cls if len(path_segments) == 0 else InMemoryDirNode, |
| 122 | ) |
| 123 | if current_node is None: |
| 124 | break |
| 125 | |
| 126 | if current_node is None and check_exists: |
| 127 | raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path) |
| 128 | |
| 129 | # If a leaf_cls is not None, check if leaf node is of right type. |
| 130 | if leaf_cls and not isinstance(current_node, leaf_cls): |
| 131 | error_cls, error_code = ( |
| 132 | (NotADirectoryError, errno.ENOTDIR) |
| 133 | if leaf_cls is InMemoryDirNode |
| 134 | else (IsADirectoryError, errno.EISDIR) |
| 135 | ) |
| 136 | raise error_cls(error_code, os.strerror(error_code), path) |
| 137 | |
| 138 | return current_node |
| 139 | |
| 140 | def _resolve_child(self, path_segment, create_if_missing, child_cls): |
| 141 | if create_if_missing: |
no test coverage detected