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
12 changes: 9 additions & 3 deletions docs/fsspec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,15 @@ 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
lookups. Reads are sequential. To create a file, use a folder ID or root
alias followed by a filename. As with the direct PyDrive2 filesystem,
a write creates a Drive item even when a sibling has the same name. All
reads require credentials, including files shared by link.
alias followed by a filename. Writing to the path of an existing file
replaces its content and keeps the file, with its ID, type and sharing.
When several files share the path, the write replaces the one that reads
return. Writing to the path of a folder raises ``IsADirectoryError``, and
to the path of a Google Docs file or a shortcut ``PermissionError``.
Threads that write one path through the same filesystem instance take
turns. Other instances and other clients do not wait, so two of them can
still create two files with the same name. All reads require credentials,
including files shared by link.

Listings
--------
Expand Down
6 changes: 6 additions & 0 deletions docs/upgrading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ Filesystem directories
Both raise ``FileExistsError`` if the folder already exists. Use
``fs.makedirs(path, exist_ok=True)`` when repeating a setup step.

Writing to the path of an existing file, with ``pipe_file()``,
``put_file()`` or ``open(path, "wb")``, now replaces that file's content.
It used to add a second file with the same name. Writing to the path of a
folder raises ``IsADirectoryError``, and to the path of a Google Docs file
or a shortcut ``PermissionError``.

The :doc:`fsspec filesystem <fsspec>` now caches folders returned by
``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs.
If another client moves or removes a folder, list its parent again or
Expand Down
71 changes: 64 additions & 7 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
_LIST_FIELDS = (
f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})"
)
# Folders, Google Docs, Sheets and the like, and shortcuts.
_WORKSPACE_TYPE_PREFIX = "application/vnd.google-apps."
_NAME_FIELDS = "nextPageToken,incompleteSearch,files(id,name,parents,mimeType)"
_MAX_QUERY_TERMS = 50
_CONNECTION_RETRIES = 3
Expand Down Expand Up @@ -86,7 +88,7 @@ class _ListedChild:
id: str
parent: str | None
name: str
is_folder: bool
mime_type: str
ambiguous: bool
size: int | None
checksum: str | None
Expand All @@ -98,12 +100,17 @@ def from_drive(cls, parent, item):
id=item["id"],
parent=parent,
name=item["name"],
is_folder=item["mimeType"] == FOLDER_MIME_TYPE,
# Listed items share a few types, so they share the strings.
mime_type=sys.intern(item["mimeType"]),
ambiguous=len(item.get("parents", ())) > 1,
size=int(size) if size is not None else None,
checksum=item.get("md5Checksum"),
)

@property
def is_folder(self):
return self.mime_type == FOLDER_MIME_TYPE

def entry(self, name, detail=True):
if not detail:
return name
Expand Down Expand Up @@ -1218,14 +1225,64 @@ def find(
return contents

def upload_fobj(self, stream, rpath, callback=None, **kwargs):
"""Write a file. A file already at the path gets the new content."""
_, base = self._split_mounted_path(rpath)
parent, name = self._split_file_path(rpath)
parent_id = self._get_item_id(parent, create=True)
_, parent_base = self._split_mounted_path(parent)
resolver = self._resolver()
parents = (
resolver.directory(parent_base, create=True).folders
if parent_base
else [self.root]
)
parent_id = min(parents)
if callback:
stream = _ReadProgress(stream, callback.relative_update)
with _unwrap_not_retried():
item = self._gdrive_upload_fobj(name, parent_id, stream)
self._dirs.file_added(parent_id, name)
return item
# Threads of this filesystem that write the same path take turns.
with self._creation_lock(parent_id, name):
existing = self._file_to_replace(
resolver, rpath, base, parents, name
)
with _unwrap_not_retried():
if existing is None:
item = self._gdrive_upload_fobj(name, parent_id, stream)
self._dirs.file_added(parent_id, name)
return item
with _translate_not_found(rpath):
return self._gdrive_replace_content(existing, stream)

def _file_to_replace(self, resolver, path, base, parents, name):
"""The file a write to the path replaces, as reads find it."""
match, _ = resolver.child(parents, base, name, folders_only=False)
if match.folders:
raise IsADirectoryError(
errno.EISDIR, os.strerror(errno.EISDIR), path
)
if not match.files:
return None
# Reads of a name that several files share use the lowest ID.
existing = min(match.files, key=attrgetter("id"))
if existing.mime_type.startswith(_WORKSPACE_TYPE_PREFIX):
raise PermissionError(
errno.EPERM,
"Drive cannot replace a Google Workspace file or a "
"shortcut with bytes",
path,
)
return existing

def _gdrive_replace_content(self, existing, stream):
def send():
# Without the type, Drive sets it from the uploaded content.
item = self.client.CreateFile(
{"id": existing.id, "mimeType": existing.mime_type}
)
item.content = stream
item.Upload()
return item

# Sending the same content to the same file again changes nothing.
return _gdrive_retry_repeatable(send)()

def put_file(self, lpath, rpath, callback=None, **kwargs):
if os.path.isdir(lpath):
Expand Down
168 changes: 167 additions & 1 deletion pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from googleapiclient.http import HttpRequest

from pydrive2.drive import GoogleDrive
from pydrive2.files import FOLDER_MIME_TYPE
from pydrive2.fs import GDriveFileSystem
from pydrive2.test.test_util import (
GDRIVE_USER_CREDENTIALS_DATA,
Expand Down Expand Up @@ -238,7 +239,8 @@ def record_listing(request, *args, **kwargs):
leaf = remote_dir + "/a/b/c"
path = leaf + "/test.txt"
fs.touch(path)
assert len(queries) == 5
# One lookup for each missing folder, and one for the file name.
assert len(queries) == 6

for operation, target, expected in (
(fs.exists, path, True),
Expand Down Expand Up @@ -734,3 +736,167 @@ 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"]


def create_on_drive(service_auth, parent_id, name, content=None, **extra):
"""Create a file, or a folder without content, as another client would."""
metadata = {"name": name, "parents": [parent_id], **extra}
if content is None:
metadata["mimeType"] = FOLDER_MIME_TYPE
file = GoogleDrive(service_auth).CreateFile(metadata)
if content is not None:
file.SetContentString(content)
pydrive_retry(file.Upload)
return file["id"]


@pytest.fixture
def remote_dir_id(service_auth, fs_factory, remote_dir):
"""Create remote_dir with the core API and return its ID."""
_, base = fs_factory()
return create_on_drive(
service_auth, base["id"], posixpath.basename(remote_dir)
)


def content_on_drive(service_auth, file_id):
file = GoogleDrive(service_auth).CreateFile({"id": file_id})
return b"".join(pydrive_retry(file.GetContentIOBuffer))


def metadata_on_drive(service_auth, file_id, fields):
file = GoogleDrive(service_auth).CreateFile({"id": file_id})
pydrive_retry(file.FetchMetadata, fields=fields)
return file


def ids_in(service_auth, folder_id):
query = f"'{folder_id}' in parents and trashed=false"
listing = GoogleDrive(service_auth).ListFile({"q": query})
return [item["id"] for item in pydrive_retry(listing.GetList)]


def pipe(fs, path, data, tmp_path):
fs.pipe_file(path, data)


def put(fs, path, data, tmp_path):
source = tmp_path / "source"
source.write_bytes(data)
fs.put_file(str(source), path)


def write_through_open(fs, path, data, tmp_path):
with fs.open(path, "wb") as stream:
stream.write(data)


@pytest.mark.parametrize(
("write", "size"),
[
(pipe, 3),
(write_through_open, 3),
# Larger than one request, so the upload is resumable.
(put, 2 * 1024 * 1024),
],
ids=["pipe_file", "open", "put_file-2MiB"],
)
def test_write_to_a_file_path_replaces_the_content_and_keeps_the_file(
service_auth, fs, remote_dir, remote_dir_id, tmp_path, write, size
):
data = (b"0123456789abcdef" * (size // 16 + 1))[:size]
file_id = create_on_drive(
service_auth,
remote_dir_id,
"a.json",
"{}",
mimeType="application/json",
)

write(fs, remote_dir + "/a.json", data, tmp_path)

assert ids_in(service_auth, remote_dir_id) == [file_id]
assert content_on_drive(service_auth, file_id) == data
kept = metadata_on_drive(service_auth, file_id, "mimeType")
assert kept["mimeType"] == "application/json"


@pytest.mark.parametrize(
"write",
[
lambda fs, path: fs.touch(path),
lambda fs, path: fs.pipe_file(path, b""),
],
ids=["touch", "pipe_file"],
)
def test_empty_write_to_a_file_path_empties_the_file(
service_auth, fs, remote_dir, remote_dir_id, write
):
file_id = create_on_drive(service_auth, remote_dir_id, "file", "old")

write(fs, remote_dir + "/file")

assert ids_in(service_auth, remote_dir_id) == [file_id]
assert content_on_drive(service_auth, file_id) == b""


def test_write_to_a_path_two_files_share_replaces_the_one_reads_return(
service_auth, fs, fs_factory, remote_dir, remote_dir_id
):
files = {
create_on_drive(service_auth, remote_dir_id, "file", "one"): b"one",
create_on_drive(service_auth, remote_dir_id, "file", "two"): b"two",
}
read_id, other_id = sorted(files)

fs.pipe_file(remote_dir + "/file", b"new")

assert fs_factory()[0].cat_file(remote_dir + "/file") == b"new"
assert content_on_drive(service_auth, read_id) == b"new"
assert content_on_drive(service_auth, other_id) == files[other_id]


def test_write_below_two_folders_with_one_name_replaces_the_file_in_either(
service_auth, fs, remote_dir, remote_dir_id
):
folders = sorted(
create_on_drive(service_auth, remote_dir_id, "dup") for _ in range(2)
)
# Writes would create a new file in the folder with the lower ID.
file_id = create_on_drive(service_auth, folders[1], "file", "old")

fs.pipe_file(remote_dir + "/dup/file", b"new")

assert ids_in(service_auth, folders[0]) == []
assert ids_in(service_auth, folders[1]) == [file_id]
assert content_on_drive(service_auth, file_id) == b"new"


def test_replace_after_drive_did_it_and_the_answer_was_lost_keeps_one_file(
service_auth, fs, remote_dir, remote_dir_id, lose_answers
):
file_id = create_on_drive(service_auth, remote_dir_id, "file", "old")
lost = lose_answers("PATCH", "")

fs.pipe_file(remote_dir + "/file", b"new")

assert len(lost) == 1
assert ids_in(service_auth, remote_dir_id) == [file_id]
assert content_on_drive(service_auth, file_id) == b"new"


def test_write_to_a_folder_path_raises_and_creates_no_file(
fs, fs_factory, remote_dir
):
fs.makedirs(remote_dir + "/dir")
with pytest.raises(IsADirectoryError):
fs.pipe_file(remote_dir + "/dir", b"data")
assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"]


@pytest.mark.parametrize("suffix", ["", "-link"], ids=["doc", "shortcut"])
def test_write_to_a_google_doc_or_shortcut_path_raises_permission_error(
fs, workspace_files, suffix
):
with pytest.raises(PermissionError):
fs.pipe_file(f"root/{workspace_files}{suffix}", b"data")
Loading
Loading