Skip to content
Draft
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
13 changes: 13 additions & 0 deletions docs/fsspec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,19 @@ the granted scopes alongside the token. Drive checks emptiness and performs the
removal in separate requests, so coordinate concurrent writers when using
this operation.

``fs.rm(path)`` and ``fs.rm_file(path)`` remove a folder the same way: only
Comment thread
shcheklein marked this conversation as resolved.
Resolved
when it is empty. ``fs.rm(path, recursive=True)`` removes a folder and
everything in it with one request, moving it to the trash or deleting it
for good as ``trash_only`` says. It first lists the folder's contents and
raises ``PermissionError``, removing nothing, if this account cannot remove
some of them, such as files that other people own. With
``trash_only=False`` the listing includes files already in the trash,
which the removal deletes too. Like ``rmdir``, it needs credentials that
can list everything in the folder, and it raises ``FileExistsError`` for a
path that two folders share. Drive checks and removes in separate
requests, so coordinate concurrent writers here too. A Drive root cannot
be removed.

One root per filesystem
-----------------------

Expand Down
177 changes: 151 additions & 26 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,13 @@ def _quote_query_value(value):
return f"'{escaped}'"


def _ancestors(path):
path = path.rstrip("/")
while "/" in path:
path = path.rsplit("/", 1)[0]
yield path


def _batches(items, size):
iterator = iter(items)
while batch := list(islice(iterator, size)):
Expand Down Expand Up @@ -760,11 +767,17 @@ def _get_root_metadata(
}
return item.metadata

def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS):
def _query_children(
self, parents, names=(), *, fields=_LIST_FIELDS, trashed=False
):
parent_query = " or ".join(
f"{_quote_query_value(p)} in parents" for p in parents
)
query = f"({parent_query}) and trashed=false"
query = (
f"({parent_query})"
if trashed
else f"({parent_query}) and trashed=false"
)
if names:
terms = " or ".join(f"name={_quote_query_value(n)}" for n in names)
query += f" and {terms}" if len(names) == 1 else f" and ({terms})"
Expand Down Expand Up @@ -871,10 +884,14 @@ def _get_item_id(self, path, create=False):
match, _ = self._lookup_path(base)
return _select_item_id(path, match.ids)

def _lookup_item(self, path):
def _lookup_item(self, path, *, refuse_shared_folder_name=False):
"""Return the ID at a path and whether it is a folder."""
_, base = self._split_mounted_path(path)
match, _ = self._lookup_path(base)
if refuse_shared_folder_name and match.folders and len(match.ids) > 1:
raise FileExistsError(
errno.EEXIST, "Ambiguous Drive path; use the folder ID", path
)
item_id = _select_item_id(path, match.ids)
if base or self.root in _ROOT_ALIASES:
return item_id, item_id in match.folders
Expand Down Expand Up @@ -1428,11 +1445,7 @@ def rmdir(self, path):
)
item_id = match.folders[0]
else:
if root in _ROOT_ALIASES:
raise PermissionError(
errno.EPERM, "Cannot remove a Drive root", path
)
item = self._get_root_metadata(fresh=True)
item = self._refuse_drive_root(path, fresh=True)
if item.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
Expand All @@ -1441,19 +1454,9 @@ def rmdir(self, path):
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

try:
with _translate_not_found(path):
self._gdrive_delete_file(item_id, empty_directory=path)
except FileNotFoundError:
self._invalidate_folder(item_id, path, known_folder=True)
raise
self._invalidate_folder(item_id, path, known_folder=True)
self._remove(item_id, path, is_folder=True, empty_directory=path)

def _check_empty_folder(self, item_id, path):
query = f"{_quote_query_value(item_id)} in parents"
Expand All @@ -1476,7 +1479,9 @@ def _check_empty_folder(self, item_id, path):
)
if pages.metadata.get("incompleteSearch"):
raise OSError(errno.EIO, "Incomplete Drive listing", path)
self._require_scopes_that_list_everything(path)

def _require_scopes_that_list_everything(self, path):
# drive.file can return an empty, complete page while hiding children.
credentials = self.client.auth.credentials
if isinstance(credentials, service_account.Credentials):
Expand All @@ -1485,7 +1490,7 @@ def _check_empty_folder(self, item_id, path):
scopes = getattr(credentials, "granted_scopes", None)
required = (
_APP_DATA_SCOPES
if params.get("spaces") == "appDataFolder"
if self._list_params.get("spaces") == "appDataFolder"
else _LIST_ALL_SCOPES
)
if required.isdisjoint(scopes or ()):
Expand All @@ -1495,13 +1500,133 @@ def _check_empty_folder(self, item_id, path):
path,
)

def rm(self, path, recursive=False, maxdepth=None):
"""Remove files, and with recursive=True whole folders.

A folder is removed with one request, after a listing checks that
this account can remove everything in it.
"""
operands = [path] if isinstance(path, (str, os.PathLike)) else path
# A root named outright is refused before any request.
for operand in operands:
self._refuse_drive_root(self._strip_protocol(os.fspath(operand)))
if not recursive or maxdepth is not None:
Comment thread
shcheklein marked this conversation as resolved.
Resolved
items = self.expand_path(
path, recursive=recursive, maxdepth=maxdepth
)
# A glob can match a root too, so check them all before removing.
for item in items:
self._refuse_drive_root(item)
for item in reversed(items):
self.rm_file(item)
return
targets = []
folders: set[str] = set()
# A folder sorts before what is in it, which goes with the folder.
for item in sorted(self.expand_path(path)):
Comment thread
shcheklein marked this conversation as resolved.
Resolved
if not folders.isdisjoint(_ancestors(item)):
continue
self._refuse_drive_root(item)
# Like rmdir, refuse a path that two folders share.
item_id, is_folder = self._lookup_item(
item, refuse_shared_folder_name=True
)
targets.append((item, item_id, is_folder))
if is_folder:
folders.add(item.rstrip("/"))
for item, item_id, is_folder in targets:
if is_folder:
self._remove_folder(item_id, item)
else:
self._remove(item_id, item, is_folder=False)

def _refuse_drive_root(self, path, *, fresh=False):
"""Raise for a Drive root, else return the metadata of a mount root."""
root, base = self._split_mounted_path(path)
if base:
return None
if root not in _ROOT_ALIASES:
metadata = self._get_root_metadata(fresh=fresh)
if metadata.get("driveId") != root:
return metadata
raise PermissionError(errno.EPERM, "Cannot remove a Drive root", path)

def _remove_folder(self, item_id, path):
capability = "canTrash" if self._trash_only else "canDelete"
action = "moved to the trash" if self._trash_only else "deleted"
self._require_scopes_that_list_everything(path)
folder = self.client.CreateFile({"id": item_id})
with self._forget_if_gone(item_id, path, is_folder=True):
_gdrive_retry_repeatable(folder.FetchMetadata)(
fields=f"capabilities/{capability}"
)
if not folder.get("capabilities", {}).get(capability):
raise PermissionError(
errno.EACCES, f"This account cannot have it {action}", path
)
stays = self._item_that_would_stay(item_id, path, capability)
if stays is not None:
raise PermissionError(
errno.EACCES,
f"Nothing was removed: this account cannot have {stays} "
f"{action}",
path,
)
self._remove(item_id, path, is_folder=True)

def _item_that_would_stay(self, folder_id, path, capability):
"""The first path below a folder that removing it would leave."""
fields = (
"nextPageToken,incompleteSearch,"
f"files(id,name,mimeType,parents,capabilities/{capability})"
)
frontier = {folder_id: path.rstrip("/")}
visited = set(frontier)
while frontier:
batch = dict(islice(frontier.items(), _MAX_QUERY_TERMS))
for parent in batch:
del frontier[parent]
# A permanent removal also deletes what is already in the trash.
children = self._query_children(
batch, fields=fields, trashed=not self._trash_only
)
for item in children:
parents = [p for p in item.get("parents", ()) if p in batch]
parent_path = batch[parents[0]] if parents else path
item_path = posixpath.join(parent_path, item["name"])
if not item.get("capabilities", {}).get(capability):
return item_path
is_folder = item["mimeType"] == FOLDER_MIME_TYPE
if is_folder and item["id"] not in visited:
visited.add(item["id"])
frontier[item["id"]] = item_path
return None

def rm_file(self, path):
_, base = self._split_mounted_path(path)
match, _ = self._lookup_path(base)
item_id = _select_item_id(path, match.ids)
known_folder = item_id in match.folders
self._gdrive_delete_file(item_id)
self._invalidate_folder(item_id, path, known_folder=known_folder)
self._refuse_drive_root(path)
item_id, is_folder = self._lookup_item(path)
# Like rmdir, a folder is removed only when it is empty.
self._remove(
item_id,
path,
is_folder=is_folder,
empty_directory=path if is_folder else None,
)

def _remove(self, item_id, path, *, is_folder, empty_directory=None):
with self._forget_if_gone(item_id, path, is_folder=is_folder):
self._gdrive_delete_file(item_id, empty_directory=empty_directory)
self._invalidate_folder(item_id, path, known_folder=is_folder)

@contextmanager
def _forget_if_gone(self, item_id, path, *, is_folder):
"""Raise FileNotFoundError for an item another client removed."""
try:
with _translate_not_found(path):
yield
except FileNotFoundError:
self._invalidate_folder(item_id, path, known_folder=is_folder)
raise

def _gdrive_delete_file(self, item_id, *, empty_directory=None):
attempts = count()
Expand Down
Loading
Loading