Google Docs connector

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, and can be read back as Markdown. Signs in with the drive.file scope only.

Version
v 1.0.14

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. What people change in the doc can be read back, so a flow can take their edits in.

from cocoindex.connectors import google_docs
Dependencies

This connector requires additional dependencies. Install with:

pip install "cocoindex[google_docs]"
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 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, including the Limited Use requirements; see how CocoIndex handles 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, 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

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 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.

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

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, 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

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 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.
  • content is Markdown; see Markdown.

On the first run, the target creates the doc in your My Drive and tags it with an id made from the context key’s name and name. From then on it finds the doc by that tag, not by its title: 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.

The tag depends on the declaration alone, as a table’s name does for a database target. A run that starts with a new state (on another machine, or after deleting the state database) finds the doc and keeps writing to it, and two apps that declare the same name under the same context key name with the same account write the same doc.

from typing import AsyncIterator

import cocoindex as coco
from cocoindex.connectors import google_docs

GDOCS = coco.ContextKey[google_docs.UserAccount]("gdocs")

@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
    builder.provide(GDOCS, google_docs.UserAccount())
    yield

@coco.fn
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 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 block that holds a pending suggestion (made in Suggesting mode, not yet accepted or rejected) is left as it is too, so the suggestion stays, and the warning says it holds one. The flow’s newer version is written once the suggestion is accepted or rejected.

A change of formatting counts as an edit as well, since the target compares the text with its bold, italic, code and links. Whitespace does not: an empty paragraph, a space at either end of a paragraph, or bold that takes in the space after a word. Text a person adds between blocks belongs to no block, and the target leaves it alone.

When a person renames a heading and the flow’s version takes the new name in, the target keeps the block where it is, under its new name, rather than writing it again (the blocks under the heading, whose heading paths changed with it, too).

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. Restored before the next declaration with the same name, the doc is the target’s again; restored after it, it is not, since that declaration created a new doc, and the newer one stays the target’s.

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.

Reading back what people changed

async def read_doc_edits(
    account: ContextKey[UserAccount], name: str, *, last_declared: str
) -> DocEdits | None

@dataclass(frozen=True)
class DocEdits:
    url: str
    edits: tuple[BlockEdit, ...]
    content: str

@dataclass(frozen=True)
class BlockEdit:
    heading_path: tuple[str, ...]
    declared: str
    current: str | None

read_doc_edits returns what people changed in the doc that declare_doc(account, name, ...) keeps, since the target last wrote it, and None when there is no such doc (not created yet, or in the trash). It writes nothing.

last_declared is the Markdown the doc was last declared with: the content of the run that last wrote it. Your code keeps it, for example in coco.use_state. The changes are reported against it:

  • edits lists the blocks people changed, in the order of last_declared. Each has its heading_path as declared (("Brief", "Risks") for the block under ## Risks under # Brief, () for the text before the first heading), its declared text, and its current text in the doc, in Markdown, or None when people deleted it.
  • content is last_declared with those changes applied: each changed block’s text replaced by its current text, each deleted one left out, the rest exactly as declared. Declaring content takes the changes in: those blocks are the target’s again, and their text is not rewritten, so comments on them stay.
  • url is the doc’s link.

A change is told from the target’s own writes the way the target tells it, by the named ranges, and the same things are not counted: whitespace, text between blocks, comments, and formatting other than the Markdown subset’s. A pending suggestion counts once someone accepts it (the target leaves a block that holds one as it is, as it does an edit).

A deleted block leaves no trace in the doc: it is a block of last_declared that the doc no longer has. The target records in the doc which content it was last written from, and when last_declared is not that content (it is newer, or a write failed), no deletion is reported, since a block the doc lacks may never have been written, and a warning names the blocks it lacks. Other edits are reported either way.

@coco.fn
async def app_main() -> None:
    report = await write_report()  # Markdown
    last = coco.use_state("brief", initial_value=None)  # what the doc was declared with
    if last.value is not None:
        doc = await google_docs.read_doc_edits(GDOCS, "Weekly brief", last_declared=last.value)
        if doc is not None and doc.edits:
            for edit in doc.edits:
                print(edit.heading_path, "deleted" if edit.current is None else "edited")
            report = keep_people_edits(report, doc)  # your own policy
    google_docs.declare_doc(GDOCS, "Weekly brief", report)
    last.value = report

A read is a data dependency of the function that made it, as a read of a file is. A memoized function that called read_doc_edits runs again when people edit or delete a block of the doc, or the doc goes to the trash or is replaced, and is reused otherwise. The target’s own writes do not make it run again: after each write the target stamps the doc with the revision it wrote, so that the next run can tell its write from a person’s. Neither does a comment or a pending suggestion. Checking the record costs one Drive and one Docs request per run, and one more read of the doc when the doc’s revision moved for another reason than the target’s write. In a preview, read_doc_edits reads the doc too.

A person’s text comes back in the Markdown below, which parses back to what the doc holds. What the subset cannot spell (a style other than a heading, such as Title; a list item two levels deeper than the one above it) reads back otherwise, and the block stays the person’s after content is declared.

Markdown

The target writes the subset of Markdown a report needs:

MarkdownIn the doc
# to ###### headingsHeading 1 to Heading 6
Paragraphs; lines of one paragraph are joinedNormal text
-, * or + list items, nested by indentationBulleted list, nested up to nine levels
**bold**, __bold__Bold
*italic*, _italic_Italic
`code`Roboto Mono
[text](url), <url>, bare http:// and https:// URLsLink
Fenced code blocksOne 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. A backslash before any ASCII punctuation character writes that character as it is (\*, \#, \[).