-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgatsby-node.js
85 lines (71 loc) · 2.09 KB
/
gatsby-node.js
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
79
80
81
82
83
84
85
const fs = require('fs').promises
const path = require('path')
const prettier = require('prettier')
const glob = require('tiny-glob')
const pLimit = require('p-limit')
const extParsers = {
js: 'babel',
html: 'html',
css: 'css',
}
exports.onPreInit = (_, opts = {}) => {
return new Promise((resolve, reject) => {
if (!opts.types) return resolve()
for (const type of opts.types) {
if (!extParsers[type])
return reject(
`gatsby-plugin-prettier-build doesn't support '${type}' files\n` +
`raise an issue? https://github.com/jmsv/gatsby-plugin-prettier-build/issues/new`
)
}
return resolve()
})
}
exports.onPostBuild = async (_, opts = {}) => {
const fileTypesToFormat = opts.types || ['html']
const verbose = opts.verbose !== false
const [prettierOpts, files] = await Promise.all([
prettier.resolveConfig(process.cwd()),
glob(`public/**/*.{${fileTypesToFormat.join(',')}}`),
])
const limit = pLimit(opts.concurrency || 20)
let filesPrettified = 0
return Promise.all(
files.map((filePath) =>
limit(() =>
prettifyFile(filePath, prettierOpts).then((done) => {
if (done === true) {
filesPrettified += 1
if (verbose) console.log('✔ prettified', filePath)
} else if (done === false) {
if (verbose) console.log('✘ failed to prettify', filePath)
}
})
)
)
).then(() => {
if (verbose) {
console.log(
`✨ finished prettifying ${filesPrettified} Gatsby build file${
filesPrettified ? 's' : ''
}`
)
}
})
}
const prettifyFile = async (filePath, prettierOpts) => {
// Don't attempt format if not a file
if (!(await fs.lstat(filePath)).isFile()) return null
const parser = extParsers[path.extname(filePath).slice(1)]
const fileBuffer = await fs.readFile(filePath)
try {
const formatted = prettier.format(
fileBuffer.toString(),
Object.assign({ parser }, prettierOpts)
)
await fs.writeFile(filePath, formatted)
} catch {
return false
}
return true
}