Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
feat(connectors): Google Docs target, updated in place (experimental) (#2863)
Jiangzhou80a8973ccb93
diff --git a/dev/google_docs_real_account_check.py b/dev/google_docs_real_account_check.pynew file mode 100644index 00000000..d1db6a11--- /dev/null+++ b/dev/google_docs_real_account_check.py@@ -0,0 +1,237 @@+"""Check the Google Docs target against a real Google account, end to end.++Run it once you have signed in with ``cocoindex auth sign-in google-docs``+(``--token-path`` if you signed in elsewhere):++ uv run python dev/google_docs_real_account_check.py++It writes one doc in your My Drive and, at the end, moves it to the trash. On+the way it asks you, in the browser, to comment on one section and edit+another; then it changes a third section and checks:++1. the doc it created reads back as exactly what was declared (nothing left+ to write), which is what makes "a person's edit" detectable at all;+2. a rerun with unchanged content makes no request to Google;+3. a change to one section rewrites that section only: the commented section+ keeps its text, and the comment is still there, quoting the same text;+4. the section you edited keeps your text, and the run warns about it;+5. dropping the declaration moves the doc to the trash (not deleted for good).++The state database lives in a temporary directory, so every run starts fresh.+"""++from __future__ import annotations++import argparse+import logging+import pathlib+import sys+import tempfile+import time+from typing import Any++import cocoindex as coco+from cocoindex.connectors import google_docs+from cocoindex.connectors.google_docs import _docs, _markdown, _target++GDOCS = coco.ContextKey[google_docs.UserAccount]("google_docs_real_account_check")++V1 = """\+# CocoIndex real-account check++## Alpha++The alpha section, version one.++## Beta++Comment on this sentence in Beta.++- a bullet with **bold**, *italic*, `code` and [a link](https://cocoindex.io)+ - a nested bullet, https://example.com/x++## Gamma++Edit a word in this Gamma sentence.+"""++V2 = V1.replace("version one.", "version two.").replace(+ "Edit a word in this Gamma sentence.", "Edit a word in this Gamma sentence, v2."+)++COMMENTED = "Comment on this sentence in Beta."+++class _Counting:+ """An ``httplib2.Http`` that counts the requests made through it."""++ count = 0++ def __init__(self, inner: Any) -> None:+ self._inner = inner++ def request(self, *args: Any, **kwargs: Any) -> Any:+ _Counting.count += 1+ return self._inner.request(*args, **kwargs)++ def __getattr__(self, name: str) -> Any:+ return getattr(self._inner, name)+++def _pause(prompt: str) -> None:+ input(f"\n{prompt}\nPress Enter when done. ")+++def _yes(prompt: str) -> bool:+ return input(f"\n{prompt} [y/n] ").strip().lower().startswith("y")+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("--token-path", default=None, help="the sign-in to use")+ args = parser.parse_args()++ account = google_docs.UserAccount(args.token_path)+ if not account.is_signed_in():+ print("No Google Docs sign-in. Run: cocoindex auth sign-in google-docs")+ return 2+ print(f"Signed in as {account.email}.")++ warnings: list[str] = []++ class _Collect(logging.Handler):+ def emit(self, record: logging.LogRecord) -> None:+ if record.levelno >= logging.WARNING:+ warnings.append(record.getMessage())++ logging.getLogger(_target.__name__).addHandler(_Collect())+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")++ plain_http = _target._new_http+ _target._new_http = lambda: _Counting(plain_http()) # type: ignore[assignment]++ name = f"CocoIndex real-account check {time.strftime('%Y-%m-%d %H:%M:%S')}"+ content: dict[str, str | None] = {"content": V1}++ @coco.fn+ def app_main() -> None:+ if content["content"] is not None:+ google_docs.declare_doc(GDOCS, name, content["content"])++ results: list[tuple[str, bool]] = []++ def check(what: str, ok: bool) -> None:+ results.append((what, ok))+ print(f"{'PASS' if ok else 'FAIL'} {what}")++ with tempfile.TemporaryDirectory() as tmp:+ settings = coco.Settings.from_env(db_path=pathlib.Path(tmp) / "db")+ env = coco.Environment(settings)+ env.context_provider.provide(GDOCS, account)+ app = coco.App(+ coco.AppConfig(name="GoogleDocsRealAccountCheck", environment=env), app_main+ )++ app.update_blocking()+ google = _target._Google(account)+ files = (+ google._drive.files()+ .list(q=f"name = '{name}' and trashed = false", fields="files(id)")+ .execute()+ )["files"]+ if len(files) != 1:+ print(f"Expected one doc named {name!r}, found {len(files)}.")+ return 1+ doc_id = files[0]["id"]+ print(f"\nThe doc: {_target.doc_url(doc_id)}")++ state = _docs.read_document(google.get(doc_id))+ blocks = _markdown.parse_blocks(V1)+ leftover = _docs.plan_write(state, blocks, None).requests+ check(+ "the new doc reads back as declared (nothing left to write)", not leftover+ )+ if leftover:+ print(" left to write:", leftover[:5])++ _Counting.count = 0+ app.update_blocking()+ check("an unchanged rerun makes no request", _Counting.count == 0)++ _pause(+ f"In the doc, add a comment on the sentence {COMMENTED!r} (section "+ "Beta), and change one word in the Gamma sentence. Leave Alpha alone."+ )+ before = _docs.read_document(google.get(doc_id))+ beta_id = blocks[2].block_id+ beta_before = before.content(before.ranges[beta_id])+ comments_before = (+ google._drive.comments()+ .list(+ fileId=doc_id, fields="comments(id,quotedFileContent,deleted,resolved)"+ )+ .execute()+ .get("comments", [])+ )+ if not comments_before:+ print("No comment found on the doc; add one and run the check again.")+ return 1++ content["content"] = V2+ app.update_blocking()+ after = _docs.read_document(google.get(doc_id))+ alpha_text = [p.text for p in after.content(after.ranges[blocks[1].block_id])]+ check("Alpha was rewritten", "The alpha section, version two." in alpha_text)+ check(+ "Beta, the commented section, kept its text and named range",+ after.content(after.ranges[beta_id]) == beta_before+ and after.ranges[beta_id].named_range_id+ == before.ranges[beta_id].named_range_id,+ )+ comments_after = {+ c["id"]: c+ for c in google._drive.comments()+ .list(+ fileId=doc_id, fields="comments(id,quotedFileContent,deleted,resolved)"+ )+ .execute()+ .get("comments", [])+ }+ check(+ "the comment is still there, quoting the same text",+ all(+ c["id"] in comments_after+ and not comments_after[c["id"]].get("deleted")+ and comments_after[c["id"]].get("quotedFileContent")+ == c.get("quotedFileContent")+ for c in comments_before+ ),+ )+ gamma_text = [p.text for p in after.content(after.ranges[blocks[3].block_id])]+ check(+ "Gamma kept your edit (the flow's v2 was not written)",+ not any("v2" in t for t in gamma_text)+ and "Edit a word in this Gamma sentence." not in gamma_text,+ )+ check("the run warned about Gamma", any("Gamma" in w for w in warnings))+ check(+ "in the browser, the comment is still anchored to its sentence",+ _yes("Look at the doc: is the comment still on its sentence in Beta?"),+ )++ content["content"] = None+ app.update_blocking()+ trashed = (+ google._drive.files()+ .get(fileId=doc_id, fields="trashed")+ .execute()["trashed"]+ )+ check("dropping the declaration moved the doc to the trash", trashed is True)++ failed = [what for what, ok in results if not ok]+ print(f"\n{len(results) - len(failed)} of {len(results)} checks passed.")+ return 1 if failed else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/docs/src/content/docs/cli.mdx b/docs/src/content/docs/cli.mdxindex ca72c952..39a141a1 100644--- a/docs/src/content/docs/cli.mdx+++ b/docs/src/content/docs/cli.mdx@@ -95,6 +95,34 @@ cocoindex auth sign-in [OPTIONS] COMMAND [ARGS]...---+### `auth sign-in google-docs`++Sign in with a Google account to keep Google Docs in its Drive.++Asks only for access to the files CocoIndex creates (drive.file): the docs+it creates and edits, nothing else in the Drive. The sign-in is kept apart+from `auth sign-in google-drive`'s.++Uses CocoIndex's own OAuth client when this release includes one. To use a+Desktop-app OAuth client of your own, pass CLIENT_SECRETS, the JSON file you+downloaded for it.+++**Usage:**++```bash+cocoindex auth sign-in google-docs [OPTIONS] [CLIENT_SECRETS]+```++**Options:**++| Option | Description |+|--------|-------------|+| `--token-path FILE` | Where to keep the sign-in; default: cocoindex/google_docs_token.json under the user's config directory. |+| `--help` | Show this message and exit. |++---+### `auth sign-in google-drive`Sign in with a Google account to read its Google Drive.@@ -141,6 +169,29 @@ cocoindex auth sign-out [OPTIONS] COMMAND [ARGS]...---+### `auth sign-out google-docs`++Revoke the Google Docs sign-in at Google and delete its token file.++Google revokes everything the OAuth client holds for the account, so an+`auth sign-in google-drive` made with the same client ends too.+++**Usage:**++```bash+cocoindex auth sign-out google-docs [OPTIONS]+```++**Options:**++| Option | Description |+|--------|-------------|+| `--token-path FILE` | The sign-in to end; default: the one `auth sign-in google-docs` writes by default. |+| `--help` | Show this message and exit. |++---+### `auth sign-out google-drive`Revoke the sign-in at Google and delete its token file.diff --git a/docs/src/content/docs/connectors/google_docs.mdx b/docs/src/content/docs/connectors/google_docs.mdxnew file mode 100644index 00000000..f06eed70--- /dev/null+++ b/docs/src/content/docs/connectors/google_docs.mdx@@ -0,0 +1,159 @@+---+title: "*Google Docs* connector"+toc_max_heading_level: 4+languages: [python]+rust_counterpart: connectors+description: >+ Keep a Google Doc in step with Markdown your flow declares. The doc is+ updated in place, block by block, so unchanged paragraphs and the comments+ on them stay; a person's edits are kept and reported. Signs in with the+ drive.file scope only.+---+The `google_docs` connector keeps a Google Doc in step with Markdown your flow declares: a report, a brief, a summary that people read and comment on in Google Docs. It creates the doc on the first run and, on each change, rewrites only the parts whose content changed.++```python+from cocoindex.connectors import google_docs+```++:::note[Dependencies]+This connector requires additional dependencies. Install with:++```bash+pip install "cocoindex[google_docs]"+```++:::++:::caution[Experimental]+The Google Docs connector is experimental. Experimental APIs are outside CocoIndex's compatibility promise: a later release, including a minor one, may change their API or semantics, or remove them.+:::++## Signing in++The connector writes as your personal Google account, signed in once through OAuth, the same way the [Google Drive connector](./google_drive#signing-in-with-a-personal-account) reads one: an authorization code with PKCE, redirected to a listener on this machine's loopback interface, from a Desktop app OAuth client.++It asks Google for one scope, `drive.file`: access to the files CocoIndex creates, and nothing else. CocoIndex creates Google Docs, and edits and trashes only the docs it created; it cannot see or change any other file in your Drive. Google classes `drive.file` as a non-sensitive scope. CocoIndex's use and transfer of information received from Google APIs adheres to the [Google API Services User Data Policy](https://developers.google.com/terms/api-services-user-data-policy), including the Limited Use requirements; see [how CocoIndex handles Google user data](https://cocoindex.io/privacy-policy/#google-user-data).++The sign-in is separate from the Google Drive connector's: its own command, its own token file and its own scope. Signing in for one never widens or narrows the other. Signing out is different: Google revokes everything an OAuth client holds for an account at once, so signing out of one also ends the other when both used the same OAuth client, and the next run of the other asks you to sign in again.++### Setting up the OAuth client++CocoIndex's own OAuth client is not in a release yet. Until a release includes it, sign in with a Desktop app OAuth client you create in your own Google Cloud project, as for [the Google Drive connector](./google_drive#setting-up-the-oauth-client), with two differences:++1. Enable both the **Google Docs API** and the **Google Drive API** under *APIs & Services > Library*. A run against a project without one of them fails with a message that names it.+2. On the consent screen's *Data access* page, add the scope `.../auth/drive.file` (*See, edit, create, and delete only the specific Google Drive files you use with this app*).++In **Testing** status, Google still expires the consent seven days after it was given; a run then fails with `SignInRequiredError` and you sign in again.++### Signing in++```bash+cocoindex auth sign-in google-docs ~/Downloads/client_secret_XXXX.json+```++Without the file argument, the command uses CocoIndex's own OAuth client, and a release that doesn't include one says so. On a machine with no browser, the command prints the link and takes the address the browser lands on, pasted back, as [`sign-in google-drive`](./google_drive#signing-in) does.++The tokens are stored at `~/.config/cocoindex/google_docs_token.json` on Linux and macOS (under `$XDG_CONFIG_HOME` when set) and under `%APPDATA%\cocoindex` on Windows; `--token-path` picks another location. CocoIndex creates the file readable by your user only and refuses one that other users can access. It holds a long-lived refresh token that can change the docs CocoIndex created: treat it like a password.++```bash+cocoindex auth sign-out google-docs # revokes the sign-in at Google and deletes the token file+```++From Python, `google_docs.UserAccount().sign_in(client_secrets_path)` and `.sign_out()` do the same.++### UserAccount++```python+class UserAccount(token_path: str | os.PathLike[str] | None = None)+UserAccount.token_path -> Path+UserAccount.sign_in(client_secrets_path: str | os.PathLike[str] | None = None) -> str+UserAccount.sign_out() -> bool+UserAccount.email -> str+UserAccount.is_signed_in() -> bool+```++It has the same methods as the Google Drive connector's [`UserAccount`](./google_drive#useraccount), over its own token file. The two classes are distinct: a run that provides a Google Drive `UserAccount` where the Docs target expects this one fails before calling Google.++The access token is refreshed with the stored refresh token as it expires, and the refreshed token is written back to the file. When no sign-in is stored, or Google refuses the stored one, the run raises `SignInRequiredError` (a `SignInError`), whose message says to sign in again.++## As target++### declare_doc++```python+def declare_doc(account: ContextKey[UserAccount], name: str, content: str) -> None+```++Declares a Google Doc whose content is `content`, in Markdown.++- `account` is the [`ContextKey`](../programming_guide/context) under which the app's lifespan provides the signed-in `UserAccount`.+- `name` is the doc's title when it is created, and, with the context key's name, its identity across runs.+- `content` is Markdown; see [Markdown](#markdown).++On the first run, the target creates the doc in your My Drive and tags it with an id it keeps in its own state. From then on it finds the doc by that tag, not by its name: rename the doc or move it to another folder, and the target keeps writing to it. Changing `name` in your code declares a different doc: the old one is trashed and a new one created.++```python+from typing import AsyncIterator++import cocoindex as coco+from cocoindex.connectors import google_docs++GDOCS = coco.ContextKey[google_docs.UserAccount]("gdocs")++async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:+ builder.provide(GDOCS, google_docs.UserAccount())+ yield++async def app_main() -> None:+ report = await write_report() # Markdown+ google_docs.declare_doc(GDOCS, "Weekly brief", report)++app = coco.App("WeeklyBrief", app_main)+```++### How a change is written++An unchanged run makes no call to Google at all: the target compares the declared content with what it wrote last time.++When the content changed, the target reads the doc and writes the difference through the Docs API's `batchUpdate`, in one request:++- **Blocks.** The content is split into blocks: each heading with the paragraphs up to the next heading, and the paragraphs before the first heading. A block is known by its heading path (`Brief > Decisions`), so it keeps its identity while its text changes. Each block is tagged with a [named range](https://developers.google.com/docs/api/how-tos/named-ranges) that records what the target wrote there.+- **Paragraphs.** Within a block that changed, only the paragraphs that changed are deleted and inserted. Unchanged paragraphs, in that block and in every other one, are never touched, so comments, suggestions and links anchored to them stay, and the doc's version history shows only the real changes.+- **New, removed and moved blocks.** A new block is inserted after the block it follows. A block no longer declared is deleted. A block that moved is deleted where it was and written where it now belongs.+- **Concurrent edits.** The write names the revision it was planned on (`requiredRevisionId`). If someone edits the doc between the target's read and its write, Google refuses the write, and the target reads the doc again and plans anew, up to three times.++### A person's edits++People can edit the doc. A block a person changed since the target last wrote it, which the target tells from its named range, **keeps the person's text**:++- The target does not rewrite it, even when the flow's version of the block changed. It logs a warning that names the doc, its link, and each such block by its heading path, and says when the flow had a newer version it did not write. The warning repeats on every write until the edit is resolved.+- When the flow's version becomes the same as the person's text (for example, because the flow took the person's fix in), the block is the target's again, and later changes to it are written.+- A block a person deleted as a whole stays deleted, and is reported the same way.+- A block the flow no longer declares, but that a person edited, is left in the doc with the person's text, and the target lets go of it.++A change of formatting counts as an edit as well, since the target compares the text with its bold, italic, code and links. Text a person adds between blocks belongs to no block, and the target leaves it alone.++### Deleting the declaration++When the declaration goes away (the code no longer declares the doc, or the app is dropped), the target moves the doc to the **trash**. It never deletes a doc permanently: Google Drive keeps a trashed file for 30 days, and you can restore it from there. A doc restored from the trash is not the target's again; the next declaration with the same `name` creates a new doc.++If a person moves the doc to the trash while it is still declared, the next change creates a new doc with the full content.++### Markdown++The target writes the subset of Markdown a report needs:++| Markdown | In the doc |+|----------|------------|+| `#` to `######` headings | Heading 1 to Heading 6 |+| Paragraphs; lines of one paragraph are joined | Normal text |+| `-`, `*` or `+` list items, nested by indentation | Bulleted list, nested up to nine levels |+| `**bold**`, `__bold__` | Bold |+| `*italic*`, `_italic_` | Italic |+| `` `code` `` | Roboto Mono |+| `[text](url)`, `<url>`, bare `http://` and `https://` URLs | Link |+| Fenced code blocks | One Roboto Mono paragraph per line |++Anything else (a table, a numbered list, a block quote) is written as the text it is. A horizontal rule is dropped.diff --git a/docs/src/content/docs/connectors/index.mdx b/docs/src/content/docs/connectors/index.mdxindex 1a8cd2e9..8efed2b9 100644--- a/docs/src/content/docs/connectors/index.mdx+++ b/docs/src/content/docs/connectors/index.mdx@@ -19,7 +19,7 @@ Each connector lives in `cocoindex::connectors::<name>` behind a Cargo feature o</Lang><RustNote>-The Discord source is Python-only: the Rust SDK has no Discord connector, so this page does not list it. See the [Python Discord connector](/docs/connectors/discord/).+The Discord source and the Google Docs target are Python-only: the Rust SDK has no Discord or Google Docs connector, so this page does not list them. See the [Python Discord connector](/docs/connectors/discord/) and the [Python Google Docs connector](/docs/connectors/google_docs/).</RustNote>## Sources@@ -89,6 +89,16 @@ Connectors that export data out of a flow. They're grouped by the kind of store,| [FalkorDB](./falkordb) | Redis-backed Cypher graph, per-graph multitenancy, vector indexes || [SurrealDB](./surrealdb) | Multi-model β normal and relation (edge) tables, vector indexes |+<Lang only="python">++### Documents++| Connector | Notes |+|-----------|-------|+| [Google Docs](./google_docs) | A Google Doc kept in step with declared Markdown, updated in place block by block; signs in with `drive.file` only |++</Lang>+### Message streams| Connector | Also a source | Notes |diff --git a/docs/src/data/docs-sidebar.ts b/docs/src/data/docs-sidebar.tsindex d3b879f7..566933ab 100644--- a/docs/src/data/docs-sidebar.ts+++ b/docs/src/data/docs-sidebar.ts@@ -73,6 +73,7 @@ export const sidebar: SidebarItem[] = [{ type: 'doc', slug: 'connectors/discord', label: 'Discord' },{ type: 'doc', slug: 'connectors/doris', label: 'Apache Doris' },{ type: 'doc', slug: 'connectors/falkordb', label: 'FalkorDB' },+ { type: 'doc', slug: 'connectors/google_docs', label: 'Google Docs' },{ type: 'doc', slug: 'connectors/google_drive', label: 'Google Drive' },{ type: 'doc', slug: 'connectors/iggy', label: 'Iggy' },{ type: 'doc', slug: 'connectors/kafka', label: 'Kafka' },diff --git a/pyproject.toml b/pyproject.tomlindex f0006a49..8b155507 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -94,6 +94,13 @@ google_drive = ["httplib2>=0.22.0","httpx>=0.27.0",]+google_docs = [+ "google-api-python-client>=2.0.0",+ "google-auth>=2.0.0",+ "google-auth-httplib2>=0.2.0",+ "httplib2>=0.22.0",+ "httpx>=0.27.0",+]amazon_s3 = ["aiobotocore>=2.0.0"]azure_blob = ["azure-identity>=1.15.0", "azure-storage-blob>=12.19.0"]doris = ["aiohttp>=3.9.0", "pymysql>=1.1.0", "aiomysql>=0.2.0"]@@ -166,7 +173,8 @@ ci-enabled-optional-deps = ["pymysql>=1.1.0","aiohttp>=3.9.0","valkey-glide>=2.5.2; sys_platform != 'win32'",- # The Google Drive connector's tests, including the OAuth sign-in, run offline.+ # The Google Drive and Google Docs connectors' tests, including the OAuth+ # sign-in, run offline."google-api-python-client>=2.0.0","google-auth>=2.0.0","google-auth-httplib2>=0.2.0",diff --git a/python/cocoindex/cli.py b/python/cocoindex/cli.pyindex 9022e0d4..de2aac14 100644--- a/python/cocoindex/cli.py+++ b/python/cocoindex/cli.py@@ -5,7 +5,7 @@ import osimport signalimport sysimport time-from typing import Any, AsyncIterator, Literal, NamedTuple, TextIO+from typing import TYPE_CHECKING, Any, AsyncIterator, Literal, NamedTuple, TextIOimport pathlibimport click@@ -39,6 +39,9 @@ from cocoindex.inspect import ()from cocoindex._internal.stable_path import StablePath+if TYPE_CHECKING:+ from cocoindex.connectors.google_drive._oauth import UserAccountBase+# ---------------------------------------------------------------------------# Logging setup@@ -1428,12 +1431,37 @@ def auth_sign_out_group() -> None:"""Sign out of an account a connector reads."""-@auth_sign_in_group.command("google-drive")+def _sign_in(account: "UserAccountBase", client_secrets: str | None) -> None:+ """Run ``account``'s interactive sign-in and say who signed in."""+ from cocoindex.connectors.google_drive import SignInError++ try:+ email = account.sign_in(client_secrets)+ except SignInError as exc:+ raise click.ClickException(str(exc)) from exc+ click.echo(f"Signed in as {email}.")+++def _sign_out(account: "UserAccountBase") -> None:+ """End ``account``'s sign-in and say whether there was one."""+ from cocoindex.connectors.google_drive import SignInError++ try:+ existed = account.sign_out()+ except SignInError as exc:+ raise click.ClickException(str(exc)) from exc+ click.echo("Signed out." if existed else "No sign-in was stored.")+++_CLIENT_SECRETS_ARGUMENT = click.argument("client_secrets",required=False,type=click.Path(exists=True, dir_okay=False, resolve_path=True),)+++@auth_sign_in_group.command("google-drive")+@_CLIENT_SECRETS_ARGUMENT@click.option("--token-path",type=click.Path(dir_okay=False),@@ -1451,13 +1479,9 @@ def google_drive_sign_in(client_secrets: str | None, token_path: str | None) ->Opens the consent page in the browser, or prints the link when this host hasnone, and keeps the tokens in a file readable by this user only."""- from cocoindex.connectors.google_drive import SignInError, UserAccount+ from cocoindex.connectors.google_drive import UserAccount- try:- email = UserAccount(token_path).sign_in(client_secrets)- except SignInError as exc:- raise click.ClickException(str(exc)) from exc- click.echo(f"Signed in as {email}.")+ _sign_in(UserAccount(token_path), client_secrets)@auth_sign_out_group.command("google-drive")@@ -1470,13 +1494,53 @@ def google_drive_sign_in(client_secrets: str | None, token_path: str | None) ->)def google_drive_sign_out(token_path: str | None) -> None:"""Revoke the sign-in at Google and delete its token file."""- from cocoindex.connectors.google_drive import SignInError, UserAccount+ from cocoindex.connectors.google_drive import UserAccount- try:- existed = UserAccount(token_path).sign_out()- except SignInError as exc:- raise click.ClickException(str(exc)) from exc- click.echo("Signed out." if existed else "No sign-in was stored.")+ _sign_out(UserAccount(token_path))+++@auth_sign_in_group.command("google-docs")+@_CLIENT_SECRETS_ARGUMENT+ "--token-path",+ type=click.Path(dir_okay=False),+ default=None,+ help="Where to keep the sign-in; default: cocoindex/google_docs_token.json "+ "under the user's config directory.",+)+def google_docs_sign_in(client_secrets: str | None, token_path: str | None) -> None:+ """Sign in with a Google account to keep Google Docs in its Drive.++ Asks only for access to the files CocoIndex creates (drive.file): the docs+ it creates and edits, nothing else in the Drive. The sign-in is kept apart+ from `auth sign-in google-drive`'s.++ Uses CocoIndex's own OAuth client when this release includes one. To use a+ Desktop-app OAuth client of your own, pass CLIENT_SECRETS, the JSON file you+ downloaded for it.+ """+ from cocoindex.connectors.google_docs import UserAccount++ _sign_in(UserAccount(token_path), client_secrets)+++@auth_sign_out_group.command("google-docs")+ "--token-path",+ type=click.Path(dir_okay=False),+ default=None,+ help="The sign-in to end; default: the one `auth sign-in google-docs` "+ "writes by default.",+)+def google_docs_sign_out(token_path: str | None) -> None:+ """Revoke the Google Docs sign-in at Google and delete its token file.++ Google revokes everything the OAuth client holds for the account, so an+ `auth sign-in google-drive` made with the same client ends too.+ """+ from cocoindex.connectors.google_docs import UserAccount++ _sign_out(UserAccount(token_path))if __name__ == "__main__":diff --git a/python/cocoindex/connectors/google_docs/__init__.py b/python/cocoindex/connectors/google_docs/__init__.pynew file mode 100644index 00000000..f7c37ad2--- /dev/null+++ b/python/cocoindex/connectors/google_docs/__init__.py@@ -0,0 +1,12 @@+# `_target` first: when Google's client libraries are missing, it says which+# extra to install before anything imports the Google Drive connector.+from . import _target+from . import _auth+from ._target import *+from ._auth import *+from cocoindex.connectors.google_drive._oauth import SignInError as SignInError+from cocoindex.connectors.google_drive._oauth import (+ SignInRequiredError as SignInRequiredError,+)++__all__ = _target.__all__ + _auth.__all__ + ["SignInError", "SignInRequiredError"]diff --git a/python/cocoindex/connectors/google_docs/_auth.py b/python/cocoindex/connectors/google_docs/_auth.pynew file mode 100644index 00000000..00eaa1e1--- /dev/null+++ b/python/cocoindex/connectors/google_docs/_auth.py@@ -0,0 +1,41 @@+"""The account the Google Docs target writes with: ``drive.file`` only."""++from __future__ import annotations++from cocoindex.connectors.google_drive import _oauth++DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file"++DOCS_GRANT = _oauth.Grant(+ provider="google-docs",+ scope=DRIVE_FILE_SCOPE,+ token_file_name="google_docs_token.json",+ notice=(+ "CocoIndex asks Google for access to only the files it creates in your "+ "Google Drive (drive.file): it creates Google Docs, and edits and trashes "+ "only the docs it created. It cannot see or change any other file."+ ),+ not_granted=(+ "The consent did not grant access to the files CocoIndex creates in "+ "Google Drive; sign in again and keep that permission selected."+ ),+ memo_namespace="cocoindex.google_docs.user_account",+)+++class UserAccount(_oauth.UserAccountBase):+ """A personal Google account signed in to keep Google Docs, kept in a token file.++ Experimental. The sign-in asks for ``drive.file`` only: access to the files+ CocoIndex creates, nothing else in the Drive. Run ``sign_in`` once, outside+ any CocoIndex run (``cocoindex auth sign-in google-docs`` does the same from+ the shell); its token file is separate from the Google Drive source's, so+ signing in for one never changes the other. (Signing out revokes the OAuth+ client's access for the account at Google, which ends both.) A run provides+ ``UserAccount()`` under a ``ContextKey`` that ``declare_doc`` names.+ """++ _grant = DOCS_GRANT+++__all__ = ["UserAccount"]diff --git a/python/cocoindex/connectors/google_docs/_docs.py b/python/cocoindex/connectors/google_docs/_docs.pynew file mode 100644index 00000000..5fda45db--- /dev/null+++ b/python/cocoindex/connectors/google_docs/_docs.py@@ -0,0 +1,831 @@+"""A Google Doc's body read back as paragraphs, and a write planned as ``batchUpdate`` requests.++Each block the target writes (``_markdown.Block``) is tagged with a named range+``cocoindex:<block id>:<fingerprint>``: the fingerprint of the paragraphs the+target wrote there. The doc thereby says by itself which blocks are the+target's and which of them a person has edited since: a block whose+paragraphs no longer match the fingerprint in its range's name.++A write reads the doc, compares each declared block with the block in the doc,+and plans requests that touch only what changed:++- a changed block is diffed paragraph by paragraph; unchanged paragraphs are+ never touched, so comments anchored to them survive;+- every insertion goes strictly inside the block it belongs to (after a+ paragraph, before that paragraph's newline), except a new block's, which+ goes after its previous block's last paragraph; only the named ranges of the+ blocks an insertion touched are recreated, at positions this module+ computes, so nothing depends on how Docs grows a range at its boundary;+- a block a person edited is left as it is and reported.++Positions are UTF-16 code units, as the Docs API counts them.+"""++from __future__ import annotations++import bisect+import re+from collections.abc import Mapping, Sequence+from dataclasses import dataclass, field+from typing import Any, Literal, NamedTuple++from ._markdown import (+ CODE_FONT,+ NORMAL_TEXT,+ Block,+ Paragraph,+ Run,+ fingerprint,+ merge_runs,+)++RANGE_PREFIX = "cocoindex:"+_RANGE_NAME = re.compile(r"^cocoindex:([0-9a-f]{16}):([0-9a-f]{16})$")++# Stands for what is not text (an image, a table) in a paragraph read back.+OBJECT = "οΏΌ"+# The named style of a structural element that is not a paragraph (a table).+_STRUCTURAL = "STRUCTURAL"++_BULLET_PRESET = "BULLET_DISC_CIRCLE_SQUARE"+# Docs' default link color (#1155cc), so a written link looks like a typed one.+_LINK_COLOR = {"color": {"rgbColor": {"red": 0.067, "green": 0.333, "blue": 0.8}}}+++def u16len(text: str) -> int:+ return len(text.encode("utf-16-le")) // 2+++def _u16slice(text: str, start: int, end: int) -> str:+ return text.encode("utf-16-le")[2 * start : 2 * end].decode(+ "utf-16-le", errors="replace"+ )+++def range_name(block_id: str, written: str) -> str:+ return f"{RANGE_PREFIX}{block_id}:{written}"+++# --- reading -------------------------------------------------------------------+++@dataclass(frozen=True)+class _Element:+ """A text run, or an object standing for one character, inside a paragraph."""++ start: int+ end: int+ text: str+ style: Run # the style of ``text``; its own ``text`` is unused+++@dataclass(frozen=True)+class DocParagraph:+ """A paragraph of the body as Docs reports it, or a structural element (a table)."""++ start: int+ end: int+ style: str+ bullet: int | None+ elements: tuple[_Element, ...]++ def clipped(self, start: int, end: int) -> Paragraph:+ """The part of this paragraph inside ``[start, end)``, its newline left out."""+ runs: list[Run] = []+ for element in self.elements:+ lo, hi = max(element.start, start), min(element.end, end)+ if lo >= hi:+ continue+ text = _u16slice(element.text, lo - element.start, hi - element.start)+ style = element.style+ runs.append(Run(text, style.bold, style.italic, style.code, style.link))+ if runs and end >= self.end and runs[-1].text.endswith("\n"):+ last = runs[-1]+ runs[-1] = Run(last.text[:-1], last.bold, last.italic, last.code, last.link)+ return Paragraph(self.style, self.bullet, merge_runs(runs))+++@dataclass(frozen=True)+class OurRange:+ """A named range this target made: the block it tags and what was written there."""++ named_range_id: str+ block_id: str+ written: str+ start: int+ end: int+++@dataclass+class DocState:+ revision_id: str+ # The body in order, the leading section break left out.+ paragraphs: list[DocParagraph]+ ranges: dict[str, OurRange] # by block id+ # Our named ranges beyond the first for one block, or of more than one stretch.+ stray_range_ids: list[str]+ _starts: list[int] = field(init=False, repr=False)+ # Blocks whose range shares text with another block's range.+ _shared: set[str] = field(init=False, repr=False)++ def __post_init__(self) -> None:+ self._starts = [p.start for p in self.paragraphs]+ self._shared = set()+ ordered = sorted(self.ranges.values(), key=lambda r: (r.start, r.end))+ reach = -1 # the furthest end of the ranges before the current one+ for i, rng in enumerate(ordered):+ following = ordered[i + 1] if i + 1 < len(ordered) else None+ if reach > rng.start or (+ following is not None and following.start < rng.end+ ):+ self._shared.add(rng.block_id)+ reach = max(reach, rng.end)++ @property+ def last(self) -> DocParagraph:+ return self.paragraphs[-1]++ def overlapping(self, start: int, end: int) -> list[DocParagraph]:+ first = max(bisect.bisect_right(self._starts, start) - 1, 0)+ found = []+ for p in self.paragraphs[first:]:+ if p.start >= end:+ break+ if p.end > start:+ found.append(p)+ return found++ def content(self, rng: OurRange) -> list[Paragraph]:+ return [+ p.clipped(rng.start, rng.end) for p in self.overlapping(rng.start, rng.end)+ ]++ def whole(self, rng: OurRange) -> bool:+ """Whether ``rng`` spans whole paragraphs, none of them the body's last+ one, and shares none with another block's range."""+ inside = self.overlapping(rng.start, rng.end)+ return (+ bool(inside)+ and inside[0].start == rng.start+ and inside[-1].end == rng.end+ and rng.end <= self.last.start+ and all(p.style != _STRUCTURAL for p in inside)+ and rng.block_id not in self._shared+ )+++def _text_style(style: Mapping[str, Any]) -> Run:+ link = style.get("link") or {}+ target = (+ link.get("url")+ or (f"#heading={link['headingId']}" if link.get("headingId") else None)+ or (f"#bookmark={link['bookmarkId']}" if link.get("bookmarkId") else None)+ )+ font = (style.get("weightedFontFamily") or {}).get("fontFamily")+ return Run(+ "",+ bold=bool(style.get("bold")),+ italic=bool(style.get("italic")),+ code=font == CODE_FONT,+ link=target,+ )+++def _paragraph(element: Mapping[str, Any]) -> DocParagraph:+ start, end = int(element.get("startIndex", 0)), int(element["endIndex"])+ paragraph = element.get("paragraph")+ if paragraph is None:+ # A table, a table of contents or a section break: never ours.+ obj = _Element(start, end, OBJECT, Run(""))+ return DocParagraph(start, end, _STRUCTURAL, None, (obj,))+ elements: list[_Element] = []+ for part in paragraph.get("elements", []):+ p_start, p_end = int(part.get("startIndex", start)), int(part["endIndex"])+ text_run = part.get("textRun")+ if text_run is not None:+ text = str(text_run.get("content", ""))+ style = _text_style(text_run.get("textStyle") or {})+ else:+ text, style = OBJECT * (p_end - p_start), Run("")+ elements.append(_Element(p_start, p_end, text, style))+ paragraph_style = paragraph.get("paragraphStyle") or {}+ bullet = paragraph.get("bullet")+ return DocParagraph(+ start,+ end,+ str(paragraph_style.get("namedStyleType", NORMAL_TEXT)),+ int(bullet.get("nestingLevel", 0)) if bullet is not None else None,+ tuple(elements),+ )+++def read_document(document: Mapping[str, Any]) -> DocState:+ content = (document.get("body") or {}).get("content") or []+ paragraphs = [+ _paragraph(element)+ for element in content+ if "sectionBreak" not in element or element.get("startIndex")+ ]+ ranges: dict[str, OurRange] = {}+ stray: list[str] = []+ for name, group in (document.get("namedRanges") or {}).items():+ if not name.startswith(RANGE_PREFIX):+ continue+ match = _RANGE_NAME.match(name)+ for named in group.get("namedRanges", []):+ spans = named.get("ranges") or []+ if match is None or len(spans) != 1 or spans[0].get("segmentId"):+ stray.append(named["namedRangeId"])+ continue+ rng = OurRange(+ named_range_id=named["namedRangeId"],+ block_id=match.group(1),+ written=match.group(2),+ start=int(spans[0].get("startIndex", 0)),+ end=int(spans[0]["endIndex"]),+ )+ held = ranges.get(rng.block_id)+ if held is None or rng.start < held.start:+ if held is not None:+ stray.append(held.named_range_id)+ ranges[rng.block_id] = rng+ else:+ stray.append(rng.named_range_id)+ return DocState(+ revision_id=str(document.get("revisionId", "")),+ paragraphs=paragraphs,+ ranges=ranges,+ stray_range_ids=stray,+ )+++# --- planning --------------------------------------------------------------------+++@dataclass(frozen=True)+class PersonEdit:+ """A block a person changed since the target last wrote it; the target left it as it is."""++ label: str # the block's heading path, or its first line when no longer declared+ # "edited": the block is there, changed. "deleted": the person removed it+ # all. "undeclared": the flow no longer declares it, so the target let go+ # of it with the person's text in place.+ kind: Literal["edited", "deleted", "undeclared"]+ # The flow has a newer version of the block, which the target did not write.+ withheld: bool+++@dataclass+class Plan:+ requests: list[dict[str, Any]]+ person_edits: list[PersonEdit]+++# same: the doc has the declared block. update: it has an older version the+# target wrote. kept: a person edited it. new: the doc never had it. gone: a+# person deleted it. move: the doc has it out of the declared order.+_Status = Literal["same", "update", "kept", "new", "gone", "move"]+++@dataclass+class _Insert:+ """New paragraphs after ``anchor`` (before its newline) or before it."""++ anchor: DocParagraph+ after: bool+ seq: int # the final order of the first new paragraph: ties go in this order+ paragraphs: list[tuple[str, Paragraph]] = field(+ default_factory=list+ ) # (owner, ...)+ # Paragraphs to delete once the new ones are in, for a replaced stretch.+ replaces: tuple[int, int] | None = None++ @property+ def position(self) -> int:+ return self.anchor.end - 1 if self.after else self.anchor.start+++@dataclass+class _Delete:+ start: int+ end: int+++def _lcs(old: Sequence[Paragraph], new: Sequence[Paragraph]) -> list[tuple[int, int]]:+ """The pairs (i, j) of a longest common subsequence of equal paragraphs."""+ m, n = len(old), len(new)+ lengths = [[0] * (n + 1) for _ in range(m + 1)]+ for i in range(m - 1, -1, -1):+ for j in range(n - 1, -1, -1):+ lengths[i][j] = (+ lengths[i + 1][j + 1] + 1+ if old[i] == new[j]+ else max(lengths[i + 1][j], lengths[i][j + 1])+ )+ pairs: list[tuple[int, int]] = []+ i = j = 0+ while i < m and j < n:+ if old[i] == new[j]:+ pairs.append((i, j))+ i, j = i + 1, j + 1+ elif lengths[i + 1][j] >= lengths[i][j + 1]:+ i += 1+ else:+ j += 1+ return pairs+++def _heaviest_increasing(positions: list[int], weights: list[int]) -> set[int]:+ """Indices of the heaviest subsequence of ``positions`` that increases strictly.++ A Fenwick tree over the positions' ranks keeps, for each prefix of ranks,+ the heaviest subsequence ending there; ties go to the earlier index, so the+ choice is the same on every run.+ """+ n = len(positions)+ rank = {+ i: r + 1+ for r, i in enumerate(sorted(range(n), key=lambda i: (positions[i], i)))+ }+ tree: list[tuple[int, int]] = [(0, 1)] * (n + 1) # (weight, -index) of the best end+ previous = [-1] * n+ best: tuple[int, int] = (0, 1)+ for i in range(n):+ r = rank[i] - 1+ found: tuple[int, int] = (0, 1)+ while r > 0:+ found = max(found, tree[r])+ r -= r & -r+ previous[i] = -found[1] if found[0] > 0 else -1+ entry = (found[0] + weights[i], -i)+ best = max(best, entry)+ r = rank[i]+ while r <= n:+ tree[r] = max(tree[r], entry)+ r += r & -r+ chosen: set[int] = set()+ index = -best[1] if best[0] > 0 else -1+ while index >= 0:+ chosen.add(index)+ index = previous[index]+ return chosen+++def plan_write(+ state: DocState, blocks: Sequence[Block], written_blocks: frozenset[str] | None+) -> Plan:+ """The requests that make the doc's blocks the declared ``blocks``.++ ``written_blocks`` are the blocks the target wrote last time, when known: a+ declared block among them that the doc no longer has was deleted by a+ person, and stays deleted.+ """+ edits: list[PersonEdit] = []+ declared = {block.block_id: block for block in blocks}+ new_fps = {block.block_id: fingerprint(block.paragraphs) for block in blocks}++ # What each declared block is now.+ status: dict[str, _Status] = {}+ for block in blocks:+ rng = state.ranges.get(block.block_id)+ new_fp = new_fps[block.block_id]+ if rng is None:+ if written_blocks is not None and block.block_id in written_blocks:+ status[block.block_id] = "gone"+ edits.append(PersonEdit(block.label, "deleted", withheld=True))+ else:+ status[block.block_id] = "new"+ continue+ current = fingerprint(state.content(rng))+ if not state.whole(rng) or current != rng.written:+ if current == new_fp and state.whole(rng):+ # The person wrote what the flow now says: the block is ours again.+ status[block.block_id] = "same"+ continue+ status[block.block_id] = "kept"+ edits.append(+ PersonEdit(block.label, "edited", withheld=new_fp != rng.written)+ )+ elif current == new_fp:+ status[block.block_id] = "same"+ else:+ status[block.block_id] = "update"++ # Blocks that keep their place: the most already in the declared order. A+ # block a person edited never moves, so the order is chosen around those+ # first; one out of that order stays where it is and anchors nothing.+ placed = [+ b.block_id for b in blocks if status[b.block_id] in ("same", "update", "kept")+ ]+ kept_weight = len(placed) + 1+ in_order = {+ placed[i]+ for i in _heaviest_increasing(+ [state.ranges[block_id].start for block_id in placed],+ [kept_weight if status[block_id] == "kept" else 1 for block_id in placed],+ )+ }+ unmoved = dict(status)+ for block_id in placed:+ if block_id not in in_order and status[block_id] != "kept":+ status[block_id] = "move"+ in_place = {+ block_id+ for block_id in placed+ if (block_id in in_order or status[block_id] == "kept")+ and state.whole(state.ranges[block_id])+ }+ anchors = in_place & in_order++ inserts: list[_Insert] = []+ deletes: list[_Delete] = []+ touched: set[str] = set() # blocks whose named range is recreated+ dropped: set[str] = set() # blocks whose named range is deleted for good++ for rng in state.ranges.values():+ if rng.block_id in declared:+ continue+ dropped.add(rng.block_id)+ if state.whole(rng) and fingerprint(state.content(rng)) == rng.written:+ deletes.append(_Delete(rng.start, rng.end))+ else:+ first = next((p.text for p in state.content(rng) if p.text), "")+ edits.append(PersonEdit(first or "(an empty block)", "undeclared", False))++ seq = 0+ pending: _Insert | None = None # consecutive new blocks share one insertion+ for index, block in enumerate(blocks):+ block_id = block.block_id+ kind = status[block_id]+ if kind in ("new", "move"):+ place = _placement(state, blocks, index, in_order, anchors)+ if place is None and kind == "move":+ # Nowhere to put it in order (its neighbors are a person's):+ # it stays where it is, so the next write finds it there too.+ kind = status[block_id] = unmoved[block_id]+ if state.whole(state.ranges[block_id]):+ in_place.add(block_id)+ else:+ if kind == "move":+ rng = state.ranges[block_id]+ deletes.append(_Delete(rng.start, rng.end))+ anchor, after, neighbor = place or _Place(state.last, False, None)+ if (+ pending is None+ or pending.anchor is not anchor+ or pending.after != after+ ):+ pending = _Insert(anchor, after, seq)+ inserts.append(pending)+ if neighbor is not None:+ touched.add(neighbor)+ pending.paragraphs.extend((block_id, p) for p in block.paragraphs)+ touched.add(block_id)+ seq += len(block.paragraphs)+ continue+ pending = None+ if kind == "same":+ if state.ranges[block_id].written != new_fps[block_id]:+ touched.add(block_id)+ seq += len(block.paragraphs)+ elif kind == "update":+ seq = _diff_block(state, block, seq, inserts, deletes)+ touched.add(block_id)+ elif kind == "kept":+ seq += len(state.content(state.ranges[block_id]))++ # Text inserted at a block's boundary may grow the block on either side.+ for insert in inserts:+ if not insert.after:+ touched.update(+ block_id+ for block_id in in_place+ if insert.anchor.start+ in (state.ranges[block_id].start, state.ranges[block_id].end)+ )++ if not (inserts or deletes or touched or dropped or state.stray_range_ids):+ return Plan([], edits)++ requests: list[dict[str, Any]] = []+ for block_id in sorted(touched | dropped):+ rng = state.ranges.get(block_id)+ if rng is not None:+ requests.append({"deleteNamedRange": {"namedRangeId": rng.named_range_id}})+ for named_range_id in state.stray_range_ids:+ requests.append({"deleteNamedRange": {"namedRangeId": named_range_id}})++ layout = _layout(state, inserts, deletes, in_place)+ ops: list[tuple[int, int, int, _Insert | _Delete]] = [+ (op.position, 1, op.seq, op) for op in inserts+ ] + [(op.start, 0, 0, op) for op in deletes]+ for _, _, _, step in sorted(ops, key=lambda o: o[:3], reverse=True):+ if isinstance(step, _Insert):+ requests.extend(_insert_requests(step, layout.inherits_bullet(step)))+ else:+ requests.append(_delete_request(step.start, step.end))++ for block_id in sorted(touched):+ extent = layout.extents.get(block_id)+ if extent is None:+ continue+ rng = state.ranges.get(block_id)+ kept = status.get(block_id) == "kept" and rng is not None+ written = rng.written if kept and rng is not None else new_fps[block_id]+ requests.append(+ {+ "createNamedRange": {+ "name": range_name(block_id, written),+ "range": {"startIndex": extent[0], "endIndex": extent[1]},+ }+ }+ )+ return Plan(requests, edits)+++class _Place(NamedTuple):+ anchor: DocParagraph+ after: bool # after the anchor (before its newline), or before it+ neighbor: str | None # the block whose named range the insertion touches+++def _placement(+ state: DocState,+ blocks: Sequence[Block],+ index: int,+ in_order: set[str],+ anchors: set[str],+) -> _Place | None:+ """Where the block at ``index`` goes so it sits in the declared order, or ``None``.++ After the nearest block before it that keeps its place; else before the+ nearest one after it; at the end when no block keeps its place. ``None``+ when the neighbors that keep their place are a person's, with no+ paragraph boundary of the target's between them.+ """+ before = next(+ (b.block_id for b in reversed(blocks[:index]) if b.block_id in in_order), None+ )+ after = next(+ (b.block_id for b in blocks[index + 1 :] if b.block_id in in_order), None+ )+ if before is not None and before in anchors:+ rng = state.ranges[before]+ return _Place(state.overlapping(rng.start, rng.end)[-1], True, before)+ if after is not None and after in anchors:+ if before is None or state.ranges[before].end <= state.ranges[after].start:+ rng = state.ranges[after]+ return _Place(state.overlapping(rng.start, rng.end)[0], False, after)+ if before is None and after is None:+ return _Place(state.last, False, None)+ return None+++def _diff_block(+ state: DocState,+ block: Block,+ seq: int,+ inserts: list[_Insert],+ deletes: list[_Delete],+) -> int:+ """Plan the paragraphs of a changed block that changed; the next ``seq``."""+ rng = state.ranges[block.block_id]+ old = state.overlapping(rng.start, rng.end)+ old_paragraphs = [p.clipped(rng.start, rng.end) for p in old]+ new = block.paragraphs+ pairs = _lcs(old_paragraphs, new) + [(len(old), len(new))]+ i = j = 0+ for next_i, next_j in pairs:+ removed, added = old[i:next_i], new[j:next_j]+ if removed:+ insert = _Insert(+ removed[-1], True, seq, replaces=(removed[0].start, removed[-1].end)+ )+ insert.paragraphs.extend((block.block_id, p) for p in added)+ if added:+ inserts.append(insert)+ else:+ deletes.append(_Delete(removed[0].start, removed[-1].end))+ elif added:+ # Before the next unchanged paragraph, which keeps its newline; at+ # the block's end, after its last one, to stay inside the block.+ anchor_after = next_i == len(old)+ anchor = old[i - 1] if anchor_after else old[next_i]+ insert = _Insert(anchor, anchor_after, seq)+ insert.paragraphs.extend((block.block_id, p) for p in added)+ inserts.append(insert)+ seq += len(added) + (1 if next_j < len(new) else 0)+ i, j = next_i + 1, next_j + 1+ return seq+++@dataclass+class _Layout:+ """Where everything lands once the plan is applied."""++ extents: dict[str, tuple[int, int]]+ # For each insertion, the paragraph that follows the new ones once applied.+ _next_bullet: dict[int, bool]++ def inherits_bullet(self, op: _Insert) -> bool:+ return self._next_bullet[id(op)]+++class _Item(NamedTuple):+ """A paragraph of the doc as the plan leaves it."""++ length: int+ owner: str | None # the block whose named range covers it+ bullet: bool+ source: _Insert | None # the insertion that adds it; None for one already there+++def _layout(+ state: DocState,+ inserts: list[_Insert],+ deletes: list[_Delete],+ in_place: set[str],+) -> _Layout:+ before: dict[int, list[_Insert]] = {}+ after: dict[int, list[_Insert]] = {}+ for op in inserts:+ (after if op.after else before).setdefault(op.anchor.start, []).append(op)+ # Deletions span whole paragraphs: the starts of those they remove.+ removed: set[int] = set()+ for lo, hi in [(d.start, d.end) for d in deletes] + [+ op.replaces for op in inserts if op.replaces is not None+ ]:+ removed.update(p.start for p in state.overlapping(lo, hi) if p.start >= lo)+ owner_of: dict[int, str] = {}+ for block_id in in_place:+ rng = state.ranges[block_id]+ for p in state.overlapping(rng.start, rng.end):+ owner_of[p.start] = block_id++ items: list[_Item] = []++ def add_inserts(ops: list[_Insert]) -> None:+ for op in sorted(ops, key=lambda o: o.seq):+ for owner, paragraph in op.paragraphs:+ length = u16len(paragraph.text) + 1+ items.append(_Item(length, owner, paragraph.bullet is not None, op))++ for p in state.paragraphs:+ add_inserts(before.get(p.start, []))+ if p.start not in removed:+ items.append(+ _Item(+ p.end - p.start, owner_of.get(p.start), p.bullet is not None, None+ )+ )+ add_inserts(after.get(p.start, []))++ extents: dict[str, tuple[int, int]] = {}+ next_bullet: dict[int, bool] = {}+ position = state.paragraphs[0].start if state.paragraphs else 1+ for index, item in enumerate(items):+ if item.owner is not None:+ lo, _hi = extents.get(item.owner, (position, position))+ extents[item.owner] = (lo, position + item.length)+ follower = items[index + 1] if index + 1 < len(items) else None+ source = item.source+ if source is not None and (follower is None or follower.source is not source):+ # After an anchor, the new paragraphs split the anchor and take its+ # paragraph style; before one, they take the style of what follows.+ if source.after:+ next_bullet[id(source)] = source.anchor.bullet is not None+ else:+ next_bullet[id(source)] = follower is not None and follower.bullet+ position += item.length+ return _Layout(extents, next_bullet)+++def _delete_request(start: int, end: int) -> dict[str, Any]:+ return {"deleteContentRange": {"range": {"startIndex": start, "endIndex": end}}}+++def _run_style(run: Run) -> tuple[dict[str, Any], list[str]] | None:+ style: dict[str, Any] = {}+ fields: list[str] = []+ if run.bold:+ style["bold"] = True+ fields.append("bold")+ if run.italic:+ style["italic"] = True+ fields.append("italic")+ if run.code:+ style["weightedFontFamily"] = {"fontFamily": CODE_FONT}+ fields.append("weightedFontFamily")+ if run.link is not None:+ style["link"] = {"url": run.link}+ style["underline"] = True+ style["foregroundColor"] = _LINK_COLOR+ fields.extend(["link", "underline", "foregroundColor"])+ return (style, fields) if fields else None+++def _insert_requests(op: _Insert, inherits_bullet: bool) -> list[dict[str, Any]]:+ """Insert ``op``'s paragraphs and give them exactly their declared styles.++ New paragraphs take the paragraph style of the paragraph they split and the+ text style of the character before them, so every style is reset first and+ then set. A list item's nesting level is spelled as leading tabs, which+ ``createParagraphBullets`` reads and removes, so it comes last.+ """+ paragraphs = [p for _, p in op.paragraphs]+ texts = [+ ("\t" * p.bullet if p.bullet is not None else "") + p.text for p in paragraphs+ ]+ position = op.position+ if op.after:+ text = "\n" + "\n".join(texts)+ first = position + 1+ else:+ text = "\n".join(texts) + "\n"+ first = position+ starts: list[int] = []+ cursor = first+ for t in texts:+ starts.append(cursor)+ cursor += u16len(t) + 1+ end = cursor+ requests: list[dict[str, Any]] = [+ {"insertText": {"location": {"index": position}, "text": text}},+ {+ "updateTextStyle": {+ "range": {"startIndex": first, "endIndex": end},+ "textStyle": {},+ "fields": "*",+ }+ },+ ]+ for paragraph, start in zip(paragraphs, starts):+ offset = start + (paragraph.bullet or 0)+ for run in paragraph.runs:+ length = u16len(run.text)+ styled = _run_style(run)+ if styled is not None:+ requests.append(+ {+ "updateTextStyle": {+ "range": {+ "startIndex": offset,+ "endIndex": offset + length,+ },+ "textStyle": styled[0],+ "fields": ",".join(styled[1]),+ }+ }+ )+ offset += length+ if inherits_bullet:+ requests.append(+ {+ "deleteParagraphBullets": {+ "range": {"startIndex": first, "endIndex": end}+ }+ }+ )+ index = 0+ while index < len(paragraphs):+ stop = index+ while (+ stop + 1 < len(paragraphs)+ and paragraphs[stop + 1].style == paragraphs[index].style+ ):+ stop += 1+ stop_end = starts[stop + 1] if stop + 1 < len(starts) else end+ requests.append(+ {+ "updateParagraphStyle": {+ "range": {"startIndex": starts[index], "endIndex": stop_end},+ "paragraphStyle": {"namedStyleType": paragraphs[index].style},+ "fields": "*",+ }+ }+ )+ index = stop + 1+ groups: list[tuple[int, int]] = []+ index = 0+ while index < len(paragraphs):+ if paragraphs[index].bullet is None:+ index += 1+ continue+ stop = index+ while stop + 1 < len(paragraphs) and paragraphs[stop + 1].bullet is not None:+ stop += 1+ stop_end = starts[stop + 1] if stop + 1 < len(starts) else end+ groups.append((starts[index], stop_end))+ index = stop + 1+ for lo, hi in reversed(groups):+ requests.append(+ {+ "createParagraphBullets": {+ "range": {"startIndex": lo, "endIndex": hi},+ "bulletPreset": _BULLET_PRESET,+ }+ }+ )+ if op.replaces is not None:+ requests.append(_delete_request(*op.replaces))+ return requestsdiff --git a/python/cocoindex/connectors/google_docs/_markdown.py b/python/cocoindex/connectors/google_docs/_markdown.pynew file mode 100644index 00000000..54047520--- /dev/null+++ b/python/cocoindex/connectors/google_docs/_markdown.py@@ -0,0 +1,381 @@+"""The Markdown the Google Docs target writes, parsed into paragraphs and blocks.++The subset is what a cited report needs: ATX headings (``#`` to ``######``),+paragraphs, bullet lists (nested by indentation), links (``[text](url)``,+``<url>`` and bare ``http(s)://`` URLs), bold, italic and inline code. Fenced+code becomes one monospace paragraph per line. Anything else (a table, a quote,+a numbered list) stays as the text it is.++A *block* is a heading and the paragraphs up to the next heading, or the+paragraphs before the first heading. Blocks are what the target compares and+rewrites, so each has a key that stays put while its text changes: the path of+headings that leads to it.++Paragraphs are the same model the target reads back from a document+(``_docs.py``), so what was written and what is there compare as equals.+"""++from __future__ import annotations++import hashlib+import json+import re+from dataclasses import dataclass++# The font that marks inline code, written and read back.+CODE_FONT = "Roboto Mono"++NORMAL_TEXT = "NORMAL_TEXT"+HEADING_STYLES = tuple(f"HEADING_{level}" for level in range(1, 7))++# Google Docs nests a list nine levels deep, 0 to 8.+MAX_NESTING_LEVEL = 8++# Characters Docs strips from inserted text (its insertText reference), and the+# object replacement character this module uses for what is not text. Taken out+# here, so what is written and what Docs keeps compare as equals.+_STRIPPED = re.compile("[\x00-\x08\x0c-\x1fξ-ο£ΏοΏΌ]")+++@dataclass(frozen=True)+class Run:+ """A stretch of a paragraph's text in one style."""++ text: str+ bold: bool = False+ italic: bool = False+ code: bool = False+ link: str | None = None++ def styled_like(self, other: Run) -> bool:+ return (self.bold, self.italic, self.code, self.link) == (+ other.bold,+ other.italic,+ other.code,+ other.link,+ )+++@dataclass(frozen=True)+class Paragraph:+ """One paragraph: its named style, its list nesting level, its runs."""++ style: str # NORMAL_TEXT or HEADING_1 ... HEADING_6+ bullet: int | None # the list nesting level, None outside a list+ runs: tuple[Run, ...]++ @property+ def text(self) -> str:+ return "".join(run.text for run in self.runs)++ def canonical(self) -> list[object]:+ return [+ self.style,+ self.bullet,+ [[r.text, r.bold, r.italic, r.code, r.link] for r in self.runs],+ ]+++@dataclass(frozen=True)+class Block:+ """A heading and its paragraphs up to the next heading; the preamble has no heading."""++ block_id: str+ # The headings that lead to this block, outermost first; () for the preamble.+ path: tuple[str, ...]+ paragraphs: tuple[Paragraph, ...]++ @property+ def label(self) -> str:+ """How a report names the block."""+ return " > ".join(self.path) if self.path else "(before the first heading)"+++def merge_runs(runs: list[Run]) -> tuple[Run, ...]:+ """Adjacent runs of one style joined, empty runs dropped: one spelling per text."""+ merged: list[Run] = []+ for run in runs:+ if not run.text:+ continue+ if merged and merged[-1].styled_like(run):+ last = merged[-1]+ merged[-1] = Run(+ last.text + run.text, last.bold, last.italic, last.code, last.link+ )+ else:+ merged.append(run)+ return tuple(merged)+++def fingerprint(paragraphs: tuple[Paragraph, ...] | list[Paragraph]) -> str:+ """A short, stable digest of paragraphs, as they would read back from Docs."""+ payload = json.dumps(+ [p.canonical() for p in paragraphs], ensure_ascii=False, separators=(",", ":")+ )+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]+++# --- inline ------------------------------------------------------------------++_ESCAPABLE = set("\\`*_{}[]()#+-.!<>|~")+_LINK = re.compile(+ r"\[((?:[^\[\]\\]|\\.)*)\]" # [text]+ r"\(\s*<?((?:[^\s()<>]|\([^\s()<>]*\))+)>?" # (url, with balanced parentheses+ r"(?:\s+\"[^\"]*\")?\s*\)" # and an optional "title")+)+_AUTOLINK = re.compile(r"<(https?://[^\s<>]+)>")+_BARE_URL = re.compile(r"https?://[^\s<>\[\]]+")+_URL_TRAILING = ".,;:!?'\")"+++@dataclass(frozen=True)+class _Style:+ bold: bool = False+ italic: bool = False+ code: bool = False+ link: str | None = None++ def run(self, text: str) -> Run:+ return Run(text, self.bold, self.italic, self.code, self.link)+++def _closing(text: str, marker: str, start: int) -> int:+ """Where the emphasis opened before ``start`` closes, or -1."""+ position = start+ while True:+ found = text.find(marker, position)+ if found < 0:+ return -1+ if text[found - 1] == "\\":+ position = found + 1+ continue+ if found == start or text[found - 1].isspace():+ position = found + 1+ continue+ after = found + len(marker)+ if marker[0] == "_" and after < len(text) and text[after].isalnum():+ position = found + 1+ continue+ if len(marker) == 1 and text.startswith(marker * 2, found):+ # ``**`` inside a single-marker span belongs to a bold span.+ closing_double = _closing(text, marker * 2, found + 2)+ if closing_double >= 0:+ position = closing_double + 2+ continue+ return found+++def _bare_url(text: str, start: int) -> tuple[str, int] | None:+ match = _BARE_URL.match(text, start)+ if match is None:+ return None+ url = match.group(0)+ while url and url[-1] in _URL_TRAILING:+ if url[-1] == ")" and url.count("(") >= url.count(")"):+ break+ url = url[:-1]+ return url, start + len(url)+++def parse_inline(text: str, style: _Style = _Style()) -> list[Run]:+ runs: list[Run] = []+ buffer: list[str] = []++ def flush() -> None:+ if buffer:+ runs.append(style.run("".join(buffer)))+ buffer.clear()++ i = 0+ while i < len(text):+ char = text[i]+ if char == "\\" and i + 1 < len(text) and text[i + 1] in _ESCAPABLE:+ buffer.append(text[i + 1])+ i += 2+ continue+ if char == "`":+ ticks = len(text[i:]) - len(text[i:].lstrip("`"))+ end = text.find("`" * ticks, i + ticks)+ if end >= 0:+ flush()+ code = text[i + ticks : end]+ if code.startswith(" ") and code.endswith(" ") and code.strip():+ code = code[1:-1]+ runs.append(+ _Style(style.bold, style.italic, True, style.link).run(code)+ )+ i = end + ticks+ continue+ buffer.append(text[i : i + ticks])+ i += ticks+ continue+ if char == "[" and style.link is None:+ match = _LINK.match(text, i)+ if match is not None:+ flush()+ inner = _Style(style.bold, style.italic, style.code, match.group(2))+ runs.extend(parse_inline(match.group(1), inner))+ i = match.end()+ continue+ if char == "<" and style.link is None:+ match = _AUTOLINK.match(text, i)+ if match is not None:+ flush()+ url = match.group(1)+ runs.append(_Style(style.bold, style.italic, style.code, url).run(url))+ i = match.end()+ continue+ if char == "h" and style.link is None and (i == 0 or not text[i - 1].isalnum()):+ bare = _bare_url(text, i)+ if bare is not None:+ flush()+ url, i = bare+ runs.append(_Style(style.bold, style.italic, style.code, url).run(url))+ continue+ if char in "*_":+ double = text.startswith(char * 2, i)+ marker = char * 2 if double else char+ opens = i + len(marker) < len(text) and not text[i + len(marker)].isspace()+ if char == "_" and i > 0 and text[i - 1].isalnum():+ opens = False+ if opens:+ end = _closing(text, marker, i + len(marker))+ if end >= 0:+ flush()+ inner = (+ _Style(True, style.italic, style.code, style.link)+ if double+ else _Style(style.bold, True, style.code, style.link)+ )+ runs.extend(parse_inline(text[i + len(marker) : end], inner))+ i = end + len(marker)+ continue+ buffer.append(marker)+ i += len(marker)+ continue+ buffer.append(char)+ i += 1+ flush()+ return runs+++# --- blocks of lines ------------------------------------------------------------++_HEADING = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$")+_BULLET = re.compile(r"^([ \t]*)[-*+][ \t]+(.*)$")+_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")+_RULE = re.compile(r"^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$")+++def _indent_width(prefix: str) -> int:+ return len(prefix.expandtabs(4))+++def _clean(text: str) -> str:+ return _STRIPPED.sub("", text)+++def _paragraph(style: str, bullet: int | None, text: str) -> Paragraph:+ return Paragraph(style, bullet, merge_runs(parse_inline(_clean(text).strip())))+++def parse(markdown: str) -> list[Paragraph]:+ """The paragraphs of ``markdown``, in order; blank paragraphs dropped outside code."""+ paragraphs: list[Paragraph] = []+ lines = markdown.replace("\r\n", "\n").replace("\r", "\n").split("\n")+ # The paragraph being gathered: (bullet level or None, lines so far).+ pending: tuple[int | None, list[str]] | None = None+ list_indents: list[int] = []+ fence: str | None = None++ def flush() -> None:+ nonlocal pending+ if pending is not None:+ level, parts = pending+ paragraph = _paragraph(NORMAL_TEXT, level, " ".join(parts))+ if paragraph.runs or level is not None:+ paragraphs.append(paragraph)+ pending = None++ for line in lines:+ if fence is not None:+ if line.strip().startswith(fence) and not line.strip().strip(fence[0]):+ fence = None+ continue+ text = _clean(line.expandtabs(4))+ runs = (Run(text, code=True),) if text else ()+ paragraphs.append(Paragraph(NORMAL_TEXT, None, runs))+ continue+ fence_match = _FENCE.match(line)+ if fence_match is not None:+ flush()+ list_indents.clear()+ fence = fence_match.group(1)+ continue+ if not line.strip():+ flush()+ continue+ heading = _HEADING.match(line)+ if heading is not None:+ flush()+ list_indents.clear()+ text = heading.group(2) or ""+ paragraph = _paragraph(+ HEADING_STYLES[len(heading.group(1)) - 1], None, text+ )+ if paragraph.runs:+ paragraphs.append(paragraph)+ continue+ if _RULE.match(line):+ flush()+ list_indents.clear()+ continue+ bullet = _BULLET.match(line)+ if bullet is not None:+ flush()+ indent = _indent_width(bullet.group(1))+ while list_indents and list_indents[-1] > indent:+ list_indents.pop()+ if not list_indents or list_indents[-1] < indent:+ list_indents.append(indent)+ level = min(len(list_indents) - 1, MAX_NESTING_LEVEL)+ pending = (level, [bullet.group(2)])+ continue+ if pending is not None:+ # A continuation line of the paragraph or list item being gathered.+ pending[1].append(line.strip())+ continue+ list_indents.clear()+ pending = (None, [line.strip()])+ flush()+ return paragraphs+++def split_blocks(paragraphs: list[Paragraph]) -> list[Block]:+ """The blocks of ``paragraphs``: the preamble, if any, then one per heading."""+ groups: list[tuple[tuple[str, ...], list[Paragraph]]] = []+ path: list[tuple[int, str]] = [] # (level, text) of the enclosing headings+ for paragraph in paragraphs:+ if paragraph.style in HEADING_STYLES:+ level = HEADING_STYLES.index(paragraph.style)+ while path and path[-1][0] >= level:+ path.pop()+ path.append((level, paragraph.text))+ groups.append((tuple(text for _, text in path), [paragraph]))+ elif groups:+ groups[-1][1].append(paragraph)+ else:+ groups.append(((), [paragraph]))+ seen: dict[tuple[str, ...], int] = {}+ blocks: list[Block] = []+ for block_path, block_paragraphs in groups:+ occurrence = seen.get(block_path, 0)+ seen[block_path] = occurrence + 1+ key = json.dumps([list(block_path), occurrence], ensure_ascii=False)+ block_id = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]+ blocks.append(Block(block_id, block_path, tuple(block_paragraphs)))+ return blocks+++def parse_blocks(markdown: str) -> list[Block]:+ return split_blocks(parse(markdown))diff --git a/python/cocoindex/connectors/google_docs/_target.py b/python/cocoindex/connectors/google_docs/_target.pynew file mode 100644index 00000000..517e3ba6--- /dev/null+++ b/python/cocoindex/connectors/google_docs/_target.py@@ -0,0 +1,359 @@+"""Google Docs target: a doc the target creates and keeps in step with declared Markdown.++The doc is found by a tag of the target's own (a Drive ``appProperties`` entry+holding an id kept in the tracking record), not by its name, so a person may+rename or move it. A change is written in place through the Docs API's+``batchUpdate``: only the blocks whose content changed (see ``_docs.py``), with+``requiredRevisionId`` so that an edit made while the target writes is read and+planned around rather than overwritten. A block a person edited since the+target wrote it keeps the person's text and is reported. Deleting the+declaration moves the doc to the trash.+"""++from __future__ import annotations++import asyncio+import json+import logging+import uuid+from dataclasses import dataclass+from typing import Any, Collection, NamedTuple, Sequence++from cocoindex._internal.extras import install_hint++try:+ import httplib2 # type: ignore+ from google_auth_httplib2 import AuthorizedHttp # type: ignore+ from googleapiclient.discovery import build # type: ignore+ from googleapiclient.errors import HttpError # type: ignore+except ImportError as e:+ raise ImportError(+ "google-auth and google-api-python-client are required to use the Google Docs target. "+ + install_hint("google_docs")+ ) from e++import msgspec++import cocoindex as coco+from cocoindex._internal.context_keys import ContextKey, ContextProvider+from cocoindex._internal.datatype import TypeChecker+from cocoindex.connectorkits.fingerprint import fingerprint_str+from cocoindex.connectors.google_drive._oauth import SignInRequiredError++from . import _docs, _markdown+from ._auth import UserAccount++_logger = logging.getLogger(__name__)++# Attempts after the first for a Docs or Drive request that may be repeated+# safely; googleapiclient retries a 5xx, a 429 and a rate-limit 403 with backoff.+# A batchUpdate is safe to repeat: its requiredRevisionId refuses a second+# application. Creating a doc is not, so it is never retried.+_RETRIES = 5+# Reads and plans of one write, when a person edits between the read and the write.+_WRITE_ATTEMPTS = 3+_DOC_MIME = "application/vnd.google-apps.document"+# The Drive appProperties key that tags a doc with the target's id for it.+_TAG_PROPERTY = "cocoindexDoc"+# Raised when what a declaration writes changes, so every doc is planned again.+_FORMAT_VERSION = 1+++def _new_http() -> Any:+ """The transport under every Docs and Drive request; tests replace it."""+ return httplib2.Http(timeout=60)+++def doc_url(doc_id: str) -> str:+ return f"https://docs.google.com/document/d/{doc_id}/edit"+++# --- target state ------------------------------------------------------------+++class _DocKey(NamedTuple):+ account_key: str # the ContextKey the UserAccount is provided under+ name: str+++_KEY_CHECKER = TypeChecker(tuple[str, str])+++class _DocRecord(msgspec.Struct, frozen=True):+ # The target's id for the doc, in the doc's appProperties: Google assigns+ # the doc's own id when the sink creates it, after this record is fixed.+ tag: str+ content_fingerprint: bytes+ # The blocks the declaration had: a later write tells a block a person+ # deleted from one that is new.+ block_ids: tuple[str, ...]+++@dataclass(frozen=True)+class _DocAction:+ key: _DocKey+ tags: tuple[str, ...]+ blocks: tuple[_markdown.Block, ...] | None # None: trash the doc+ written_blocks: frozenset[str] | None+++def _content_fingerprint(content: str) -> bytes:+ return fingerprint_str(f"{_FORMAT_VERSION}\n{content}")+++class _DocHandler(coco.TargetHandler[str, _DocRecord, None]):+ def reconcile(+ self,+ key: coco.StableKey,+ desired_target_state: str | coco.NonExistenceType,+ prev_possible_records: Collection[_DocRecord],+ prev_may_be_missing: bool,+ /,+ ) -> coco.TargetReconcileOutput[_DocAction, _DocRecord, None] | None:+ doc_key = _DocKey(*_KEY_CHECKER.check(key))+ tags = sorted({record.tag for record in prev_possible_records})+ if coco.is_non_existence(desired_target_state):+ if not tags:+ return None+ return coco.TargetReconcileOutput(+ action=_DocAction(doc_key, tuple(tags), None, None),+ sink=_sink,+ tracking_record=coco.NON_EXISTENCE,+ )+ content_fp = _content_fingerprint(desired_target_state)+ tag = tags[0] if tags else uuid.uuid4().hex+ if (+ not prev_may_be_missing+ and prev_possible_records+ and all(r.content_fingerprint == content_fp for r in prev_possible_records)+ ):+ return None+ blocks = tuple(_markdown.parse_blocks(desired_target_state))+ written: frozenset[str] | None = None+ if len(prev_possible_records) == 1 and not prev_may_be_missing:+ written = frozenset(next(iter(prev_possible_records)).block_ids)+ return coco.TargetReconcileOutput(+ action=_DocAction(doc_key, (tag,), blocks, written),+ sink=_sink,+ tracking_record=_DocRecord(+ tag=tag,+ content_fingerprint=content_fp,+ block_ids=tuple(block.block_id for block in blocks),+ ),+ )+++# --- talking to Google ---------------------------------------------------------+++def _explained(exc: HttpError) -> Exception | None:+ """What to do about a refusal Google explains; ``None`` for any other."""+ try:+ error = json.loads(exc.content)["error"]+ except (ValueError, KeyError, TypeError):+ return None+ if not isinstance(error, dict):+ return None+ reasons = {+ str(item.get("reason"))+ for item in (error.get("details") or []) + (error.get("errors") or [])+ if isinstance(item, dict)+ }+ message = str(error.get("message") or "")+ if reasons & {"SERVICE_DISABLED", "accessNotConfigured"}:+ return RuntimeError(+ "A Google API the Google Docs target needs is not enabled for the OAuth "+ f"client's project: {message} Enable the Google Docs API and the Google "+ "Drive API there (APIs & Services > Library), then run again."+ )+ if reasons & {"ACCESS_TOKEN_SCOPE_INSUFFICIENT", "insufficientPermissions"}:+ return SignInRequiredError(+ "The stored sign-in does not grant access to the files CocoIndex creates "+ "in Google Drive. Sign in with `cocoindex auth sign-in google-docs`."+ )+ return None+++def _execute(request: Any, retries: int = _RETRIES) -> Any:+ try:+ return request.execute(num_retries=retries)+ except HttpError as exc:+ explained = _explained(exc)+ if explained is None:+ raise+ raise explained from exc+++class _Google:+ """The Docs and Drive calls of one write, signed with the account's token."""++ def __init__(self, account: UserAccount) -> None:+ http = AuthorizedHttp(account._credentials(), http=_new_http())+ self._docs = build("docs", "v1", http=http, cache_discovery=False)+ self._drive = build("drive", "v3", http=http, cache_discovery=False)++ def find(self, tag: str) -> str | None:+ """The doc tagged ``tag`` that is not in the trash; the oldest, if copies carry the tag."""+ query = (+ f"appProperties has {{ key='{_TAG_PROPERTY}' and value='{tag}' }} "+ "and trashed = false"+ )+ response = _execute(+ self._drive.files().list(+ q=query, spaces="drive", fields="files(id, createdTime)", pageSize=100+ )+ )+ files = sorted(+ response.get("files", []),+ key=lambda f: (str(f.get("createdTime", "")), str(f["id"])),+ )+ return str(files[0]["id"]) if files else None++ def create(self, name: str, tag: str) -> str:+ body = {+ "name": name,+ "mimeType": _DOC_MIME,+ "appProperties": {_TAG_PROPERTY: tag},+ }+ created = _execute(+ self._drive.files().create(body=body, fields="id"), retries=0+ )+ return str(created["id"])++ def trash(self, doc_id: str) -> None:+ try:+ _execute(+ self._drive.files().update(+ fileId=doc_id, body={"trashed": True}, supportsAllDrives=True+ )+ )+ except HttpError as exc:+ if exc.resp.status != 404:+ raise++ def get(self, doc_id: str) -> Any:+ return _execute(+ self._docs.documents().get(+ documentId=doc_id, fields="revisionId,body(content),namedRanges"+ )+ )++ def update(+ self, doc_id: str, requests: list[dict[str, Any]], revision_id: str+ ) -> bool:+ """Apply ``requests`` to revision ``revision_id``; ``False`` when the doc moved on."""+ body = {+ "requests": requests,+ "writeControl": {"requiredRevisionId": revision_id},+ }+ try:+ _execute(self._docs.documents().batchUpdate(documentId=doc_id, body=body))+ except HttpError as exc:+ if exc.resp.status != 400:+ raise+ current = _execute(+ self._docs.documents().get(documentId=doc_id, fields="revisionId")+ )+ if current.get("revisionId") == revision_id:+ raise+ return False+ return True+++def _apply_action(account: UserAccount, action: _DocAction) -> None:+ google = _Google(account)+ name = action.key.name+ if action.blocks is None:+ for tag in action.tags:+ doc_id = google.find(tag)+ if doc_id is not None:+ google.trash(doc_id)+ _logger.info(+ "Moved Google Doc %r to the trash: %s", name, doc_url(doc_id)+ )+ return++ (tag,) = action.tags+ written_blocks = action.written_blocks+ doc_id = google.find(tag)+ if doc_id is None:+ doc_id = google.create(name, tag)+ # A new doc (the first, or one replacing a doc that was deleted or+ # trashed) has none of the blocks yet; none of them was deleted by a person.+ written_blocks = None+ _logger.info("Created Google Doc %r: %s", name, doc_url(doc_id))++ for _ in range(_WRITE_ATTEMPTS):+ state = _docs.read_document(google.get(doc_id))+ plan = _docs.plan_write(state, action.blocks, written_blocks)+ if not plan.requests or google.update(doc_id, plan.requests, state.revision_id):+ break+ else:+ raise RuntimeError(+ f"Google Doc {name!r} ({doc_url(doc_id)}) changed every time CocoIndex "+ f"read it to write, {_WRITE_ATTEMPTS} times; run again once it is quiet."+ )+ if plan.person_edits:+ _logger.warning(+ "Google Doc %r (%s) keeps a person's edits; CocoIndex left these blocks "+ "as they are: %s",+ name,+ doc_url(doc_id),+ "; ".join(_describe(edit) for edit in plan.person_edits),+ )+++def _describe(edit: _docs.PersonEdit) -> str:+ if edit.kind == "deleted":+ what = "deleted; the flow still declares it, and it was not written back"+ elif edit.kind == "undeclared":+ what = "edited, then no longer declared: left with the person's text"+ elif edit.withheld:+ what = "edited; the flow's newer version was not written"+ else:+ what = "edited"+ return f"{edit.label!r} ({what})"+++async def _apply(+ context_provider: ContextProvider, actions: Sequence[_DocAction]+) -> None:+ for action in actions:+ account = context_provider.get(action.key.account_key, UserAccount)+ await asyncio.to_thread(_apply_action, account, action)+++_sink = coco.TargetActionSink.from_async_fn(_apply)+_provider = coco.register_root_target_states_provider(+ "cocoindex/google_docs", _DocHandler()+)+++# --- public API ----------------------------------------------------------------+++def declare_doc(account: ContextKey[UserAccount], name: str, content: str) -> None:+ """Declare a Google Doc named ``name`` whose content is ``content``, in Markdown (experimental).++ The target creates the doc in the account's My Drive on the first run and+ keeps it in step after that, rewriting only the blocks (a heading and its+ paragraphs) whose content changed. A block a person edited since the+ target wrote it keeps the person's text and is reported in a warning.+ When the declaration goes away, the doc moves to the trash.++ Args:+ account: The ``ContextKey`` the run provides the signed-in+ ``UserAccount`` under. Its name, with ``name``, identifies the doc.+ name: The doc's title when it is created, and its identity: a person+ may rename or move the doc, and the target keeps writing to it.+ content: Markdown: headings, paragraphs, bullet lists, links, bold,+ italic and inline code.+ """+ if not name:+ raise ValueError("declare_doc needs a non-empty name")+ target_state = _provider.target_state(_DocKey(account.key, name), content)+ coco.declare_target_state(target_state)+++__all__ = ["declare_doc"]diff --git a/python/cocoindex/connectors/google_drive/_oauth.py b/python/cocoindex/connectors/google_drive/_oauth.pyindex e10f6c23..393cbb5b 100644--- a/python/cocoindex/connectors/google_drive/_oauth.py+++ b/python/cocoindex/connectors/google_drive/_oauth.py@@ -9,6 +9,11 @@ authorization link instead and accepts the address the browser lands on,pasted back. ``GoogleDriveSource`` then signs its requests with the storedaccess token and refreshes it with the refresh token as it expires.+What a sign-in asks Google for is its ``Grant``: Drive's ``UserAccount`` asks+for ``drive.readonly``; the Google Docs target's account, a sibling class over+the same flow, asks for ``drive.file`` and keeps its own token file, so one+sign-in never widens or narrows the other.+What the file holds is a credential, so this module keeps it out ofeverything that persists or prints: the file is created ``0600`` and refusedwhen another user can read it; no token enters a memo key (an account is@@ -39,7 +44,7 @@ from collections.abc import Callable, Mappingfrom dataclasses import dataclass, replacefrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any+from typing import Any, ClassVarimport httpxfrom google.auth import credentials as google_credentials # type: ignore@@ -98,14 +103,44 @@ class _Refusal(SignInError):self.description = description-def default_token_path() -> Path:- """Where ``UserAccount()`` keeps its token: under the user's config directory."""+@dataclass(frozen=True)+class Grant:+ """What a sign-in asks Google for, and where and how it keeps what Google returns."""++ # The provider's name in `cocoindex auth sign-in <provider>`.+ provider: str+ scope: str+ # The token file's name under the user's config directory.+ token_file_name: str+ # The data notice's first line: what the scope lets CocoIndex do.+ notice: str+ # The error when the consent came back without ``scope``.+ not_granted: str+ # The first element of an account's memo key.+ memo_namespace: str+++DRIVE_READONLY_GRANT = Grant(+ provider="google-drive",+ scope=DRIVE_READONLY_SCOPE,+ token_file_name="google_drive_token.json",+ notice="CocoIndex asks Google for read-only access to your Google Drive.",+ not_granted=(+ "The consent did not grant read access to Google Drive; sign in again "+ "and keep the Drive permission selected."+ ),+ memo_namespace="cocoindex.google_drive.user_account",+)+++def default_token_path(grant: Grant = DRIVE_READONLY_GRANT) -> Path:+ """Where an account of ``grant`` keeps its token by default: under the user's config directory."""if os.name == "nt":base = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")else:xdg = os.environ.get("XDG_CONFIG_HOME", "").strip()base = Path(xdg) if xdg else Path.home() / ".config"- return base / "cocoindex" / "google_drive_token.json"+ return base / "cocoindex" / grant.token_file_name@dataclass@@ -524,10 +559,10 @@ def _await_redirect(raise SignInError("The sign-in timed out before Google redirected back.")-def _data_notice(token_path: Path) -> str:+def _data_notice(token_path: Path, grant: Grant) -> str:"""What the sign-in asks Google for, and where it keeps what Google returns."""return (- "CocoIndex asks Google for read-only access to your Google Drive.\n"+ f"{grant.notice}\n"f"The sign-in is stored at {token_path}, on this computer only; ""nothing is sent to CocoIndex.\n"f"How CocoIndex handles Google user data: {PRIVACY_POLICY}\n"@@ -569,6 +604,7 @@ def _instructions(url: str, port: int, browser_opened: bool) -> str:def _run_consent(client_cfg: _Client,*,+ scope: str,http_client: httpx.Client,open_browser: Callable[[str], object],read_line: Callable[[], str | None],@@ -600,7 +636,7 @@ def _run_consent("response_type": "code","client_id": client_cfg.client_id,"redirect_uri": redirect_uri,- "scope": DRIVE_READONLY_SCOPE,+ "scope": scope,"state": state,"code_challenge": challenge,"code_challenge_method": "S256",@@ -665,6 +701,7 @@ def run_sign_in(client_secrets_path: Path | None,token_path: Path,*,+ grant: Grant = DRIVE_READONLY_GRANT,http_client: httpx.Client | None = None,open_browser: Callable[[str], object] = webbrowser.open,read_line: Callable[[], str | None] = _read_stdin_line,@@ -672,7 +709,7 @@ def run_sign_in(browser_available: bool | None = None,timeout: float = SIGN_IN_TIMEOUT_SECONDS,) -> str:- """Sign in and store the tokens at ``token_path``; the account's address.+ """Sign in for ``grant`` and store the tokens at ``token_path``; the account's address.``client_secrets_path`` is the downloaded JSON of the user's own Desktop appclient; ``None`` takes the client built into this release, and fails when@@ -687,7 +724,7 @@ def run_sign_in(# Said before the browser opens or the link prints: Google's verification# of a restricted scope wants the app itself to disclose how it uses the# data, not only the privacy policy.- say(_data_notice(token_path))+ say(_data_notice(token_path, grant))if browser_available is None:browser_available = has_browser()owned = http_client is None@@ -695,6 +732,7 @@ def run_sign_in(try:payload = _run_consent(client_cfg,+ scope=grant.scope,http_client=http_client,open_browser=open_browser,read_line=read_line,@@ -703,11 +741,8 @@ def run_sign_in(timeout=timeout,)granted = str(payload.get("scope") or "").split()- if granted and DRIVE_READONLY_SCOPE not in granted:- raise SignInError(- "The consent did not grant read access to Google Drive; sign in "- "again and keep the Drive permission selected."- )+ if granted and grant.scope not in granted:+ raise SignInError(grant.not_granted)refresh_token = payload.get("refresh_token")if not isinstance(refresh_token, str) or not refresh_token:raise SignInError(@@ -735,25 +770,25 @@ def run_sign_in(# --- the public handle --------------------------------------------------------class UserAccount:- """A personal Google account signed in with OAuth, kept in a token file.+class UserAccountBase:+ """A personal Google account signed in with OAuth for one ``Grant``, kept in a token file.- Experimental. ``sign_in`` is the interactive step; run it once, outside any- CocoIndex run (``cocoindex auth sign-in google-drive`` does the same from- the shell). A run then passes ``UserAccount()`` to ``GoogleDriveSource``,- which reads the file and raises ``SignInRequiredError`` when it holds no- usable sign-in.+ Each connector's account is a subclass that names its grant; the classes+ are siblings, so an account signed in for one connector's scope is never+ taken for another's."""+ _grant: ClassVar[Grant]+def __init__(self, token_path: str | os.PathLike[str] | None = None) -> None:self._token_path = (Path(token_path).expanduser()if token_path is not None- else default_token_path()+ else default_token_path(self._grant))def __repr__(self) -> str:- return f"UserAccount(token_path={str(self._token_path)!r})"+ return f"{type(self).__name__}(token_path={str(self._token_path)!r})"@propertydef token_path(self) -> Path:@@ -773,7 +808,7 @@ class UserAccount:if client_secrets_path is not Noneelse None)- return run_sign_in(path, self._token_path)+ return run_sign_in(path, self._token_path, grant=self._grant)def sign_out(self) -> bool:"""Revoke the stored sign-in at Google and delete the token file; whether one existed.@@ -807,7 +842,7 @@ class UserAccount:def __coco_memo_key__(self) -> object:# The account, never its tokens: a refreshed token must not invalidate# memoized work, a different account must.- return ("cocoindex.google_drive.user_account", self.email)+ return (self._grant.memo_namespace, self.email)def _tokens(self) -> _Tokens:tokens = _load_tokens(self._token_path)@@ -815,16 +850,30 @@ class UserAccount:raise SignInRequiredError(f"No usable Google sign-in is stored at {self._token_path}. ""Sign in once with "- "`cocoindex auth sign-in google-drive <client_secret.json>` "+ f"`cocoindex auth sign-in {self._grant.provider} <client_secret.json>` ""or `UserAccount().sign_in(...)`.")return tokensdef _credentials(self) -> _UserCredentials:- """What signs Drive API requests; refreshed as it expires and persisted."""+ """What signs Google API requests; refreshed as it expires and persisted."""return _UserCredentials(self._token_path, self._tokens())+class UserAccount(UserAccountBase):+ """A personal Google account signed in with OAuth to read its Drive, kept in a token file.++ Experimental. ``sign_in`` is the interactive step; run it once, outside any+ CocoIndex run (``cocoindex auth sign-in google-drive`` does the same from+ the shell). A run then passes ``UserAccount()`` to ``GoogleDriveSource``,+ which reads the file and raises ``SignInRequiredError`` when it holds no+ usable sign-in. The sign-in asks for read-only access to Drive+ (``drive.readonly``).+ """++ _grant = DRIVE_READONLY_GRANT++class _UserCredentials(google_credentials.Credentials): # type: ignore[misc]"""google-auth credentials over the token file, so ``googleapiclient`` can use them.diff --git a/python/tests/connectors/test_google_docs_target.py b/python/tests/connectors/test_google_docs_target.pynew file mode 100644index 00000000..1c383f38--- /dev/null+++ b/python/tests/connectors/test_google_docs_target.py@@ -0,0 +1,1302 @@+"""The Google Docs target, against a fake Google Docs and Drive API.++No network and no real account. ``FakeGoogle`` plays the Docs API (a document+kept as UTF-16 code units, with Docs' style inheritance on insertion, named+ranges and revision ids), the Drive API (doc creation, lookup by+``appProperties``, trash) behind the ``httplib2`` transport the target signs+with, and Google's OAuth endpoints behind ``httpx.MockTransport``. Its named+ranges grow when text is inserted at either of their boundaries, the least+helpful reading of Docs' behavior, so the target must not depend on it.++A *comment* in the fake is anchored to the code units of a quoted text, as a+Docs comment is: it survives only if those units were never deleted.+"""++from __future__ import annotations++import copy+import json+import logging+import os+import pathlib+import socket+import stat+import threading+import urllib.parse+from dataclasses import dataclass, field+from typing import Any, Callable++import pytest+from click.testing import CliRunner++import cocoindex as coco+from tests import common++try:+ import httplib2 # type: ignore[import-untyped]+ import httpx++ from cocoindex.connectors import google_docs, google_drive+ from cocoindex.connectors.google_docs import _auth, _docs, _markdown, _target+ from cocoindex.connectors.google_drive import _oauth++ HAS_GOOGLE = True+except ImportError:+ HAS_GOOGLE = False++pytestmark = pytest.mark.skipif(+ not HAS_GOOGLE,+ reason="google-auth / google-api-python-client / httpx are not installed",+)++coco_env = common.create_test_env(__file__)++GDOCS: coco.ContextKey[google_docs.UserAccount] = coco.ContextKey("gdocs")+CLIENT_ID = "123-fake.apps.googleusercontent.com"+CLIENT_SECRET = "fake-client-secret"+EMAIL = "[email protected]"+++# --- the fake document ----------------------------------------------------------+++@dataclass(eq=False)+class _Unit:+ """One UTF-16 code unit; a newline carries its paragraph's style and bullet."""++ ch: str+ style: dict[str, Any]+ para: dict[str, Any] | None = None+++class BadRequest(Exception):+ pass+++def _code_units(text: str) -> list[str]:+ raw = text.encode("utf-16-le", "surrogatepass")+ return [+ raw[i : i + 2].decode("utf-16-le", "surrogatepass")+ for i in range(0, len(raw), 2)+ ]+++class FakeDoc:+ """A document body: index ``i`` is ``units[i - 1]``; index 0 is the section break."""++ def __init__(self, doc_id: str) -> None:+ self.doc_id = doc_id+ self.units = [+ _Unit(+ "\n", {}, {"style": {"namedStyleType": "NORMAL_TEXT"}, "bullet": None}+ )+ ]+ self.ranges: dict[str, tuple[str, int, int]] = {} # id -> (name, start, end)+ self.revision = 1+ self._next_range = 0+ self.comments: dict[str, tuple[str, list[_Unit]]] = {}++ @property+ def end(self) -> int:+ return len(self.units) + 1++ def spans(self) -> list[tuple[int, int]]:+ spans, start = [], 1+ for i, unit in enumerate(self.units):+ if unit.ch == "\n":+ spans.append((start, i + 2))+ start = i + 2+ return spans++ def _overlapping(self, start: int, end: int) -> list[tuple[int, int]]:+ return [(s, e) for s, e in self.spans() if s < end and e > start]++ def _newline_at_or_after(self, index: int) -> _Unit:+ for unit in self.units[index - 1 :]:+ if unit.ch == "\n":+ return unit+ raise BadRequest("no paragraph")++ # Editing, as the Docs API does it.++ def insert(self, index: int, text: str) -> None:+ if not 1 <= index <= self.end - 1 or not text:+ raise BadRequest(f"insertText at {index} (end {self.end})")+ pos = index - 1+ style = dict(self.units[pos - 1].style) if pos > 0 else {}+ para = self._newline_at_or_after(index).para # the paragraph being split+ new = [+ _Unit(ch, dict(style), copy.deepcopy(para) if ch == "\n" else None)+ for ch in _code_units(text)+ ]+ self.units[pos:pos] = new+ n = len(new)+ for rid, (name, s, e) in list(self.ranges.items()):+ if index < s:+ s, e = s + n, e + n+ elif index <= e:+ e += n # grows at either boundary: the least helpful reading+ self.ranges[rid] = (name, s, e)++ def delete(self, start: int, end: int, *, keep_last: bool = True) -> None:+ if not 1 <= start < end <= (self.end - 1 if keep_last else self.end):+ raise BadRequest(f"deleteContentRange [{start}, {end}) (end {self.end})")+ del self.units[start - 1 : end - 1]+ n = end - start++ def shift(x: int) -> int:+ return x if x <= start else (start if x <= end else x - n)++ for rid, (name, s, e) in list(self.ranges.items()):+ s, e = shift(s), shift(e)+ if s >= e:+ del self.ranges[rid]+ else:+ self.ranges[rid] = (name, s, e)++ def _check_range(self, start: int, end: int) -> None:+ if not 1 <= start < end <= self.end:+ raise BadRequest(f"range [{start}, {end}) (end {self.end})")++ def apply(self, request: dict[str, Any]) -> None:+ ((kind, body),) = request.items()+ rng = body.get("range") or {}+ start, end = int(rng.get("startIndex", 0)), int(rng.get("endIndex", 0))+ if kind == "insertText":+ self.insert(body["location"]["index"], body["text"])+ elif kind == "deleteContentRange":+ self.delete(start, end)+ elif kind == "updateTextStyle":+ self._check_range(start, end)+ fields = body["fields"]+ if not fields:+ raise BadRequest("no fields")+ for unit in self.units[start - 1 : end - 1]:+ if fields == "*":+ unit.style = copy.deepcopy(body["textStyle"])+ continue+ for name in fields.split(","):+ if name in body["textStyle"]:+ unit.style[name] = copy.deepcopy(body["textStyle"][name])+ else:+ unit.style.pop(name, None)+ elif kind == "updateParagraphStyle":+ self._check_range(start, end)+ for s, e in self._overlapping(start, end):+ para = self.units[e - 2].para+ assert para is not None+ if body["fields"] == "*":+ para["style"] = copy.deepcopy(body["paragraphStyle"])+ else:+ for name in body["fields"].split(","):+ para["style"][name] = body["paragraphStyle"][name]+ elif kind == "deleteParagraphBullets":+ self._check_range(start, end)+ for s, e in self._overlapping(start, end):+ para = self.units[e - 2].para+ assert para is not None+ if para["bullet"] is not None:+ # Docs keeps the nesting visible as an indent.+ para["style"]["indentStart"] = {+ "magnitude": 36 * (para["bullet"] + 1)+ }+ para["bullet"] = None+ elif kind == "createParagraphBullets":+ self._check_range(start, end)+ for s, e in reversed(self._overlapping(start, end)):+ tabs = 0+ while self.units[s - 1 + tabs].ch == "\t":+ tabs += 1+ if tabs:+ self.delete(s, s + tabs)+ para = self.units[e - 2 - tabs].para+ assert para is not None+ para["bullet"] = min(tabs, 8)+ elif kind == "createNamedRange":+ self._check_range(start, end)+ self._next_range += 1+ self.ranges[f"nr-{self._next_range}"] = (body["name"], start, end)+ elif kind == "deleteNamedRange":+ if body.get("namedRangeId") not in self.ranges:+ raise BadRequest(f"no named range {body.get('namedRangeId')}")+ del self.ranges[body["namedRangeId"]]+ else:+ raise BadRequest(f"unknown request {kind}")++ def clone(self) -> tuple[FakeDoc, dict[int, tuple[_Unit, _Unit]]]:+ """A copy to try a batch on, and (copy, original) by the copy's id.++ The map holds every copy, so no unit the batch creates can take the id+ of a copy the batch deleted.+ """+ trial = FakeDoc(self.doc_id)+ trial.units = [+ _Unit(u.ch, copy.deepcopy(u.style), copy.deepcopy(u.para))+ for u in self.units+ ]+ trial.ranges = dict(self.ranges)+ trial._next_range = self._next_range+ return trial, {id(c): (c, u) for c, u in zip(trial.units, self.units)}++ def commit(self, trial: FakeDoc, origin: dict[int, tuple[_Unit, _Unit]]) -> None:+ """Take the batch's result, keeping the unit objects that survived it."""+ units = []+ for c in trial.units:+ pair = origin.get(id(c))+ if pair is None:+ units.append(c)+ else:+ original = pair[1]+ original.style, original.para = c.style, c.para+ units.append(original)+ self.units, self.ranges = units, trial.ranges+ self._next_range = trial._next_range++ # What documents.get returns.++ def to_json(self) -> dict[str, Any]:+ content: list[dict[str, Any]] = [+ {"endIndex": 1, "sectionBreak": {"sectionStyle": {}}}+ ]+ for s, e in self.spans():+ units = self.units[s - 1 : e - 1]+ elements = []+ i = 0+ while i < len(units):+ j = i+ while j + 1 < len(units) and units[j + 1].style == units[i].style:+ j += 1+ text = "".join(u.ch for u in units[i : j + 1])+ text = text.encode("utf-16-le", "surrogatepass").decode("utf-16-le")+ elements.append(+ {+ "startIndex": s + i,+ "endIndex": s + j + 1,+ "textRun": {+ "content": text,+ "textStyle": copy.deepcopy(units[i].style),+ },+ }+ )+ i = j + 1+ para = units[-1].para+ assert para is not None+ paragraph: dict[str, Any] = {+ "elements": elements,+ "paragraphStyle": copy.deepcopy(para["style"]),+ }+ if para["bullet"] is not None:+ paragraph["bullet"] = {"listId": "kix.list"}+ if para["bullet"]:+ paragraph["bullet"]["nestingLevel"] = para["bullet"]+ content.append({"startIndex": s, "endIndex": e, "paragraph": paragraph})+ named: dict[str, Any] = {}+ for rid, (name, s, e) in self.ranges.items():+ named.setdefault(name, {"name": name, "namedRanges": []})[+ "namedRanges"+ ].append(+ {+ "namedRangeId": rid,+ "name": name,+ "ranges": [{"startIndex": s, "endIndex": e}],+ }+ )+ return {+ "documentId": self.doc_id,+ "revisionId": f"rev-{self.revision}",+ "body": {"content": content},+ "namedRanges": named,+ }++ # What a test reads, and what a person does.++ def lines(self) -> list[tuple[str, int | None, str]]:+ """Each paragraph as (named style, nesting level, text), the empty last one left out."""+ out = []+ for s, e in self.spans()[:-1]:+ units = self.units[s - 1 : e - 2]+ text = "".join(u.ch for u in units).encode("utf-16-le", "surrogatepass")+ para = self.units[e - 2].para+ assert para is not None+ out.append(+ (+ para["style"].get("namedStyleType", ""),+ para["bullet"],+ text.decode("utf-16-le"),+ )+ )+ return out++ def find(self, text: str) -> int:+ joined = "".join(u.ch for u in self.units)+ offset = joined.find("".join(_code_units(text)))+ assert offset >= 0, f"{text!r} not in the doc"+ return offset + 1++ def range_names(self) -> dict[str, str]:+ """Named range id -> name."""+ return {rid: name for rid, (name, _, _) in self.ranges.items()}++ def range_text(self, rid: str) -> str:+ _, s, e = self.ranges[rid]+ return "".join(u.ch for u in self.units[s - 1 : e - 1])++ def person_replace(self, old: str, new: str) -> None:+ index = self.find(old)+ self.insert(index + len(_code_units(old)), new)+ self.delete(index, index + len(_code_units(old)))+ self.revision += 1++ def person_delete_paragraph(self, text: str) -> None:+ index = self.find(text)+ span = next((s, e) for s, e in self.spans() if s <= index < e)+ self.delete(*span)+ self.revision += 1++ def comment(self, quoted: str) -> str:+ index = self.find(quoted)+ cid = f"c{len(self.comments) + 1}"+ units = self.units[index - 1 : index - 1 + len(_code_units(quoted))]+ self.comments[cid] = (quoted, units)+ return cid++ def comment_survives(self, cid: str) -> bool:+ quoted, units = self.comments[cid]+ alive = {id(u) for u in self.units}+ return (+ all(id(u) in alive for u in units)+ and "".join(u.ch for u in units) == quoted+ )+++# --- the fake Google --------------------------------------------------------------+++@dataclass+class FakeGoogle:+ docs: dict[str, FakeDoc] = field(default_factory=dict)+ files: dict[str, dict[str, Any]] = field(default_factory=dict)+ valid_tokens: set[str] = field(default_factory=set)+ refresh_tokens: set[str] = field(default_factory=lambda: {"refresh-1"})+ issued: int = 0+ calls: list[tuple[str, str]] = field(default_factory=list) # (method, path)+ token_requests: list[dict[str, str]] = field(default_factory=list)+ # Runs once right after the next documents.get: a person typing meanwhile.+ after_read: Callable[[FakeDoc], None] | None = None+ disabled_api: str | None = None # "docs" refuses every Docs call as not enabled+ grant_scope: str = ""++ def issue(self) -> str:+ self.issued += 1+ token = f"access-{self.issued}"+ self.valid_tokens.add(token)+ return token++ def writes(self) -> list[tuple[str, str]]:+ return [call for call in self.calls if call[0] != "GET"]++ def only_doc(self) -> FakeDoc:+ (doc,) = [self.docs[i] for i, f in self.files.items() if not f["trashed"]]+ return doc++ # The Docs and Drive APIs, as googleapiclient calls them.++ def serve(+ self, uri: str, method: str, body: Any, headers: dict[str, str]+ ) -> tuple[int, Any]:+ auth = {k.lower(): v for k, v in (headers or {}).items()}.get(+ "authorization", ""+ )+ if auth.removeprefix("Bearer ") not in self.valid_tokens:+ return 401, {"error": {"code": 401, "message": "Invalid Credentials"}}+ parts = urllib.parse.urlsplit(uri)+ path = urllib.parse.unquote(parts.path)+ query = dict(urllib.parse.parse_qsl(parts.query))+ if isinstance(body, bytes):+ body = body.decode()+ payload = json.loads(body) if body else None+ self.calls.append((method, path))+ if parts.netloc == "docs.googleapis.com":+ if self.disabled_api == "docs":+ return 403, {+ "error": {+ "code": 403,+ "message": "Google Docs API has not been used in project 42 "+ "before or it is disabled.",+ "status": "PERMISSION_DENIED",+ "details": [+ {+ "@type": "type.googleapis.com/google.rpc.ErrorInfo",+ "reason": "SERVICE_DISABLED",+ }+ ],+ }+ }+ return self._docs_api(method, path, query, payload)+ assert parts.netloc == "www.googleapis.com", uri+ return self._drive_api(method, path, query, payload)++ def _docs_api(+ self, method: str, path: str, query: dict[str, str], payload: Any+ ) -> tuple[int, Any]:+ rest = path.removeprefix("/v1/documents/")+ if method == "GET":+ doc = self.docs.get(rest)+ if doc is None:+ return 404, {"error": {"code": 404, "message": "not found"}}+ if query.get("fields") == "revisionId":+ return 200, {"revisionId": f"rev-{doc.revision}"}+ result = doc.to_json()+ if self.after_read is not None:+ edit, self.after_read = self.after_read, None+ edit(doc)+ return 200, result+ doc_id = rest.removesuffix(":batchUpdate")+ doc = self.docs[doc_id]+ required = (payload.get("writeControl") or {}).get("requiredRevisionId")+ if required is not None and required != f"rev-{doc.revision}":+ return 400, {+ "error": {+ "code": 400,+ "message": "The required revision ID does not match.",+ }+ }+ # All or nothing, as Docs applies a batch.+ trial, origin = doc.clone()+ try:+ for request in payload["requests"]:+ trial.apply(request)+ except BadRequest as exc:+ return 400, {"error": {"code": 400, "message": str(exc)}}+ doc.commit(trial, origin)+ doc.revision += 1+ return 200, {"documentId": doc_id, "replies": [{} for _ in payload["requests"]]}++ def _drive_api(+ self, method: str, path: str, query: dict[str, str], payload: Any+ ) -> tuple[int, Any]:+ if path == "/drive/v3/files" and method == "POST":+ doc_id = f"doc-{len(self.files) + 1}"+ self.files[doc_id] = {+ "id": doc_id,+ "name": payload["name"],+ "mimeType": payload["mimeType"],+ "appProperties": dict(payload.get("appProperties") or {}),+ "trashed": False,+ "createdTime": f"2026-11-26T00:00:{len(self.files):02d}Z",+ }+ self.docs[doc_id] = FakeDoc(doc_id)+ return 200, {"id": doc_id}+ if path == "/drive/v3/files" and method == "GET":+ q = query["q"]+ key, value = (+ q.split("key='")[1].split("'")[0],+ q.split("value='")[1].split("'")[0],+ )+ assert "trashed = false" in q+ found = [+ {"id": f["id"], "createdTime": f["createdTime"]}+ for f in self.files.values()+ if f["appProperties"].get(key) == value and not f["trashed"]+ ]+ return 200, {"files": found}+ file_id = path.removeprefix("/drive/v3/files/")+ if method == "PATCH" and file_id in self.files:+ self.files[file_id].update(payload)+ return 200, {"id": file_id}+ return 404, {"error": {"code": 404, "message": "File not found"}}++ # Google's OAuth endpoints, as the sign-in and the token refresh call them (httpx).++ def oauth(self, request: httpx.Request) -> httpx.Response:+ url = str(request.url).split("?")[0]+ if url == _oauth.TOKEN_ENDPOINT:+ form = dict(urllib.parse.parse_qsl(request.content.decode()))+ self.token_requests.append(form)+ assert (+ form["client_id"] == CLIENT_ID+ and form["client_secret"] == CLIENT_SECRET+ )+ if form["grant_type"] == "refresh_token":+ if form["refresh_token"] not in self.refresh_tokens:+ return httpx.Response(400, json={"error": "invalid_grant"})+ return httpx.Response(+ 200, json={"access_token": self.issue(), "expires_in": 3599}+ )+ return httpx.Response(+ 200,+ json={+ "access_token": self.issue(),+ "refresh_token": "refresh-1",+ "expires_in": 3599,+ "scope": self.grant_scope,+ },+ )+ if url == _oauth.ABOUT_ENDPOINT:+ return httpx.Response(200, json={"user": {"emailAddress": EMAIL}})+ if url == _oauth.REVOCATION_ENDPOINT:+ return httpx.Response(200)+ return httpx.Response(404)+++class FakeHttp:+ """The ``httplib2.Http`` the target signs requests on, answered by ``FakeGoogle``."""++ def __init__(self, google: FakeGoogle) -> None:+ self.google = google++ def request(+ self,+ uri: str,+ method: str = "GET",+ body: Any = None,+ headers: dict[str, str] | None = None,+ **_: Any,+ ) -> tuple[Any, bytes]:+ status, payload = self.google.serve(uri, method, body, headers or {})+ response = httplib2.Response(+ {"status": status, "content-type": "application/json"}+ )+ return response, json.dumps(payload).encode()+++# --- fixtures ----------------------------------------------------------------------+++def _write_token_file(path: pathlib.Path, access_token: str, expires_at: float) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps(+ {+ "version": _oauth.TOKEN_FILE_VERSION,+ "client_id": CLIENT_ID,+ "client_secret": CLIENT_SECRET,+ "refresh_token": "refresh-1",+ "access_token": access_token,+ "expires_at": expires_at,+ "email": EMAIL,+ }+ )+ )+ path.chmod(0o600)+++@dataclass+class Setup:+ google: FakeGoogle+ token_path: pathlib.Path+ content: dict[str, str | None] = field(default_factory=lambda: {"content": None})++ def app(self, name: str) -> coco.App[[], None]:+ content = self.content++ @coco.fn+ def main() -> None:+ if content["content"] is not None:+ google_docs.declare_doc(GDOCS, "Weekly brief", content["content"])++ return coco.App(coco.AppConfig(name=name, environment=coco_env), main)++ def run(self, app: coco.App[[], None], content: str | None) -> None:+ self.content["content"] = content+ self.google.calls.clear()+ app.update_blocking()+++def setup(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> Setup:+ google = FakeGoogle(grant_scope=_auth.DRIVE_FILE_SCOPE)+ monkeypatch.setattr(_target, "_new_http", lambda: FakeHttp(google))+ monkeypatch.setattr(+ _oauth,+ "_http_client",+ lambda: httpx.Client(transport=httpx.MockTransport(google.oauth)),+ )+ token_path = tmp_path / "google_docs_token.json"+ _write_token_file(token_path, google.issue(), expires_at=4102444800.0) # 2100+ coco_env.context_provider.provide(GDOCS, google_docs.UserAccount(token_path))+ return Setup(google, token_path)+++BRIEF = """\+Kept current from the sources.++# Brief++## Decisions++- Ship the **connector** in 1.3.+ - Docs come with it, see [the plan](https://example.com/plan).+- Keep `drive.readonly` users unaffected.++## Risks++Google may change *named range* behavior.++## Sources++https://example.com/a and https://example.com/b.+"""+++def _blocks(markdown: str) -> list[_markdown.Block]:+ return _markdown.parse_blocks(markdown)+++def _ranges_by_block(doc: FakeDoc) -> dict[str, tuple[str, str]]:+ """Block id -> (named range id, the range's text)."""+ out = {}+ for rid, name in doc.range_names().items():+ assert name.startswith(_docs.RANGE_PREFIX)+ out[name.split(":")[1]] = (rid, doc.range_text(rid))+ return out+++# --- creating ----------------------------------------------------------------------+++def test_the_first_run_creates_the_doc_with_a_named_range_per_block(+ setup: Setup,+) -> None:+ setup.run(setup.app("create"), BRIEF)+ google = setup.google+ (file,) = google.files.values()+ assert file["name"] == "Weekly brief"+ assert file["mimeType"] == "application/vnd.google-apps.document"+ assert set(file["appProperties"]) == {"cocoindexDoc"}+ doc = google.only_doc()+ assert doc.lines() == [+ ("NORMAL_TEXT", None, "Kept current from the sources."),+ ("HEADING_1", None, "Brief"),+ ("HEADING_2", None, "Decisions"),+ ("NORMAL_TEXT", 0, "Ship the connector in 1.3."),+ ("NORMAL_TEXT", 1, "Docs come with it, see the plan."),+ ("NORMAL_TEXT", 0, "Keep drive.readonly users unaffected."),+ ("HEADING_2", None, "Risks"),+ ("NORMAL_TEXT", None, "Google may change named range behavior."),+ ("HEADING_2", None, "Sources"),+ ("NORMAL_TEXT", None, "https://example.com/a and https://example.com/b."),+ ]+ # Inline styles, as Docs reports them.+ runs = {+ (u.ch, json.dumps(u.style, sort_keys=True))+ for u in doc.units+ if u.style and u.ch not in "\n"+ }+ styles = {style for _, style in runs}+ assert any('"bold": true' in s for s in styles)+ assert any('"italic": true' in s for s in styles)+ assert any('"fontFamily": "Roboto Mono"' in s for s in styles)+ assert any('"url": "https://example.com/plan"' in s for s in styles)+ # One named range per block, spanning exactly its paragraphs.+ blocks = _blocks(BRIEF)+ by_block = _ranges_by_block(doc)+ assert set(by_block) == {b.block_id for b in blocks}+ assert (+ by_block[blocks[3].block_id][1]+ == "Risks\nGoogle may change named range behavior.\n"+ )+ # Read back, the doc is exactly what was declared: nothing left to write.+ state = _docs.read_document(doc.to_json())+ assert (+ _docs.plan_write(state, blocks, frozenset(b.block_id for b in blocks)).requests+ == []+ )+ # One create, one batchUpdate.+ assert [m for m, _ in google.writes()] == ["POST", "POST"]+++def test_an_unchanged_rerun_makes_no_api_call(setup: Setup) -> None:+ app = setup.app("unchanged")+ setup.run(app, BRIEF)+ setup.run(app, BRIEF)+ assert setup.google.calls == []+++def test_a_preview_plans_without_calling_google(setup: Setup) -> None:+ app = setup.app("preview")+ setup.content["content"] = BRIEF+ actions = app.update_blocking(preview=True)+ assert actions is not None and len(actions) == 1+ assert setup.google.calls == [] and setup.google.files == {}+++# --- in-place updates ------------------------------------------------------------------+++def test_a_changed_section_rewrites_only_its_changed_paragraphs(setup: Setup) -> None:+ app = setup.app("change_one")+ setup.run(app, BRIEF)+ doc = setup.google.only_doc()+ before = _ranges_by_block(doc)+ on_risks = doc.comment("Google may change")+ on_kept_bullet = doc.comment("Ship the")+ on_sources = doc.comment("https://example.com/a")++ changed = BRIEF.replace(+ "- Keep `drive.readonly` users unaffected.",+ "- Keep `drive.readonly` users **entirely** unaffected.",+ )+ setup.run(app, changed)++ assert [m for m, _ in setup.google.writes()] == ["POST"] # one batchUpdate+ assert (+ "NORMAL_TEXT",+ 0,+ "Keep drive.readonly users entirely unaffected.",+ ) in doc.lines()+ after = _ranges_by_block(doc)+ decisions = _blocks(BRIEF)[2].block_id+ for block_id, (rid, text) in before.items():+ if block_id == decisions:+ assert after[block_id][0] != rid # recreated with the new fingerprint+ assert "entirely" in after[block_id][1]+ else:+ assert after[block_id] == (rid, text) # the same named range, the same text+ # Comments on other sections, and on the section's unchanged bullet, survive.+ assert doc.comment_survives(on_risks)+ assert doc.comment_survives(on_sources)+ assert doc.comment_survives(on_kept_bullet)+ # And the doc reads back as declared.+ state = _docs.read_document(doc.to_json())+ assert _docs.plan_write(state, _blocks(changed), None).requests == []+++def test_a_removed_section_and_a_new_one(setup: Setup) -> None:+ app = setup.app("remove_add")+ setup.run(app, BRIEF)+ doc = setup.google.only_doc()+ before = _ranges_by_block(doc)+ on_sources = doc.comment("https://example.com/b")++ without_risks = BRIEF.replace(+ "## Risks\n\nGoogle may change *named range* behavior.\n\n", ""+ )+ setup.run(app, without_risks)+ assert [text for _, _, text in doc.lines()] == [+ "Kept current from the sources.",+ "Brief",+ "Decisions",+ "Ship the connector in 1.3.",+ "Docs come with it, see the plan.",+ "Keep drive.readonly users unaffected.",+ "Sources",+ "https://example.com/a and https://example.com/b.",+ ]+ after = _ranges_by_block(doc)+ risks = _blocks(BRIEF)[3].block_id+ assert risks not in after+ assert {k: v for k, v in before.items() if k != risks} == after+ assert doc.comment_survives(on_sources)++ # A new section between two others: only the one before it has its named+ # range recreated (the new text went inside it), with the same text.+ with_open_questions = without_risks.replace(+ "## Sources", "## Open questions\n\n- Which folder?\n\n## Sources"+ )+ setup.run(app, with_open_questions)+ lines = [text for _, _, text in doc.lines()]+ assert lines[6:9] == ["Open questions", "Which folder?", "Sources"]+ final = _ranges_by_block(doc)+ blocks = _blocks(with_open_questions)+ assert final[blocks[3].block_id][1] == "Open questions\nWhich folder?\n"+ assert final[blocks[2].block_id][1] == after[blocks[2].block_id][1]+ for block in (blocks[0], blocks[1], blocks[4]):+ assert final[block.block_id] == after[block.block_id]+ assert doc.comment_survives(on_sources)+ state = _docs.read_document(doc.to_json())+ assert _docs.plan_write(state, blocks, None).requests == []+++def test_a_new_first_section_and_reordered_sections(setup: Setup) -> None:+ app = setup.app("reorder")+ setup.run(app, "## A\n\none\n\n## B\n\ntwo\n\n## C\n\nthree\n")+ doc = setup.google.only_doc()+ on_b = doc.comment("two")+ setup.run(app, "# Top\n\n## A\n\none\n\n## C\n\nthree\n\n## B\n\ntwo\n")+ assert [text for _, _, text in doc.lines()] == [+ "Top",+ "A",+ "one",+ "C",+ "three",+ "B",+ "two",+ ]+ # Moving a block rewrites it: "B" or "C", whichever had to move.+ assert doc.comment_survives(on_b) or doc.lines()[3][2] == "C"+ state = _docs.read_document(doc.to_json())+ blocks = _blocks("# Top\n\n## A\n\none\n\n## C\n\nthree\n\n## B\n\ntwo\n")+ assert _docs.plan_write(state, blocks, None).requests == []+++def test_text_outside_the_basic_plane_counts_utf16_units(setup: Setup) -> None:+ app = setup.app("utf16")+ setup.run(app, "## CafΓ© π\n\n- π **launch** day\n\n## Next\n\nplain\n")+ setup.run(app, "## CafΓ© π\n\n- π **launch** day 2\n\n## Next\n\nplain\n")+ doc = setup.google.only_doc()+ assert doc.lines() == [+ ("HEADING_2", None, "CafΓ© π"),+ ("NORMAL_TEXT", 0, "π launch day 2"),+ ("HEADING_2", None, "Next"),+ ("NORMAL_TEXT", None, "plain"),+ ]+ bold = "".join(u.ch for u in doc.units if u.style.get("bold"))+ assert bold == "launch"+++# --- a person's edits -------------------------------------------------------------------+++def _warnings(caplog: pytest.LogCaptureFixture) -> list[logging.LogRecord]:+ return [+ r+ for r in caplog.records+ if r.name == _target.__name__ and r.levelno >= logging.WARNING+ ]+++def test_a_persons_edit_is_kept_and_reported(+ setup: Setup, caplog: pytest.LogCaptureFixture+) -> None:+ app = setup.app("person_edit")+ setup.run(app, BRIEF)+ doc = setup.google.only_doc()+ doc.person_replace("Google may change", "Google could change")+ risks_rid = _ranges_by_block(doc)[_blocks(BRIEF)[3].block_id][0]++ # The flow changes both the section the person edited and another one.+ changed = BRIEF.replace(+ "*named range* behavior", "*named range* behavior soon"+ ).replace("Ship the", "Ship the new")+ with caplog.at_level(logging.WARNING, logger=_target.__name__):+ setup.run(app, changed)++ texts = [text for _, _, text in doc.lines()]+ assert "Google could change named range behavior." in texts # the person's, kept+ assert "Ship the new connector in 1.3." in texts # the other change, written+ assert risks_rid in doc.ranges # the edited block's range is not touched+ (record,) = _warnings(caplog)+ assert "'Brief > Risks' (edited; the flow's newer version was not written)" in (+ record.getMessage()+ )+ assert (+ "Weekly brief" in record.getMessage()+ and "docs.google.com" in record.getMessage()+ )++ # Once the flow says what the person wrote, the block is the target's again.+ caplog.clear()+ adopted = changed.replace(+ "Google may change *named range* behavior soon.",+ "Google could change *named range* behavior.",+ )+ with caplog.at_level(logging.WARNING, logger=_target.__name__):+ setup.run(app, adopted)+ assert not _warnings(caplog)+ blocks = _blocks(adopted)+ state = _docs.read_document(doc.to_json())+ assert state.ranges[blocks[3].block_id].written == _markdown.fingerprint(+ blocks[3].paragraphs+ )+ # The next change to it is written again.+ setup.run(app, adopted.replace("could change", "will change"))+ assert (+ "NORMAL_TEXT",+ None,+ "Google will change named range behavior.",+ ) in doc.lines()+++def test_a_section_a_person_deleted_stays_deleted(+ setup: Setup, caplog: pytest.LogCaptureFixture+) -> None:+ app = setup.app("person_delete")+ setup.run(app, BRIEF)+ doc = setup.google.only_doc()+ _, start, end = next(+ (n, s, e) for n, s, e in doc.ranges.values() if doc.find("Risks") == s+ )+ doc.delete(start, end)+ doc.revision += 1+ with caplog.at_level(logging.WARNING, logger=_target.__name__):+ setup.run(app, BRIEF.replace("Ship the", "Ship the new"))+ texts = [text for _, _, text in doc.lines()]+ assert "Risks" not in texts and "Ship the new connector in 1.3." in texts+ assert "'Brief > Risks' (deleted" in caplog.text+++def test_an_edit_between_the_read_and_the_write_is_not_overwritten(+ setup: Setup,+) -> None:+ app = setup.app("concurrent")+ setup.run(app, BRIEF)+ doc = setup.google.only_doc()+ # A person edits "Risks" right after the target read the doc to write.+ setup.google.after_read = lambda d: d.person_replace("Google may", "Google might")+ setup.run(app, BRIEF.replace("Google may change", "Google may well change"))+ # The first batchUpdate was refused (stale revision); the second read saw the+ # person's edit, and kept it.+ batch_updates = [c for c in setup.google.writes() if c[1].endswith(":batchUpdate")]+ assert len(batch_updates) == 1+ assert (+ "NORMAL_TEXT",+ None,+ "Google might change named range behavior.",+ ) in doc.lines()+++# --- the trash, and the doc's identity --------------------------------------------------+++def test_deleting_the_declaration_trashes_the_doc(setup: Setup) -> None:+ app = setup.app("trash")+ setup.run(app, BRIEF)+ (doc_id,) = setup.google.files+ setup.run(app, None)+ assert setup.google.files[doc_id]["trashed"] is True+ assert doc_id in setup.google.docs # in the trash, not deleted for good+ assert setup.google.writes() == [("PATCH", f"/drive/v3/files/{doc_id}")]+ # A second drop has nothing left to do.+ setup.run(app, None)+ assert setup.google.calls == []+++def test_a_renamed_doc_keeps_being_written_and_a_trashed_one_is_replaced(+ setup: Setup,+) -> None:+ app = setup.app("identity")+ setup.run(app, BRIEF)+ (doc_id,) = setup.google.files+ setup.google.files[doc_id]["name"] = "Renamed by a person"+ setup.run(app, BRIEF.replace("Ship the", "Ship the new"))+ assert list(setup.google.files) == [doc_id]+ assert setup.google.files[doc_id]["name"] == "Renamed by a person"+ assert "Ship the new connector in 1.3." in [+ t for _, _, t in setup.google.docs[doc_id].lines()+ ]++ # Trashed by a person: the next change writes a new doc, in full.+ setup.google.files[doc_id]["trashed"] = True+ setup.run(app, BRIEF)+ new_doc = setup.google.only_doc()+ assert new_doc.doc_id != doc_id+ assert len(new_doc.lines()) == 10+++# --- the account ------------------------------------------------------------------------+++def test_an_expired_access_token_is_refreshed_during_a_run(setup: Setup) -> None:+ _write_token_file(setup.token_path, "access-stale", expires_at=0)+ setup.run(setup.app("refresh"), BRIEF)+ assert setup.google.only_doc().lines()+ (refresh,) = setup.google.token_requests+ assert (+ refresh["grant_type"] == "refresh_token"+ and refresh["refresh_token"] == "refresh-1"+ )+ stored = json.loads(setup.token_path.read_text())+ assert stored["access_token"] == f"access-{setup.google.issued}"+ assert stored["refresh_token"] == "refresh-1"+ if os.name != "nt":+ assert stat.S_IMODE(setup.token_path.stat().st_mode) == 0o600+++def test_a_disabled_docs_api_says_what_to_enable(setup: Setup) -> None:+ setup.google.disabled_api = "docs"+ with pytest.raises(Exception) as excinfo:+ setup.run(setup.app("disabled"), BRIEF)+ assert "Enable the Google Docs API" in "".join(+ str(e) for e in _chain(excinfo.value)+ )+++def _chain(exc: BaseException) -> list[BaseException]:+ out: list[BaseException] = []+ while exc is not None and exc not in out:+ out.append(exc)+ exc = exc.__cause__ or exc.__context__ # type: ignore[assignment]+ return out+++def test_a_google_drive_account_is_not_taken_for_a_docs_one(setup: Setup) -> None:+ coco_env.context_provider.provide(+ GDOCS,+ google_drive.UserAccount(setup.token_path), # type: ignore[arg-type]+ )+ with pytest.raises(Exception) as excinfo:+ setup.run(setup.app("drive_account"), BRIEF)+ assert "expected UserAccount" in "".join(str(e) for e in _chain(excinfo.value))+ assert setup.google.calls == []+++# --- signing in -----------------------------------------------------------------------+++def test_sign_in_asks_for_drive_file_only_and_keeps_its_own_token_file(+ tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from cocoindex.cli import cli++ google = FakeGoogle(grant_scope=_auth.DRIVE_FILE_SCOPE)+ monkeypatch.setattr(+ _oauth,+ "_http_client",+ lambda: httpx.Client(transport=httpx.MockTransport(google.oauth)),+ )+ monkeypatch.setattr(socket, "getfqdn", lambda name="": name)+ client = tmp_path / "client_secret.json"+ client.write_text(+ json.dumps(+ {"installed": {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET}}+ )+ )+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))+ monkeypatch.setenv("APPDATA", str(tmp_path / "config"))+ asked: list[dict[str, str]] = []++ def browser(url: str) -> None:+ params = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query))+ asked.append(params)+ landing = (+ params["redirect_uri"]+ + "?"+ + urllib.parse.urlencode({"code": "code-1", "state": params["state"]})+ )+ threading.Thread(target=lambda: httpx.get(landing), daemon=True).start()++ interactive = _oauth.run_sign_in++ def scripted(+ client_path: pathlib.Path | None, token: pathlib.Path, **kw: Any+ ) -> str:+ return interactive(+ client_path,+ token,+ grant=kw["grant"],+ http_client=httpx.Client(transport=httpx.MockTransport(google.oauth)),+ open_browser=browser,+ read_line=lambda: None,+ browser_available=True,+ timeout=10,+ )++ monkeypatch.setattr(_oauth, "run_sign_in", scripted)+ result = CliRunner().invoke(cli, ["auth", "sign-in", "google-docs", str(client)])+ assert result.exit_code == 0, result.output+ assert f"Signed in as {EMAIL}." in result.output+ # The notice says what drive.file lets CocoIndex do, before the consent.+ assert "only the files it creates in your Google Drive" in result.output+ assert "edits and trashes only the docs it created" in result.output+ assert "It cannot see or change any other file." in result.output+ (params,) = asked+ assert params["scope"] == "https://www.googleapis.com/auth/drive.file"+ # Its own token file; the Google Drive source's sign-in is untouched.+ docs_token = tmp_path / "config" / "cocoindex" / "google_docs_token.json"+ assert google_docs.UserAccount().token_path == docs_token+ assert json.loads(docs_token.read_text())["email"] == EMAIL+ assert not google_drive.UserAccount().is_signed_in()+ assert google_docs.UserAccount().__coco_memo_key__() == (+ "cocoindex.google_docs.user_account",+ EMAIL,+ )++ result = CliRunner().invoke(cli, ["auth", "sign-out", "google-docs"])+ assert result.exit_code == 0 and "Signed out." in result.output+ assert not docs_token.exists()+++def test_a_consent_without_drive_file_is_refused(+ tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ google = FakeGoogle(grant_scope="openid")+ client = tmp_path / "client_secret.json"+ client.write_text(+ json.dumps(+ {"installed": {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET}}+ )+ )++ def browser(url: str) -> None:+ params = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query))+ landing = (+ params["redirect_uri"]+ + "?"+ + urllib.parse.urlencode({"code": "code-1", "state": params["state"]})+ )+ threading.Thread(target=lambda: httpx.get(landing), daemon=True).start()++ with pytest.raises(google_docs.SignInError, match="files CocoIndex creates"):+ _oauth.run_sign_in(+ client,+ tmp_path / "t.json",+ grant=_auth.DOCS_GRANT,+ http_client=httpx.Client(transport=httpx.MockTransport(google.oauth)),+ open_browser=browser,+ read_line=lambda: None,+ say=lambda _: None,+ browser_available=True,+ timeout=10,+ )+++def test_a_run_without_a_sign_in_names_the_docs_sign_in(+ setup: Setup, tmp_path: pathlib.Path+) -> None:+ coco_env.context_provider.provide(+ GDOCS, google_docs.UserAccount(tmp_path / "none.json")+ )+ with pytest.raises(Exception) as excinfo:+ setup.run(setup.app("no_sign_in"), BRIEF)+ assert "cocoindex auth sign-in google-docs" in "".join(+ str(e) for e in _chain(excinfo.value)+ )+++# --- the Markdown subset -----------------------------------------------------------------+++def test_the_markdown_subset() -> None:+ blocks = _markdown.parse_blocks(+ "Intro *it* and __bold__, snake_case, `a*b`, \\*literal\\*.\n"+ "# One\n"+ "## Two ##\n"+ "- a\n"+ " - b, [x](https://w.org/A_(b))\n"+ " continued\n"+ "- c <https://q.org>\n"+ "\n"+ "```\n"+ "# not a heading\n"+ "```\n"+ "### Two\n"+ "## Two\n"+ )+ assert [b.path for b in blocks] == [+ (),+ ("One",),+ ("One", "Two"),+ ("One", "Two", "Two"),+ ("One", "Two"),+ ]+ # A repeated heading path gets a block id of its own.+ assert len({b.block_id for b in blocks}) == 5+ intro = blocks[0].paragraphs[0]+ assert intro.text == "Intro it and bold, snake_case, a*b, *literal*."+ assert [r.text for r in intro.runs if r.italic] == ["it"]+ assert [r.text for r in intro.runs if r.bold] == ["bold"]+ assert [r.text for r in intro.runs if r.code] == ["a*b"]+ two = blocks[2].paragraphs+ assert [(p.bullet, p.text) for p in two[1:4]] == [+ (0, "a"),+ (1, "b, x continued"),+ (0, "c https://q.org"),+ ]+ assert [r.link for r in two[2].runs if r.link] == ["https://w.org/A_(b)"]+ assert two[4] == _markdown.Paragraph(+ "NORMAL_TEXT", None, (_markdown.Run("# not a heading", code=True),)+ )+++def test_paragraphs_added_in_and_after_a_section_touch_no_other_range(+ setup: Setup,+) -> None:+ app = setup.app("insert_inside")+ original = "## A\n\na1\n\na2\n\n## B\n\nb1\n\nb2\n\n## C\n\nc1\n"+ setup.run(app, original)+ doc = setup.google.only_doc()+ before = _ranges_by_block(doc)+ on_b1, on_b2 = doc.comment("b1"), doc.comment("b2")+ changed = original.replace("b1\n\nb2\n", "b1\n\n- middle\n\nb2\n\nb3 *tail*\n")+ setup.run(app, changed)+ assert [text for _, _, text in doc.lines()] == [+ "A",+ "a1",+ "a2",+ "B",+ "b1",+ "middle",+ "b2",+ "b3 tail",+ "C",+ "c1",+ ]+ after = _ranges_by_block(doc)+ blocks = _blocks(changed)+ for block in (blocks[0], blocks[2]):+ assert after[block.block_id] == before[block.block_id]+ assert after[blocks[1].block_id][1] == "B\nb1\nmiddle\nb2\nb3 tail\n"+ assert doc.comment_survives(on_b1) and doc.comment_survives(on_b2)+ assert (+ _docs.plan_write(_docs.read_document(doc.to_json()), blocks, None).requests+ == []+ )+++def test_an_undeclared_block_a_person_edited_is_left_with_the_persons_text(+ setup: Setup, caplog: pytest.LogCaptureFixture+) -> None:+ app = setup.app("release")+ setup.run(app, "## A\n\na1\n\n## B\n\nb1\n")+ doc = setup.google.only_doc()+ doc.person_replace("b1", "b1 with a note")+ with caplog.at_level(logging.WARNING, logger=_target.__name__):+ setup.run(app, "## A\n\na1\n")+ assert [text for _, _, text in doc.lines()] == ["A", "a1", "B", "b1 with a note"]+ assert len(doc.ranges) == 1 # the target let go of B+ assert "no longer declared" in caplog.text+++def _random_markdown(rng: Any, sections: list[str]) -> str:+ variants = [+ "plain {}",+ "- item {}",+ " - nested {}",+ "- **bold** {} with [link](https://e.com/{})",+ "`code` {} π",+ "*italic* {}",+ ]+ parts = []+ if rng.random() < 0.3:+ parts.append(f"preamble {rng.randrange(3)}")+ for name in sections:+ heading = f"## {name}" if rng.random() < 0.8 else f"## **{name}**"+ parts.append(heading)+ for _ in range(rng.randrange(5)):+ parts.append(+ rng.choice(variants).format(rng.randrange(4), rng.randrange(4))+ )+ return "\n\n".join(parts) + "\n"+++def test_random_successive_versions_leave_exactly_the_declared_doc(+ setup: Setup,+) -> None:+ import random++ rng = random.Random(20261126)+ app = setup.app("fuzz")+ pool = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"]+ sections = rng.sample(pool, 3)+ for step in range(40):+ roll = rng.random()+ if roll < 0.15 and len(sections) < len(pool):+ sections.insert(+ rng.randrange(len(sections) + 1),+ rng.choice([s for s in pool if s not in sections]),+ )+ elif roll < 0.25 and len(sections) > 1:+ sections.remove(rng.choice(sections))+ elif roll < 0.35 and len(sections) > 1:+ i, j = rng.sample(range(len(sections)), 2)+ sections[i], sections[j] = sections[j], sections[i]+ markdown = _random_markdown(rng, sections)+ setup.run(app, markdown)+ doc = setup.google.only_doc()+ expected = [(p.style, p.bullet, p.text) for p in _markdown.parse(markdown)]+ assert doc.lines() == expected, f"step {step}:\n{markdown}"+ blocks = _blocks(markdown)+ state = _docs.read_document(doc.to_json())+ assert _docs.plan_write(state, blocks, None).requests == [], f"step {step}"+ assert set(state.ranges) == {b.block_id for b in blocks}diff --git a/uv.lock b/uv.lockindex 14a6531b..76156e3c 100644--- a/uv.lock+++ b/uv.lock@@ -841,6 +841,13 @@ entity-resolution-llm = [falkordb = [{ name = "falkordb" },]+google-docs = [+ { name = "google-api-python-client" },+ { name = "google-auth" },+ { name = "google-auth-httplib2" },+ { name = "httplib2" },+ { name = "httpx" },+]google-drive = [{ name = "google-api-python-client" },{ name = "google-auth" },@@ -1006,18 +1013,23 @@ requires-dist = [{ name = "falkordb", marker = "extra == 'all'", specifier = ">=1.6.0" },{ name = "falkordb", marker = "extra == 'falkordb'", specifier = ">=1.6.0" },{ name = "google-api-python-client", marker = "extra == 'all'", specifier = ">=2.0.0" },+ { name = "google-api-python-client", marker = "extra == 'google-docs'", specifier = ">=2.0.0" },{ name = "google-api-python-client", marker = "extra == 'google-drive'", specifier = ">=2.0.0" },{ name = "google-auth", marker = "extra == 'all'", specifier = ">=2.0.0" },{ name = "google-auth", marker = "extra == 'bigquery'", specifier = ">=2.0.0" },+ { name = "google-auth", marker = "extra == 'google-docs'", specifier = ">=2.0.0" },{ name = "google-auth", marker = "extra == 'google-drive'", specifier = ">=2.0.0" },{ name = "google-auth-httplib2", marker = "extra == 'all'", specifier = ">=0.2.0" },+ { name = "google-auth-httplib2", marker = "extra == 'google-docs'", specifier = ">=0.2.0" },{ name = "google-auth-httplib2", marker = "extra == 'google-drive'", specifier = ">=0.2.0" },{ name = "google-cloud-bigquery", marker = "extra == 'all'", specifier = ">=3.0.0" },{ name = "google-cloud-bigquery", marker = "extra == 'bigquery'", specifier = ">=3.0.0" },{ name = "httplib2", marker = "extra == 'all'", specifier = ">=0.22.0" },+ { name = "httplib2", marker = "extra == 'google-docs'", specifier = ">=0.22.0" },{ name = "httplib2", marker = "extra == 'google-drive'", specifier = ">=0.22.0" },{ name = "httpx", marker = "extra == 'all'", specifier = ">=0.27.0" },{ name = "httpx", marker = "extra == 'discord'", specifier = ">=0.27.0" },+ { name = "httpx", marker = "extra == 'google-docs'", specifier = ">=0.27.0" },{ name = "httpx", marker = "extra == 'google-drive'", specifier = ">=0.27.0" },{ name = "instructor", marker = "extra == 'all'", specifier = ">=1.0" },{ name = "instructor", marker = "extra == 'entity-resolution-llm'", specifier = ">=1.0" },@@ -1059,7 +1071,7 @@ requires-dist = [{ name = "zvec", marker = "extra == 'all'", specifier = ">=0.5.0" },{ name = "zvec", marker = "extra == 'zvec'", specifier = ">=0.5.0" },]-provides-extras = ["all", "amazon-s3", "azure-blob", "bigquery", "colpali", "discord", "doris", "entity-resolution", "entity-resolution-llm", "falkordb", "google-drive", "iggy", "kafka", "lancedb", "litellm", "neo4j", "oci", "postgres", "qdrant", "sentence-transformers", "snowflake", "sqlite", "surrealdb", "turbopuffer", "valkey", "zvec"]+provides-extras = ["all", "amazon-s3", "azure-blob", "bigquery", "colpali", "discord", "doris", "entity-resolution", "entity-resolution-llm", "falkordb", "google-docs", "google-drive", "iggy", "kafka", "lancedb", "litellm", "neo4j", "oci", "postgres", "qdrant", "sentence-transformers", "snowflake", "sqlite", "surrealdb", "turbopuffer", "valkey", "zvec"][package.metadata.requires-dev]build-test = [