-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
238 lines (206 loc) · 6.13 KB
/
Copy pathindex.ts
File metadata and controls
238 lines (206 loc) · 6.13 KB
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
#!/usr/bin/env node
import { createApp, DownloadError } from "./create-app";
import { isFolderEmpty } from "./helpers/is-folder-empty";
import { validateNpmName } from "./helpers/validate-pkg";
import packageJson from "./package.json";
import chalk from "chalk";
import Commander from "commander";
import Conf from "conf";
import fs from "fs";
import path from "path";
import prompts from "prompts";
import checkForUpdate from "update-check";
let projectPath: string = "";
const handleSigTerm = () => process.exit(0);
process.on("SIGINT", handleSigTerm);
process.on("SIGTERM", handleSigTerm);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const onPromptState = (state: any) => {
if (state.aborted) {
// If we don't re-enable the terminal cursor before exiting
// the program, the cursor will remain hidden
process.stdout.write("\x1B[?25h");
process.stdout.write("\n");
process.exit(1);
}
};
const program = new Commander.Command(packageJson.name)
.version(packageJson.version)
.arguments("<project-directory>")
.usage(`${chalk.green("<project-directory>")} [options]`)
.action(name => {
projectPath = name;
})
.option(
"-t, --template [name]|[github-url]",
`
An template to bootstrap the app with. You can use an template name
from the Create 206 repo or a GitHub URL. The URL can use
any branch and/or subdirectory
`,
)
.option(
"--template-path <path-to-template>",
`
In a rare case, your GitHub URL might contain a branch name with
a slash (e.g. bug/fix-1) and the path to the template (e.g. foo/bar).
In this case, you must specify the path to the template separately:
--template-path foo/bar
`,
)
.option(
"--reset-preferences",
`
Explicitly tell the CLI to reset any stored preferences
`,
)
.option(
"--branch <branch>",
`Specify a branch other than the repo's main branch to download a
template from. This is useful for downloading testing a template
that is not yet merged into the main branch.`,
"main",
)
.allowUnknownOption()
.parse(process.argv);
async function run(): Promise<void> {
const conf = new Conf({ projectName: "create-next-app" });
if (program.resetPreferences) {
conf.clear();
console.log("Preferences reset successfully");
return;
}
if (typeof projectPath === "string") {
projectPath = projectPath.trim();
}
if (!projectPath) {
const res = await prompts({
onState: onPromptState,
type: "text",
name: "path",
message: "What is your project named?",
initial: "my-app",
validate: name => {
const validation = validateNpmName(path.basename(path.resolve(name)));
if (validation.valid) {
return true;
}
return "Invalid project name: " + validation.problems![0];
},
});
if (typeof res.path === "string") {
projectPath = res.path.trim();
}
}
if (!projectPath) {
console.log(
"\nPlease specify the project directory:\n" +
` ${chalk.cyan(program.name())} ${chalk.green("<project-directory>")}\n` +
"For example:\n" +
` ${chalk.cyan(program.name())} ${chalk.green("my-next-app")}\n\n` +
`Run ${chalk.cyan(`${program.name()} --help`)} to see all options.`,
);
process.exit(1);
}
const resolvedProjectPath = path.resolve(projectPath);
const projectName = path.basename(resolvedProjectPath);
const { valid, problems } = validateNpmName(projectName);
if (!valid) {
console.error(
`Could not create a project called ${chalk.red(
`"${projectName}"`,
)} because of npm naming restrictions:`,
);
problems!.forEach(p => console.error(` ${chalk.red.bold("*")} ${p}`));
process.exit(1);
}
if (program.example === true) {
console.error("Please provide an example name or url, otherwise remove the example option.");
process.exit(1);
}
/**
* Verify the project dir is empty or doesn't exist
*/
const root = path.resolve(resolvedProjectPath);
const appName = path.basename(root);
const folderExists = fs.existsSync(root);
if (folderExists && !isFolderEmpty(root, appName)) {
process.exit(1);
}
let template = typeof program.template === "string" && program.template.trim();
const preferences = (conf.get("preferences") || {}) as Record<string, boolean | string>;
/**
* If the user does not provide the necessary flags, prompt them for which
* template to use.
*/
if (!template) {
const { template: selectedTemplate } = await prompts({
type: "select",
name: "template",
message: "Select a template",
choices: [
{
title: "Default (Pages)",
value: "default-pages",
},
{
title: "Default (App)",
value: "default-app",
},
{
title: "Sanity + Next.js (Pages)",
value: "sanity-pages",
},
],
});
template = selectedTemplate;
}
try {
await createApp({
appPath: resolvedProjectPath,
example: template ? template : undefined,
options: {
customBranch: program.branch,
},
});
} catch (reason) {
if (!(reason instanceof DownloadError)) {
throw reason;
}
throw reason;
}
conf.set("preferences", preferences);
}
const update = checkForUpdate(packageJson).catch(() => null);
async function notifyUpdate(): Promise<void> {
try {
const res = await update;
if (res?.latest) {
const updateMessage = "pnpm add -g create-206-app";
console.log(
chalk.yellow.bold("A new version of `create-206-app` is available!") +
"\n" +
"You can update by running: " +
chalk.cyan(updateMessage) +
"\n",
);
}
process.exit();
} catch {
// ignore error
}
}
run()
.then(notifyUpdate)
.catch(async reason => {
console.log();
console.log("Aborting installation.");
if (reason.command) {
console.log(` ${chalk.cyan(reason.command)} has failed.`);
} else {
console.log(chalk.red("Unexpected error. Please report it as a bug:") + "\n", reason);
}
console.log();
await notifyUpdate();
process.exit(1);
});