gdocs #
Read, comment on and edit Google Docs from OCaml or from the command line.
Getting text out of a Google Doc is harder than it should be. The export
formats drop structure, and the Google Docs REST API returns a
deeply nested JSON tree. gdocs fetches a document by its ID and converts it
to plain text or to CommonMark Markdown. Headings, lists, emphasis, inline code
and links survive the conversion, and the document's comments can be added as
footnotes. Comment threads can be listed with their replies, replied to and
resolved, and a document can be edited in place by replacing a unique piece
of text or adding a paragraph after one. Authentication uses
gauth. Reading needs the documents.readonly OAuth scope and
reading comments drive.readonly; editing needs documents, and replying
to and resolving comments the full drive scope.
Installation #
Install with opam:
$ opam install gdocs
If opam cannot find the package, it is not in the public
opam-repository yet. Add the overlay repository first:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install gdocs
Usage #
You fetch a document with Gdocs.get, then read it with Document.title,
Document.to_text or Markdown.of_document:
let fetch_markdown http ~token ~document_id =
match Gdocs.get http ~token document_id with
| Error (`Msg m) -> Error m
| Ok doc ->
let body = Gdocs.Markdown.of_document doc in
Ok (Gdocs.Document.title doc, body)
A complete program gets a token from a service account with gauth and runs under Eio:
let run env ~key_path ~document_id =
Eio.Switch.run @@ fun sw ->
let http = Requests_eio.v ~sw ~mono:env#mono_clock ~clock:env#clock env#net in
let clock = Eio.Stdenv.clock env in
match Gauth.Service_account.of_file key_path with
| Error (`Msg m) -> failwith m
| Ok key ->
match
Gauth.Service_account.token http ~clock
~scopes:[ Gdocs.scope_readonly ] key
with
| Error (`Msg m) -> failwith m
| Ok token ->
match Gdocs.get http ~token document_id with
| Ok doc ->
Fmt.pr "# %s@.@.%s@."
(Gdocs.Document.title doc)
(Gdocs.Markdown.of_document doc)
| Error (`Msg m) -> Fmt.pr "fetch failed: %s@." m
Plain text #
Document.to_text joins every textRun in paragraph order. The API
already puts a newline at the end of each paragraph, so the result keeps
the paragraph breaks:
let title_and_text doc =
Gdocs.Document.title doc, Gdocs.Document.to_text doc
Scopes #
let readonly = Gdocs.scope_readonly
let readwrite = Gdocs.scope_readwrite
An HTTP error comes back as a Msg that includes the response status.
A 401 means the token is invalid or expired, a 403 means a scope or
access is missing, and a 404 means no document has that ID.
Comments #
Comments live in the Drive API. Comments.threads fetches every thread of
a document, following the API's pages, and Comments.resolve resolves one,
here with a reply:
let resolve_all_open http ~token ~document_id ~message =
match Gdocs.Comments.threads http ~token document_id with
| Error _ as e -> e
| Ok threads ->
List.iter
(fun (th : Gdocs.Comments.thread) ->
if not th.comment.resolved then
match
Gdocs.Comments.resolve ~content:message http ~token document_id
~comment:th.comment.id
with
| Ok _ -> ()
| Error (`Msg m) -> Fmt.epr "%s: %s@." th.comment.id m)
threads;
Ok ()
Replying and resolving need Comments.scope_readwrite, the full drive
scope. The narrower drive.file scope only covers files the OAuth client
created or opened, so it cannot reach the comments of an existing document.
Editing #
An edit is planned from a freshly fetched document and sent as one
documents.batchUpdate request. Gdocs.replace replaces the only
occurrence of a piece of text, and Gdocs.insert_after adds a paragraph
after the paragraph holding a unique anchor:
let reword http ~token ~document_id =
match
Gdocs.replace http ~token document_id
~old:"we\u{2019}ll ship it \u{2014} eventually"
~by:"we ship it in Q3"
with
| Ok edit -> Fmt.pr "done: %a@." Gdocs.Edit.pp edit
| Error (`Msg m) -> Fmt.epr "not edited: %s@." m
Both refuse text that does not occur or occurs more than once, and text
that spans a paragraph break; quoting more of the surrounding text singles
out an occurrence. The search covers every tab of the body and counts
positions in UTF-16 code units, as the API does, so typographic quotes,
accents and emoji land where they should. The new text keeps its paragraph
and the style of the replaced text. The request requires the revision the
plan was computed from: if someone edits the document in between, the API
refuses it rather than applying it at positions that moved, and nothing is
written. ~dry_run:true plans the edit without sending it, and
Gdocs.Edit.to_json shows the request.
Command-line tool #
The gdocs command makes the same calls. Run gdocs install once to
register an OAuth client with your Google account, then gdocs login to
authorise it in the browser. Both store their files in
$XDG_CONFIG_HOME/google/, where the gsheets and gslides tools find
them too. Each login replaces the saved token. After that,
gdocs md DOCUMENT_ID prints the document as Markdown (add --comments for
its comments), gdocs text DOCUMENT_ID prints the plain text, and
gdocs get DOCUMENT_ID prints the raw JSON.
gdocs login is read-only. gdocs login --write also grants the
documents and drive scopes that the commands below need:
$ gdocs comments DOCUMENT_ID # open threads; --all adds resolved ones
$ gdocs comments DOCUMENT_ID --json # the same, as JSON
$ gdocs reply DOCUMENT_ID COMMENT_ID "Done, see the new wording."
$ gdocs resolve DOCUMENT_ID COMMENT_ID --reply "Integrated, thanks."
$ gdocs replace DOCUMENT_ID --old "the old wording" --new "the new wording"
$ gdocs insert-after DOCUMENT_ID --anchor "end of a paragraph" --text "A new paragraph."
replace and insert-after take --dry-run to print the request instead
of sending it.
A command that fails for lack of a scope says which login to run.
License #
ISC. See LICENSE.md.