Skip to content
87 changes: 43 additions & 44 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -714,10 +714,7 @@ def _list_params(self):
if self.root == "appDataFolder":
params["spaces"] = "appDataFolder"
elif self.root != "root":
try:
metadata = self._get_root_metadata()
except FileNotFoundError as exc:
raise PermissionError from exc
metadata = self._get_root_metadata(missing_error=PermissionError)
if "appDataFolder" in metadata.get("spaces", ()):
params["spaces"] = "appDataFolder"
elif metadata.get("driveId"):
Expand All @@ -726,8 +723,18 @@ def _list_params(self):

@_gdrive_retry_repeatable
def _get_root_metadata(
self, *, fresh=False, fields="driveId,mimeType,trashed"
self,
path=None,
*,
fresh=False,
fields="driveId,mimeType,trashed",
missing_error=FileNotFoundError,
):
"""Return the root's metadata, treating a trashed root as missing.

Drive answers 404 for a root that is gone or not shared, which raises
missing_error.
"""
cached = self._root_metadata
if cached and not fresh:
return cached
Expand All @@ -739,11 +746,13 @@ def _get_root_metadata(
try:
with _translate_not_found(self.root):
item.FetchMetadata(f"{fields},spaces")
except FileNotFoundError:
except FileNotFoundError as exc:
with self._dirs.lock:
if self._root_metadata is cached:
self.invalidate_cache(self.root)
raise
if missing_error is FileNotFoundError:
raise
raise missing_error from exc
with self._dirs.lock:
if self._root_metadata is cached:
if item.get("trashed"):
Expand All @@ -754,6 +763,11 @@ def _get_root_metadata(
"driveId": item.get("driveId"),
"mimeType": item.get("mimeType"),
}
# A trashed folder still lists its children for a while.
if item.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path or self.root
)
return item.metadata

def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS):
Expand Down Expand Up @@ -864,6 +878,9 @@ def _get_item_id(self, path, create=False):
if create and base:
match = self._resolver().directory(base, create=True)
return _select_item_id(path, match.folders)
if create and self.root not in _ROOT_ALIASES:
# Drive accepts new files in a trashed folder.
self._get_root_metadata(missing_error=PermissionError)
match, _ = self._lookup_path(base)
return _select_item_id(path, match.ids)

Expand All @@ -874,11 +891,7 @@ def _lookup_item(self, 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
metadata = self._get_root_metadata()
if metadata.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
metadata = self._get_root_metadata(path)
return item_id, metadata.get("mimeType") == FOLDER_MIME_TYPE

def _forget_new_ids(self):
Expand Down Expand Up @@ -969,11 +982,7 @@ def _mkdir(self, path, create_parents, exist_ok):
root, base = self._split_mounted_path(path)
cached = base and self._dirs.has_directory(base, self.base)
if not cached and root not in _ROOT_ALIASES:
metadata = self._get_root_metadata(fresh=True)
if metadata.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), root
)
metadata = self._get_root_metadata(root, fresh=True)
if metadata.get("mimeType") != FOLDER_MIME_TYPE:
if base:
raise NotADirectoryError(
Expand Down Expand Up @@ -1013,20 +1022,15 @@ def info(self, path):
bucket, base = self._split_mounted_path(path)
if not base and bucket not in _ROOT_ALIASES:
gdrive_file = self._get_root_metadata(
fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}"
path, fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}"
)
else:
with _translate_not_found(path):
item_id = self._get_item_id(path)
gdrive_file = self.client.CreateFile({"id": item_id})
fields = _INFO_FIELDS if base else f"{_INFO_FIELDS},trashed"
_gdrive_retry_repeatable(gdrive_file.FetchMetadata)(
fields=fields
fields=_INFO_FIELDS
)
if not base and gdrive_file.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)

return _file_entry(
posixpath.join(bucket, base).rstrip("/"), gdrive_file
Expand All @@ -1039,17 +1043,13 @@ def ls(self, path, detail=False):
if not base and bucket not in _ROOT_ALIASES:
cached = self._root_metadata
if not cached or cached.get("mimeType") != FOLDER_MIME_TYPE:
try:
root = self._get_root_metadata(
fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}"
)
except FileNotFoundError as exc:
raise PermissionError from exc
root = self._get_root_metadata(
path,
fresh=True,
fields=f"driveId,trashed,{_INFO_FIELDS}",
missing_error=PermissionError,
)
if root["mimeType"] != FOLDER_MIME_TYPE:
if root.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
return [_file_entry(bucket, root, detail)]

match, generation = self._lookup_path(base, folders_only=True)
Expand Down Expand Up @@ -1163,7 +1163,13 @@ def find(
if maxdepth is not None and maxdepth < 1:
raise ValueError("maxdepth must be at least 1")
resolver = self._resolver()
match = resolver.resolve(base, folders_only=not (withdirs and detail))
try:
Comment thread
shcheklein marked this conversation as resolved.
Resolved
match = resolver.resolve(
base, folders_only=not (withdirs and detail)
)
except FileNotFoundError:
# The root is in the trash, so nothing under it exists.
return {} if detail else []
start = posixpath.join(root, base).rstrip("/")
check_empty_root = False
if not base and root not in _ROOT_ALIASES:
Expand Down Expand Up @@ -1432,11 +1438,7 @@ def rmdir(self, path):
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
)
item = self._get_root_metadata(path, fresh=True)
if item.get("mimeType") != FOLDER_MIME_TYPE:
raise NotADirectoryError(
errno.ENOTDIR, os.strerror(errno.ENOTDIR), path
Expand Down Expand Up @@ -1496,10 +1498,7 @@ def _check_empty_folder(self, item_id, path):
)

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
item_id, known_folder = self._lookup_item(path)
self._gdrive_delete_file(item_id)
self._invalidate_folder(item_id, path, known_folder=known_folder)

Expand Down
58 changes: 58 additions & 0 deletions pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -734,3 +734,61 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy(
fs.cp_file(f"root/{workspace_files}-link", remote_dir + "/copy")
assert len(lost) == 1
assert items_below(fs_factory()[0], remote_dir) == ["copy"]


@pytest.fixture
def folder_with_a_file(service_auth, fs_factory, request):
drive = GoogleDrive(service_auth)
base_id = fs_factory()[1]["id"]
folder = drive.CreateFile(
{
"name": uuid.uuid4().hex,
"mimeType": "application/vnd.google-apps.folder",
"parents": [base_id],
}
)
pydrive_retry(folder.Upload)
request.addfinalizer(lambda: pydrive_retry(folder.Delete))
file = drive.CreateFile({"name": "a.txt", "parents": [folder["id"]]})
file.SetContentString("a")
pydrive_retry(file.Upload)
return folder["id"]


def assert_missing(fs, root):
child = f"{root}/a.txt"
for path in (root, child):
with pytest.raises(FileNotFoundError):
fs.ls(path)
with pytest.raises(FileNotFoundError):
fs.info(path)
assert not fs.exists(path)
with pytest.raises(FileNotFoundError):
fs.cat_file(child)
# As for any missing path, find() and walk() return nothing.
assert fs.find(root) == []
assert fs.find(child) == []
assert list(fs.walk(root)) == []
# Drive accepts new files in a trashed folder.
with pytest.raises(FileNotFoundError):
fs.pipe_file(f"{root}/c.txt", b"c")
with pytest.raises(FileNotFoundError):
fs.rm_file(root)


def test_folder_id_root_trashed_by_another_client_is_missing_with_or_without_cache(
service_auth, folder_with_a_file
):
root = folder_with_a_file
cached = GDriveFileSystem(root, service_auth, skip_instance_cache=True)
assert cached.ls(root) == [f"{root}/a.txt"]
# After a write the filesystem holds IDs that Drive generated for later ones.
cached.pipe_file(f"{root}/b.txt", b"b")

pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": root}).Trash)

# The filesystem learns of changes by other clients when told to.
cached.invalidate_cache()
assert_missing(cached, root)
new = GDriveFileSystem(root, service_auth, skip_instance_cache=True)
assert_missing(new, root)
10 changes: 7 additions & 3 deletions pydrive2/test/test_fs_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,19 +213,23 @@ def test_file_id_errors(mock_drive, tmp_path, method, status, reason):
def test_trashed_file_id_is_absent_from_metadata(mock_drive):
trashed = {"mimeType": "text/plain", "trashed": True}
drive, requests = mock_drive(
response({"trashed": True}), response(trashed), response(trashed)
response({"mimeType": "text/plain"}),
response({"trashed": True}),
response(trashed),
response(trashed),
)
fs, path = fsspec.core.url_to_fs("gdrive://FiLe", google_auth=drive.auth)
fs.rm_file(path)
assert not fs.exists(path)
with pytest.raises(FileNotFoundError) as error:
fs.info(path)
assert error.value.filename == path
trash, *metadata = requests
first, trash, *metadata = requests
assert trash[1] == "PATCH"
assert json.loads(trash[2]) == {"trashed": True}
assert all(
"trashed" in query(req)["fields"][0].split(",") for req in metadata
"trashed" in query(req)["fields"][0].split(",")
for req in [first, *metadata]
)


Expand Down
38 changes: 38 additions & 0 deletions pydrive2/test/test_fs_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,44 @@ def test_find_trashed_root_id_skips_listing(mock_drive):
assert "trashed" in query(stat)["fields"][0].split(",")


@pytest.mark.parametrize(
"operation",
[
lambda fs: fs.info("FolderID/a.txt"),
lambda fs: fs.ls("FolderID/a.txt"),
lambda fs: fs.cat_file("FolderID/a.txt"),
],
ids=["info", "ls", "cat_file"],
)
def test_path_under_a_trashed_folder_id_root_is_missing_while_drive_lists_it(
mock_drive, operation
):
a_file = {"name": "a.txt", "id": "A", "mimeType": "text/plain"}
drive, requests = mock_drive(
response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}),
listing(a_file),
)
with pytest.raises(FileNotFoundError):
operation(filesystem(drive, "FolderID"))
(stat,) = requests
assert "trashed" in query(stat)["fields"][0].split(",")


@pytest.mark.parametrize(("detail", "nothing"), [(False, []), (True, {})])
def test_find_under_a_trashed_folder_id_root_finds_nothing_while_drive_lists_it(
mock_drive, detail, nothing
):
a_file = {"name": "a.txt", "id": "A", "mimeType": "text/plain"}
drive, requests = mock_drive(
response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}),
listing(a_file),
)
fs = filesystem(drive, "FolderID")
assert fs.find("FolderID/a.txt", detail=detail) == nothing
(stat,) = requests
assert "trashed" in query(stat)["fields"][0].split(",")


@pytest.mark.parametrize("survivors", [[], [folder("empty", "B")]])
def test_find_after_external_removal_of_a_cached_named_folder(
mock_drive, survivors
Expand Down
Loading