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
117 changes: 87 additions & 30 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import appdirs
from fsspec.spec import AbstractFileSystem
from funcy import (
cached_property,
chunks,
distinct,
retry,
Expand Down Expand Up @@ -281,6 +280,7 @@ def __init__(
super().__init__(**kwargs)
self._cache_lock = threading.RLock()
self._directory_ids = _DirectoryCache()
self._root_metadata: dict = {}
self.path = path
self.root, self.base = self.split_path(self.path)

Expand Down Expand Up @@ -393,6 +393,8 @@ def _invalidate_paths(self, *paths):
for path in paths:
super().invalidate_cache(path)
with self._cache_lock:
if "" in subtrees:
self._root_metadata = {}
if _in_subtrees(self.base, subtrees):
self._directory_ids = _DirectoryCache()
else:
Expand All @@ -405,39 +407,39 @@ def _is_cached_directory(self, item_id):
cache = self._directory_ids
return item_id == self.root or item_id in cache.by_id

@cached_property
@property
def _list_params(self):
params = {"corpora": "user"}
if self.root == "appDataFolder":
params["spaces"] = "appDataFolder"
elif self.root != "root":
drive_id = self._gdrive_shared_drive_id(self.root)
try:
drive_id = self._get_root_metadata().get("driveId")
except FileNotFoundError as exc:
raise PermissionError from exc
if drive_id:
logger.debug(
f"GDrive remote '{self.path}' is using shared drive id '{drive_id}'."
)
params["driveId"] = drive_id
params["corpora"] = "drive"
params.update(driveId=drive_id, corpora="drive")
return params

@_gdrive_retry
def _gdrive_shared_drive_id(self, item_id):
from pydrive2.files import ApiRequestError

param = {"id": item_id}
# it does not create a file on the remote
item = self.client.CreateFile(param)
# ID of the shared drive the item resides in.
# Only populated for items in shared drives.
try:
item.FetchMetadata("driveId")
except ApiRequestError as exc:
error_code = exc.error.get("code", 0)
if error_code == 404:
raise PermissionError from exc
raise

return item.get("driveId", None)
def _get_root_metadata(self):
with self._cache_lock:
# A root invalidation during the request replaces this dictionary.
metadata = self._root_metadata
if not metadata:
item = self.client.CreateFile({"id": self.root})
with _translate_not_found(self.root):
item.FetchMetadata("driveId,mimeType,trashed")
if item.get("trashed"):
return item.metadata
metadata.update(item.metadata)
if drive_id := metadata.get("driveId"):
logger.debug(
"GDrive remote %r is using shared drive id %r.",
self.path,
drive_id,
)
return metadata

def _gdrive_list(self, query):
param = {
Expand Down Expand Up @@ -474,7 +476,14 @@ def _gdrive_list_ids(self, query_ids, *, name=None):
yield item

def _resolve_path(
self, path, cache, mount=None, *, create=False
self,
path,
cache,
mount=None,
*,
create=False,
create_parents=True,
exist_ok=True,
) -> _PathMatch:
# Start at the deepest cached folder and only fetch unknown components.
parent = path
Expand All @@ -501,14 +510,27 @@ def _resolve_path(
match.files.append(item)
cache = self._cache_path_id(cache, parent, *match.folders)
if create and not match.folders:
leaf = parent == path
if match.files:
raise NotADirectoryError(posixpath.join(self.root, parent))
match = _PathMatch(
[self._create_dir(cache, min(folders), name, parent)]
error = FileExistsError if leaf else NotADirectoryError
raise error(posixpath.join(self.root, parent))
if not leaf and not create_parents:
raise FileNotFoundError(posixpath.join(self.root, parent))
folder_id = self._create_dir(
cache,
min(folders),
name,
parent,
exist_ok=not leaf or exist_ok,
)
match = _PathMatch([folder_id])
if leaf:
return match
if not match.folders and parent != path:
return _PathMatch([])
folders = match.folders
if create and not exist_ok:
raise FileExistsError(posixpath.join(self.root, path))
return match

def _path_to_item_ids(self, path, create=False):
Expand Down Expand Up @@ -538,15 +560,50 @@ def _gdrive_create_dir(self, parent_id, name):
return item

@wrap_with(threading.RLock())
def _create_dir(self, cache, parent_id, name, remote_path):
def _create_dir(
self, cache, parent_id, name, remote_path, *, exist_ok=True
):
with self._cache_lock:
if cached := cache.by_path.get(remote_path):
if not exist_ok:
raise FileExistsError(
posixpath.join(self.root, remote_path)
)
return cached[0]
item = self._gdrive_create_dir(parent_id, name)
self._cache_path_id(cache, remote_path, item["id"])

return item["id"]

def mkdir(self, path, create_parents=True, **kwargs):
self._mkdir(path, create_parents, exist_ok=False)

def makedirs(self, path, exist_ok=False):
self._mkdir(path, create_parents=True, exist_ok=exist_ok)

def _mkdir(self, path, create_parents, exist_ok):
root, base = self._split_mounted_path(path)
if not base:
if root not in {"root", "appDataFolder"}:
metadata = self._get_root_metadata()
if metadata.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
if metadata.get("mimeType") != FOLDER_MIME_TYPE:
raise FileExistsError(path)
if not exist_ok:
raise FileExistsError(path)
return

self._resolve_path(
base,
*self._directory_cache(),
create=True,
create_parents=create_parents,
exist_ok=exist_ok,
)

def exists(self, path):
root, base = self._split_mounted_path(path)
try:
Expand Down
13 changes: 10 additions & 3 deletions pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,14 @@ def test_move(fs, remote_dir):
assert initial_info == secondary_info


def test_create_empty_directory(fs, fs_factory, remote_dir):
path = remote_dir + "/empty/sub"
fs.makedirs(path)
other, _ = fs_factory()
assert other.info(path)["type"] == "directory"
assert other.ls(path) == []


def test_copy_file_to_new_directory(fs, remote_dir):
source = remote_dir + "/source"
target = remote_dir + "/nested/copy"
Expand Down Expand Up @@ -169,8 +177,7 @@ def test_rm(fs, remote_dir):


def test_ls(fs, remote_dir):
_, base = fs.split_path(remote_dir + "/dir/")
fs._path_to_item_ids(base, create=True)
fs.makedirs(remote_dir + "/dir")
assert fs.ls(remote_dir + "/dir/") == []

files = set()
Expand Down Expand Up @@ -279,7 +286,7 @@ def test_find(fs, fs_factory, remote_dir):
dirnames = {posixpath.dirname(file) for file in files}

for dirname in dirnames:
fs.mkdir(dirname)
fs.makedirs(dirname, exist_ok=True)

for file in files:
fs.touch(file)
Expand Down
Loading
Loading