google-docs-sync
v0.2.2
Published
Sync a Google Drive folder of Google Docs to local Markdown or MDX files
Maintainers
Readme
google-docs-sync syncs a Google Drive folder of Google Docs to a local directory of Markdown or MDX files, with their images. It is the framework-agnostic core of gatsby-source-google-docs, astro-loader-google-docs and next-google-docs, and it works with any static site generator or script: use it from a build script, a content loader or the command line.
The Markdown conversion is done by google-docs-to-markdown.
Features
- The documents of a folder and of its subfolders, written as one file per document
- Slugs, breadcrumbs and custom metadata taken from the Google Drive tree
- Images downloaded next to the documents, with their paths rewritten
- Incremental syncs: only the documents and images that changed are fetched
- Files that are not part of the sync anymore are deleted
- A Node API and a command line
Installation
npm install google-docs-syncNode 22.12 or later is required. The package is an ES module and comes with its TypeScript types.
Token generation
The sync needs 3 variables, in the environment or in a .env file.
GOOGLE_OAUTH_CLIENT_ID=2...m.apps.googleusercontent.com
GOOGLE_OAUTH_CLIENT_SECRET=Q...axL
GOOGLE_DOCS_TOKEN={"access_token":"ya...J0","refresh_token":"1..mE","scope":"https://www.googleapis.com/auth/documents.readonly https://www.googleapis.com/auth/drive.readonly","token_type":"Bearer","expiry_date":1598284554759}Run the following command at the root of your project to generate them:
npx google-docs-sync-tokenThe command walks you through the setup in the terminal:
- Enable the Google Docs API and the Google Drive API in the Google Cloud console.
- Create an OAuth 2.0 client of type "Desktop app", and paste its
Client IDandClient secretwhen asked. - Authorize the application in your browser.
The variables are written to your .env file, which you should add to your .gitignore. The token can read Google Docs and Google Drive. The generation is done by google-oauth2-env-vars, which tells more about what the command does.
Usage
Node API
import {syncGoogleDocs} from "google-docs-sync"
const {documents, files} = await syncGoogleDocs({
// https://drive.google.com/drive/folders/FOLDER_ID
folder: "FOLDER_ID",
outputDir: "src/content/docs",
})
for (const {filePath, markdown, metadata} of documents) {
console.log(metadata.slug, filePath)
}syncGoogleDocs(options) returns a promise of:
| Field | Description |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| documents | {filePath, markdown, metadata} for every document: where it is written, what is written, and its frontmatter (id, name, slug, path, breadcrumb, date, cover, and your own metadata) |
| files | Every file of outputDir after the sync: the documents and their images |
| fetchedCount | The number of documents fetched from Google Docs, the others came from the cache |
| imagesCount | The number of images in outputDir |
| downloadedImagesCount | The number of images downloaded from Google, the others came from the cache |
It throws when the folder is missing or when Google refuses a request.
The package also exports:
getAuth(): the Google client built from the environment variablesgenerateToken(): whatgoogle-docs-sync-tokenrunsfetchDocument(id, {auth}): the Google Docs API document of one document id
import {fetchDocument} from "google-docs-sync"
import {toMarkdown} from "google-docs-to-markdown"
const markdown = toMarkdown(await fetchDocument(id), {
frontmatter: {title: "Home"},
})Command line
npx google-docs-sync --folder FOLDER_ID --output-dir src/content/docs| Flag | Description |
| -------------------- | ------------------------------------------------------- |
| --folder <id> | Google Drive folder id, GOOGLE_DOCS_FOLDER by default |
| --output-dir <dir> | outputDir |
| --cache-dir <dir> | cacheDir |
| --extension <ext> | extension: md or mdx |
| --skip-images | skipImages |
| --debug | debug |
The variables of the token generation are read from the environment or from .env.
Options
| Option | Required | Type | Default | Example |
| ------------- | -------- | ------- | ----------------------- | ------------------------------ |
| folder | true | String | null | "1Tn1dCbIc" |
| outputDir | false | String | "content/google-docs" | "src/content/docs" |
| cacheDir | false | String | ".google-docs" | ".cache-docs" |
| extension | false | String | "md" | "mdx" |
| imagesOptions | false | Object | null | {width: 512} |
| comments | false | Boolean | false | true |
| debug | false | Boolean | false | true |
| auth | false | Object | from the environment | a google-auth-library client |
| logger | false | Object | console | {info, warn, error} |
outputDiris managed by the sync: any other file it contains is deleted, so point it at a directory of its own and add it to your.gitignore.imagesOptionsis the size the images are downloaded at, between 1 and 16383 (width,height,crop). Changing it downloads them again.commentsadds the comments of every document to its metadata, undercomments:{id, content, author: {displayName}, createdTime, modifiedTime, resolved, quote, replies}, wherequoteis the passage of the document the comment is attached to and thereplieshave the sameid,content,authorandcreatedTime, plus anaction(resolveorreopen) for the reply that resolves or reopens the thread. Resolved comments are kept withresolved: true, deleted ones are left out. They are written in the frontmatter, so the adapters read them like any other metadata. It costs one more Drive request per document on every sync, cached or not, and the existingdrive.readonlyscope is enough.loggerreceives the messages of the sync:warnfor what is skipped (a description that is not valid YAML, an image that could not be downloaded),infofor the progress indebugmode.
The conversion options of google-docs-to-markdown are accepted too: escapeMdxSyntax, demoteHeadings (true by default here), keepDefaultStyle and the skip* ones. mdx follows extension, and frontmatter and links are filled by the sync.
Output
Every document is written under outputDir at the path of its slug, and its images in an images directory next to it:
content/google-docs
├── index.md # the document whose slug is "/"
├── installation.md
├── images.md
└── images
└── images # one directory per document
├── alt-text.png
└── images-2.pngEach file holds the document metadata as YAML frontmatter and its content as Markdown. The images are referenced by paths relative to the document.
Organize your documents
Go to your Google Drive, create a folder and put some documents inside it.
↳ 🗂 Root folder `template: page`
↳ 🗂 en `locale: en` `skip: true`
↳ 📝 Home `template: home`
↳ 📝 About
↳ 🗂 Posts `template: post`
↳ 🗂 Drafts `exclude: true`
↳ 📝 Draft 1
↳ 📝 My year 2020 `date: 2021-01-01`
↳ 📝 Post 2 `slug: /custom/slug` `template: special-post`
↳ 🗂 fr `locale: fr`
↳ 📝 Accueil `template: home`- Fill the document (or folder)
descriptionfield in Google Drive with aYAMLobject
locale: fr
template: post
category: Category Name
tags: [tag1, tag2]
slug: /custom-slug
date: 2019-01-01There are special metadata
- For folders:
exclude: true: Exclude the folder and its documentsskip: true: Remove the folder from slug but keep its documents- For documents:
index:true: Use document as the folder indexpage: false: Prevent page creation by the plugins that create pages, such asgatsby-source-google-docswith itscreatePagesoption
- Spread metadata into the tree using folders metadata.
⬆️ For the tree example above:
- Every node will have
template: pagedefined as default excepts if you redefine it later.templateis plain metadata: what uses it (a Gatsby template, an Astro layout, ...) is up to the framework.- "en" folder will be removed from slug because of
skip: true
- Exclude folders and documents using
exclude: true. Perfect to keep drafts documents. One you want to publish a page, juste move the document one level up.
⬆️ For the tree example above:
- Documents under
Draftswill be exclude because ofexclude: true.
- Every metadata is written in the frontmatter of the document, and returned in the
metadatafield of the documents ofsyncGoogleDocs
Add an image in your Google Document first page header
slug and breadcrumb fields add automatically generated using the folders tree structure and transformed using kebab-case.
⬆️ For the tree example above: The frontmatter of the document
My year 2020{ path: "/en/posts/my-year-2020" // Original Google Drive path slug: "/posts/my-year-2020" // `en` is out because of `skip: true` breadcrumb: [ {name: "Posts", slug: "/posts"}, {name: "My year 2020", slug: "/posts/my-year-2020"}, ], template: "post" ,// src/templates/post.js locale: "fr", date: "2021-01-01" // Fixed date ! }The frontmatter of the document
Post 2will have a custom slug{ path: "/en/posts/post-2" slug: "/custom/slug" breadcrumb: [ {name: "Posts", slug: "/posts"}, {name: "Post 2", slug: "/custom/slug"}, ], template: "special-post", // src/templates/special-post.js locale: "en", date: "2020-09-12" // Google Drive document creation date }
You also can add metadata (locale, date, template, ...) to your documents.
Only what changed is fetched
Fetching a document is one request, and every image it holds is a download of
its own: a folder of long documents full of images takes minutes to fetch. google-docs-sync keeps them in the cacheDir directory
(.google-docs by default), and a sync only fetches what changed since the
previous one.
.google-docs
├── documents
│ └── 1Tn1dCbIc.json # one file per document, as Google gave it
├── images
│ └── 1Tn1dCbIc # the images it references, downloaded once
│ └── kix.4dmdp8b4.png
└── state.jsonGoogle Drive gives the time a document was last modified while listing the folder, which the sync already does: a document that has not been touched since it was stored is never fetched again, and neither are its images. Editing a document on Google Docs, renaming it, changing its description or moving it to another folder is picked up on the next sync — its metadata always comes from the listing, fetched or not.
The documents are stored as Google gave them, not as markdown: changing
demoteHeadings, extension or any other option takes effect on the next
sync without fetching anything again. Changing imagesOptions downloads the
images again, since their size is part of the URL they are downloaded from.
The comments are the exception: they are not stored, and the comments option fetches them again on every sync, one Drive request per document, because Google Drive does not reliably change the modification time of a document when a comment is added or resolved.
Add
.google-docsto your.gitignore, or commit it to give your continuous integration a folder it does not have to fetch. Delete it to fetch everything again.
This directory is not the cache of a framework, on purpose: frameworks empty their own whenever their configuration or a dependency changes, and a continuous integration job never has one, so adding a dependency to your site would cost a complete refetch.
