-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
init-starter.ts
366 lines (315 loc) · 9.63 KB
/
init-starter.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import opn from "better-opn"
import { execSync } from "child_process"
import execa from "execa"
import { sync as existsSync } from "fs-exists-cached"
import fs from "fs-extra"
import { trackCli, trackError } from "gatsby-telemetry"
import hostedGitInfo from "hosted-git-info"
import isValid from "is-valid-path"
import sysPath from "path"
import prompts from "prompts"
import url from "url"
import { updateSiteMetadata } from "gatsby-core-utils"
import report from "./reporter"
import { getPackageManager, setPackageManager } from "./util/package-manager"
import reporter from "../lib/reporter"
const spawnWithArgs = (
file: string,
args: Array<string>,
options?: execa.Options
): execa.ExecaChildProcess =>
execa(file, args, { stdio: `inherit`, preferLocal: false, ...options })
const spawn = (
cmd: string,
options?: execa.Options
): execa.ExecaChildProcess => {
const [file, ...args] = cmd.split(/\s+/)
return spawnWithArgs(file, args, options)
}
// Checks the existence of yarn package
// We use yarnpkg instead of yarn to avoid conflict with Hadoop yarn
// Refer to https://github.com/yarnpkg/yarn/issues/673
const checkForYarn = async (): Promise<boolean> => {
try {
execSync(`yarnpkg --version`, { stdio: `ignore` })
return true
} catch (e) {
return false
}
}
const isAlreadyGitRepository = async (): Promise<boolean> => {
try {
return await spawn(`git rev-parse --is-inside-work-tree`, {
stdio: `pipe`,
}).then(output => output.stdout === `true`)
} catch (err) {
return false
}
}
// Initialize newly cloned directory as a git repo
const gitInit = async (
rootPath: string
): Promise<execa.ExecaReturnBase<string>> => {
report.info(`Initialising git in ${rootPath}`)
return await spawn(`git init`, { cwd: rootPath })
}
// Create a .gitignore file if it is missing in the new directory
const maybeCreateGitIgnore = async (rootPath: string): Promise<void> => {
if (existsSync(sysPath.join(rootPath, `.gitignore`))) {
return
}
report.info(`Creating minimal .gitignore in ${rootPath}`)
await fs.writeFile(
sysPath.join(rootPath, `.gitignore`),
`.cache\nnode_modules\npublic\n`
)
}
// Create an initial git commit in the new directory
const createInitialGitCommit = async (
rootPath: string,
starterUrl: string
): Promise<void> => {
report.info(`Create initial git commit in ${rootPath}`)
await spawn(`git add -A`, { cwd: rootPath })
// use execSync instead of spawn to handle git clients using
// pgp signatures (with password)
try {
execSync(`git commit -m "Initial commit from gatsby: (${starterUrl})"`, {
cwd: rootPath,
})
} catch {
// Remove git support if initial commit fails
report.info(`Initial git commit failed - removing git support\n`)
fs.removeSync(sysPath.join(rootPath, `.git`))
}
}
// Executes `npm install` or `yarn install` in rootPath.
const install = async (rootPath: string): Promise<void> => {
const prevDir = process.cwd()
report.info(`Installing packages...`)
process.chdir(rootPath)
try {
if (!getPackageManager()) {
setPackageManager(`npm`)
}
if (getPackageManager() === `yarn` && checkForYarn()) {
if (await fs.pathExists(`package-lock.json`)) {
if (!(await fs.pathExists(`yarn.lock`))) {
await spawn(`yarnpkg import`)
}
await fs.remove(`package-lock.json`)
}
await spawn(`yarnpkg`)
} else {
await fs.remove(`yarn.lock`)
await spawn(`npm install`)
}
} finally {
process.chdir(prevDir)
}
}
const ignored = (path: string): boolean =>
!/^\.(git|hg)$/.test(sysPath.basename(path))
// Copy starter from file system.
const copy = async (
starterPath: string,
rootPath: string
): Promise<boolean> => {
// Chmod with 755.
// 493 = parseInt('755', 8)
await fs.ensureDir(rootPath, { mode: 493 })
if (!existsSync(starterPath)) {
throw new Error(`starter ${starterPath} doesn't exist`)
}
if (starterPath === `.`) {
throw new Error(
`You can't create a starter from the existing directory. If you want to
create a new site in the current directory, the trailing dot isn't
necessary. If you want to create a new site from a local starter, run
something like "gatsby new new-gatsby-site ../my-gatsby-starter"`
)
}
report.info(`Creating new site from local starter: ${starterPath}`)
report.log(`Copying local starter to ${rootPath} ...`)
await fs.copy(starterPath, rootPath, { filter: ignored })
report.success(`Created starter directory layout`)
await install(rootPath)
return true
}
// Clones starter from URI.
const clone = async (
hostInfo: hostedGitInfo,
rootPath: string
): Promise<void> => {
let url: string
// Let people use private repos accessed over SSH.
if (hostInfo.getDefaultRepresentation() === `sshurl`) {
url = hostInfo.ssh({ noCommittish: true })
// Otherwise default to normal git syntax.
} else {
url = hostInfo.https({ noCommittish: true, noGitPlus: true })
}
const branch = hostInfo.committish ? [`-b`, hostInfo.committish] : []
report.info(`Creating new site from git: ${url}`)
const args = [
`clone`,
...branch,
url,
rootPath,
`--recursive`,
`--depth=1`,
].filter(arg => Boolean(arg))
await spawnWithArgs(`git`, args)
report.success(`Created starter directory layout`)
await fs.remove(sysPath.join(rootPath, `.git`))
await install(rootPath)
const isGit = await isAlreadyGitRepository()
if (!isGit) await gitInit(rootPath)
await maybeCreateGitIgnore(rootPath)
if (!isGit) await createInitialGitCommit(rootPath, url)
}
interface IGetPaths {
starterPath: string
rootPath: string
selectedOtherStarter: boolean
}
const getPaths = async (
starterPath?: string,
rootPath?: string
): Promise<IGetPaths> => {
let selectedOtherStarter = false
// if no args are passed, prompt user for path and starter
if (!starterPath && !rootPath) {
const response = await prompts.prompt([
{
type: `text`,
name: `path`,
message: `What is your project called?`,
initial: `my-gatsby-project`,
},
{
type: `select`,
name: `starter`,
message: `What starter would you like to use?`,
choices: [
{ title: `gatsby-starter-default`, value: `gatsby-starter-default` },
{
title: `gatsby-starter-hello-world`,
value: `gatsby-starter-hello-world`,
},
{ title: `gatsby-starter-blog`, value: `gatsby-starter-blog` },
{ title: `(Use a different starter)`, value: `different` },
],
initial: 0,
},
])
// exit gracefully if responses aren't provided
if (!response.starter || !response.path.trim()) {
throw new Error(
`Please mention both starter package and project name along with path(if its not in the root)`
)
}
selectedOtherStarter = response.starter === `different`
starterPath = `gatsbyjs/${response.starter}`
rootPath = response.path
}
// set defaults if no root or starter has been set yet
rootPath = rootPath || process.cwd()
starterPath = starterPath || `gatsbyjs/gatsby-starter-default`
return { starterPath, rootPath, selectedOtherStarter }
}
const successMessage = (path: string): void => {
report.info(`
Your new Gatsby site has been successfully bootstrapped. Start developing it by running:
cd ${path}
gatsby develop
`)
}
/**
* Main function that clones or copies the starter.
*/
export async function initStarter(
starter?: string,
root?: string
): Promise<void> {
const { starterPath, rootPath, selectedOtherStarter } = await getPaths(
starter,
root
)
const urlObject = url.parse(rootPath)
if (selectedOtherStarter) {
report.info(
`Opening the starter library at https://gatsby.dev/starters?v=2...\nThe starter library has a variety of options for starters you can browse\n\nYou can then use the gatsby new command with the link to a repository of a starter you'd like to use, for example:\ngatsby new ${rootPath} https://github.com/gatsbyjs/gatsby-starter-default`
)
opn(`https://gatsby.dev/starters?v=2`)
return
}
if (urlObject.protocol && urlObject.host) {
trackError(`NEW_PROJECT_NAME_MISSING`)
const isStarterAUrl =
starter && !url.parse(starter).hostname && !url.parse(starter).protocol
if (/gatsby-starter/gi.test(rootPath) && isStarterAUrl) {
report.panic({
id: `11610`,
context: {
starter,
rootPath,
},
})
return
}
report.panic({
id: `11611`,
context: {
rootPath,
},
})
return
}
if (!isValid(rootPath)) {
report.panic({
id: `11612`,
context: {
path: sysPath.resolve(rootPath),
},
})
return
}
if (existsSync(sysPath.join(rootPath, `package.json`))) {
trackError(`NEW_PROJECT_IS_NPM_PROJECT`)
report.panic({
id: `11613`,
context: {
rootPath,
},
})
return
}
const hostedInfo = hostedGitInfo.fromUrl(starterPath)
trackCli(`NEW_PROJECT`, {
starterName: hostedInfo ? hostedInfo.shortcut() : `local:starter`,
})
if (hostedInfo) {
await clone(hostedInfo, rootPath)
} else {
await copy(starterPath, rootPath)
}
const sitePath = sysPath.resolve(rootPath)
const sitePackageJson = await fs
.readJSON(sysPath.join(sitePath, `package.json`))
.catch(() => {
reporter.verbose(
`Could not read "${sysPath.join(sitePath, `package.json`)}"`
)
})
await updateSiteMetadata(
{
name: sitePackageJson?.name || rootPath,
sitePath,
lastRun: Date.now(),
},
false
)
successMessage(rootPath)
trackCli(`NEW_PROJECT_END`)
}