-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathsync-essays-to-github.ts
78 lines (67 loc) · 2.35 KB
/
sync-essays-to-github.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Octokit } from '@octokit/rest'
import { getBlogPosts } from './app/thoughts/utils'
import env from '@next/env'
const projectDir = process.cwd()
env.loadEnvConfig(projectDir)
async function main() {
console.log('Start')
const octokit = new Octokit({
auth: process.env.GITHUB_ACCESS_TOKEN,
})
try {
console.log('Getting file…')
const response = await octokit.repos.getContent({
owner: 'mxstbr',
repo: 'mxstbr',
path: 'README.md',
})
if (Array.isArray(response.data) || response.data.type !== 'file') {
throw new Error('README.md is not a file. Aborting.')
}
const content = Buffer.from(response.data.content, 'base64').toString()
console.log('Got file:')
console.log(content)
const blogPosts = getBlogPosts()
// Markdown output for each essay:
// ### [You probably don't need GraphQL](https://mxstbr.com/thoughts/graphql) (19,386 views)
//
// It might be surprising to hear the co-founder of a GraphQL company say you probably don't need it. Let me explain.
const text = blogPosts
.map(
(post) =>
`### [${post.metadata.title}](https://mxstbr.com/thoughts/${
post.slug
}) (${post.metadata.views.toLocaleString(undefined, {
maximumFractionDigits: 0,
})} views)\n\n${post.metadata.summary}`
)
.join('\n\n')
console.log('New content:')
console.log(text)
const newContent = content.replace(
/<!-- essay-marker -->[\s\S]*<!-- \/essay-marker -->/,
`<!-- essay-marker -->\n\n${text}\n\n<!-- \/essay-marker -->`
)
console.log('New file:')
console.log(newContent)
if (newContent.replace(/\s/g, '') === content.replace(/\s/g, '')) {
console.log('No changes detected. Exiting.')
return
}
console.log('Committing file...')
const result = await octokit.repos.createOrUpdateFileContents({
owner: 'mxstbr',
repo: 'mxstbr',
path: 'README.md',
message:
'bot: update essays\n\n(see https://github.com/mxstbr/mxstbr.com/blob/master/sync-essays-to-github.ts)',
content: Buffer.from(newContent).toString('base64'),
sha: response.data.sha,
})
console.log(result.status, result.data)
console.log('File committed successfully!')
} catch (error) {
console.error('Error retrieving README.md:', error)
}
}
main()