From 726b08462cd208e02f333a95b365abfe4c4d444a Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:25:00 -0800 Subject: [PATCH 1/2] Upload in-place edits of nested metadata PyDrive2 finds edits by comparing the file with a copy taken when Drive last answered. The copy shared nested values with the file, so an edit made in place, such as file["appProperties"]["stage"] = "done" or a changed entry in file["parents"], changed both, and Upload() sent nothing. The copy now has its own appProperties, properties, contentHints and parents. Co-Authored-By: Claude Opus 5.5 --- pydrive2/files.py | 34 +++++++++++++++++++++++++- pydrive2/test/test_file.py | 41 ++++++++++++++++++++++++++++++++ pydrive2/test/test_files_unit.py | 16 +++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) diff --git a/pydrive2/files.py b/pydrive2/files.py index a1766669..752b3152 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -1,4 +1,5 @@ import codecs +import copy import io import json import mimetypes @@ -55,6 +56,29 @@ "expirationDate": "'expirationTime'", } +# Fields that hold a dict or a list and that an upload can change. +_EDITABLE_NESTED_FIELDS = ( + "appProperties", + "properties", + "contentHints", + "parents", +) + + +def _saved_copy(values): + """Copy of the values to find edits by when uploading. + + Nested values that an upload can change get their own copy, so that an + edit made in place, such as file["appProperties"]["stage"] = "done", + shows up as a change. + """ + saved = dict(values) + for key in _EDITABLE_NESTED_FIELDS: + if key in saved: + saved[key] = copy.deepcopy(saved[key]) + return saved + + # One request must send its whole body within http_timeout, so keep it small. _SINGLE_REQUEST_UPLOAD_SIZE = 1024 * 1024 # The Google client cannot put these in a one-request body as raw bytes. @@ -316,6 +340,12 @@ def __init__(self, auth=None, metadata=None, uploaded=False): self.has_bom = True self._export_mimetype = None + def UpdateMetadata(self, metadata=None): + """Update metadata and mark all of them to be clean.""" + if metadata: + self.update(metadata) + self.metadata = _saved_copy(self) + def __getitem__(self, key): """Overwrites manner of accessing Files resource. @@ -549,7 +579,9 @@ def FetchMetadata(self, fields=None, fetch_all=False): pending.pop("id", None) self.uploaded = True # What Drive is known to hold: earlier answers, then this one. - self.metadata = {**self.metadata, "id": file_id, **metadata} + self.metadata = _saved_copy( + {**self.metadata, "id": file_id, **metadata} + ) self.update(metadata) self.update(pending) self["id"] = self.metadata["id"] diff --git a/pydrive2/test/test_file.py b/pydrive2/test/test_file.py index 3582de1f..4202ed3e 100644 --- a/pydrive2/test/test_file.py +++ b/pydrive2/test/test_file.py @@ -346,6 +346,47 @@ def test_move_after_a_partial_read_puts_the_file_in_the_new_folder( } +@pytest.mark.parametrize( + ("field", "created", "edited"), + [ + ("appProperties", {"stage": "draft"}, {"stage": "done"}), + ("properties", {"owner": "ml"}, {"owner": "ops"}), + ], + ids=["appProperties", "properties"], +) +def test_upload_after_an_in_place_edit_of_a_nested_field_stores_the_edit( + service_auth, request, field, created, edited +): + drive = GoogleDrive(service_auth) + file = drive.CreateFile( + {"name": test_util.CreateRandomFileName(), field: created} + ) + pydrive_retry(file.Upload) + request.addfinalizer(lambda: pydrive_retry(file.Delete)) + + read = drive.CreateFile({"id": file["id"]}) + pydrive_retry(read.FetchMetadata, fields=field) + (key,) = edited + read[field][key] = edited[key] + pydrive_retry(read.Upload) + + assert stored(service_auth, file["id"], field) == {field: edited} + + +# new_folder comes first, so that the file in it is deleted before it. +def test_upload_after_an_in_place_edit_of_parents_moves_the_file( + service_auth, new_folder, uploaded_file +): + read = GoogleDrive(service_auth).CreateFile({"id": uploaded_file["id"]}) + pydrive_retry(read.FetchMetadata, fields="parents") + read["parents"][0] = new_folder["id"] + pydrive_retry(read.Upload) + + assert stored(service_auth, uploaded_file["id"], "parents") == { + "parents": [new_folder["id"]] + } + + def test_changing_the_id_of_an_uploaded_file_raises_and_changes_neither_file( service_auth, uploaded_file, request ): diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index 502dfa1f..e0a8f1d3 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -110,6 +110,22 @@ def test_upload_rejects_listed_file_without_id(mock_drive): assert [request[1] for request in requests] == ["GET"] +def test_upload_after_an_in_place_edit_of_content_hints_sends_them( + mock_drive, +): + # Drive never returns contentHints, so only the request can show this. + drive, requests = mock_drive(response({"id": "A"}), response({"id": "A"})) + file = drive.CreateFile({"contentHints": {"indexableText": "draft"}}) + file.Upload() + file["contentHints"]["indexableText"] = "final" + file.Upload() + update = requests[-1] + assert update[1] == "PATCH" + assert json.loads(update[2]) == { + "contentHints": {"indexableText": "final"} + } + + def test_upload_updates_listed_file_with_id(mock_drive): drive, requests = mock_drive( response({"files": [{"id": "existing", "name": "original"}]}), From 02890f1a7ba1f45d6f2c43125e6bf96f43000ecf Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:07:56 -0800 Subject: [PATCH 2/2] Keep in-place edits of content and download restrictions too contentRestrictions and downloadRestrictions are writable nested fields, so the saved copy gets its own copy of them. parents, properties and appProperties hold only strings, so a shallow copy is enough and keeps listings fast. Co-Authored-By: Claude Opus 5.5 --- pydrive2/files.py | 19 ++++++++++------- pydrive2/test/test_file.py | 43 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/pydrive2/files.py b/pydrive2/files.py index 752b3152..3cb9e8b8 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -56,23 +56,28 @@ "expirationDate": "'expirationTime'", } -# Fields that hold a dict or a list and that an upload can change. +# Fields that an upload can change and that hold a list of strings or a +# dict of strings. +_EDITABLE_FLAT_FIELDS = ("appProperties", "parents", "properties") +# Fields that an upload can change and that hold dicts inside. _EDITABLE_NESTED_FIELDS = ( - "appProperties", - "properties", "contentHints", - "parents", + "contentRestrictions", + "downloadRestrictions", ) def _saved_copy(values): """Copy of the values to find edits by when uploading. - Nested values that an upload can change get their own copy, so that an - edit made in place, such as file["appProperties"]["stage"] = "done", - shows up as a change. + Values that an upload can change get their own copy, so that an edit + made in place, such as file["appProperties"]["stage"] = "done", shows + up as a change. """ saved = dict(values) + for key in _EDITABLE_FLAT_FIELDS: + if key in saved: + saved[key] = copy.copy(saved[key]) for key in _EDITABLE_NESTED_FIELDS: if key in saved: saved[key] = copy.deepcopy(saved[key]) diff --git a/pydrive2/test/test_file.py b/pydrive2/test/test_file.py index 4202ed3e..cbe49adb 100644 --- a/pydrive2/test/test_file.py +++ b/pydrive2/test/test_file.py @@ -387,6 +387,49 @@ def test_upload_after_an_in_place_edit_of_parents_moves_the_file( } +# new_folder comes first, so that the file in it is deleted before it. +def test_upload_after_an_in_place_edit_of_parents_of_a_listed_file_moves_it( + service_auth, new_folder, uploaded_file +): + query = f"name = '{uploaded_file['name']}'" + listing = GoogleDrive(service_auth).ListFile({"q": query}) + (listed,) = pydrive_retry(listing.GetList) + listed["parents"][0] = new_folder["id"] + pydrive_retry(listed.Upload) + + assert stored(service_auth, uploaded_file["id"], "parents") == { + "parents": [new_folder["id"]] + } + + +def test_upload_after_appending_a_second_parent_in_place_raises( + service_auth, uploaded_file +): + read = GoogleDrive(service_auth).CreateFile({"id": uploaded_file["id"]}) + pydrive_retry(read.FetchMetadata, fields="parents") + read["parents"].append("another-folder") + with pytest.raises(ValueError, match="only one parent"): + read.Upload() + + +def test_upload_after_an_in_place_edit_of_content_restrictions_unlocks_it( + service_auth, uploaded_file +): + uploaded_file["contentRestrictions"] = [{"readOnly": True}] + pydrive_retry(uploaded_file.Upload) + + read = GoogleDrive(service_auth).CreateFile({"id": uploaded_file["id"]}) + pydrive_retry(read.FetchMetadata, fields="contentRestrictions(readOnly)") + read["contentRestrictions"][0]["readOnly"] = False + pydrive_retry(read.Upload) + + restrictions = stored(service_auth, read["id"], "contentRestrictions") + assert not any( + restriction.get("readOnly") + for restriction in restrictions["contentRestrictions"] or [] + ) + + def test_changing_the_id_of_an_uploaded_file_raises_and_changes_neither_file( service_auth, uploaded_file, request ):