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
127 changes: 96 additions & 31 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import appdirs
from fsspec.spec import AbstractFileSystem
from funcy import (
cached_property,
chunks,
distinct,
retry,
Expand Down Expand Up @@ -282,6 +281,8 @@ def __init__(
self._cache_lock = threading.RLock()
self._directory_ids = _DirectoryCache()
self._mount_lock = threading.RLock()
self._root_lock = threading.RLock()
self._root_metadata: dict = {}
self._creation_locks: WeakValueDictionary = WeakValueDictionary()
self.path = path
self.root, self.base = self.split_path(self.path)
Expand Down Expand Up @@ -401,6 +402,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 @@ -413,39 +416,50 @@ 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, *, fresh=False):
cached = self._root_metadata
if cached and not fresh:
return cached
with self._root_lock:
cached = self._root_metadata
if cached and not fresh:
return cached
item = self.client.CreateFile({"id": self.root})
try:
with _translate_not_found(self.root):
item.FetchMetadata("driveId,mimeType,trashed")
except FileNotFoundError:
with self._cache_lock:
if self._root_metadata is cached:
self._root_metadata = {}
raise
with self._cache_lock:
if self._root_metadata is cached:
# Trash status is only valid for the request that observed it.
self._root_metadata = (
{}
if item.get("trashed")
else {
"driveId": item.get("driveId"),
"mimeType": item.get("mimeType"),
}
)
return item.metadata

def _gdrive_list(self, query):
param = {
Expand Down Expand Up @@ -564,7 +578,9 @@ def _gdrive_create_dir(self, parent_id, name):
item.Upload()
return item

def _get_or_create_child(self, cache, parents, path, name, mount=None):
def _get_or_create_child(
self, cache, parents, path, name, mount=None, *, exist_ok=True
):
parent_id = min(parents)
key = (parent_id, name)
with self._cache_lock:
Expand All @@ -573,18 +589,67 @@ def _get_or_create_child(self, cache, parents, path, name, mount=None):
lock = self._creation_locks[key] = threading.RLock()
with lock:
with self._cache_lock:
if cached := cache.by_path.get(path):
return _PathMatch(cached.copy()), cache
# An invalidation can give two writers different caches. Check
# Drive under the same name lock as the create.
match, cache = self._match_child(cache, parents, path, name, mount)
folders = cache.by_path.get(path, []).copy()
if folders:
match = _PathMatch(folders)
else:
# An invalidation can give two writers different caches. Check
# Drive under the same name lock as the create.
match, cache = self._match_child(
cache, parents, path, name, mount
)
if match.folders or match.files:
if not exist_ok:
raise FileExistsError(posixpath.join(self.root, path))
return match, cache
item = self._gdrive_create_dir(parent_id, name)
return _PathMatch([item["id"]]), self._cache_path_id(
cache, path, 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(fresh=True)
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

cache, mount = self._directory_cache()
with self._cache_lock:
if base in cache.by_path:
if not exist_ok:
raise FileExistsError(path)
return
parent, name = posixpath.split(base)
if create_parents:
folders, cache = self._ensure_dirs(parent, cache, mount)
else:
prefix, match, cache = self._resolve_prefix(parent, cache, mount)
if not match.folders:
raise NotADirectoryError(posixpath.join(root, prefix))
if prefix != parent:
raise FileNotFoundError(posixpath.join(root, parent))
folders = match.folders
leaf, _ = self._get_or_create_child(
cache, folders, base, name, mount, exist_ok=exist_ok
)
if not leaf.folders:
raise FileExistsError(path)

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