|
| 1 | +import { defineDocumentType } from 'contentlayer/source-files' |
| 2 | +import { spawn } from 'node:child_process' |
| 3 | +import { makeSource } from 'contentlayer/source-remote-files' |
| 4 | + |
| 5 | +const Post = defineDocumentType(() => ({ |
| 6 | + name: 'Post', |
| 7 | + filePathPattern: `docs/**/*.md`, |
| 8 | + fields: { |
| 9 | + title: { |
| 10 | + type: 'string', |
| 11 | + required: false, |
| 12 | + }, |
| 13 | + description: { |
| 14 | + type: 'string', |
| 15 | + required: false, |
| 16 | + }, |
| 17 | + }, |
| 18 | + computedFields: { |
| 19 | + url: { |
| 20 | + type: 'string', |
| 21 | + resolve: (doc) => `/posts/${doc._raw.flattenedPath}`, |
| 22 | + }, |
| 23 | + }, |
| 24 | +})) |
| 25 | + |
| 26 | +const syncContentFromGit = async (contentDir: string) => { |
| 27 | + const syncRun = async () => { |
| 28 | + const gitUrl = 'https://github.com/vercel/next.js.git' |
| 29 | + await runBashCommand(` |
| 30 | + if [ -d "${contentDir}" ]; |
| 31 | + then |
| 32 | + cd "${contentDir}"; git pull; |
| 33 | + else |
| 34 | + git clone --depth 1 --single-branch ${gitUrl} ${contentDir}; |
| 35 | + fi |
| 36 | + `) |
| 37 | + } |
| 38 | + |
| 39 | + let wasCancelled = false |
| 40 | + let syncInterval |
| 41 | + |
| 42 | + const syncLoop = async () => { |
| 43 | + console.log('Syncing content files from git') |
| 44 | + |
| 45 | + await syncRun() |
| 46 | + |
| 47 | + if (wasCancelled) return |
| 48 | + |
| 49 | + syncInterval = setTimeout(syncLoop, 1000 * 60) |
| 50 | + } |
| 51 | + |
| 52 | + // Block until the first sync is done |
| 53 | + await syncLoop() |
| 54 | + |
| 55 | + return () => { |
| 56 | + wasCancelled = true |
| 57 | + clearTimeout(syncInterval) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +const runBashCommand = (command: string) => |
| 62 | + new Promise((resolve, reject) => { |
| 63 | + const child = spawn(command, [], { shell: true }) |
| 64 | + |
| 65 | + child.stdout.setEncoding('utf8') |
| 66 | + child.stdout.on('data', (data) => process.stdout.write(data)) |
| 67 | + |
| 68 | + child.stderr.setEncoding('utf8') |
| 69 | + child.stderr.on('data', (data) => process.stderr.write(data)) |
| 70 | + |
| 71 | + child.on('close', function (code) { |
| 72 | + if (code === 0) { |
| 73 | + resolve(void 0) |
| 74 | + } else { |
| 75 | + reject(new Error(`Command failed with exit code ${code}`)) |
| 76 | + } |
| 77 | + }) |
| 78 | + }) |
| 79 | + |
| 80 | +export default makeSource({ |
| 81 | + syncFiles: syncContentFromGit, |
| 82 | + contentDirPath: 'nextjs-repo', |
| 83 | + contentDirInclude: ['docs'], |
| 84 | + documentTypes: [Post], |
| 85 | + disableImportAliasWarning: true, |
| 86 | +}) |
0 commit comments