diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index c820006..933e42c 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -13,7 +13,6 @@ import appdirs from fsspec.spec import AbstractFileSystem from funcy import ( - cached_property, chunks, distinct, retry, @@ -282,6 +281,8 @@ def __init__( self._cache_lock = threading.RLock() self._directory_ids = _DirectoryCache() self._mount_lock = threading.RLock() + self._root_lock = threading.RLock() + self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() self.path = path self.root, self.base = self.split_path(self.path) @@ -401,6 +402,8 @@ def _invalidate_paths(self, *paths): for path in paths: super().invalidate_cache(path) with self._cache_lock: + if "" in subtrees: + self._root_metadata = {} if _in_subtrees(self.base, subtrees): self._directory_ids = _DirectoryCache() else: @@ -413,39 +416,50 @@ def _is_cached_directory(self, item_id): cache = self._directory_ids return item_id == self.root or item_id in cache.by_id - @cached_property + @property def _list_params(self): params = {"corpora": "user"} if self.root == "appDataFolder": params["spaces"] = "appDataFolder" elif self.root != "root": - drive_id = self._gdrive_shared_drive_id(self.root) + try: + drive_id = self._get_root_metadata().get("driveId") + except FileNotFoundError as exc: + raise PermissionError from exc if drive_id: - logger.debug( - f"GDrive remote '{self.path}' is using shared drive id '{drive_id}'." - ) - params["driveId"] = drive_id - params["corpora"] = "drive" + params.update(driveId=drive_id, corpora="drive") return params @_gdrive_retry - def _gdrive_shared_drive_id(self, item_id): - from pydrive2.files import ApiRequestError - - param = {"id": item_id} - # it does not create a file on the remote - item = self.client.CreateFile(param) - # ID of the shared drive the item resides in. - # Only populated for items in shared drives. - try: - item.FetchMetadata("driveId") - except ApiRequestError as exc: - error_code = exc.error.get("code", 0) - if error_code == 404: - raise PermissionError from exc - raise - - return item.get("driveId", None) + def _get_root_metadata(self, *, fresh=False): + cached = self._root_metadata + if cached and not fresh: + return cached + with self._root_lock: + cached = self._root_metadata + if cached and not fresh: + return cached + item = self.client.CreateFile({"id": self.root}) + try: + with _translate_not_found(self.root): + item.FetchMetadata("driveId,mimeType,trashed") + except FileNotFoundError: + with self._cache_lock: + if self._root_metadata is cached: + self._root_metadata = {} + raise + with self._cache_lock: + if self._root_metadata is cached: + # Trash status is only valid for the request that observed it. + self._root_metadata = ( + {} + if item.get("trashed") + else { + "driveId": item.get("driveId"), + "mimeType": item.get("mimeType"), + } + ) + return item.metadata def _gdrive_list(self, query): param = { @@ -564,7 +578,9 @@ def _gdrive_create_dir(self, parent_id, name): item.Upload() return item - def _get_or_create_child(self, cache, parents, path, name, mount=None): + def _get_or_create_child( + self, cache, parents, path, name, mount=None, *, exist_ok=True + ): parent_id = min(parents) key = (parent_id, name) with self._cache_lock: @@ -573,18 +589,67 @@ def _get_or_create_child(self, cache, parents, path, name, mount=None): lock = self._creation_locks[key] = threading.RLock() with lock: with self._cache_lock: - if cached := cache.by_path.get(path): - return _PathMatch(cached.copy()), cache - # An invalidation can give two writers different caches. Check - # Drive under the same name lock as the create. - match, cache = self._match_child(cache, parents, path, name, mount) + folders = cache.by_path.get(path, []).copy() + if folders: + match = _PathMatch(folders) + else: + # An invalidation can give two writers different caches. Check + # Drive under the same name lock as the create. + match, cache = self._match_child( + cache, parents, path, name, mount + ) if match.folders or match.files: + if not exist_ok: + raise FileExistsError(posixpath.join(self.root, path)) return match, cache item = self._gdrive_create_dir(parent_id, name) return _PathMatch([item["id"]]), self._cache_path_id( cache, path, item["id"] ) + def mkdir(self, path, create_parents=True, **kwargs): + self._mkdir(path, create_parents, exist_ok=False) + + def makedirs(self, path, exist_ok=False): + self._mkdir(path, create_parents=True, exist_ok=exist_ok) + + def _mkdir(self, path, create_parents, exist_ok): + root, base = self._split_mounted_path(path) + if not base: + if root not in {"root", "appDataFolder"}: + metadata = self._get_root_metadata(fresh=True) + if metadata.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path + ) + if metadata.get("mimeType") != FOLDER_MIME_TYPE: + raise FileExistsError(path) + if not exist_ok: + raise FileExistsError(path) + return + + cache, mount = self._directory_cache() + with self._cache_lock: + if base in cache.by_path: + if not exist_ok: + raise FileExistsError(path) + return + parent, name = posixpath.split(base) + if create_parents: + folders, cache = self._ensure_dirs(parent, cache, mount) + else: + prefix, match, cache = self._resolve_prefix(parent, cache, mount) + if not match.folders: + raise NotADirectoryError(posixpath.join(root, prefix)) + if prefix != parent: + raise FileNotFoundError(posixpath.join(root, parent)) + folders = match.folders + leaf, _ = self._get_or_create_child( + cache, folders, base, name, mount, exist_ok=exist_ok + ) + if not leaf.folders: + raise FileExistsError(path) + def exists(self, path): root, base = self._split_mounted_path(path) try: diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 90c41b5..4ae1a60 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -131,6 +131,14 @@ def test_move(fs, remote_dir): assert initial_info == secondary_info +def test_create_empty_directory(fs, fs_factory, remote_dir): + path = remote_dir + "/empty/sub" + fs.makedirs(path) + other, _ = fs_factory() + assert other.info(path)["type"] == "directory" + assert other.ls(path) == [] + + def test_copy_file_to_new_directory(fs, remote_dir): source = remote_dir + "/source" target = remote_dir + "/nested/copy" @@ -169,8 +177,7 @@ def test_rm(fs, remote_dir): def test_ls(fs, remote_dir): - _, base = fs.split_path(remote_dir + "/dir/") - fs._path_to_item_ids(base, create=True) + fs.makedirs(remote_dir + "/dir") assert fs.ls(remote_dir + "/dir/") == [] files = set() @@ -279,7 +286,7 @@ def test_find(fs, fs_factory, remote_dir): dirnames = {posixpath.dirname(file) for file in files} for dirname in dirnames: - fs.mkdir(dirname) + fs.makedirs(dirname, exist_ok=True) for file in files: fs.touch(file) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 6ef1c0b..1c20778 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -515,15 +515,17 @@ def test_find_uses_current_parent_links_after_a_rename( def test_empty_root_marker_refreshes_a_folder_id_mount(mock_drive): - drive, _ = mock_drive( + drive, requests = mock_drive( response({"driveId": "shared"}), listing(folder("dir", "old")), + response({"driveId": "new-drive"}), listing(), ) fs = filesystem(drive, "FolderID") assert fs.exists("FolderID/dir") fs.invalidate_cache("") assert not fs.exists("FolderID/dir") + assert query(requests[-1])["driveId"] == ["new-drive"] @pytest.mark.parametrize("operation", ["rename", "trash", "delete"]) @@ -823,3 +825,206 @@ def test_large_write_after_close_does_not_open_a_tempfile(mock_drive, mocker): with pytest.raises(ValueError, match="closed"): writer.write(b"too large") backing_file.assert_not_called() + + +def test_makedirs_creates_empty_drive_folders(mock_drive): + drive, requests = mock_drive( + response({"driveId": "shared"}), + response({"files": []}), + response({"id": "A"}), + response({"files": []}), + response({"id": "B"}), + ) + fs = filesystem(drive, "shared") + fs.makedirs("gdrive://shared/parent/leaf") + assert [r[1] for r in requests] == ["GET", "GET", "POST", "GET", "POST"] + cold_requests = len(requests) + assert fs.exists("shared/parent/leaf") + fs.makedirs("shared/parent/leaf", exist_ok=True) + with pytest.raises(FileExistsError): + fs.makedirs("shared/parent/leaf") + with pytest.raises(FileExistsError): + fs.mkdir("shared/parent/leaf") + assert len(requests) == cold_requests + assert [json.loads(req[2]) for req in requests if req[1] == "POST"] == [ + { + "name": "parent", + "parents": ["shared"], + "mimeType": FOLDER_MIME_TYPE, + }, + {"name": "leaf", "parents": ["A"], "mimeType": FOLDER_MIME_TYPE}, + ] + + +def test_mkdir_without_missing_parents(mock_drive): + drive, requests = mock_drive(response({"files": []})) + with pytest.raises(FileNotFoundError): + filesystem(drive).mkdir("root/missing/leaf", create_parents=False) + assert [req[1] for req in requests] == ["GET"] + + +def test_mkdir_in_existing_parent(mock_drive): + drive, requests = mock_drive( + listing(folder("parent", "P")), listing(), response({"id": "leaf"}) + ) + fs = filesystem(drive) + assert fs.exists("root/parent") + before = len(requests) + fs.mkdir("root/parent/leaf", create_parents=False) + lookup, create = requests[before:] + assert "'P' in parents" in query(lookup)["q"][0] + assert create[1] == "POST" and json.loads(create[2])["parents"] == ["P"] + before = len(requests) + fs.makedirs("root/parent/leaf", exist_ok=True) + assert len(requests) == before + + +@pytest.mark.parametrize( + "path,expected", + [("root/blob", FileExistsError), ("root/blob/sub", NotADirectoryError)], +) +def test_makedirs_rejects_file(mock_drive, path, expected): + drive, requests = mock_drive( + response( + {"files": [{"name": "blob", "id": "F", "mimeType": "text/plain"}]} + ) + ) + with pytest.raises(expected): + filesystem(drive).makedirs(path, exist_ok=True) + assert [req[1] for req in requests] == ["GET"] + + +def test_explicit_bare_folder_check_refreshes_trash_status(mock_drive): + root = {"driveId": "shared", "mimeType": FOLDER_MIME_TYPE} + drive, requests = mock_drive( + response(root), listing(), response(dict(root, trashed=True)) + ) + fs = filesystem(drive, "FolderID") + fs.makedirs("FolderID", exist_ok=True) + assert fs.ls("FolderID") == [] + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID", exist_ok=True) + first, children, fresh = requests + assert first[:2] == fresh[:2] + assert query(children)["driveId"] == ["shared"] + + +@pytest.mark.parametrize("operation", ["upload", "copy"]) +def test_file_blocking_write_parent_is_not_a_directory(mock_drive, operation): + from io import BytesIO + + file = {"id": "F", "name": "block", "mimeType": "text/plain"} + source = [listing(dict(file, name="src"))] if operation == "copy" else [] + drive, requests = mock_drive(*source, listing(file)) + fs = filesystem(drive) + with pytest.raises(NotADirectoryError, match="block"): + if operation == "copy": + fs.cp_file("root/src", "root/block/out") + else: + fs.upload_fobj(BytesIO(b"data"), "root/block/out") + assert [r[1] for r in requests] == ["GET"] * (1 + len(source)) + + +def test_invalidating_root_during_stat_discards_its_result(mock_drive): + def invalidate(request): + fs.invalidate_cache("FolderID") + + root = {"mimeType": FOLDER_MIME_TYPE} + drive, _ = mock_drive( + response(root), + response(dict(root, trashed=True)), + on_request=invalidate, + ) + fs = filesystem(drive, "FolderID") + fs.makedirs("FolderID", exist_ok=True) + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID", exist_ok=True) + + +def test_makedirs_after_trashing_and_restoring_the_mount(mock_drive): + root = {"mimeType": FOLDER_MIME_TYPE} + drive, _ = mock_drive( + response(root), + response({"trashed": True}), + response(dict(root, trashed=True)), + response(root), + ) + fs = filesystem(drive, "FolderID", trash_only=True) + fs.makedirs("FolderID", exist_ok=True) + fs.rm_file("FolderID") + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID", exist_ok=True) + fs.makedirs("FolderID", exist_ok=True) + + +@pytest.mark.parametrize( + "failure, error", + [ + (response({"mimeType": "text/plain"}), FileExistsError), + (error_response(404, "notFound"), FileNotFoundError), + ], +) +def test_makedirs_rejects_invalid_mount_id(mock_drive, failure, error): + drive, _ = mock_drive(failure) + with pytest.raises(error): + filesystem(drive, "FolderID").makedirs("FolderID", exist_ok=True) + + +def test_makedirs_bare_root_is_independent_of_named_mount(mock_drive): + drive, requests = mock_drive(response({"mimeType": FOLDER_MIME_TYPE})) + filesystem(drive, "FolderID/missing").makedirs("FolderID", exist_ok=True) + (stat,) = requests + assert "q" not in query(stat) + + +def test_makedirs_starts_at_cached_mount(mock_drive): + drive, requests = mock_drive( + response({"driveId": "shared"}), + listing(folder("a", "a")), + listing(folder("b", "b")), + listing(), + response({"id": "new"}), + ) + fs = filesystem(drive, "FolderID/a/b") + fs.makedirs("FolderID/a/b/new") + fs.makedirs("FolderID/a/b/new", exist_ok=True) + assert [query(req)["q"][0] for req in requests if "q" in query(req)] == [ + "('FolderID' in parents) and trashed=false and name='a'", + "('a' in parents) and trashed=false and name='b'", + "('b' in parents) and trashed=false and name='new'", + ] + + +def test_makedirs_uses_the_matching_folder_during_invalidation(mock_drive): + def invalidate(request): + if "name='sub'" in query(request).get("q", [""])[0]: + fs.invalidate_cache("root/sub") + + drive, requests = mock_drive( + listing( + {"name": "sub", "id": "file", "mimeType": "text/plain"}, + folder("Sub", "wrong-case"), + folder("sub", "folder"), + ), + listing(), + response({"id": "leaf"}), + listing(), + on_request=invalidate, + ) + fs = filesystem(drive) + fs.makedirs("root/sub/leaf") + (create,) = [r for r in requests if r[1] == "POST"] + assert json.loads(create[2])["parents"] == ["folder"] + assert not fs.exists("root/sub/leaf") + + +def test_makedirs_rejects_file_at_nested_mount(mock_drive): + blob = response( + {"files": [{"name": "blob", "id": "F", "mimeType": "text/plain"}]} + ) + drive, requests = mock_drive(blob) + fs = filesystem(drive, "root/blob") + with pytest.raises(NotADirectoryError): + fs.makedirs("root/blob/child") + (lookup,) = requests + assert "name='blob'" in query(lookup)["q"][0]