/
plugin-add.ts
83 lines (75 loc) · 2.09 KB
/
plugin-add.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
79
80
81
82
83
import { NPMPackage, GatsbyPlugin } from "gatsby-recipes"
import reporter from "./reporter"
const normalizePluginName = (plugin: string): string => {
if (plugin.startsWith(`gatsby-`)) {
return plugin
}
if (
plugin.startsWith(`source-`) ||
plugin.startsWith(`transformer-`) ||
plugin.startsWith(`plugin-`)
) {
return `gatsby-${plugin}`
}
return `gatsby-plugin-${plugin}`
}
async function installPluginPackage(
plugin: string,
root: string
): Promise<void> {
const installTimer = reporter.activityTimer(`Installing ${plugin}`)
installTimer.start()
reporter.info(`Installing ${plugin}`)
try {
const result = await NPMPackage.create({ root }, { name: plugin })
reporter.info(result._message)
} catch (err) {
reporter.error(JSON.parse(err)?.message)
installTimer.setStatus(`FAILED`)
}
installTimer.end()
}
async function installPluginConfig(
plugin: string,
options: Record<string, unknown> | undefined,
root: string
): Promise<void> {
// Plugins can optionally include a key, to allow duplicates
const [pluginName, pluginKey] = plugin.split(`:`)
const installTimer = reporter.activityTimer(
`Adding ${pluginName} to gatsby-config`
)
installTimer.start()
reporter.info(`Adding ${pluginName}`)
try {
const result = await GatsbyPlugin.create(
{ root },
{ name: pluginName, options, key: pluginKey }
)
reporter.info(result._message)
} catch (err) {
reporter.error(JSON.parse(err)?.message)
installTimer.setStatus(`FAILED`)
}
installTimer.end()
}
export async function addPlugins(
plugins: Array<string>,
pluginOptions: Record<string, Record<string, unknown>>,
directory: string,
packages: Array<string> = []
): Promise<void> {
if (!plugins?.length) {
reporter.error(`Please specify a plugin to install`)
return
}
const pluginList = plugins.map(normalizePluginName)
await Promise.all(
packages.map(plugin => installPluginPackage(plugin, directory))
)
await Promise.all(
pluginList.map(plugin =>
installPluginConfig(plugin, pluginOptions[plugin], directory)
)
)
}