From 417ae10f0475092df434333cfee276c173e6e68b Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 18:46:24 -0800 Subject: [PATCH 1/9] Test that recursive get and copy skip a lookup per listed file Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_fs.py | 146 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..b926975f 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -13,6 +13,7 @@ from googleapiclient.http import HttpRequest from pydrive2.drive import GoogleDrive +from pydrive2.files import FOLDER_MIME_TYPE from pydrive2.fs import GDriveFileSystem from pydrive2.test.test_util import ( GDRIVE_USER_CREDENTIALS_DATA, @@ -524,6 +525,151 @@ def test_recursive_get_downloads_a_folder_addressed_by_its_id( assert (target / "a.txt").read_bytes() == b"a" +def add_item(drive, name, parent, content=None): + """Create a file with this content, or a folder, as another client can.""" + metadata = {"name": name, "parents": [parent]} + if content is None: + metadata["mimeType"] = FOLDER_MIME_TYPE + item = drive.CreateFile(metadata) + if content is not None: + item.SetContentString(content) + pydrive_retry(item.Upload) + return item["id"] + + +@pytest.fixture(scope="module") +def listed_tree(fs_factory, base_remote_dir): + """A folder with a file, a subfolder and two files of one name.""" + fs, base_item = fs_factory() + name = uuid.uuid4().hex + folder = add_item(fs.client, name, base_item["id"]) + add_item(fs.client, "a.txt", folder, "a") + add_item(fs.client, "b.txt", add_item(fs.client, "nested", folder), "b") + add_item(fs.client, "same.txt", folder, "first") + add_item(fs.client, "same.txt", folder, "second") + return f"{base_remote_dir}/{name}" + + +@pytest.fixture +def answered_requests(service_auth, monkeypatch): + """The method and URL of every request of this thread that Drive did. + + A request that Drive refused, for example with a rate limit, and that + the filesystem then repeated, counts once. + """ + http = service_auth.Get_Http_Object() + send = http.request + answered = [] + + def request(uri, method="GET", **kwargs): + response, content = send(uri, method, **kwargs) + if response.status < 400: + answered.append((method, uri)) + return response, content + + monkeypatch.setattr(http, "request", request) + monkeypatch.setattr(service_auth.thread_local, "http", http, raising=False) + return answered + + +def downloads(requests): + return [ + uri + for _, uri in requests + if dict(parse_qsl(urlsplit(uri).query)).get("alt") == "media" + ] + + +def test_recursive_get_after_making_a_tree_sends_only_its_listing_and_downloads( + fs_factory, listed_tree, tmp_path, answered_requests +): + target = tmp_path / "target" + lister, _ = fs_factory() + lister.find(listed_tree, withdirs=True) + listing = len(answered_requests) + answered_requests.clear() + + getter, _ = fs_factory() + getter.get(listed_tree, str(target), recursive=True) + + assert len(downloads(answered_requests)) == 3 + assert len(answered_requests) == listing + 3 + assert (target / "a.txt").read_bytes() == b"a" + assert (target / "nested" / "b.txt").read_bytes() == b"b" + same = getter.cat_file(listed_tree + "/same.txt") + assert (target / "same.txt").read_bytes() == same + + +def test_recursive_copy_after_making_a_tree_searches_for_no_file_name( + fs, listed_tree, answered_requests +): + target = listed_tree + "-copy" + + fs.copy(listed_tree, target, recursive=True) + + queries = [ + dict(parse_qsl(urlsplit(uri).query)).get("q", "") + for _, uri in answered_requests + ] + names = ("'a.txt'", "'b.txt'", "'same.txt'") + assert [q for q in queries if any(name in q for name in names)] == [] + paths = [urlsplit(uri).path for _, uri in answered_requests] + assert len([path for path in paths if path.endswith("/copy")]) == 3 + assert fs.cat_file(target + "/a.txt") == b"a" + assert fs.cat_file(target + "/nested/b.txt") == b"b" + same = fs.cat_file(listed_tree + "/same.txt") + assert fs.cat_file(target + "/same.txt") == same + + +def test_get_file_after_a_recursive_get_looks_the_path_up_again( + fs, listed_tree, tmp_path, answered_requests +): + fs.get(listed_tree, str(tmp_path / "target"), recursive=True) + answered_requests.clear() + + fs.get_file(listed_tree + "/a.txt", str(tmp_path / "again.txt")) + + assert len(answered_requests) == 2 + assert len(downloads(answered_requests)) == 1 + + +class RemoveBeforeTransfer(fsspec.Callback): + """Remove a file through another filesystem just before its transfer.""" + + def __init__(self, path, other): + super().__init__() + self.path = path + self.other = other + + def branched(self, path_1, path_2, **kwargs): + if path_1 == self.path: + self.other.rm_file(path_1) + return fsspec.Callback() + + +def test_recursive_get_after_another_client_deletes_a_listed_file_raises( + fs_factory, base_remote_dir, tmp_path +): + fs, base_item = fs_factory() + name = uuid.uuid4().hex + add_item( + fs.client, "a.txt", add_item(fs.client, name, base_item["id"]), "a" + ) + source = f"{base_remote_dir}/{name}" + other = GDriveFileSystem( + base_remote_dir, + fs.client.auth, + trash_only=False, + skip_instance_cache=True, + ) + removal = RemoveBeforeTransfer(source + "/a.txt", other) + + with pytest.raises(FileNotFoundError): + fs.get( + source, str(tmp_path / "target"), recursive=True, callback=removal + ) + + def test_get_file_callback(fs, tmpdir, remote_dir): src_file = tmpdir / "a.txt" dest_file = tmpdir / "b.txt" From 4651fa3b4ceb84830388326b623539b58e4f70a3 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 18:46:25 -0800 Subject: [PATCH 2/9] Get and copy listed files by their listed IDs A recursive get or copy listed the tree and then looked every file up by name again: 2,007 requests for 1,000 files where 1,006 do. The IDs the listing returns are kept on the calling thread until the call returns. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 8 ++++++ pydrive2/fs/spec.py | 46 ++++++++++++++++++++++++++++++++--- pydrive2/test/test_fs_unit.py | 7 +++--- 3 files changed, 54 insertions(+), 7 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..0426edd3 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -99,6 +99,14 @@ Only folder IDs are cached between calls. Both ``ls()`` and ``find()`` build their results in memory, so larger listings use more memory during the call. +A recursive ``get()`` or ``copy()``, or one given a glob, downloads or +copies each file by the Drive ID its listing returned, without looking +the file up again. The IDs take about 150 bytes per file and are dropped +when the call returns. If another client trashes a listed file or puts a +new file at its path during the call, the call still reads the listed +file, because Drive serves a trashed file by its ID. A listed file deleted +for good raises ``FileNotFoundError``. + Trashed items ------------- diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index dfac751e..949f64d2 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -229,6 +229,13 @@ def _select_item_id(path, ids): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path) +def _remember_id(ids, path, item_id, is_folder): + """Keep the lowest ID at a path, as a lookup of the path would.""" + known = ids.get(path) + if known is None or item_id < known[0]: + ids[path] = (item_id, is_folder) + + class GDriveAuthError(AuthError): pass @@ -608,6 +615,7 @@ def __init__( self._root_lock = threading.RLock() self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() + self._listed = threading.local() self._forget_new_ids() if not google_auth: @@ -869,7 +877,12 @@ def _get_item_id(self, path, create=False): def _lookup_item(self, path): """Return the ID at a path and whether it is a folder.""" - _, base = self._split_mounted_path(path) + root, base = self._split_mounted_path(path) + listed = getattr(self._listed, "ids", None) + if listed and base: + known = listed.get(posixpath.join(root, base).rstrip("/")) + if known is not None: + return known match, _ = self._lookup_path(base) item_id = _select_item_id(path, match.ids) if base or self.root in _ROOT_ALIASES: @@ -1165,6 +1178,10 @@ def find( resolver = self._resolver() match = resolver.resolve(base, folders_only=not (withdirs and detail)) start = posixpath.join(root, base).rstrip("/") + listed = getattr(self._listed, "ids", None) + if listed is not None and base and match: + item_id = min(match.ids) + _remember_id(listed, start, item_id, item_id in match.folders) check_empty_root = False if not base and root not in _ROOT_ALIASES: if self._root_metadata.get("mimeType") == FOLDER_MIME_TYPE: @@ -1196,11 +1213,13 @@ def find( check_empty_root = False preferred = _preferred_ids(children, withdirs) if detail else {} for item in _drain(children): + name = posixpath.join(parent, item.name) + if listed is not None: + _remember_id(listed, name, item.id, item.is_folder) if item.is_folder and not withdirs: continue if preferred and item.id != preferred.get(item.name, item.id): continue - name = posixpath.join(parent, item.name) contents.append(item.entry(name, detail)) if check_empty_root: @@ -1215,6 +1234,26 @@ def find( contents.sort() return contents + @contextmanager + def _remember_listed_ids(self): + """Keep the IDs that listings return on this thread until the end.""" + outer = getattr(self._listed, "ids", None) + self._listed.ids = {} if outer is None else outer + try: + yield + finally: + self._listed.ids = outer + + def get(self, *args, **kwargs): + # Each listed file is downloaded by its listed ID, without a lookup. + with self._remember_listed_ids(): + return super().get(*args, **kwargs) + + def copy(self, *args, **kwargs): + # Each listed file is copied by its listed ID, without a lookup. + with self._remember_listed_ids(): + return super().copy(*args, **kwargs) + def upload_fobj(self, stream, rpath, callback=None, **kwargs): parent, name = self._split_file_path(rpath) parent_id = self._get_item_id(parent, create=True) @@ -1254,7 +1293,8 @@ def cp_file(self, lpath, rpath, **kwargs): return parent, name = self._split_file_path(rpath) parent_id = self._get_item_id(parent, create=True) - self._gdrive_copy_file(source_id, parent_id, name) + with _translate_not_found(lpath): + self._gdrive_copy_file(source_id, parent_id, name) self._dirs.file_added(parent_id, name) def _gdrive_copy_file(self, source_id, parent_id, name): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..a930e045 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -2978,18 +2978,17 @@ def send(request): assert (progress.size, progress.value) == (size, size) -def test_recursive_get_makes_one_lookup_and_one_download_per_file( +def test_recursive_get_makes_one_download_per_file_and_no_lookup( mock_drive, tmp_path ): drive, requests = mock_drive( listing(folder("source", "S")), listing(TEXT_FILE), - listing(TEXT_FILE), DOWNLOAD, ) filesystem(drive).get("root/source", str(tmp_path / "out"), recursive=True) assert (tmp_path / "out" / "a.txt").read_bytes() == b"data" - assert len(requests) == 4 + assert len(requests) == 3 def test_recursive_put_uploads_files_and_creates_empty_folders( @@ -3020,10 +3019,10 @@ def test_recursive_copy_puts_the_contents_of_a_folder_into_the_root( listing(folder("source", "S")), listing(TEXT_FILE), response({"mimeType": FOLDER_MIME_TYPE}), - listing(TEXT_FILE), response({"id": "copy"}), ) filesystem(drive).copy("root/source/", "root", recursive=True) + assert len(requests) == 4 copy = requests[-1] assert urlsplit(copy[0]).path == "/drive/v3/files/A/copy" assert json.loads(copy[2]) == { From a4e60a4b866117f3966020ce3ef713abaa5628fd Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 20:06:19 -0800 Subject: [PATCH 3/9] Look the start path up as before and give each transfer its own IDs The start of a recursive call came from a folders-only lookup, so an older file of the same name could lose to the folder; its lookup is served from the folder cache anyway. A get or copy started from a callback now lists with its own IDs instead of the outer call's. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 5 +---- pydrive2/test/test_fs_unit.py | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 949f64d2..47851ea8 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1179,9 +1179,6 @@ def find( match = resolver.resolve(base, folders_only=not (withdirs and detail)) start = posixpath.join(root, base).rstrip("/") listed = getattr(self._listed, "ids", None) - if listed is not None and base and match: - item_id = min(match.ids) - _remember_id(listed, start, item_id, item_id in match.folders) check_empty_root = False if not base and root not in _ROOT_ALIASES: if self._root_metadata.get("mimeType") == FOLDER_MIME_TYPE: @@ -1238,7 +1235,7 @@ def find( def _remember_listed_ids(self): """Keep the IDs that listings return on this thread until the end.""" outer = getattr(self._listed, "ids", None) - self._listed.ids = {} if outer is None else outer + self._listed.ids = {} try: yield finally: diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index a930e045..270f9820 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -2991,6 +2991,48 @@ def test_recursive_get_makes_one_download_per_file_and_no_lookup( assert len(requests) == 3 +class GetAgainBeforeTransfer(Callback): + """Start another recursive get of the same folder before one file.""" + + def __init__(self, fs, path, source, target): + super().__init__() + self.fs = fs + self.path = path + self.source = source + self.target = target + + def branched(self, path_1, path_2, **kwargs): + if path_1 == self.path: + self.fs.get(self.source, self.target, recursive=True) + return Callback() + + +def test_nested_get_after_the_file_was_replaced_downloads_the_new_file( + mock_drive, tmp_path +): + replaced = dict(TEXT_FILE, id="B") + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE), + listing(replaced), + ({"status": "200"}, b"new"), + DOWNLOAD, + ) + fs = filesystem(drive) + nested = GetAgainBeforeTransfer( + fs, "root/source/a.txt", "root/source", str(tmp_path / "nested") + ) + + fs.get( + "root/source", str(tmp_path / "out"), recursive=True, callback=nested + ) + + assert (tmp_path / "nested" / "a.txt").read_bytes() == b"new" + assert (tmp_path / "out" / "a.txt").read_bytes() == b"data" + downloads = [urlsplit(uri).path for uri, *_ in requests[-2:]] + assert downloads == ["/drive/v3/files/B", "/drive/v3/files/A"] + + def test_recursive_put_uploads_files_and_creates_empty_folders( mock_drive, tmp_path ): From b51b634afb1428230102aef3b2bca40d56a6d549 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 20:54:39 -0800 Subject: [PATCH 4/9] Leave names with a slash to the lookup and test the copy 404 A lookup splits paths at slashes, so it cannot reach a Drive name such as "../escaped.txt" or anything below a folder named "x/y". Remembering those let a recursive get or copy reach them by ID, and an older fsspec then wrote "../escaped.txt" above the target. They now go through the lookup as before. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 9 +++++++- pydrive2/test/test_fs.py | 17 ++++++++++++++ pydrive2/test/test_fs_unit.py | 42 +++++++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 1 deletion(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 47851ea8..4da5d071 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1203,6 +1203,7 @@ def find( entry = file.entry(start) contents.append(entry) fields = _LIST_FIELDS if detail else _NAME_FIELDS + unreachable: set[str] = set() for parent, children in self._walk_folders( start, match.folders, resolver.generation, maxdepth, fields ): @@ -1211,7 +1212,13 @@ def find( preferred = _preferred_ids(children, withdirs) if detail else {} for item in _drain(children): name = posixpath.join(parent, item.name) - if listed is not None: + if listed is None: + pass + elif parent in unreachable or "/" in item.name: + # A lookup splits paths at slashes and cannot reach it. + if item.is_folder: + unreachable.add(name) + else: _remember_id(listed, name, item.id, item.is_folder) if item.is_folder and not withdirs: continue diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index b926975f..c49c94ec 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -633,6 +633,23 @@ def test_get_file_after_a_recursive_get_looks_the_path_up_again( assert len(downloads(answered_requests)) == 1 +def test_recursive_copy_after_making_names_with_slashes_copies_what_a_lookup_finds( + fs_factory, base_remote_dir +): + fs, base_item = fs_factory() + name = uuid.uuid4().hex + folder = add_item(fs.client, name, base_item["id"]) + add_item(fs.client, "a.txt", folder, "a") + add_item(fs.client, "../escaped.txt", folder, "escaped") + add_item(fs.client, "c.txt", add_item(fs.client, "x/y", folder), "c") + source = f"{base_remote_dir}/{name}" + target = source + "-copy" + + fs.copy(source, target, recursive=True) + + assert fs.find(target) == [target + "/a.txt"] + + class RemoveBeforeTransfer(fsspec.Callback): """Remove a file through another filesystem just before its transfer.""" diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 270f9820..fd072dd4 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -2991,6 +2991,48 @@ def test_recursive_get_makes_one_download_per_file_and_no_lookup( assert len(requests) == 3 +def test_recursive_get_after_listing_a_name_with_a_slash_looks_it_up( + mock_drive, tmp_path +): + slashed = dict(TEXT_FILE, name="a/b.txt", id="E") + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(slashed), + listing(), + ) + with pytest.raises(FileNotFoundError): + filesystem(drive).get( + "root/source", str(tmp_path / "out"), recursive=True + ) + assert "name='a'" in query(requests[-1])["q"][0] + + +def test_cp_file_after_the_source_is_deleted_raises_file_not_found(mock_drive): + drive, requests = mock_drive( + listing(TEXT_FILE), + error_response(404, "notFound"), + ) + with pytest.raises(FileNotFoundError): + filesystem(drive).cp_file("root/a.txt", "root/b.txt") + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/A/copy" + + +def test_recursive_copy_after_a_listed_file_is_deleted_copies_the_rest( + mock_drive, +): + second = dict(TEXT_FILE, name="b.txt", id="B") + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE, second), + response({"mimeType": FOLDER_MIME_TYPE}), + error_response(404, "notFound"), + response({"id": "copy"}), + ) + filesystem(drive).copy("root/source/", "root", recursive=True) + copies = [urlsplit(uri).path for uri, *_ in requests[-2:]] + assert copies == ["/drive/v3/files/A/copy", "/drive/v3/files/B/copy"] + + class GetAgainBeforeTransfer(Callback): """Start another recursive get of the same folder before one file.""" From 52f7cd899b8193750f7b05cb0879c1948d3ba357 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 21:51:09 -0800 Subject: [PATCH 5/9] Skip a copied file only when its source is gone A 404 on the copy request also comes when the destination folder was removed. Main raised Drive's error then, and a recursive copy would now have skipped the file. On a 404 the source is checked by ID, and only a missing source becomes FileNotFoundError. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 19 ++++++++++++++++++- pydrive2/test/test_fs_unit.py | 28 +++++++++++++++++++++++++--- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 4da5d071..a177eed5 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1297,10 +1297,27 @@ def cp_file(self, lpath, rpath, **kwargs): return parent, name = self._split_file_path(rpath) parent_id = self._get_item_id(parent, create=True) - with _translate_not_found(lpath): + try: self._gdrive_copy_file(source_id, parent_id, name) + except ApiRequestError as exc: + # A missing destination folder is also a 404 on the copy. + if _is_not_found(exc) and not self._gdrive_exists(source_id): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), lpath + ) from exc + raise self._dirs.file_added(parent_id, name) + def _gdrive_exists(self, item_id): + item = self.client.CreateFile({"id": item_id}) + try: + _gdrive_retry_repeatable(item.FetchMetadata)(fields="id") + except ApiRequestError as exc: + if _is_not_found(exc): + return False + raise + return True + def _gdrive_copy_file(self, source_id, parent_id, name): source = self.client.CreateFile({"id": source_id}) self._gdrive_create( diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index fd072dd4..050217c8 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -3011,10 +3011,27 @@ def test_cp_file_after_the_source_is_deleted_raises_file_not_found(mock_drive): drive, requests = mock_drive( listing(TEXT_FILE), error_response(404, "notFound"), + error_response(404, "notFound"), ) with pytest.raises(FileNotFoundError): filesystem(drive).cp_file("root/a.txt", "root/b.txt") - assert urlsplit(requests[-1][0]).path == "/drive/v3/files/A/copy" + copy, check = (urlsplit(uri).path for uri, *_ in requests[-2:]) + assert (copy, check) == ("/drive/v3/files/A/copy", "/drive/v3/files/A") + + +def test_cp_file_after_the_destination_folder_is_deleted_raises_drive_error( + mock_drive, +): + drive, requests = mock_drive( + listing(TEXT_FILE), + error_response(404, "notFound"), + response({"id": "A"}), + ) + with pytest.raises(ApiRequestError) as error: + filesystem(drive).cp_file("root/a.txt", "root/b.txt") + assert not isinstance(error.value, FileNotFoundError) + assert error.value.error["code"] == 404 + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/A" def test_recursive_copy_after_a_listed_file_is_deleted_copies_the_rest( @@ -3026,11 +3043,16 @@ def test_recursive_copy_after_a_listed_file_is_deleted_copies_the_rest( listing(TEXT_FILE, second), response({"mimeType": FOLDER_MIME_TYPE}), error_response(404, "notFound"), + error_response(404, "notFound"), response({"id": "copy"}), ) filesystem(drive).copy("root/source/", "root", recursive=True) - copies = [urlsplit(uri).path for uri, *_ in requests[-2:]] - assert copies == ["/drive/v3/files/A/copy", "/drive/v3/files/B/copy"] + paths = [urlsplit(uri).path for uri, *_ in requests[-3:]] + assert paths == [ + "/drive/v3/files/A/copy", + "/drive/v3/files/A", + "/drive/v3/files/B/copy", + ] class GetAgainBeforeTransfer(Callback): From b6627380e35ade3cb71544939512d8701666d8f5 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 22:33:50 -0800 Subject: [PATCH 6/9] Say that a recursive copy skips a deleted file by default Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 0426edd3..22193ffa 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -105,7 +105,9 @@ the file up again. The IDs take about 150 bytes per file and are dropped when the call returns. If another client trashes a listed file or puts a new file at its path during the call, the call still reads the listed file, because Drive serves a trashed file by its ID. A listed file deleted -for good raises ``FileNotFoundError``. +for good makes ``get()`` raise ``FileNotFoundError``. A recursive +``copy()`` skips it, because fsspec ignores missing files there unless +``on_error="raise"`` is passed. Trashed items ------------- From 9e85e42ea18f4cf0123625ab81a91842ef8ffab5 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 6 Dec 2026 09:46:17 -0800 Subject: [PATCH 7/9] Keep listed IDs in a per-call view instead of on the thread get() and copy() run fsspec's code against a view that records what its own listings return. The view answers the isdir() filter, get_file() and cp_file() from that record, so a glob sends no lookup per match. Callbacks reach the filesystem itself and look paths up again. A listed item with several parents turns the record off, because a listing of several folders places it under only one. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 4 +- pydrive2/fs/spec.py | 112 ++++++++++++++++++++++------------ pydrive2/test/test_fs.py | 19 ++++-- pydrive2/test/test_fs_unit.py | 67 +++++++++++++++++--- 4 files changed, 145 insertions(+), 57 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 22193ffa..9bac1030 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -107,7 +107,9 @@ new file at its path during the call, the call still reads the listed file, because Drive serves a trashed file by its ID. A listed file deleted for good makes ``get()`` raise ``FileNotFoundError``. A recursive ``copy()`` skips it, because fsspec ignores missing files there unless -``on_error="raise"`` is passed. +``on_error="raise"`` is passed. If the listing finds an item with more +than one parent folder, which older Drive files can have, the call looks +each file up by its path instead. Trashed items ------------- diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index a177eed5..1a895f06 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -229,11 +229,62 @@ def _select_item_id(path, ids): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path) -def _remember_id(ids, path, item_id, is_folder): - """Keep the lowest ID at a path, as a lookup of the path would.""" - known = ids.get(path) - if known is None or item_id < known[0]: - ids[path] = (item_id, is_folder) +class _ListedTransfer: + """Run one fsspec get() or copy() by the IDs that its own listings return. + + Callbacks still get the filesystem, so their calls look paths up again. + """ + + def __init__(self, fs): + self._fs = fs + self._ids: dict[str, tuple[str, bool]] | None = {} + self._unreachable: set[str] = set() + + def __getattr__(self, name): + return getattr(self._fs, name) + + # fsspec expands paths with these, and they must call find() on this object. + def expand_path(self, *args, **kwargs): + return AbstractFileSystem.expand_path(self, *args, **kwargs) + + def glob(self, *args, **kwargs): + return AbstractFileSystem.glob(self, *args, **kwargs) + + def find(self, *args, **kwargs): + return self._fs.find(*args, _transfer=self, **kwargs) + + def listed(self, parent, item): + """Keep the lowest ID at a path, as a lookup of the path would.""" + if self._ids is None: + return + if item.ambiguous: + # A listing of several folders places such an item under only one. + self._ids = None + return + path = posixpath.join(parent, item.name) + if parent in self._unreachable or "/" in item.name: + # A lookup splits paths at slashes and cannot reach it. + if item.is_folder: + self._unreachable.add(path) + return + known = self._ids.get(path) + if known is None or item.id < known[0]: + self._ids[path] = (item.id, item.is_folder) + + def _known(self, path): + return self._ids.get(path) if self._ids else None + + def isdir(self, path): + known = self._known(path) + return self._fs.isdir(path) if known is None else known[1] + + def get_file(self, rpath, lpath, **kwargs): + listed = self._known(rpath) + return self._fs.get_file(rpath, lpath, _listed=listed, **kwargs) + + def cp_file(self, path1, path2, **kwargs): + listed = self._known(path1) + return self._fs.cp_file(path1, path2, _listed=listed, **kwargs) class GDriveAuthError(AuthError): @@ -615,7 +666,6 @@ def __init__( self._root_lock = threading.RLock() self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() - self._listed = threading.local() self._forget_new_ids() if not google_auth: @@ -875,14 +925,11 @@ def _get_item_id(self, path, create=False): match, _ = self._lookup_path(base) return _select_item_id(path, match.ids) - def _lookup_item(self, path): + def _lookup_item(self, path, listed=None): """Return the ID at a path and whether it is a folder.""" - root, base = self._split_mounted_path(path) - listed = getattr(self._listed, "ids", None) - if listed and base: - known = listed.get(posixpath.join(root, base).rstrip("/")) - if known is not None: - return known + if listed is not None: + return listed + _, base = self._split_mounted_path(path) match, _ = self._lookup_path(base) item_id = _select_item_id(path, match.ids) if base or self.root in _ROOT_ALIASES: @@ -1178,7 +1225,7 @@ def find( resolver = self._resolver() match = resolver.resolve(base, folders_only=not (withdirs and detail)) start = posixpath.join(root, base).rstrip("/") - listed = getattr(self._listed, "ids", None) + transfer = kwargs.get("_transfer") check_empty_root = False if not base and root not in _ROOT_ALIASES: if self._root_metadata.get("mimeType") == FOLDER_MIME_TYPE: @@ -1203,7 +1250,6 @@ def find( entry = file.entry(start) contents.append(entry) fields = _LIST_FIELDS if detail else _NAME_FIELDS - unreachable: set[str] = set() for parent, children in self._walk_folders( start, match.folders, resolver.generation, maxdepth, fields ): @@ -1211,19 +1257,13 @@ def find( check_empty_root = False preferred = _preferred_ids(children, withdirs) if detail else {} for item in _drain(children): - name = posixpath.join(parent, item.name) - if listed is None: - pass - elif parent in unreachable or "/" in item.name: - # A lookup splits paths at slashes and cannot reach it. - if item.is_folder: - unreachable.add(name) - else: - _remember_id(listed, name, item.id, item.is_folder) + if transfer is not None: + transfer.listed(parent, item) if item.is_folder and not withdirs: continue if preferred and item.id != preferred.get(item.name, item.id): continue + name = posixpath.join(parent, item.name) contents.append(item.entry(name, detail)) if check_empty_root: @@ -1238,25 +1278,15 @@ def find( contents.sort() return contents - @contextmanager - def _remember_listed_ids(self): - """Keep the IDs that listings return on this thread until the end.""" - outer = getattr(self._listed, "ids", None) - self._listed.ids = {} - try: - yield - finally: - self._listed.ids = outer - + @wraps(AbstractFileSystem.get) def get(self, *args, **kwargs): # Each listed file is downloaded by its listed ID, without a lookup. - with self._remember_listed_ids(): - return super().get(*args, **kwargs) + return AbstractFileSystem.get(_ListedTransfer(self), *args, **kwargs) + @wraps(AbstractFileSystem.copy) def copy(self, *args, **kwargs): # Each listed file is copied by its listed ID, without a lookup. - with self._remember_listed_ids(): - return super().copy(*args, **kwargs) + return AbstractFileSystem.copy(_ListedTransfer(self), *args, **kwargs) def upload_fobj(self, stream, rpath, callback=None, **kwargs): parent, name = self._split_file_path(rpath) @@ -1291,7 +1321,7 @@ def send(new_id): def cp_file(self, lpath, rpath, **kwargs): """Ask Drive to copy the file directly into the destination folder.""" self._split_mounted_path(rpath) - source_id, is_folder = self._lookup_item(lpath) + source_id, is_folder = self._lookup_item(lpath, kwargs.get("_listed")) if is_folder: self.makedirs(rpath, exist_ok=True) return @@ -1408,7 +1438,9 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): with _translate_not_found(rpath): - item_id, is_folder = self._lookup_item(rpath) + item_id, is_folder = self._lookup_item( + rpath, kwargs.get("_listed") + ) if is_folder: os.makedirs(lpath, exist_ok=True) return None diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index c49c94ec..e0b657ef 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -621,16 +621,23 @@ def test_recursive_copy_after_making_a_tree_searches_for_no_file_name( assert fs.cat_file(target + "/same.txt") == same -def test_get_file_after_a_recursive_get_looks_the_path_up_again( - fs, listed_tree, tmp_path, answered_requests +def test_get_of_a_glob_after_making_a_tree_sends_only_its_listing_and_downloads( + fs_factory, listed_tree, tmp_path, answered_requests ): - fs.get(listed_tree, str(tmp_path / "target"), recursive=True) + target = tmp_path / "target" + lister, _ = fs_factory() + lister.glob(listed_tree + "/*.txt") + listing = len(answered_requests) answered_requests.clear() - fs.get_file(listed_tree + "/a.txt", str(tmp_path / "again.txt")) + getter, _ = fs_factory() + getter.get(listed_tree + "/*.txt", str(target)) - assert len(answered_requests) == 2 - assert len(downloads(answered_requests)) == 1 + assert len(downloads(answered_requests)) == 2 + assert len(answered_requests) == listing + 2 + assert (target / "a.txt").read_bytes() == b"a" + same = getter.cat_file(listed_tree + "/same.txt") + assert (target / "same.txt").read_bytes() == same def test_recursive_copy_after_making_names_with_slashes_copies_what_a_lookup_finds( diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 050217c8..de514ec2 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -3055,8 +3055,8 @@ def test_recursive_copy_after_a_listed_file_is_deleted_copies_the_rest( ] -class GetAgainBeforeTransfer(Callback): - """Start another recursive get of the same folder before one file.""" +class ListAndGetBeforeTransfer(Callback): + """List the folder and download one file through the filesystem first.""" def __init__(self, fs, path, source, target): super().__init__() @@ -3067,34 +3067,81 @@ def __init__(self, fs, path, source, target): def branched(self, path_1, path_2, **kwargs): if path_1 == self.path: - self.fs.get(self.source, self.target, recursive=True) + self.fs.find(self.source) + self.fs.get_file(self.path, self.target) return Callback() -def test_nested_get_after_the_file_was_replaced_downloads_the_new_file( +def test_recursive_get_after_a_callback_lists_a_replaced_file_keeps_the_listed_id( mock_drive, tmp_path ): + listed = dict(TEXT_FILE, id="Z") replaced = dict(TEXT_FILE, id="B") drive, requests = mock_drive( listing(folder("source", "S")), - listing(TEXT_FILE), + listing(listed), + listing(replaced), listing(replaced), ({"status": "200"}, b"new"), DOWNLOAD, ) fs = filesystem(drive) - nested = GetAgainBeforeTransfer( - fs, "root/source/a.txt", "root/source", str(tmp_path / "nested") + callback = ListAndGetBeforeTransfer( + fs, "root/source/a.txt", "root/source", str(tmp_path / "new.txt") ) fs.get( - "root/source", str(tmp_path / "out"), recursive=True, callback=nested + "root/source", str(tmp_path / "out"), recursive=True, callback=callback ) - assert (tmp_path / "nested" / "a.txt").read_bytes() == b"new" + assert (tmp_path / "new.txt").read_bytes() == b"new" assert (tmp_path / "out" / "a.txt").read_bytes() == b"data" + assert "name='a.txt'" in query(requests[3])["q"][0] downloads = [urlsplit(uri).path for uri, *_ in requests[-2:]] - assert downloads == ["/drive/v3/files/B", "/drive/v3/files/A"] + assert downloads == ["/drive/v3/files/B", "/drive/v3/files/Z"] + + +def test_get_file_after_a_recursive_get_looks_the_path_up_again( + mock_drive, tmp_path +): + replaced = dict(TEXT_FILE, id="B") + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE), + DOWNLOAD, + listing(replaced), + ({"status": "200"}, b"new"), + ) + fs = filesystem(drive) + fs.get("root/source", str(tmp_path / "out"), recursive=True) + + fs.get_file("root/source/a.txt", str(tmp_path / "again.txt")) + + assert (tmp_path / "again.txt").read_bytes() == b"new" + assert "name='a.txt'" in query(requests[-2])["q"][0] + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/B" + + +def test_recursive_get_after_listing_a_file_with_two_parents_looks_it_up( + mock_drive, tmp_path +): + shared = dict(TEXT_FILE, parents=["P", "Q"]) + other = dict(TEXT_FILE, id="Z", parents=["Q"]) + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(folder("p", "P"), folder("q", "Q")), + listing(shared, other), + listing(shared), + DOWNLOAD, + listing(shared, other), + DOWNLOAD, + ) + + filesystem(drive).get("root/source", str(tmp_path / "out"), recursive=True) + + assert (tmp_path / "out" / "q" / "a.txt").read_bytes() == b"data" + paths = [urlsplit(uri).path for uri, *_ in requests] + assert paths[4] == paths[6] == "/drive/v3/files/A" def test_recursive_put_uploads_files_and_creates_empty_folders( From bb491ccff07920d8586e2f29d99dbc33cc2b0e3c Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 6 Dec 2026 10:02:43 -0800 Subject: [PATCH 8/9] Keep subclass hooks and the copy destination check A subclass that overrides a hook the transfer replaces keeps fsspec's own transfer. The copy destination is checked as before, the ID hint goes through private helpers after the path is validated, and the listing and the record share each path string. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 2 +- pydrive2/fs/spec.py | 70 ++++++++++++++++++++++++----------- pydrive2/test/test_fs_unit.py | 49 ++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 22 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 9bac1030..a0afd66b 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -101,7 +101,7 @@ the call. A recursive ``get()`` or ``copy()``, or one given a glob, downloads or copies each file by the Drive ID its listing returned, without looking -the file up again. The IDs take about 150 bytes per file and are dropped +the file up again. The IDs take about 160 bytes per file and are dropped when the call returns. If another client trashes a listed file or puts a new file at its path during the call, the call still reads the listed file, because Drive serves a trashed file by its ID. A listed file deleted diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 1a895f06..ff42e8ab 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -235,8 +235,9 @@ class _ListedTransfer: Callbacks still get the filesystem, so their calls look paths up again. """ - def __init__(self, fs): + def __init__(self, fs, destination=None): self._fs = fs + self._destination = destination self._ids: dict[str, tuple[str, bool]] | None = {} self._unreachable: set[str] = set() @@ -250,10 +251,12 @@ def expand_path(self, *args, **kwargs): def glob(self, *args, **kwargs): return AbstractFileSystem.glob(self, *args, **kwargs) - def find(self, *args, **kwargs): - return self._fs.find(*args, _transfer=self, **kwargs) + def find( + self, path, maxdepth=None, withdirs=False, detail=False, **kwargs + ): + return self._fs._find(path, maxdepth, withdirs, detail, self) - def listed(self, parent, item): + def listed(self, parent, path, item): """Keep the lowest ID at a path, as a lookup of the path would.""" if self._ids is None: return @@ -261,7 +264,6 @@ def listed(self, parent, item): # A listing of several folders places such an item under only one. self._ids = None return - path = posixpath.join(parent, item.name) if parent in self._unreachable or "/" in item.name: # A lookup splits paths at slashes and cannot reach it. if item.is_folder: @@ -275,16 +277,27 @@ def _known(self, path): return self._ids.get(path) if self._ids else None def isdir(self, path): - known = self._known(path) + # fsspec places a copy by the destination's current type. + known = None if path == self._destination else self._known(path) return self._fs.isdir(path) if known is None else known[1] - def get_file(self, rpath, lpath, **kwargs): + def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): listed = self._known(rpath) - return self._fs.get_file(rpath, lpath, _listed=listed, **kwargs) + return self._fs._get_file(rpath, lpath, listed, callback, block_size) def cp_file(self, path1, path2, **kwargs): - listed = self._known(path1) - return self._fs.cp_file(path1, path2, _listed=listed, **kwargs) + return self._fs._cp_file(path1, path2, self._known(path1)) + + +# A subclass that changes one of these keeps fsspec's own transfer. +_TRANSFER_HOOKS = ( + "expand_path", + "glob", + "find", + "isdir", + "get_file", + "cp_file", +) class GDriveAuthError(AuthError): @@ -927,9 +940,9 @@ def _get_item_id(self, path, create=False): def _lookup_item(self, path, listed=None): """Return the ID at a path and whether it is a folder.""" + _, base = self._split_mounted_path(path) if listed is not None: return listed - _, base = self._split_mounted_path(path) match, _ = self._lookup_path(base) item_id = _select_item_id(path, match.ids) if base or self.root in _ROOT_ALIASES: @@ -1219,13 +1232,15 @@ def find( ) detail = detail or maxdepth maxdepth = None + return self._find(path, maxdepth, withdirs, detail) + + def _find(self, path, maxdepth, withdirs, detail, transfer=None): root, base = self._split_mounted_path(path) if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") resolver = self._resolver() match = resolver.resolve(base, folders_only=not (withdirs and detail)) start = posixpath.join(root, base).rstrip("/") - transfer = kwargs.get("_transfer") check_empty_root = False if not base and root not in _ROOT_ALIASES: if self._root_metadata.get("mimeType") == FOLDER_MIME_TYPE: @@ -1257,13 +1272,13 @@ def find( check_empty_root = False preferred = _preferred_ids(children, withdirs) if detail else {} for item in _drain(children): + name = posixpath.join(parent, item.name) if transfer is not None: - transfer.listed(parent, item) + transfer.listed(parent, name, item) if item.is_folder and not withdirs: continue if preferred and item.id != preferred.get(item.name, item.id): continue - name = posixpath.join(parent, item.name) contents.append(item.entry(name, detail)) if check_empty_root: @@ -1278,15 +1293,24 @@ def find( contents.sort() return contents + def _transfer(self, destination=None): + """Return the object that fsspec's get() or copy() should run on.""" + cls = type(self) + for name in _TRANSFER_HOOKS: + if getattr(cls, name) is not getattr(GDriveFileSystem, name): + return self + return _ListedTransfer(self, destination) + @wraps(AbstractFileSystem.get) def get(self, *args, **kwargs): # Each listed file is downloaded by its listed ID, without a lookup. - return AbstractFileSystem.get(_ListedTransfer(self), *args, **kwargs) + return AbstractFileSystem.get(self._transfer(), *args, **kwargs) @wraps(AbstractFileSystem.copy) - def copy(self, *args, **kwargs): + def copy(self, path1, path2, *args, **kwargs): # Each listed file is copied by its listed ID, without a lookup. - return AbstractFileSystem.copy(_ListedTransfer(self), *args, **kwargs) + transfer = self._transfer(destination=path2) + return AbstractFileSystem.copy(transfer, path1, path2, *args, **kwargs) def upload_fobj(self, stream, rpath, callback=None, **kwargs): parent, name = self._split_file_path(rpath) @@ -1320,8 +1344,11 @@ def send(new_id): def cp_file(self, lpath, rpath, **kwargs): """Ask Drive to copy the file directly into the destination folder.""" + self._cp_file(lpath, rpath) + + def _cp_file(self, lpath, rpath, listed=None): self._split_mounted_path(rpath) - source_id, is_folder = self._lookup_item(lpath, kwargs.get("_listed")) + source_id, is_folder = self._lookup_item(lpath, listed) if is_folder: self.makedirs(rpath, exist_ok=True) return @@ -1437,10 +1464,11 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): ) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): + return self._get_file(rpath, lpath, None, callback, block_size) + + def _get_file(self, rpath, lpath, listed, callback, block_size): with _translate_not_found(rpath): - item_id, is_folder = self._lookup_item( - rpath, kwargs.get("_listed") - ) + item_id, is_folder = self._lookup_item(rpath, listed) if is_folder: os.makedirs(lpath, exist_ok=True) return None diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index de514ec2..7c4288cc 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -3144,6 +3144,55 @@ def test_recursive_get_after_listing_a_file_with_two_parents_looks_it_up( assert paths[4] == paths[6] == "/drive/v3/files/A" +def test_recursive_copy_after_a_listed_destination_file_became_a_folder_copies_into_it( + mock_drive, +): + listed = {"name": "out", "id": "O", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(listed), + listing(folder("out", "D")), + response(folder("out", "D")), + listing(), + response({"id": "new-1"}), + response({"id": "new-2"}), + ) + + filesystem(drive).copy("root/source", "root/source/out", recursive=True) + + created, copied = (json.loads(body) for _, _, body, *_ in requests[-2:]) + assert (created["name"], created["parents"]) == ("source", ["D"]) + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/O/copy" + assert copied["parents"] == [created["id"]] + + +class CsvOnlyFileSystem(GDriveFileSystem): + def glob(self, path, **kwargs): + matches = super().glob(path, **kwargs) + return [match for match in matches if match.endswith(".csv")] + + +def test_get_after_a_subclass_changes_glob_downloads_only_its_matches( + mock_drive, tmp_path +): + csv = {"name": "a.csv", "id": "A", "mimeType": "text/csv"} + text = {"name": "b.txt", "id": "B", "mimeType": "text/plain"} + drive, _ = mock_drive( + listing(csv, text), + listing(csv), + response(dict(csv, size="4")), + listing(csv), + DOWNLOAD, + ) + fs = CsvOnlyFileSystem( + "root", google_auth=drive.auth, skip_instance_cache=True + ) + + fs.get("root/*", str(tmp_path / "out")) + + assert [path.name for path in (tmp_path / "out").iterdir()] == ["a.csv"] + + def test_recursive_put_uploads_files_and_creates_empty_folders( mock_drive, tmp_path ): From 28b55d2869d3539f76dd7139b7e987203f15233e Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 6 Dec 2026 11:16:02 -0800 Subject: [PATCH 9/9] Use listed IDs only for PyDrive2's own class and one source A subclass, a filesystem with a transfer method set on itself, or a list of sources keeps fsspec's own transfer. Only paths that the expansion returns keep their IDs, and the transfer's find() checks the depth type as the public one does. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 22 +++++++------- pydrive2/fs/spec.py | 45 +++++++++++++++------------- pydrive2/test/test_fs_unit.py | 55 +++++++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 32 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index a0afd66b..f4838ea8 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -99,17 +99,17 @@ Only folder IDs are cached between calls. Both ``ls()`` and ``find()`` build their results in memory, so larger listings use more memory during the call. -A recursive ``get()`` or ``copy()``, or one given a glob, downloads or -copies each file by the Drive ID its listing returned, without looking -the file up again. The IDs take about 160 bytes per file and are dropped -when the call returns. If another client trashes a listed file or puts a -new file at its path during the call, the call still reads the listed -file, because Drive serves a trashed file by its ID. A listed file deleted -for good makes ``get()`` raise ``FileNotFoundError``. A recursive -``copy()`` skips it, because fsspec ignores missing files there unless -``on_error="raise"`` is passed. If the listing finds an item with more -than one parent folder, which older Drive files can have, the call looks -each file up by its path instead. +A recursive ``get()`` or ``copy()`` of one path, or one given one glob, +downloads or copies each file by the Drive ID its listing returned, +without looking the file up again. The IDs take about 160 bytes per file +and are dropped when the call returns. If another client trashes a listed +file or puts a new file at its path during the call, the call still reads +the listed file, because Drive serves a trashed file by its ID. A listed +file deleted for good makes ``get()`` raise ``FileNotFoundError``. A +recursive ``copy()`` skips it, because fsspec ignores missing files there +unless ``on_error="raise"`` is passed. If the listing finds an item with +more than one parent folder, which older Drive files can have, the call +looks each file up by its path instead. Trashed items ------------- diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 4686c747..a72e44f1 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -245,7 +245,11 @@ def __getattr__(self, name): # fsspec expands paths with these, and they must call find() on this object. def expand_path(self, *args, **kwargs): - return AbstractFileSystem.expand_path(self, *args, **kwargs) + paths = AbstractFileSystem.expand_path(self, *args, **kwargs) + if self._ids: + # Only the paths that fsspec will transfer keep their listed IDs. + self._ids = {p: self._ids[p] for p in paths if p in self._ids} + return paths def glob(self, *args, **kwargs): return AbstractFileSystem.glob(self, *args, **kwargs) @@ -288,14 +292,9 @@ def cp_file(self, path1, path2, **kwargs): return self._fs._cp_file(path1, path2, self._known(path1)) -# A subclass that changes one of these keeps fsspec's own transfer. -_TRANSFER_HOOKS = ( - "expand_path", - "glob", - "find", - "isdir", - "get_file", - "cp_file", +# A filesystem that sets one of these on itself keeps fsspec's own transfer. +_TRANSFER_HOOKS = frozenset( + ("expand_path", "glob", "find", "isdir", "info", "get_file", "cp_file") ) @@ -1222,15 +1221,15 @@ def _walk_folders(self, start, start_ids, generation, maxdepth, fields): def find( self, path, maxdepth=None, withdirs=False, detail=False, **kwargs ): + return self._find(path, maxdepth, withdirs, detail) + + def _find(self, path, maxdepth, withdirs, detail, transfer=None): # PyDrive2 1.x took detail as the second argument, and True is 1. if isinstance(maxdepth, bool): raise TypeError( "find() takes maxdepth as its second argument. " f"Pass detail by keyword: find(path, detail={maxdepth})." ) - return self._find(path, maxdepth, withdirs, detail) - - def _find(self, path, maxdepth, withdirs, detail, transfer=None): root, base = self._split_mounted_path(path) if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") @@ -1295,23 +1294,27 @@ def _find(self, path, maxdepth, withdirs, detail, transfer=None): contents.sort() return contents - def _transfer(self, destination=None): + def _transfer(self, source, destination=None): """Return the object that fsspec's get() or copy() should run on.""" - cls = type(self) - for name in _TRANSFER_HOOKS: - if getattr(cls, name) is not getattr(GDriveFileSystem, name): - return self - return _ListedTransfer(self, destination) + # Listed IDs need PyDrive2's own methods and one source path or glob. + if ( + type(self) is GDriveFileSystem + and isinstance(source, str) + and _TRANSFER_HOOKS.isdisjoint(vars(self)) + ): + return _ListedTransfer(self, destination) + return self @wraps(AbstractFileSystem.get) - def get(self, *args, **kwargs): + def get(self, rpath, *args, **kwargs): # Each listed file is downloaded by its listed ID, without a lookup. - return AbstractFileSystem.get(self._transfer(), *args, **kwargs) + transfer = self._transfer(rpath) + return AbstractFileSystem.get(transfer, rpath, *args, **kwargs) @wraps(AbstractFileSystem.copy) def copy(self, path1, path2, *args, **kwargs): # Each listed file is copied by its listed ID, without a lookup. - transfer = self._transfer(destination=path2) + transfer = self._transfer(path1, destination=path2) return AbstractFileSystem.copy(transfer, path1, path2, *args, **kwargs) def upload_fobj(self, stream, rpath, callback=None, **kwargs): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index a9af9772..6025ce2e 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -613,6 +613,17 @@ def test_find_with_a_depth_that_is_not_a_positive_number_raises_before_listing( assert requests == [] +def test_recursive_get_with_a_boolean_depth_raises_before_listing( + mock_drive, tmp_path +): + drive, requests = mock_drive() + with pytest.raises(TypeError, match="detail=True"): + filesystem(drive).get( + "root", str(tmp_path / "out"), recursive=True, maxdepth=True + ) + assert requests == [] + + @pytest.mark.parametrize("bare", [True, False]) def test_find_missing_path_uses_one_lookup(mock_drive, bare): drive, requests = mock_drive( @@ -3231,6 +3242,50 @@ def test_get_after_a_subclass_changes_glob_downloads_only_its_matches( assert [path.name for path in (tmp_path / "out").iterdir()] == ["a.csv"] +def test_get_of_a_glob_and_a_path_after_the_path_was_replaced_downloads_the_new_file( + mock_drive, tmp_path +): + csv = {"name": "a.csv", "id": "A", "mimeType": "text/csv"} + old = {"name": "manual.txt", "id": "OLD", "mimeType": "text/plain"} + new = dict(old, id="NEW") + drive, requests = mock_drive( + listing(csv, old), + listing(csv), + DOWNLOAD, + listing(new), + DOWNLOAD, + ) + + filesystem(drive).get( + ["root/*.csv", "root/manual.txt"], str(tmp_path / "out") + "/" + ) + + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/NEW" + + +def test_get_after_replacing_get_file_on_the_instance_calls_it( + mock_drive, tmp_path +): + drive, _ = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE), + listing(TEXT_FILE), + DOWNLOAD, + ) + fs = filesystem(drive) + get_file = fs.get_file + called = [] + + def recording_get_file(rpath, lpath, **kwargs): + called.append(rpath) + return get_file(rpath, lpath, **kwargs) + + fs.get_file = recording_get_file + fs.get("root/source", str(tmp_path / "out"), recursive=True) + + assert called == ["root/source", "root/source/a.txt"] + + def test_recursive_put_uploads_files_and_creates_empty_folders( mock_drive, tmp_path ):