diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 8ce4b06..4f1a724 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -65,6 +65,12 @@ The filesystem extra requires fsspec 2024.2.0 or newer. Use argument specifies traversal depth. Directory names returned by ``ls()`` and ``info()`` end in a slash. ``find(withdirs=True)`` returns directory paths without a trailing slash, like fsspec's other traversal methods. +When several Drive items share a path, detailed ``find()`` reports the +matching file with the lowest Drive ID. With ``withdirs=True``, folders +also participate in that choice, as they do in ``info()``. The search +visits every matching folder. If a file and a folder both match the +starting path, the default ``withdirs=False`` lists only files inside +the folder. Named directory lookups reuse cached Drive IDs. Listing a parent refreshes the folders seen under that parent. If a listing discovers a folder under diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 8e747db..b53681c 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -9,7 +9,8 @@ import warnings from contextlib import contextmanager, nullcontext from dataclasses import dataclass, field -from itertools import islice +from itertools import islice, pairwise +from operator import attrgetter from weakref import WeakValueDictionary import appdirs @@ -179,6 +180,18 @@ def _drain(items): yield items.pop() +def _preferred_ids(children, withdirs): + """Only same-name siblings need a tie-breaker, as in info().""" + items = (item for item in children if withdirs or not item.is_folder) + preferred: dict[str, str] = {} + for left, right in pairwise(sorted(items, key=attrgetter("name"))): + if left.name == right.name: + preferred[left.name] = min( + preferred.get(left.name, left.id), right.id + ) + return preferred + + def _select_item_id(path, ids): if ids: return min(ids) @@ -827,16 +840,26 @@ def _walk_folders(self, start, start_ids, generation, maxdepth, fields): children[item.parent].append(item) generation = listing.generation - visited.update(frontier) - following = {} + # Several physical folders can have the same display path. + by_path: dict[str, list[_ListedChild]] = {} for parent, parent_path in frontier.items(): - for item in _drain(children.pop(parent)): - path = posixpath.join(parent_path, item.name) - if item.is_folder and item.id not in visited: - following[item.id] = path - yield path, item + if parent_path in by_path: + by_path[parent_path].extend(children.pop(parent)) + else: + by_path[parent_path] = children.pop(parent) if depth == maxdepth: + yield from by_path.items() return + + visited.update(frontier) + following = {} + for parent_path, siblings in by_path.items(): + for item in siblings: + if item.is_folder and item.id not in visited: + following[item.id] = posixpath.join( + parent_path, item.name + ) + yield parent_path, siblings frontier = following to_list = { item_id: None @@ -860,7 +883,7 @@ def find( 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=True) + match = resolver.resolve(base, folders_only=not (withdirs and detail)) start = posixpath.join(root, base).rstrip("/") check_empty_root = False if not base and root not in _ROOT_ALIASES: @@ -873,21 +896,31 @@ def find( return {} if detail else [] if entry["type"] == "file": return {start: entry} if detail else [start] + file = min(match.files, key=lambda item: item.id, default=None) if not match.folders: - if match.files: - file = min(match.files, key=lambda item: item.id) + if file is not None: return {start: file.entry(start)} if detail else [start] return {} if detail else [] contents = [] if withdirs: - contents.append(_directory_entry(start) if detail else start) + entry = _directory_entry(start) if detail else start + if detail and file is not None and file.id < min(match.folders): + entry = file.entry(start) + contents.append(entry) fields = _LIST_FIELDS if detail else _NAME_FIELDS - for name, item in self._walk_folders( + for parent, children in self._walk_folders( start, match.folders, resolver.generation, maxdepth, fields ): - check_empty_root = False - if withdirs or not item.is_folder: + if children: + check_empty_root = False + preferred = _preferred_ids(children, withdirs) if detail else {} + for item in _drain(children): + 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: @@ -898,7 +931,7 @@ def find( if detail: contents.sort(key=lambda entry: entry["name"]) - return {entry["name"]: entry for entry in contents} + return {entry["name"]: entry for entry in _drain(contents)} contents.sort() return contents diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 08055fb..9240b41 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -306,6 +306,82 @@ def test_find_wide_directory(mock_drive, detail): ] +@pytest.mark.parametrize("warm", [False, True]) +@pytest.mark.parametrize("folder_id", ["A", "Z"]) +def test_detailed_find_and_info_agree_under_duplicate_folders( + mock_drive, warm, folder_id +): + parents = listing(folder("dup", "P1"), folder("dup", "P2")) + subdirs = listing( + dict(folder("a", "A2"), parents=["P2"]), + dict(folder("a", "A1"), parents=["P1"]), + ) + directory = dict(folder("x", folder_id), parents=["A1"]) + file = { + "name": "x", + "id": "M", + "parents": ["A2"], + "mimeType": "text/plain", + "size": "7", + "md5Checksum": "original", + } + items = listing(directory, file) + child = dict(file, name="inside", id="N", parents=[folder_id]) + winner = directory if folder_id < file["id"] else file + pages = [parents, subdirs, items, listing(child)] + if warm: + pages.append(listing(directory, file, child)) + drive, requests = mock_drive(*pages, items, response(winner)) + fs = filesystem(drive) + if warm: + fs.find("root") + start = "root/dup/a" + before = len(requests) + found = fs.find(start, withdirs=True, detail=True) + assert len(requests) - before == (1 if warm else 4) + assert found[start + "/x/inside"]["type"] == "file" + path = start + "/x" + stat = fs.info(path) + assert found[path] == dict(stat, name=path) + assert urlsplit(requests[-1][0]).path.endswith("/files/" + winner["id"]) + + +def test_detailed_find_selects_the_lowest_file_id_across_pages(mock_drive): + first = {"name": "x", "id": "A", "mimeType": "text/plain", "size": "5"} + middle = dict(first, id="M", size="7") + last = dict(first, id="Z", size="9") + drive, requests = mock_drive( + response({"files": [first], "nextPageToken": "next"}), + listing(middle, last, folder("x", "0")), + listing(first, middle, last, folder("x", "0")), + ) + fs = filesystem(drive) + assert fs.find("root", maxdepth=1, detail=True)["root/x"]["size"] == 5 + assert fs.find("root", maxdepth=1) == ["root/x"] * 3 + assert len(requests) == 3 + + +@pytest.mark.parametrize("folder_id", ["0", "Z"]) +def test_detailed_find_and_info_agree_at_the_start(mock_drive, folder_id): + file = {"name": "x", "id": "A", "mimeType": "text/plain", "size": "7"} + directory = folder("x", folder_id) + winner = directory if folder_id == "0" else file + both = listing(file, directory) + drive, requests = mock_drive( + both, + both, + listing(dict(file, name="inside", id="N")), + both, + response(winner), + ) + fs = filesystem(drive) + fs.ls("root") + found = fs.find("root/x", withdirs=True, detail=True) + assert found["root/x/inside"]["type"] == "file" + assert found["root/x"] == dict(fs.info("root/x"), name="root/x") + assert urlsplit(requests[-1][0]).path.endswith("/files/" + winner["id"]) + + @pytest.fixture def live_heap_bytes(): def measure(): @@ -773,9 +849,11 @@ def test_find_tracks_a_moved_file_that_now_shares_its_name_with_a_folder( assert urlsplit(requests[-1][0]).path.endswith("/files/A") -@pytest.mark.parametrize("operation", ["ls", "find"]) +@pytest.mark.parametrize( + ("operation", "detail"), [("ls", False), ("find", False), ("find", True)] +) def test_warm_directory_listing_uses_one_request_when_a_file_shares_its_name( - mock_drive, operation + mock_drive, operation, detail ): file = {"id": "A", "name": "data", "mimeType": "text/plain"} drive, requests = mock_drive( @@ -784,7 +862,8 @@ def test_warm_directory_listing_uses_one_request_when_a_file_shares_its_name( ) fs = filesystem(drive) fs.ls("root") - assert getattr(fs, operation)("root/data") == ["root/data/note"] + found = getattr(fs, operation)("root/data", detail=detail) + assert list(found) == ["root/data/note"] assert [query(r)["q"] for r in requests[1:]] == [ ["('Z' in parents) and trashed=false"] ]