Skip to content

Add native move / rename (mv) - #72

Closed
Light2Dark wants to merge 83 commits into
fsspec:masterfrom
marimo-team:feat/native-mv
Closed

Light2Dark wants to merge 83 commits into
fsspec:masterfrom
marimo-team:feat/native-mv

Conversation

@Light2Dark

Copy link
Copy Markdown
Collaborator

Summary

Closes #24. GoogleDriveFileSystem inherited fsspec's default mv, a copy-then-delete that round-trips a new file, mints a fresh id, and (for directories) recreates the tree file-by-file. This replaces it with a native mv backed by a single Drive files.update:

  • Metadata-only move: renames and/or re-parents in place via files.update(fileId=..., body={"name": ...}, addParents=..., removeParents=...). The file id is preserved and no bytes are transferred.
  • Atomic directory moves: moving a folder relocates its whole subtree in one call (recursive is irrelevant for a native move).
  • Semantics mirror cp_file: move into an existing directory keeps the source basename; an existing file at the destination is trashed before the update (recoverable if it fails). IsADirectoryError when a name would overwrite a folder, NotADirectoryError when a directory would overwrite a file, and moving an item onto itself (including into its own parent) is a no-op.
  • Fallbacks: lists, globs, and maxdepth delegate to fsspec's base mv (they need its path-expansion machinery).
  • dircache repair: both source and destination parent listings are updated, and a moved directory's now-stale subtree is dropped so it re-lists lazily.
  • Refactor: shared destination handling is factored out of cp_file into _resolve_into_directory, _trash_existing_destination, and _basename, so the copy and move paths can't drift on the subtle overwrite/redirect logic.

files.update's addParents / removeParents / supportsAllDrives params were verified against the live Drive v3 discovery document (per .agents/verifying-drive-api-params.md).

Test plan

  • Unit tests (tests/test_core_fs.py): rename, cross-dir reparent, overwrite, move-into-dir, both no-op paths, directory subtree drop, uncached-parent, both occupancy guards, and list/glob delegation. cp_file's existing tests pass unchanged against the refactor.
  • Integration tests (tests/test_integration.py): 9 mv + 6 cp_file cases pass against real Google Drive (uv run pytest -m integration -k "mv or cp_file" — 15 passed).
  • ruff check + format, pyrefly check (0 errors), full unit suite (266 passed).

Made with Cursor

Light2Dark and others added 30 commits June 23, 2026 07:51
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Request mimeType and reject non-folder IDs so a regular file passed as
root_file_id no longer masquerades as an empty directory under ls("").
Add a TODO for the conflicting drive vs shared-drive root_file_id case
(issue #2) to handle in a follow-up.

Co-authored-by: Cursor <cursoragent@cursor.com>
Add integration tests asserting a file ID is rejected as root
(NotADirectoryError) and a folder ID lists its children. Introduce a
typed DriveConfig + make_fs factory fixture in conftest so live
filesystems are built from env in one place and tests can create
multiple instances with a shared teardown. Add tests to pyrefly
search-path and document Drive API constants.

Co-authored-by: Cursor <cursoragent@cursor.com>
Enforce that a scoped drive and root_file_id agree: reject a folder root
whose driveId differs from the configured drive, and raise on a
shared-drive root_file_id that conflicts with an already-set drive
(previously a silent no-op).

Also resolve the `drive` argument by id or name (was name-only) and
correct the docstring accordingly.

Co-authored-by: Cursor <cursoragent@cursor.com>
…tency

Validate drive/root consistency; accept drive id or name
- conftest: collapse unreachable pytest.skip branch in make_fs
- test_core_fs: replace export AttributeError test with strict xfail
  documenting that export() calls a nonexistent path_to_file_id
- test_integration: assert info("") against the real root, not TESTDIR;
  drop dangling issue reference from dircache xfail reason

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Light2Dark and others added 28 commits July 2, 2026 17:01
add a comment, and do a small test cleanup
fix cache stashing and retrieval
PR #51 (merged from master) added test_rm_deletes_file and
test_rmdir_deletes_empty_directory that mock info() without
capabilities, tripping the canDelete check in _rm. Provide
deletable capabilities via the existing _deletable_info helper.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- _info_by_id: drop reserved keys (fileId/fields/supportsAllDrives) from
  forwarded **kwargs to avoid TypeError
- ls/info: normalize a blank/whitespace field mask to None so it keeps the
  cache fast path instead of forcing a fresh listing / files.get
- _rm: raise ValueError on the filesystem root instead of a misleading
  PermissionError
- use a relative import for utils; readonly_fs skips without GDRIVE_FSSPEC_DRIVE

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Permission-aware rm and dircache correctness fixes
* add multiple profiles testing

* add back removed

* update docstring

* fix lint
* increase num retries, and wire it to all callers

* add retries for export

* Add retry wiring and googleapiclient backoff tests.

Assert num_retries is forwarded from export, list, and get paths, and
document the transient-error filtering we rely on for 503 and 403 cases.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
* Retry transient failures on hand-rolled resumable uploads.

Discovery-client calls already retry via num_retries; chunk PUTs and session
initiation bypass that path, so mirror googleapiclient's retry policy locally.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix _authed_request docstring grammar and retry wording.

Drop the blanket idempotency claim; POST session initiation can create
multiple sessions on retry.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
…#62)

* initial rewrite

* resolve version error

* address review

* Address review: sync robustness fixes and simpler cache-sync flow

- Keep _maybe_sync_cache dormant when reconnected to anonymous credentials
- Simplify the cache-sync flow: _maybe_sync_cache is a plain TTL gate that
  stamps on every attempt (so a failed sync/baseline honors the interval
  instead of hot-looping), and _sync_cache establishes the baseline token as
  its natural first-call state. Drops the return-value/un-stamp dance.
- Fix _await_change_for to re-poll from the original token, so an
  eventually-consistent change is not skipped past
- Add size to FileInfo test fixtures to match normalized Drive responses

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix _until off-by-one: exactly _SYNC_RETRIES polls, no wasted trailing sleep

Check at the start of each attempt and sleep only between attempts, so the
helper calls the predicate exactly _SYNC_RETRIES times (matching its docstring)
instead of _SYNC_RETRIES + 1, and drops the redundant final sleep.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Type page_kwargs as a TypedDict instead of dict[str, Any]

Replaces the untyped page_kwargs blobs in drives / _list_children /
_find_child_by_name with a _PageTokenKwargs TypedDict, so the dict's contents
are type-checked (wrong value type or unknown key both error).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* simplify

* add docstring

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* Split core.py into core, _file, and _constants modules

core.py had grown to ~1730 lines holding three concerns in one file: the
GoogleDriveFileSystem class, the GoogleDriveFile buffered-file class, and a
block of module constants plus shared helpers.

Extract two modules, keeping the GoogleDriveFile class and moved helpers
byte-for-byte identical (behavior-preserving move):

- _constants.py: module constants, type aliases, MultipleFilesError, and the
  two pure helpers both layers share (_normalize_path, _finfo_from_response).
  Imports nothing from the package except .types, so it never joins a cycle.
- _file.py: GoogleDriveFile plus its private helpers (_should_retry_status,
  _with_supports_all_drives, _parse_range_end). Imports GoogleDriveFileSystem
  only under TYPE_CHECKING.

No re-exports: each symbol now lives in exactly one module, and the tests
import moved symbols from their new homes instead of from .core. The public
API (gdrive_fsspec.GoogleDriveFileSystem) is unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Type open() precisely and enforce upload invariants

Follow-up typing pass on the module split. fsspec ships no py.typed, so a
GoogleDriveFile opened via fs.open() was inferred as a text-mode file and
f.write(bytes) tripped bad-argument-type across the integration tests
(previously silenced with 36 per-call pyrefly ignores).

- Override open() with overloads: an uncompressed binary open ("rb"/"wb")
  is typed as a concrete GoogleDriveFile, so read/write are known to take
  and return bytes; text mode and compression fall through to the base
  wrappers and are typed Any. Behavior is unchanged (delegates to super()).
  Removes all 36 bad-argument-type ignores.
- Guard the resumable-upload invariants with explicit raises instead of
  relying on pyrefly-ignored None arithmetic: _upload_chunk now raises if
  offset/location are unset, and _fetch_range raises if file_id is unset
  (rather than sending fileId=None). Raises, not asserts, so they survive
  python -O.
- Initialize _media_object unconditionally in __init__ so it is not a
  branch-conditional attribute.

pyrefly suppressions drop from 44 to 4 (the remainder are irreducible
untyped-fsspec cases). No asserts in src/.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Type info() as FileInfo and type the capabilities fields

info() always builds a FileInfo but returned dict[str, Any], forcing a
cast() round-trip at its only typed consumer (GoogleDriveFile.__init__) and
leaving the Drive fields it carries untyped.

- Narrow info() to -> FileInfo and drop the two internal dict[str, Any]
  downcasts; drop the now-redundant cast(FileInfo, fs.info(...)) in _file.py.
- Give capabilities and driveId real types (new _Capabilities TypedDict) so
  the shared-drive permission checks in _rm type-check on known value types
  instead of untyped extra-items.

Narrowing the return needs a [bad-override] ignore (fsspec's base info() is
dict[str, Any]). That ignore is scoped to the error code, so on its own it
would also mask a future fsspec change to info()'s return type. A
TYPE_CHECKING pin next to the override asserts the base still returns a
Mapping[str, Any]; if fsspec changes it, that line fails as [bad-assignment]
on its own — a different code the ignore cannot suppress — so the drift
surfaces instead of hiding.

Net: three cast() calls removed, one suppression added, info() honestly
typed. pyrefly 5 suppressed / 0 errors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* remove comment block

* remove comment block

* Honor end=None as through-EOF in _fetch_range

_fetch_range documents end=None as "fetch through the end", but the range
logic did `end = end or 0` and emitted `bytes=<start>--1` — a malformed
range — whenever start was set and end was None. fsspec's read path never
triggers this (its caches always pass a concrete integer end), so it was
latent, but the code contradicted its own docstring and was a trap for any
direct caller.

Emit an open-ended `bytes=<start>-` when end is None, and only compute the
inclusive end (`end - 1`) when end is provided. Adds a test for the
open-ended case.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* Export Google-native files on read

Google-native files (Docs/Sheets/Slides) have no binary content, so
files.get_media returns 403 fileNotDownloadable and reads silently
return empty. Detect them and materialize via files.export instead,
serving reads from the in-memory buffer, with a sensible per-type
default export target (overridable via export_mime_type).

Fixes #25

Co-authored-by: Cursor <cursoragent@cursor.com>

* Address review: init location on read, fix export example

- Initialize self.location unconditionally so read-mode files never
  hit AttributeError on the class-annotated attribute.
- Fix README export example to match the new default-format behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
* Add native server-side copy (cp_file)

Implement cp_file using the Drive files.copy API so fs.copy / fs.cp
perform a server-side copy instead of falling back to fsspec's default
(which streams bytes down to the client and back up). Closes #23.

- Directory sources are recreated via makedirs (files.copy cannot copy
  folders), so recursive copy reproduces the tree.
- Request INFO_FIELDS on the copy so the dircache entry carries an
  accurate size/mimeType (the default files.copy response omits size).
- Create the destination parent if missing and guard against copying
  onto an existing path (Drive would otherwise create a duplicate name).
- Update the destination parent's cached listing.

Add unit tests (server-side copy + dircache, existing-destination guard,
directory source, uncached-parent branch) and integration tests
(server-side copy, live dircache update, recursive directory copy,
missing-parent creation, larger-content integrity, mv-via-copy).

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refine cp_file semantics: overwrite, copy-into-dir, and guards

Address review feedback on the server-side cp_file (PR #65):

- Copy into an existing destination directory under the source's basename
  (POSIX cp semantics), so fs.copy(file, existing_dir) works.
- Overwrite an existing destination file by trashing it before the copy,
  instead of raising FileExistsError. This makes mv-over-existing work and
  keeps recursive copy from aborting mid-tree (fsspec's copy loop only
  swallows FileNotFoundError).
- Guard collisions: raise NotADirectoryError when a directory source's
  destination is an existing file, and IsADirectoryError when a file would
  overwrite a directory.
- Refuse copying a file onto itself (ValueError).
- Surface MultipleFilesError on an ambiguous destination via a new
  _resolve_optional helper, and document that a recursive copy still skips
  an ambiguous source (MultipleFilesError subclasses FileNotFoundError).
- Resolve the destination once (dir-detection + collision check) to cut
  redundant round-trips, and fix the docstring exception contract.

Expand unit tests (overwrite, copy-into-dir, self-copy, ambiguous dest,
dir-over-file, file-over-dir, native-file zero-size) and integration tests
(public-API copy-into-dir, recursive overwrite of colliding files,
mv-over-existing).

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
* Speed up integration tests with session fixtures and pytest-xdist.

Reuse filesystem instances and per-worker TESTDIRs to cut API overhead,
improve change-feed polling, and run the CI integration job in parallel.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Address Copilot review: poll sleep order and xdist_group marker.

Sleep before each change-feed poll in _await_change_for (no trailing delay)
and register xdist_group for --strict-markers when SERIAL_SYNC is enabled.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Wipe TESTDIR once at session start for idempotent integration runs.

Stale artifacts from interrupted runs could make existence assertions fail;
session-scoped cleanup preserves the speedup over per-test resets.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix make_fs to return distinct instances for watcher/other tests.

Session-level caching is kept for default fixtures; the make_fs factory
opts out via _fresh so sync tests get independent filesystem objects.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Override fsspec's default copy-then-delete `mv` with a single Drive
`files.update` that renames and/or re-parents the resource in place,
preserving the file id, transferring no bytes, and moving a directory's
whole subtree atomically (closes #24).

- Move into an existing directory keeps the source basename; an existing
  file at the destination is trashed before the update (recoverable).
- Same-parent renames skip parent creation/resolution entirely.
- Guards mirror cp_file: IsADirectoryError when overwriting a folder,
  NotADirectoryError when a directory would overwrite a file; moving an
  item onto itself is a no-op. Lists/globs/maxdepth fall back to base mv.
- dircache is repaired on both parents, dropping the moved subtree.
- Factor shared destination handling out of cp_file into
  _resolve_into_directory / _trash_existing_destination / _basename.

Co-authored-by: Cursor <cursoragent@cursor.com>
@Light2Dark

Copy link
Copy Markdown
Collaborator Author

Opened against the wrong base repo; recreating on marimo-team/gdrive-fsspec.

@Light2Dark Light2Dark closed this Jul 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

License for this repo

1 participant