Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/fsspec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ folder that the account can access:
fs = fsspec.filesystem("gdrive", path="FOLDER_ID", **options)
names = fs.ls("FOLDER_ID")

Use ``fs.rmdir("root/empty")`` to remove an empty folder. A nonempty
folder raises ``OSError`` with ``errno.ENOTEMPTY``. If the name is
ambiguous, open a filesystem at the intended folder ID and remove it by
ID. In trash mode, already trashed children are ignored. Permanent removal
also checks for trashed children. Drive checks emptiness and performs the
removal in separate requests, so coordinate concurrent writers when using
this operation.

A filesystem instance is scoped to one root. Use URLs under the same folder
ID or root alias in a single ``fsspec.open_files`` call. Sibling URLs reuse
the filesystem and its directory ID cache. Reads by file ID skip name
Expand Down
70 changes: 69 additions & 1 deletion pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -885,21 +885,89 @@ def _gdrive_open_file(self, item_id, block_size=None):
)
return IterStream(iter(fd))

def rmdir(self, path):
"""Remove one empty Drive folder, honoring the trash_only setting."""
root, base = self._split_mounted_path(path)
if base:
# Name duplicates and external renames must be checked before
# deleting. A cached folder ID alone cannot establish uniqueness.
match = self._resolve_path(base, _DirectoryCache())
if not match.ids:
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
if not match.folders:
raise NotADirectoryError(
errno.ENOTDIR, os.strerror(errno.ENOTDIR), path
)
if len(match.ids) != 1:
raise FileExistsError(
errno.EEXIST,
"Ambiguous Drive path; use the folder ID",
path,
)
item_id = match.folders[0]
else:
if root in {"root", "appDataFolder"}:
raise PermissionError(
errno.EPERM, "Cannot remove a Drive root", path
)
item = self._get_root_metadata(fresh=True)
if item.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
if item.get("mimeType") != FOLDER_MIME_TYPE:
raise NotADirectoryError(
errno.ENOTDIR, os.strerror(errno.ENOTDIR), path
)
if item.get("driveId") == root:
raise PermissionError(
errno.EPERM, "Cannot remove a Drive root", path
)
item_id = root

with _translate_not_found(path):
self._gdrive_delete_file(item_id, empty_directory=path)
self.invalidate_cache(path)

def _check_empty_folder(self, item_id, path):
query = f"{_quote_query_value(item_id)} in parents"
if self._trash_only:
query += " and trashed=false"
pages = self.client.ListFile(
dict(
self._list_params,
q=query,
pageSize=1,
fields="nextPageToken,incompleteSearch,files(id)",
)
)
for page in pages:
if page:
raise OSError(
errno.ENOTEMPTY, os.strerror(errno.ENOTEMPTY), path
)
if pages.metadata.get("incompleteSearch"):
raise OSError(errno.EIO, "Incomplete Drive listing", path)

def rm_file(self, path):
item_id = self._get_item_id(path)
self._gdrive_delete_file(item_id)
if self._is_cached_directory(item_id):
self.invalidate_cache(path)

@_gdrive_retry
def _gdrive_delete_file(self, item_id):
def _gdrive_delete_file(self, item_id, *, empty_directory=None):
from pydrive2.files import ApiRequestError

param = {"id": item_id}
# it does not create a file on the remote
item = self.client.CreateFile(param)

try:
if empty_directory is not None:
self._check_empty_folder(item_id, empty_directory)
item.Trash() if self._trash_only else item.Delete()
except ApiRequestError as exc:
http_error_code = exc.error.get("code", 0)
Expand Down
13 changes: 13 additions & 0 deletions pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import errno
import os
import posixpath
import secrets
Expand Down Expand Up @@ -162,6 +163,18 @@ def test_invalidating_parent_reloads_replaced_mount(fs, remote_dir):
assert reader.ls(mount) == [mount + "/after"]


def test_rmdir_only_removes_empty_folders(fs, fs_factory, remote_dir):
path = remote_dir + "/empty"
fs.makedirs(path)
with pytest.raises(OSError) as error:
fs.rmdir(remote_dir)
assert error.value.errno == errno.ENOTEMPTY
fs.rmdir(path)
reader, _ = fs_factory()
assert reader.exists(remote_dir)
assert not reader.exists(path)


def test_rm(fs, remote_dir):
fs.touch(remote_dir + "/a.txt")
fs.rm(remote_dir + "/a.txt")
Expand Down
95 changes: 95 additions & 0 deletions pydrive2/test/test_fs_unit.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import errno
import json
import re
import tempfile
Expand Down Expand Up @@ -363,6 +364,100 @@ def copy(fs, http, name):
pending.result(timeout=5)


@pytest.mark.parametrize("trash_only", [True, False])
def test_rmdir_removes_only_a_freshly_resolved_empty_folder(
mock_drive, trash_only
):
drive, requests = mock_drive(
listing(folder("dir", "old")),
listing(folder("dir", "current")),
listing(),
response({}),
listing(),
)
fs = filesystem(drive, trash_only=trash_only)
assert fs.exists("root/dir")
fs.rmdir("root/dir")
assert not fs.exists("root/dir")
_, resolve, children, remove, _ = requests
assert "name='dir'" in query(resolve)["q"][0]
assert query(children)["pageSize"] == ["1"]
q = query(children)["q"][0]
assert "'current' in parents" in q and ("trashed=false" in q) == trash_only
assert urlsplit(remove[0]).path.endswith("/files/current")
assert remove[1] == ("PATCH" if trash_only else "DELETE")


@pytest.mark.parametrize(
"items,error",
[
([], FileNotFoundError),
(
[{"name": "dir", "id": "F", "mimeType": "text/plain"}],
NotADirectoryError,
),
([folder("dir", "A"), folder("dir", "B")], FileExistsError),
(
[
folder("dir", "A"),
{"name": "dir", "id": "F", "mimeType": "text/plain"},
],
FileExistsError,
),
],
)
def test_rmdir_refuses_missing_files_and_ambiguous_names(
mock_drive, items, error
):
drive, requests = mock_drive(listing(*items))
with pytest.raises(error):
filesystem(drive).rmdir("root/dir")
assert [req[1] for req in requests] == ["GET"]


@pytest.mark.parametrize("root", ["root", "appDataFolder"])
def test_rmdir_protects_root_aliases(mock_drive, root):
drive, requests = mock_drive()
with pytest.raises(PermissionError):
filesystem(drive, root).rmdir(root)
assert not requests


@pytest.mark.parametrize(
"page,code",
[
(listing({"id": "child"}), errno.ENOTEMPTY),
(response({"files": [], "incompleteSearch": True}), errno.EIO),
],
)
def test_rmdir_checks_later_pages_before_removing_by_id(
mock_drive, page, code
):
drive, requests = mock_drive(
response({"mimeType": FOLDER_MIME_TYPE}),
response({"files": [], "nextPageToken": "next"}),
page,
)
with pytest.raises(OSError) as error:
filesystem(drive, "FolderID").rmdir("FolderID")
assert error.value.errno == code
assert [r[1] for r in requests] == ["GET"] * 3
assert query(requests[-1])["pageToken"] == ["next"]


def test_rmdir_checks_emptiness_again_after_transient_failure(mock_drive):
drive, requests = mock_drive(
listing(folder("dir", "D")),
listing(),
error_response(503, "backendError"),
listing({"id": "new-child"}),
)
with pytest.raises(OSError) as error:
filesystem(drive, trash_only=False).rmdir("root/dir")
assert error.value.errno == errno.ENOTEMPTY
assert [r[1] for r in requests] == ["GET", "GET", "DELETE", "GET"]


def test_concurrent_copies_share_a_folder_after_unrelated_invalidation(
mock_drive,
):
Expand Down
Loading