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
17 changes: 17 additions & 0 deletions docs/fsspec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,23 @@ path. 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.

``cp_file()`` and ``mv()`` onto an existing file replace it, as rclone
does. Drive cannot copy or move onto a file, so the old file is moved to
the trash afterwards, or deleted with ``trash_only=False``:

- ``cp_file()`` replaces a file that the filesystem knows at the path, by
the same rule as writes, and looks the path up once more before removing
it. The copy is a new file with its own ID, so the old file's sharing and
links do not carry over.
- ``mv()`` already looks the path up, so it replaces any file there. It
moves the source first, so a failed move leaves the target as it was. The
moved file keeps its ID. A folder at the path keeps its meaning: the
source moves into it.

If several files share the target path, the one that reads return is
replaced and the others stay. Copying or moving a file onto itself changes
nothing.

Listings
--------

Expand Down
5 changes: 4 additions & 1 deletion docs/upgrading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ same name. Other writes still create a file without asking Drive first, so
call ``fs.exists(path)`` before writing to replace a file that another
client or an earlier process wrote. Writing to the path of a known folder
raises ``IsADirectoryError``, and to the path of a known Google Docs file
or shortcut ``PermissionError``. See :ref:`fsspec-writing-files`.
or shortcut ``PermissionError``. ``cp_file()`` onto a known file and
``mv()`` onto any file now replace it, moving the old file to the trash;
``mv()`` used to raise ``NotADirectoryError``. See
:ref:`fsspec-writing-files`.

The :doc:`fsspec filesystem <fsspec>` now caches folders returned by
``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs.
Expand Down
92 changes: 80 additions & 12 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -1355,19 +1355,67 @@ def send(new_id):
return self._gdrive_create(send)

def cp_file(self, lpath, rpath, **kwargs):
"""Ask Drive to copy the file directly into the destination folder."""
self._split_mounted_path(rpath)
"""Copy a file on Drive, replacing a file this filesystem knows there."""
_, base = self._split_mounted_path(rpath)
source_id, is_folder = self._lookup_item(lpath)
if is_folder:
self.makedirs(rpath, exist_ok=True)
return
if self._split_mounted_path(lpath)[1] == base:
return
parent, name = self._split_file_path(rpath)
parent_id = self._get_item_id(parent, create=True)
item = self._gdrive_copy_file(source_id, parent_id, name)
self._dirs.file_added(parent_id, name)
self._known_files.add(
parent_id, name, item["id"], item.get("mimeType")
_, parent_base = self._split_mounted_path(parent)
parents = (
self._resolver().directory(parent_base, create=True).folders
if parent_base
else [self.root]
)
parent_id = min(parents)
with self._creation_lock(parent_id, name):
replaced = None
target_files = []
if self._known_files.get(parents, name) is not None:
# Look again, so only a file still at the path is removed.
match, _ = self._lookup_path(base)
if not match.folders:
target_files = match.files
replaced = min(
target_files, key=attrgetter("id"), default=None
)
if replaced is not None and replaced.id == source_id:
return
Comment thread
shcheklein marked this conversation as resolved.
Resolved
item = self._gdrive_copy_file(source_id, parent_id, name)
self._dirs.file_added(parent_id, name)
try:
if replaced is not None:
self._remove_replaced(replaced, target_files)
finally:
# A copy that a failed removal left beside the old file counts too.
self._known_files.add(
parent_id, name, item["id"], item.get("mimeType")
)

def _remove_replaced(self, replaced, target_files):
"""Remove the file a copy or move replaced, as rm_file would."""
self._gdrive_delete_file(replaced.id)
self._known_files.discard(replaced.parent, replaced.name)
# Reads now return the lowest ID left at the path, so writes must too.
left = [
item
for item in target_files
if item.id != replaced.id
and item.parent == replaced.parent
and not item.ambiguous
]
if left:
first = min(left, key=attrgetter("id"))
self._known_files.add(
first.parent,
first.name,
first.id,
first.mime_type,
looked_up=True,
)

def _gdrive_copy_file(self, source_id, parent_id, name):
source = self.client.CreateFile({"id": source_id})
Expand All @@ -1393,17 +1441,32 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
src_name = posixpath.basename(path1)
src_parent = self._parent(path1)

if self.exists(path2):
_, target = self._split_mounted_path(path2)
target_files = []
if target and not self._dirs.has_directory(target, self.base):
target_match, _ = self._lookup_path(target)
into_folder = bool(target_match.folders)
target_files = target_match.files
Comment thread
shcheklein marked this conversation as resolved.
Resolved
else:
into_folder = self.exists(path2)
replaced = None
if into_folder:
dst_name = src_name
dst_parent = path2
else:
dst_name = posixpath.basename(path2)
dst_parent = self._parent(path2)
replaced = min(target_files, key=attrgetter("id"), default=None)

_, source = self._split_mounted_path(path1)
_, parent_path = self._split_mounted_path(dst_parent)
match, generation = self._lookup_path(source)
file1_id = _select_item_id(path1, match.ids)
if replaced is not None:
if replaced.id == file1_id:
return
if file1_id in match.folders:
raise NotADirectoryError(path2)
file1 = self.client.CreateFile({"id": file1_id})

destination_parent = None
Expand Down Expand Up @@ -1458,10 +1521,15 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
)
moved = next(item for item in match.files if item.id == file1_id)
self._known_files.discard(moved.parent, moved.name)
if destination_parent is not None:
self._known_files.add(
destination_parent, dst_name, file1_id, moved.mime_type
)
try:
# The old target goes only after the move has succeeded.
if replaced is not None:
self._remove_replaced(replaced, target_files)
finally:
if destination_parent is not None:
self._known_files.add(
destination_parent, dst_name, file1_id, moved.mime_type
)

def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs):
with _translate_not_found(rpath):
Expand Down
92 changes: 91 additions & 1 deletion pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from googleapiclient.http import HttpRequest

from pydrive2.drive import GoogleDrive
from pydrive2.files import FOLDER_MIME_TYPE
from pydrive2.files import FOLDER_MIME_TYPE, ApiRequestError
from pydrive2.fs import GDriveFileSystem
from pydrive2.test.test_util import (
GDRIVE_USER_CREDENTIALS_DATA,
Expand Down Expand Up @@ -1030,6 +1030,96 @@ def test_write_after_mv_to_the_path_replaces_the_moved_file(
assert other.cat_file(remote_dir + "/target") == b"new"


def left_on_drive(service_auth, file_id):
"""Whether Drive keeps a file, has it in the trash, or deleted it."""
file = GoogleDrive(service_auth).CreateFile({"id": file_id})
try:
pydrive_retry(file.FetchMetadata, fields="trashed")
except ApiRequestError as error:
if error.error.get("code") == 404:
return "deleted"
raise
return "trashed" if file["trashed"] else "kept"


def test_cp_file_after_a_write_to_the_target_replaces_it_and_trashes_the_old_file(
service_auth, fs, remote_dir, remote_dir_id, drive_methods
):
fs.pipe_file(remote_dir + "/target", b"old")
fs.pipe_file(remote_dir + "/source", b"new")
[old_id] = ids_in(service_auth, remote_dir_id, "target")
drive_methods.clear()

fs.cp_file(remote_dir + "/source", remote_dir + "/target")

# The source and the target are looked up, then copied and trashed.
assert drive_methods == [
"drive.files.list",
"drive.files.list",
"drive.files.copy",
"drive.files.update",
]
[new_id] = ids_in(service_auth, remote_dir_id, "target")
assert new_id != old_id
assert content_on_drive(service_auth, new_id) == b"new"
assert left_on_drive(service_auth, old_id) == "trashed"


def test_cp_file_after_exists_found_the_target_deletes_it_without_trash(
base_remote_dir, service_auth, remote_dir, remote_dir_id
):
old_id = create_on_drive(service_auth, remote_dir_id, "target", "old")
create_on_drive(service_auth, remote_dir_id, "source", "new")
fs = GDriveFileSystem(base_remote_dir, service_auth, trash_only=False)
assert fs.exists(remote_dir + "/target")

fs.cp_file(remote_dir + "/source", remote_dir + "/target")

[new_id] = ids_in(service_auth, remote_dir_id, "target")
assert new_id != old_id
assert content_on_drive(service_auth, new_id) == b"new"
assert left_on_drive(service_auth, old_id) == "deleted"


def test_mv_after_another_client_made_the_target_replaces_it_and_keeps_the_moved_id(
service_auth, fs, remote_dir, remote_dir_id
):
sub_id = create_on_drive(service_auth, remote_dir_id, "sub")
old_id = create_on_drive(service_auth, sub_id, "target", "old")
source_id = create_on_drive(service_auth, remote_dir_id, "source", "new")

fs.mv(remote_dir + "/source", remote_dir + "/sub/target")

assert ids_in(service_auth, sub_id) == [source_id]
assert ids_in(service_auth, remote_dir_id, "source") == []
assert content_on_drive(service_auth, source_id) == b"new"
assert left_on_drive(service_auth, old_id) == "trashed"


def test_mv_after_a_write_to_the_target_in_the_same_folder_deletes_the_old_file(
base_remote_dir, service_auth, remote_dir, remote_dir_id, drive_methods
):
fs = GDriveFileSystem(base_remote_dir, service_auth, trash_only=False)
fs.pipe_file(remote_dir + "/target", b"old")
fs.pipe_file(remote_dir + "/source", b"new")
[old_id] = ids_in(service_auth, remote_dir_id, "target")
[source_id] = ids_in(service_auth, remote_dir_id, "source")
drive_methods.clear()

fs.mv(remote_dir + "/source", remote_dir + "/target")

# The target and the source are looked up, then renamed and deleted.
assert drive_methods == [
"drive.files.list",
"drive.files.list",
"drive.files.update",
"drive.files.delete",
]
assert ids_in(service_auth, remote_dir_id) == [source_id]
assert content_on_drive(service_auth, source_id) == b"new"
assert left_on_drive(service_auth, old_id) == "deleted"


def test_write_after_makedirs_of_the_path_raises_and_creates_no_file(
fs, fs_factory, remote_dir
):
Expand Down
Loading
Loading