diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..67ec84a3 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -99,6 +99,19 @@ 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()`` of one path, or a non-recursive 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 cannot place an item, for example one 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 57c3cbbc..62bf5f57 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -15,6 +15,7 @@ from contextlib import contextmanager, nullcontext from dataclasses import dataclass, field from functools import wraps +from glob import has_magic from http.client import IncompleteRead from itertools import count, islice, pairwise from operator import attrgetter @@ -228,6 +229,82 @@ def _select_item_id(path, ids): raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path) +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, destination=None): + self._fs = fs + self._destination = ( + posixpath.join(*fs.split_path(destination)).rstrip("/") + if isinstance(destination, str) + else None + ) + 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): + matches = AbstractFileSystem.glob(self, *args, **kwargs) + if self._ids: + # Only the paths that the pattern selects keep their listed IDs. + self._ids = {p: self._ids[p] for p in matches if p in self._ids} + return matches + + def find( + self, path, maxdepth=None, withdirs=False, detail=False, **kwargs + ): + return self._fs._find(path, maxdepth, withdirs, detail, self) + + 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 + if parent in self._unreachable or not item.name 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 forget(self): + """Look every path up, because a listing could not place an item.""" + self._ids = None + + def _known(self, path): + # fsspec places a copy by the destination's current type. + if not self._ids or path == self._destination: + return None + return self._ids.get(path) + + 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, callback=None, block_size=None, **kwargs): + listed = self._known(rpath) + return self._fs._get_file(rpath, lpath, listed, callback, block_size) + + def cp_file(self, path1, path2, **kwargs): + return self._fs._cp_file(path1, path2, self._known(path1)) + + +# 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") +) + + class GDriveAuthError(AuthError): pass @@ -883,9 +960,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.""" _, base = self._split_mounted_path(path) + if listed is not None: + return listed match, _ = self._lookup_path(base) item_id = _select_item_id(path, match.ids) if base or self.root in _ROOT_ALIASES: @@ -1102,7 +1181,9 @@ def _ls_folder(self, listing, parent, path, fields, detail): listing.files.add((parent, names[file_path])) return entries - def _walk_folders(self, start, start_ids, generation, maxdepth, fields): + def _walk_folders( + self, start, start_ids, generation, maxdepth, fields, transfer=None + ): frontier = dict.fromkeys(start_ids, start) to_list = self._dirs.warm_parents(frontier, maxdepth, generation) depth = 0 @@ -1118,6 +1199,9 @@ def _walk_folders(self, start, start_ids, generation, maxdepth, fields): ): children[item.parent].append(item) generation = listing.generation + if transfer is not None and not listing.complete: + # The cache distrusts this listing, so lookups decide. + transfer.forget() # Several physical folders can have the same display path. by_path: dict[str, list[_ListedChild]] = {} @@ -1149,6 +1233,9 @@ 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( @@ -1192,17 +1279,24 @@ def find( contents.append(entry) fields = _LIST_FIELDS if detail else _NAME_FIELDS for parent, children in self._walk_folders( - start, match.folders, resolver.generation, maxdepth, fields + start, + match.folders, + resolver.generation, + maxdepth, + fields, + transfer, ): if children: 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, 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: @@ -1217,6 +1311,35 @@ def find( contents.sort() return contents + def _transfer(self, source, recursive, destination=None): + """Return the object that fsspec's get() or copy() should run on.""" + # Listed IDs need PyDrive2's own methods and one source path or glob. + # fsspec looks up each match of a recursive glob by name anyway. + if ( + type(self) is GDriveFileSystem + and isinstance(source, str) + and not (recursive and has_magic(source)) + and _TRANSFER_HOOKS.isdisjoint(vars(self)) + ): + return _ListedTransfer(self, destination) + return self + + @wraps(AbstractFileSystem.get) + def get(self, rpath, lpath, recursive=False, *args, **kwargs): + # Each listed file is downloaded by its listed ID, without a lookup. + transfer = self._transfer(rpath, recursive) + return AbstractFileSystem.get( + transfer, rpath, lpath, recursive, *args, **kwargs + ) + + @wraps(AbstractFileSystem.copy) + def copy(self, path1, path2, recursive=False, *args, **kwargs): + # Each listed file is copied by its listed ID, without a lookup. + transfer = self._transfer(path1, recursive, path2) + return AbstractFileSystem.copy( + transfer, path1, path2, recursive, *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) @@ -1249,16 +1372,37 @@ 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) + source_id, is_folder = self._lookup_item(lpath, listed) if is_folder: self.makedirs(rpath, exist_ok=True) 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) + 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( @@ -1348,8 +1492,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) + 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.py b/pydrive2/test/test_fs.py index a79ea3b9..a54fa5c6 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -599,6 +599,158 @@ def test_recursive_get_downloads_a_folder_addressed_by_its_id( assert (target / "a.txt").read_bytes() == b"a" +@pytest.fixture(scope="module") +def listed_tree(service_auth, fs_factory, base_remote_dir): + """A folder with a file, a subfolder and two files of one name.""" + name = uuid.uuid4().hex + folder = create_on_drive(service_auth, fs_factory()[1]["id"], name)["id"] + create_on_drive(service_auth, folder, "a.txt", "a") + nested = create_on_drive(service_auth, folder, "nested")["id"] + create_on_drive(service_auth, nested, "b.txt", "b") + create_on_drive(service_auth, folder, "same.txt", "first") + create_on_drive(service_auth, folder, "same.txt", "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_of_a_glob_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.glob(listed_tree + "/*.txt") + listing = len(answered_requests) + answered_requests.clear() + + getter, _ = fs_factory() + getter.get(listed_tree + "/*.txt", str(target)) + + 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( + service_auth, fs, remote_dir, remote_dir_id +): + create_on_drive(service_auth, remote_dir_id, "a.txt", "a") + create_on_drive(service_auth, remote_dir_id, "../escaped.txt", "escaped") + slashed = create_on_drive(service_auth, remote_dir_id, "x/y")["id"] + create_on_drive(service_auth, slashed, "c.txt", "c") + target = remote_dir + "-copy" + + fs.copy(remote_dir, target, recursive=True) + + assert fs.find(target) == [target + "/a.txt"] + + +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( + service_auth, fs, base_remote_dir, remote_dir, remote_dir_id, tmp_path +): + create_on_drive(service_auth, remote_dir_id, "a.txt", "a") + other = GDriveFileSystem( + base_remote_dir, + fs.client.auth, + trash_only=False, + skip_instance_cache=True, + ) + removal = RemoveBeforeTransfer(remote_dir + "/a.txt", other) + + with pytest.raises(FileNotFoundError): + fs.get( + remote_dir, + 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" diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 71c9d786..2b008585 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( @@ -3016,18 +3027,366 @@ 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_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"), + error_response(404, "notFound"), + ) + with pytest.raises(FileNotFoundError): + filesystem(drive).cp_file("root/a.txt", "root/b.txt") + 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( + 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"), + error_response(404, "notFound"), + response({"id": "copy"}), + ) + filesystem(drive).copy("root/source/", "root", recursive=True) + 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 ListAndGetBeforeTransfer(Callback): + """List the folder and download one file through the filesystem first.""" + + 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.find(self.source) + self.fs.get_file(self.path, self.target) + return Callback() + + +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(listed), + listing(replaced), + listing(replaced), + ({"status": "200"}, b"new"), + DOWNLOAD, + ) + fs = filesystem(drive) + 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=callback + ) + + 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/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_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"}), + listing(), + response({"id": "new-2"}), + ) + + filesystem(drive).copy("root/source", "root/source/out", recursive=True) + + created = [ + json.loads(body) for _, verb, body, *_ in requests if verb == "POST" + ] + folders = [ + (item["name"], item["parents"], item["mimeType"]) for item in created + ] + assert folders == [ + ("source", ["D"], FOLDER_MIME_TYPE), + ("out", ["new-1"], FOLDER_MIME_TYPE), + ] + + +def test_copy_of_a_glob_to_a_tuple_of_paths_copies_the_match(mock_drive): + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE), + response({"id": "new-1"}), + ) + + filesystem(drive).copy("root/source/*.txt", ("root/b.txt",)) + + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/A/copy" + assert json.loads(requests[-1][2])["name"] == "b.txt" + + +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_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_get_after_a_cached_folder_moved_out_looks_a_shared_file_up( + mock_drive, tmp_path +): + shared = dict(TEXT_FILE, parents=["Q", "P"]) + other = dict(TEXT_FILE, id="Z", parents=["P"]) + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(folder("p", "P"), folder("q", "Q")), + # Another client has moved q out of source since the first listing. + listing(dict(folder("p", "P"), parents=["S"]), shared, other), + listing(shared, other), + DOWNLOAD, + ) + fs = filesystem(drive) + fs.ls("root/source") + + fs.get("root/source", str(tmp_path / "out"), recursive=True) + + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/A" + + +def test_recursive_get_after_listing_a_nameless_folder_keeps_the_sibling_id( + mock_drive, tmp_path +): + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(dict(TEXT_FILE, id="Z"), folder("", "F")), + listing(TEXT_FILE), + DOWNLOAD, + ) + + filesystem(drive).get("root/source", str(tmp_path / "out"), recursive=True) + + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/Z" + + +def test_recursive_get_of_a_glob_after_its_match_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), + listing(replaced), + ({"status": "200"}, b"new"), + ) + + filesystem(drive).get( + "root/source/*.txt", str(tmp_path / "out"), recursive=True + ) + + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/B" + + +@pytest.mark.parametrize( + "destination", + [ + "root/source/out", + "gdrive://root/source/out", + "root//source/out", + "gdrive:///source/out", + ], +) +def test_copy_of_a_glob_after_a_listed_destination_became_a_folder_copies_into_it( + mock_drive, destination +): + listed = {"name": "out", "id": "O", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(folder("source", "S")), + listing(TEXT_FILE, listed), + listing(folder("out", "D")), + response(folder("out", "D")), + response(folder("out", "D")), + response({"id": "new-1"}), + ) + + filesystem(drive).copy("root/source/*", destination) + + assert urlsplit(requests[-1][0]).path == "/drive/v3/files/A/copy" + assert json.loads(requests[-1][2])["parents"] == ["D"] def test_recursive_put_uploads_files_and_creates_empty_folders( @@ -3058,10 +3417,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]) == {