diff --git a/docs/fsspec.rst b/docs/fsspec.rst index b4aa34f4..f13dd1e4 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -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 -------- diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 653b42c7..178ee1af 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -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 ` now caches folders returned by ``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs. diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 00ae89e5..8bddd9ff 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -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 + 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}) @@ -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 + 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 @@ -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): diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 832541d5..526526de 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -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, @@ -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 ): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 355fb0af..1502ddf3 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1705,13 +1705,59 @@ def test_move_into_a_folder_that_shares_its_name_with_a_file(mock_drive): assert len(requests) == 4 -def test_move_rejects_a_file_as_the_destination_parent(mock_drive): +def test_mv_after_a_file_at_the_target_renames_the_source_then_trashes_it( + mock_drive, +): file = {"id": "A", "name": "dest", "mimeType": "text/plain"} source = dict(file, id="source", name="source") - drive, requests = mock_drive(listing(file), listing(source), listing(file)) + drive, requests = mock_drive( + listing(file), + listing(source), + response(dict(source, name="dest")), + response(dict(file, trashed=True)), + ) + filesystem(drive).mv("root/source", "root/dest") + assert [ + (method, urlsplit(uri).path.rsplit("/", 1)[-1], body) + for uri, method, body, _ in requests[2:] + ] == [ + ("PATCH", "source", json.dumps({"name": "dest"})), + ("PATCH", "A", json.dumps({"trashed": True})), + ] + + +def test_mv_of_a_folder_after_a_file_at_the_target_raises_and_changes_nothing( + mock_drive, +): + file = {"id": "A", "name": "dest", "mimeType": "text/plain"} + drive, requests = mock_drive(listing(file), listing(folder("dir", "D"))) with pytest.raises(NotADirectoryError): - filesystem(drive).mv("root/source", "root/dest") - assert all(r[1] == "GET" for r in requests) + filesystem(drive).mv("root/dir", "root/dest") + assert [r[1] for r in requests] == ["GET", "GET"] + + +def test_mv_of_a_file_onto_its_own_path_changes_nothing(mock_drive): + file = {"id": "A", "name": "file", "mimeType": "text/plain"} + drive, requests = mock_drive(listing(file), listing(file)) + filesystem(drive).mv("root/file", "root/file") + assert [r[1] for r in requests] == ["GET", "GET"] + + +@pytest.mark.parametrize( + "parents", [["root"], ["root", "other"]], ids=["one", "two"] +) +def test_cp_file_of_a_file_onto_its_own_path_changes_nothing( + mock_drive, parents +): + file = { + "id": "A", + "name": "file", + "mimeType": "text/plain", + "parents": parents, + } + drive, requests = mock_drive(listing(file)) + filesystem(drive).cp_file("root/file", "root/file") + assert [r[1] for r in requests] == ["GET"] def test_move_directory_to_implicit_root(mock_drive): @@ -2335,15 +2381,17 @@ def test_write_after_exists_no_longer_finds_a_known_file_replaces_the_other( assert urlsplit(requests[-1][0]).path.endswith("/files/B") -def test_write_after_cp_file_onto_a_found_file_replaces_the_one_reads_return( +def test_write_after_cp_file_onto_a_found_file_replaces_the_copy( mock_drive, ): found = {"id": "A", "name": "item", "mimeType": "text/plain"} drive, requests = mock_drive( listing(found), listing(dict(found, id="S", name="source")), + listing(found), response(dict(found, id="B")), - response(dict(found, parents=["RealRoot"])), + response(dict(found, trashed=True)), + response(dict(found, id="B", parents=["RealRoot"])), response({"id": "RealRoot"}), ) fs = filesystem(drive) @@ -2352,10 +2400,97 @@ def test_write_after_cp_file_onto_a_found_file_replaces_the_one_reads_return( fs.pipe_file("root/item", b"new") + # The copy, the trash of the old file, then the write to the copy. assert [ (method, urlsplit(uri).path.rsplit("/", 1)[-1]) for uri, method, *_ in requests[3:] - ] == [("PATCH", "A"), ("GET", "root")] + ] == [ + ("POST", "copy"), + ("PATCH", "A"), + ("PATCH", "B"), + ("GET", "root"), + ] + + +def sent(requests): + return [ + (method, urlsplit(uri).path.rsplit("/", 1)[-1]) + for uri, method, *_ in requests + ] + + +def test_write_after_cp_file_replaced_the_lower_of_two_files_updates_the_other( + mock_drive, +): + first = {"id": "A", "name": "item", "mimeType": "text/plain"} + second = dict(first, id="B") + drive, requests = mock_drive( + listing(first, second), + listing(dict(first, id="S", name="source")), + listing(first, second), + response(dict(first, id="C")), + response(dict(first, trashed=True)), + response(dict(second, parents=["RealRoot"])), + response({"id": "RealRoot"}), + ) + fs = filesystem(drive) + assert fs.exists("root/item") + fs.cp_file("root/source", "root/item") + + fs.pipe_file("root/item", b"new") + + # Reads return B, the lowest ID left at the path, so the write goes there. + assert sent(requests[3:]) == [ + ("POST", "copy"), + ("PATCH", "A"), + ("PATCH", "B"), + ("GET", "root"), + ] + + +def test_write_after_cp_file_failed_to_trash_the_old_file_updates_the_lower_copy( + mock_drive, +): + found = {"id": "B", "name": "item", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(found), + listing(dict(found, id="S", name="source")), + listing(found), + response(dict(found, id="A")), + error_response(403, "insufficientFilePermissions"), + response(dict(found, id="A", parents=["RealRoot"])), + response({"id": "RealRoot"}), + ) + fs = filesystem(drive) + assert fs.exists("root/item") + with pytest.raises(ApiRequestError): + fs.cp_file("root/source", "root/item") + + fs.pipe_file("root/item", b"new") + + assert sent(requests[5:]) == [("PATCH", "A"), ("GET", "root")] + + +def test_write_after_mv_failed_to_trash_the_old_target_creates_a_file_at_the_source( + mock_drive, +): + target = {"id": "A", "name": "dest", "mimeType": "text/plain"} + source = dict(target, id="S", name="source") + drive, requests = mock_drive( + listing(target), + listing(source), + response(dict(source, name="dest")), + error_response(403, "insufficientFilePermissions"), + response(dict(source, id="N")), + ) + fs = filesystem(drive) + with pytest.raises(ApiRequestError): + fs.mv("root/source", "root/dest") + + fs.pipe_file("root/source", b"new") + + # The moved file is no longer known at its old path. + assert sent(requests[4:]) == [("POST", "files")] def test_write_after_10000_writes_to_other_paths_creates_a_second_file(