feat: add workflow to generate doc post data for extracting data

This commit is contained in:
Anda Toshiki 2023-05-24 13:36:21 +08:00
parent c883f02e55
commit cef4db06a3

View File

@ -1,29 +1,26 @@
// from https://github.com/vuejs/blog
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const matter = require('gray-matter') const matter = require('gray-matter')
const { createMarkdownRenderer } = require('vitepress') const { createMarkdownRenderer } = require('vitepress')
const cwd = process.cwd() const md = createMarkdownRenderer(process.cwd())
module.exports = { module.exports = {
watch: path.relative(__dirname, cwd + '/docs/*.md').replace(/\\/g, '/'), watch: '../../docs/*.md',
async load(asFeed = false) { load(asFeed = false) {
const md = await createMarkdownRenderer(cwd) const postDir = path.resolve(__dirname, '../../docs')
const postDir = path.join(cwd, 'docs')
return fs return fs
.readdirSync(postDir) .readdirSync(postDir)
.filter(file => file.endsWith('.md')) .map(file => getPost(file, postDir, asFeed))
.map(file => getPost(md, file, postDir, asFeed)) .sort((a, b) => b.date.time - a.date.time)
.sort((a, b) => b.create - a.create)
} }
} }
const cache = new Map() const cache = new Map()
function getPost(md, file, postDir, asFeed = false) { function getPost(file, postDir, asFeed = false) {
const fullePath = path.join(postDir, file) const fullePath = path.join(postDir, file)
const timestamp = Math.floor(fs.statSync(fullePath).mtimeMs) const timestamp = fs.statSync(fullePath).mtimeMs
const cached = cache.get(fullePath) const cached = cache.get(fullePath)
if (cached && timestamp === cached.timestamp) { if (cached && timestamp === cached.timestamp) {
@ -36,10 +33,7 @@ function getPost(md, file, postDir, asFeed = false) {
const post = { const post = {
title: data.title, title: data.title,
href: `${file.replace(/\.md$/, '.html')}`, href: `${file.replace(/\.md$/, '.html')}`,
create: +new Date(data.date) || timestamp, date: formatDate(data.date),
update: timestamp,
tags: data.tags,
cover: data.cover,
excerpt: md.render(excerpt) excerpt: md.render(excerpt)
} }
if (asFeed) { if (asFeed) {
@ -54,3 +48,18 @@ function getPost(md, file, postDir, asFeed = false) {
}) })
return post return post
} }
function formatDate(date) {
if (!(date instanceof Date)) {
date = new Date(date)
}
date.setUTCHours(12)
return {
time: +date,
string: date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
})
}
}