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
65 changes: 42 additions & 23 deletions pydrive2/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,20 @@
from .auth import LoadAuth

FOLDER_MIME_TYPE = "application/vnd.google-apps.folder"
SHORTCUT_MIME_TYPE = "application/vnd.google-apps.shortcut"
DEFAULT_FILE_FIELDS = (
"id,name,mimeType,description,parents,trashed,size,md5Checksum,"
"resourceKey,webViewLink,createdTime,modifiedTime"
)

# Drive's reasons for an export it refuses in the asked type.
_EXPORT_TYPE_REFUSALS = frozenset(
{"badRequest", "conversionUnsupported", "exportFormatNotFound"}
)
# Drive's reasons for refusing every export of a file.
_EXPORT_FILE_REFUSALS = frozenset({"cannotExportFile", "fileNotExportable"})
_NO_CONTENT_TYPES = frozenset({FOLDER_MIME_TYPE, SHORTCUT_MIME_TYPE})

WORKSPACE_EXPORT_TYPES = frozenset(
{
"application/vnd.google-apps.document",
Expand Down Expand Up @@ -485,7 +494,7 @@ def GetContentIOBuffer(
identified as abusive.
:type acknowledge_abuse: bool
:returns: MediaIoReadable -- file-like object.
:raises: ApiRequestError, FileNotUploadedError
:raises: ApiRequestError, FileNotUploadedError, FileNotDownloadableError
"""

def open_stream(request, content_type):
Expand All @@ -500,6 +509,10 @@ def open_stream(request, content_type):
file_id = self._FileId()
files = self.auth.service.files()
source_type = self._SourceMimeType()
if source_type in _NO_CONTENT_TYPES:
raise FileNotDownloadableError(
"Folders and shortcuts have no content"
)
if source_type not in WORKSPACE_EXPORT_TYPES:
request = files.get_media(
fileId=file_id,
Expand All @@ -517,7 +530,30 @@ def open_stream(request, content_type):

export_type = mimetype or "text/plain"
request = files.export_media(fileId=file_id, mimeType=export_type)
return open_stream(request, export_type)
try:
return open_stream(request, export_type)
except ApiRequestError as error:
Comment thread
shcheklein marked this conversation as resolved.
Resolved
reason = error.GetField("reason")
if reason in _EXPORT_FILE_REFUSALS:
raise FileNotDownloadableError(str(error)) from error
if reason not in _EXPORT_TYPE_REFUSALS:
raise
if source_type is None:
# Only the type tells a shortcut from a Workspace file.
self.FetchMetadata(fields="mimeType")
source_type = self._SourceMimeType()
if source_type in _NO_CONTENT_TYPES:
raise FileNotDownloadableError(
"Folders and shortcuts have no content"
) from error
if not source_type.startswith("application/vnd.google-apps."):
raise
raise FileNotDownloadableError(
f"Drive cannot export this file as {export_type}. Pass "
"another mimetype to GetContentString(), GetContentFile() "
"or GetContentIOBuffer(), such as text/csv for a Google "
"Sheet."
) from error

@LoadAuth
def FetchMetadata(self, fields=None, fetch_all=False):
Expand Down Expand Up @@ -558,27 +594,10 @@ def FetchContent(self, mimetype=None, remove_bom=False):
"""Download file content or a Workspace export into memory."""
if not self.uploaded and not self._SourceMimeType():
self.FetchMetadata()
if self._SourceMimeType() in {
FOLDER_MIME_TYPE,
"application/vnd.google-apps.shortcut",
}:
raise FileNotDownloadableError(
"Folders and shortcuts have no content"
)
try:
stream = self.GetContentIOBuffer(
mimetype=mimetype, remove_bom=remove_bom
)
self.content = io.BytesIO(b"".join(stream))
except ApiRequestError as error:
if error.GetField("reason") in {
"fileNotExportable",
"exportFormatNotFound",
"conversionUnsupported",
"cannotExportFile",
}:
raise FileNotDownloadableError(str(error)) from error
raise
stream = self.GetContentIOBuffer(
mimetype=mimetype, remove_bom=remove_bom
)
self.content = io.BytesIO(b"".join(stream))
self.dirty["content"] = False
self.has_bom = not remove_bom
self._export_mimetype = mimetype
Expand Down
20 changes: 20 additions & 0 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -1407,6 +1407,26 @@ def _gdrive_open_file(self, item_id, block_size=None):
)
return IterStream(iter(_gdrive_retry_repeatable(fd.read), None))

def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs):
"""Bytes used below a path, from one listing of the tree.

An item that Drive gives no size, such as a shortcut, counts as 0.
"""
kwargs["detail"] = True
if total:
# Folders have no size, and with withdirs=True a folder can
# hide a file of the same name.
found = self.find(path, maxdepth=maxdepth, **kwargs)
return sum(entry["size"] or 0 for entry in found.values())
found = self.find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs)
sizes = {}
for name, entry in found.items():
if entry["type"] == "directory":
# info() spells a directory name with a slash at the end.
name = name.rstrip("/") + "/"
sizes[name] = entry["size"] or 0
return sizes

def rmdir(self, path):
"""Remove one empty Drive folder, honoring the trash_only setting."""
root, base = self._split_mounted_path(path)
Expand Down
61 changes: 60 additions & 1 deletion pydrive2/test/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
from pydrive2.files import ApiRequestError
from pydrive2.files import (
SHORTCUT_MIME_TYPE,
ApiRequestError,
FileNotDownloadableError,
)
from pydrive2.test import test_util
from pydrive2.test.test_util import (
create_file,
Expand Down Expand Up @@ -984,6 +988,61 @@ def test_Gfile_Conversion_Add_Remove_BOM(uploaded_document):
assert content_no_bom == buffer_no_bom


@pytest.fixture
def uploaded_sheet(service_auth, delete_after_test):
file = GoogleDrive(service_auth).CreateFile(
{"mimeType": "application/vnd.google-apps.spreadsheet"}
)
file.SetContentString("a,b\n1,2\n")
pydrive_retry(file.Upload, media_mime_type="text/csv")
delete_after_test(file)
return file


def test_content_string_by_id_of_a_sheet_as_text_raises_file_not_downloadable(
service_auth, uploaded_sheet
):
file = GoogleDrive(service_auth).CreateFile({"id": uploaded_sheet["id"]})
with pytest.raises(FileNotDownloadableError, match="text/csv"):
file.GetContentString()


def test_content_string_by_id_of_a_sheet_as_csv_is_its_table(
service_auth, uploaded_sheet
):
file = GoogleDrive(service_auth).CreateFile({"id": uploaded_sheet["id"]})
content = file.GetContentString(mimetype="text/csv")
assert content.splitlines() == ["a,b", "1,2"]


def test_content_string_by_id_of_a_shortcut_raises_file_not_downloadable(
service_auth, delete_after_test, uploaded_document
):
document, _ = uploaded_document
drive = GoogleDrive(service_auth)
shortcut = drive.CreateFile(
{
"mimeType": SHORTCUT_MIME_TYPE,
"shortcutDetails": {"targetId": document["id"]},
}
)
pydrive_retry(shortcut.Upload)
delete_after_test(shortcut)
file = drive.CreateFile({"id": shortcut["id"]})
with pytest.raises(FileNotDownloadableError, match="shortcuts"):
file.GetContentString()


def test_content_file_by_id_of_a_google_doc_exports_pdf(
service_auth, uploaded_document, tmp_path
):
document, _ = uploaded_document
file = GoogleDrive(service_auth).CreateFile({"id": document["id"]})
path = tmp_path / "doc.pdf"
file.GetContentFile(str(path), mimetype="application/pdf")
assert path.read_bytes().startswith(b"%PDF")


# Setup for concurrent upload testing.
# =====================================

Expand Down
47 changes: 46 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 FileNotDownloadableError
from pydrive2.fs import GDriveFileSystem
from pydrive2.test.test_util import (
GDRIVE_USER_CREDENTIALS_DATA,
Expand Down Expand Up @@ -696,7 +697,10 @@ def test_delete_after_drive_did_it_and_the_answer_was_lost_removes_the_file(

@pytest.fixture
def workspace_files(service_auth, request):
"""A Google Doc and a shortcut to it, in the root of the Drive."""
"""A Google Doc, a shortcut to it and a Google Sheet, in My Drive.

Returns the Doc's name; the shortcut and the Sheet add -link and -sheet.
"""
drive = GoogleDrive(service_auth)
name = uuid.uuid4().hex
document = drive.CreateFile(
Expand All @@ -714,9 +718,50 @@ def workspace_files(service_auth, request):
)
pydrive_retry(shortcut.Upload)
request.addfinalizer(lambda: pydrive_retry(shortcut.Delete))
sheet = drive.CreateFile(
{
"name": name + "-sheet",
"mimeType": "application/vnd.google-apps.spreadsheet",
}
)
sheet.SetContentString("a,b\n1,2\n")
pydrive_retry(sheet.Upload, media_mime_type="text/csv")
request.addfinalizer(lambda: pydrive_retry(sheet.Delete))
return name


def test_cat_file_of_a_google_doc_returns_its_text(fs, workspace_files):
assert fs.cat_file(f"root/{workspace_files}").endswith(b"text")


@pytest.mark.parametrize(
("suffix", "message"),
[("-link", "shortcuts"), ("-sheet", "text/csv")],
ids=["shortcut", "sheet"],
)
def test_cat_file_of_a_shortcut_or_a_sheet_raises_file_not_downloadable(
fs, workspace_files, suffix, message
):
with pytest.raises(FileNotDownloadableError, match=message):
fs.cat_file(f"root/{workspace_files}{suffix}")


def test_du_counts_a_shortcut_as_empty(fs, remote_dir, workspace_files):
fs.makedirs(remote_dir + "/sub")
fs.pipe_file(remote_dir + "/plain.txt", b"plain")
fs.cp_file(f"root/{workspace_files}-link", remote_dir + "/link")

sizes = {remote_dir + "/link": 0, remote_dir + "/plain.txt": 5}
assert fs.du(remote_dir, total=False) == sizes
assert fs.du(remote_dir, total=False, withdirs=True) == {
remote_dir + "/": 0,
remote_dir + "/sub/": 0,
**sizes,
}
assert fs.du(remote_dir) == 5
assert fs.du(remote_dir, detail=False) == 5


def test_cp_file_copies_a_google_doc_which_drive_gives_its_own_id(
fs, fs_factory, remote_dir, workspace_files
):
Expand Down
14 changes: 14 additions & 0 deletions pydrive2/test/test_fs_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,20 @@ def measure():
tracemalloc.stop()


# Drive assigns IDs, so only a mock can put the folder's ID first.
@pytest.mark.parametrize("withdirs", [False, True])
def test_du_total_counts_a_file_that_shares_its_name_with_a_folder(
mock_drive, withdirs
):
file = {"id": "M", "name": "x", "mimeType": "text/plain", "size": "7"}
drive, _ = mock_drive(
listing(folder("dir", "D")),
listing(folder("x", "A"), file),
listing(),
)
assert filesystem(drive).du("root/dir", withdirs=withdirs) == 7


@pytest.mark.parametrize("operation", ["ls", "find"])
def test_listing_a_hash_prefix_releases_file_names_and_ids(
mock_drive, operation, live_heap_bytes
Expand Down
Loading