def _update_sizes(self, path, size): """ Updates sizes of all entities in the path by size """ path_list = path_parse(path) self._recurse_sizes(path_list, self._root, size)
def path(self, new_path): # cleanup leading/trailing \'s new_path = path_parse(new_path) path_name = new_path[-1] if self.name != path_name: raise PathNotFound('Name in path does not match file name') else: self._path = '\\'.join(new_path)
def test_path_parse(): """ Test the path parser, which should remove leading/trailing \s and return a list of the path's entities """ path = '\\A\\stuff\\list\\' parsed_path = path_parse(path) expected_results = ['A', 'stuff', 'list'] assert parsed_path == expected_results
def _get_entity_at_path(self, path): """ Given a path string, returns the entity at the path """ current_entity = self._root path_list = path_parse(path) for entity in path_list: if entity in current_entity.get_names(): current_entity = current_entity.get_child(entity) else: raise PathNotFound('Invalid target path') return current_entity
def delete(self, path): """ Deletes an existing entry :param path path to the entity to be deleted """ # validate target path and find the target parent entity target_path = path_parse(path) base_path = '\\'.join(target_path[:-1]) name = target_path[-1] try: parent = self._get_entity_at_path(base_path) except Exception: raise # decrement the sizes of ancestors self._update_sizes(parent.path, (parent.get_child(name).size * -1)) # delete child parent.delete_child(name)
def move(self, source_path, destination_path): """ Change the parent of an entity :param source_path the path to the entity to be moved :param destination_path the parent to move the entity under """ # find source parent and child target_path = path_parse(source_path) source_parent_path = '\\'.join(target_path[:-1]) source_child = target_path[-1] try: source_parent = self._get_entity_at_path(source_parent_path) except Exception: raise # find destination entity try: destination_entity = self._get_entity_at_path(destination_path) except Exception: raise # if the destination does not already contain an entity of the source's name, move it. if source_child not in destination_entity.get_names(): source_child_entity = source_parent.get_child(source_child) self._update_sizes(source_parent.path, (source_child_entity.size * -1)) # dec sizes of sources ancestors self._update_sizes(destination_entity.path, source_child_entity.size) # inc sizes of destinations ancestors # add reference to child at destination and update paths destination_entity.add_child(source_child_entity) source_child_entity.path = destination_entity.path + '\\' + source_child_entity.name # delete reference at source and update paths source_parent.delete_child(source_child_entity.name) else: raise PathAlreadyExists('Destination already has an entity with the source\'s name')