-
Notifications
You must be signed in to change notification settings - Fork 0
/
read-files.ts
77 lines (64 loc) · 1.98 KB
/
read-files.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
import { REPO_ORG, REPO_NAME, dataDir, REPO_REF } from './constants.js'
import { parallel } from 'radashi'
import fs from 'node:fs'
import path from 'node:path'
import { Readable } from 'node:stream'
main()
async function main() {
const githubToken = process.env.GITHUB_TOKEN
if (!githubToken) {
throw new Error('GITHUB_TOKEN is not set')
}
let files = JSON.parse(
fs.readFileSync(path.join(dataDir, 'files.json'), 'utf8')
) as string[]
const keywordRegex =
/\b(functions?|views|indexes|triggers|tutorial|administration|plpgsql)\b/
files = files.filter(file => {
// Ignore root files in "content/postgresql/"
if (file.split('/').length === 3) {
return false
}
if (!path.basename(file).startsWith('postgresql-')) {
return false
}
if (keywordRegex.test(file)) {
return true
}
return false
})
console.log(`Processing ${files.length} files`)
const names = new Set<string>()
await parallel(20, files, async file => {
const outName =
path.basename(file).replace(/(^postgresql-)|((-function)?\.md$)/g, '') +
'.md'
if (names.has(outName)) {
console.log(`Skipping ${outName} because it already exists`)
return
}
names.add(outName)
const url = `https://raw.githubusercontent.com/${REPO_ORG}/${REPO_NAME}/${REPO_REF}/${file}`
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${githubToken}`,
},
})
if (!response.ok || !response.body) {
if (response.status === 403) {
throw new Error('Rate limit exceeded')
}
console.error(`Failed to fetch ${file}: ${response.statusText}`)
return
}
await new Promise<void>((resolve, reject) => {
Readable.fromWeb(response.body as any)
.pipe(fs.createWriteStream(path.join(dataDir, outName)), { end: true })
.on('finish', () => {
console.log('finish %s', outName)
resolve()
})
.on('error', reject)
})
})
}