/
index.ts
291 lines (248 loc) · 8.44 KB
/
index.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import Enquirer from "enquirer"
import cmses from "./cmses.json"
import styles from "./styles.json"
import features from "./features.json"
import { initStarter, getPackageManager } from "./init-starter"
import { installPlugins } from "./install-plugins"
import c from "ansi-colors"
import path from "path"
import fs from "fs"
import { plugin } from "./components/plugin"
import { makePluginConfigQuestions } from "./plugin-options-form"
import { center, rule, wrap } from "./components/utils"
import { stripIndent } from "common-tags"
// eslint-disable-next-line no-control-regex
const INVALID_FILENAMES = /[<>:"/\\|?*\u0000-\u001F]/g
const INVALID_WINDOWS = /^(con|prn|aux|nul|com\d|lpt\d)$/i
// We're using a fork because it points to the canary version of gatsby
const DEFAULT_STARTER = `https://github.com/ascorbic/gatsby-starter-hello-world.git`
const makeChoices = (
options: Record<string, { message: string; dependencies?: Array<string> }>,
multi = false
): Array<{ message: string; name: string; disabled?: boolean }> => {
const entries = Object.entries(options).map(([name, message]) => {
return { name, message: message.message }
})
if (multi) {
return entries
}
const none = { name: `none`, message: `No (or I'll add it later)` }
const divider = { name: `–`, role: `separator`, message: `–` }
return [none, divider, ...entries]
}
export const validateProjectName = async (
value: string
): Promise<string | boolean> => {
if (INVALID_FILENAMES.test(value)) {
return `The destination "${value}" is not a valid filename. Please try again, avoiding special characters.`
}
if (process.platform === `win32` && INVALID_WINDOWS.test(value)) {
return `The destination "${value}" is not a valid Windows filename. Please try another name`
}
if (fs.existsSync(path.resolve(value))) {
return `The destination "${value}" already exists. Please choose a different name`
}
return true
}
// The enquirer types are not accurate
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const questions: any = [
{
type: `textinput`,
name: `project`,
message: `What would you like to name the folder where your site will be created?`,
hint: path.basename(process.cwd()),
separator: `/`,
initial: `my-gatsby-site`,
format: (value: string): string => c.cyan(value),
validate: validateProjectName,
},
{
type: `selectinput`,
name: `cms`,
message: `Will you be using a CMS?`,
hint: `(Single choice) Arrow keys to move, enter to confirm`,
choices: makeChoices(cmses),
},
{
type: `selectinput`,
name: `styling`,
message: `Would you like to install a styling system?`,
hint: `(Single choice) Arrow keys to move, enter to confirm`,
choices: makeChoices(styles),
},
{
type: `multiselectinput`,
name: `features`,
message: `Would you like to install additional features with other plugins?`,
hint: `(Multiple choice) Use arrow keys to move, enter to select, and choose "Done" to confirm your choices`,
choices: makeChoices(features, true),
},
]
interface IAnswers {
project: string
styling?: keyof typeof styles
cms?: keyof typeof cmses
features?: Array<keyof typeof features>
}
interface IPluginEntry {
/**
* Message displayed in the menu when selecting the plugin
*/
message: string
/**
* Extra NPM packages to install
*/
dependencies?: Array<string>
/**
* Items are either the plugin name, or the plugin name and key, separated by a colon (":")
* This allows duplicate entries for plugins such as gatsby-source-filesystem.
*/
plugins?: Array<string>
/**
* Keys must match plugin names or name:key combinations from the plugins array
*/
options?: PluginConfigMap
}
export type PluginMap = Record<string, IPluginEntry>
export type PluginConfigMap = Record<string, Record<string, unknown>>
const removeKey = (plugin: string): string => plugin.split(`:`)[0]
export async function run(): Promise<void> {
const { version } = require(`../package.json`)
console.log(c.grey(`create-gatsby version ${version}`))
console.log(
`
${center(c.blueBright.bold.underline(`Welcome to Gatsby!`))}
`
)
console.log(c.red(rule()))
console.log(center(c.red(`⚠️ This is currently for testing purposes only`)))
console.log(c.red(rule()))
console.log(
wrap(
`This command will generate a new Gatsby site for you in ${c.bold(
process.cwd()
)} with the setup you select. ${c.white.bold(
`Let's answer some questions:\n`
)}`,
process.stdout.columns
)
)
console.log(``)
const enquirer = new Enquirer<IAnswers>()
enquirer.use(plugin)
const data = await enquirer.prompt(questions)
const messages: Array<string> = [
`🛠 Create a new Gatsby site in the folder ${c.magenta(data.project)}`,
]
const plugins: Array<string> = []
const packages: Array<string> = []
let pluginConfig: PluginConfigMap = {}
if (data.cms && data.cms !== `none`) {
messages.push(
`📚 Install and configure the plugin for ${c.magenta(
cmses[data.cms].message
)}`
)
const extraPlugins = cmses[data.cms].plugins || []
plugins.push(data.cms, ...extraPlugins)
packages.push(
data.cms,
...(cmses[data.cms].dependencies || []),
...extraPlugins
)
pluginConfig = { ...pluginConfig, ...cmses[data.cms].options }
}
if (data.styling && data.styling !== `none`) {
messages.push(
`🎨 Get you set up to use ${c.magenta(
styles[data.styling].message
)} for styling your site`
)
const extraPlugins = styles[data.styling].plugins || []
plugins.push(data.styling, ...extraPlugins)
packages.push(
data.styling,
...(styles[data.styling].dependencies || []),
...extraPlugins
)
pluginConfig = { ...pluginConfig, ...styles[data.styling].options }
}
if (data.features?.length) {
messages.push(
`🔌 Install ${data.features
?.map((feat: string) => c.magenta(feat))
.join(`, `)}`
)
plugins.push(...data.features)
const featureDependencies = data.features?.map(featureKey => {
const extraPlugins = features[featureKey].plugins || []
plugins.push(...extraPlugins)
return [
// Spread in extra dependencies
...(features[featureKey].dependencies || []),
// Spread in plugins
...extraPlugins,
]
})
const flattenedDependencies = ([] as Array<string>).concat.apply(
[],
featureDependencies
) // here until we upgrade to node 11 and can use flatMap
packages.push(...data.features, ...flattenedDependencies)
// Merge plugin options
pluginConfig = data.features.reduce((prev, key) => {
return { ...prev, ...features[key].options }
}, pluginConfig)
}
const config = makePluginConfigQuestions(plugins)
if (config.length) {
console.log(
`\nGreat! A few of the selections you made need to be configured. Please fill in the options for each plugin now:\n`
)
const enquirer = new Enquirer<Record<string, {}>>()
enquirer.use(plugin)
pluginConfig = { ...pluginConfig, ...(await enquirer.prompt(config)) }
}
console.log(`
${c.bold(`Thanks! Here's what we'll now do:`)}
${messages.join(`\n `)}
`)
const { confirm } = await new Enquirer<{ confirm: boolean }>().prompt({
type: `confirm`,
name: `confirm`,
initial: `Yes`,
message: `Shall we do this?`,
format: value => (value ? c.greenBright(`Yes`) : c.red(`No`)),
})
if (!confirm) {
console.log(`OK, bye!`)
return
}
await initStarter(DEFAULT_STARTER, data.project, packages.map(removeKey))
console.log(c.green(`✔ `) + `Created site in ` + c.green(data.project))
console.log({ plugins, pluginConfig })
if (plugins.length) {
console.log(c.bold(`🔌 Installing plugins...`))
await installPlugins(plugins, pluginConfig, path.resolve(data.project), [])
}
const pm = await getPackageManager()
const runCommand = pm === `npm` ? `npm run` : `yarn`
console.log(
stripIndent`
🎉 Your new Gatsby site ${c.bold(
data.project
)} has been successfully bootstrapped
at ${c.bold(path.resolve(data.project))}.
`
)
console.log(`Start by going to the directory with\n
${c.magenta(`cd ${data.project}`)}
`)
console.log(`Start the local development server with\n
${c.magenta(`${runCommand} develop`)}
`)
console.log(`See all commands at\n
${c.blueBright(`https://www.gatsbyjs.com/docs/gatsby-cli/`)}
`)
}