-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
chore: seed docs script #231
Open
jbmoelker
wants to merge
6
commits into
main
Choose a base branch
from
chore/seed-docs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
09a9dc1
chore: seed docs script
jbmoelker 722287e
fix: page record item type in seed docs script
jbmoelker 2993ed4
chore: resolve links in seed docs
jbmoelker fa8a408
refactor: seed docs as standalone script
jbmoelker d1d211d
chore: seed documention parent page
jbmoelker a00c799
chore: seed documentation partial as nav for docs
jbmoelker File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,12 @@ | ||
{ | ||
"type": "commonjs" | ||
"type": "commonjs", | ||
"dependencies": { | ||
"@datocms/cma-client-node": "^3.4.0", | ||
"datocms-html-to-structured-text": "^4.0.1", | ||
"datocms-structured-text-utils": "^4.0.1", | ||
"dotenv-safe": "^9.1.0", | ||
"mdast-util-from-markdown": "^2.0.2", | ||
"mdast-util-to-hast": "^13.2.0", | ||
"unist-util-visit": "^5.0.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,214 @@ | ||
import { readdir, readFile } from 'node:fs/promises'; | ||
import path from 'node:path'; | ||
import dotenv from 'dotenv-safe'; | ||
import { buildClient } from '@datocms/cma-client-node'; | ||
import { fromMarkdown } from 'mdast-util-from-markdown'; | ||
import type { Root } from 'mdast'; | ||
import { toHast } from 'mdast-util-to-hast'; | ||
import { hastToStructuredText, type HastRootNode } from 'datocms-html-to-structured-text'; | ||
import { validate } from 'datocms-structured-text-utils'; | ||
import { visit } from 'unist-util-visit'; | ||
import { datocmsEnvironment } from '../../../datocms-environment'; | ||
|
||
dotenv.config({ | ||
allowEmptyValues: Boolean(process.env.CI), | ||
}); | ||
|
||
const client = buildClient({ | ||
apiToken: process.env.DATOCMS_API_TOKEN!, | ||
environment: datocmsEnvironment, | ||
}); | ||
const docExtension = '.md'; | ||
const docDirectory = path.resolve(__dirname,'../../../docs'); | ||
const modelType = 'page'; | ||
const documentationSlug = 'documentation'; | ||
const mainBranchUrl = 'https://github.com/voorhoede/head-start/tree/main/'; | ||
|
||
async function listDocs() { | ||
const filenames = await readdir(docDirectory); | ||
return filenames.filter(file => file.endsWith(docExtension)); | ||
} | ||
|
||
async function readDoc(filename: string) { | ||
const filepath = path.join(docDirectory, filename); | ||
const contents = await readFile(filepath, 'utf-8'); | ||
const titlePattern = /^# .*\n/; | ||
const title = contents.match(titlePattern)?.[0].replace(/^# /, '').trim() ?? ''; | ||
const text = contents.replace(titlePattern, '')?.trim() ?? ''; | ||
const slug = path.basename(filename, docExtension); | ||
return { slug, title, text }; | ||
} | ||
|
||
type Model = { | ||
id: string; | ||
} | ||
type Document = { | ||
slug: string; | ||
title: string; | ||
text: string; | ||
} | ||
type Page = { | ||
id: string; | ||
[key: string]: unknown; | ||
} | ||
async function upsertRecord ({ model, document, parent }: { model: Model, document: Document, parent?: Page }) { | ||
const record = await findRecordBySlug(document.slug); | ||
const note = `!Note: this page is auto-generated from [docs/${document.slug}.md](${mainBranchUrl}docs/${document.slug}.md).`; | ||
const markdown = `${note}\n\n${document.text}`; | ||
const structuredText = await markdownToStructuredText(markdown); | ||
const textBlockItemType = await client.itemTypes.find('text_block'); | ||
|
||
const data = { | ||
item_type: { type: 'item_type' as const, id: model.id }, | ||
title: { en: document.title }, | ||
slug: { en: document.slug }, | ||
parent_page: parent?.id, | ||
body_blocks: { | ||
en: [ | ||
{ | ||
type: 'item', | ||
attributes: { | ||
text: structuredText, | ||
}, | ||
relationships: { | ||
item_type: { | ||
data: { | ||
type: 'item_type', | ||
id: textBlockItemType.id | ||
} | ||
}, | ||
} | ||
} | ||
], | ||
} | ||
}; | ||
|
||
const newRecord = record | ||
? await client.items.update(record.id, { ...record, ...data }) | ||
: await client.items.create(data); | ||
await client.items.publish(newRecord.id); | ||
console.log('✨', record ? 'updated' : 'created', document.title); | ||
return newRecord; | ||
} | ||
|
||
async function findRecordBySlug (slug: string) { | ||
const items = await client.items.list({ | ||
nested: true, | ||
filter: { | ||
type: modelType, | ||
fields: { | ||
slug: { eq: slug }, | ||
} | ||
}, | ||
}); | ||
return items[0]; | ||
} | ||
|
||
async function upsertDocumentationPartialRecord(documents: Document[]) { | ||
const title = 'Documentation index'; | ||
const itemType = 'page_partial'; | ||
const model = await client.itemTypes.find(itemType); | ||
const items = await client.items.list({ | ||
nested: true, | ||
filter: { | ||
type: itemType, | ||
fields: { | ||
title: { eq: title }, | ||
} | ||
}, | ||
}); | ||
const record = items[0]; | ||
|
||
const markdown = documents.map(doc => { | ||
return `* [${doc.title}](/en/${documentationSlug}/${doc.slug}/)`; | ||
}).join('\n'); | ||
const structuredText = await markdownToStructuredText(markdown); | ||
const textBlockItemType = await client.itemTypes.find('text_block'); | ||
|
||
const data = { | ||
item_type: { type: 'item_type' as const, id: model.id }, | ||
title: { en: title }, | ||
blocks: { | ||
en: [ | ||
{ | ||
type: 'item', | ||
attributes: { | ||
text: structuredText, | ||
}, | ||
relationships: { | ||
item_type: { | ||
data: { | ||
type: 'item_type', | ||
id: textBlockItemType.id | ||
} | ||
}, | ||
} | ||
} | ||
], | ||
} | ||
}; | ||
|
||
record | ||
? await client.items.update(record.id, { ...record, ...data }) | ||
: await client.items.create(data); | ||
console.log('✨', record ? 'updated' : 'created', 'page partial:', title); | ||
} | ||
|
||
async function getDocumentationRecord() { | ||
const page = await findRecordBySlug(documentationSlug); | ||
if (page) { | ||
console.log('✅ documentation page already exists'); | ||
return page; | ||
} | ||
|
||
console.log('✨ creating new documentation page'); | ||
const model = await client.itemTypes.find(modelType); | ||
return await upsertRecord({ model, document: { | ||
slug: documentationSlug, | ||
title: 'Documentation', | ||
text: '' | ||
} }); | ||
} | ||
|
||
/** | ||
* adapted from https://www.datocms.com/docs/structured-text/migrating-content-to-structured-text#migrating-markdown-content | ||
*/ | ||
async function markdownToStructuredText(markdown: string) { | ||
const mdast = fromMarkdown(markdown); | ||
resolveLinks(mdast); | ||
const hast = toHast(mdast) as HastRootNode; | ||
const structuredText = await hastToStructuredText(hast); | ||
const validationResult = validate(structuredText); | ||
if (!validationResult.valid) { | ||
throw new Error(validationResult.message); | ||
} | ||
return structuredText; | ||
} | ||
|
||
function resolveLinks (mdast: Root) { | ||
visit(mdast, 'link', (node) => { | ||
if (node.url.startsWith('./') && node.url.includes('.md')) { | ||
node.url = node.url | ||
.replace('./', '../') | ||
.replace('.md', '/'); | ||
} else if (node.url.startsWith('../')) { | ||
node.url = node.url.replace('../', mainBranchUrl); | ||
} | ||
}); | ||
} | ||
|
||
async function seedDocs() { | ||
const filenames = await listDocs(); | ||
const model = await client.itemTypes.find(modelType); | ||
const parent = await getDocumentationRecord(); | ||
const documents: Document[] = []; | ||
for (const filename of filenames) { | ||
const document = await readDoc(filename); | ||
documents.push(document); | ||
await upsertRecord({ model, document, parent }); | ||
} | ||
await upsertDocumentationPartialRecord(documents); | ||
} | ||
|
||
seedDocs() | ||
.then(() => console.log('✅ Docs seeded')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Astro check in the CI lint job fails on this module. Not sure why it's not found. Locally I can verify it exists. Maybe it has to do with the
"type": "commonjs"
inpackage.json
? But I can't change that to"module"
as then running DatoCMS migrations will fail 🤷 .It's a bit of a non-issue. Astro check shouldn't even lint this file and just stick to
src/
. But I'm unable to configure that. What I could do as a workaround is in the CI lint job, deleteconfig/datocms/scripts/
before runningnpm run lint:astro
. What do you think?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
patch available as PR: #241
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Think it fails in CI because the packages in
config/datocms
are not installed. Locally I get the same error unless Icd
into that directory and runnpm install
.