forked from remix-run/remix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli-test.ts
360 lines (310 loc) · 10.6 KB
/
cli-test.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
import childProcess from "child_process";
import os from "os";
import path from "path";
import util from "util";
import fse from "fs-extra";
import semver from "semver";
import { jestTimeout } from "./setupAfterEnv";
let DOWN = "\x1B\x5B\x42";
let ENTER = "\x0D";
let execFile = util.promisify(childProcess.execFile);
const TEMP_DIR = path.join(
fse.realpathSync(os.tmpdir()),
`remix-tests-${Math.random().toString(32).slice(2)}`
);
jest.setTimeout(30_000);
beforeAll(async () => {
await fse.remove(TEMP_DIR);
await fse.ensureDir(TEMP_DIR);
});
afterAll(async () => {
await fse.remove(TEMP_DIR);
});
async function execRemix(
args: Array<string>,
options: Exclude<Parameters<typeof execFile>[2], null | undefined> = {}
) {
if (process.platform === "win32") {
let cp = childProcess.spawnSync(
"node",
[
"--require",
require.resolve("esbuild-register"),
"--require",
path.join(__dirname, "./msw.ts"),
path.resolve(__dirname, "../cli.ts"),
...args,
],
{
cwd: TEMP_DIR,
...options,
env: {
...process.env,
NO_COLOR: "1",
...options.env,
},
}
);
return {
stdout: cp.stdout?.toString("utf-8"),
};
} else {
let result = await execFile(
"node",
[
"--require",
require.resolve("esbuild-register"),
"--require",
path.join(__dirname, "./msw.ts"),
path.resolve(__dirname, "../cli.ts"),
...args,
],
{
cwd: TEMP_DIR,
...options,
env: {
...process.env,
NO_COLOR: "1",
...options.env,
},
}
);
return {
...result,
stdout: result.stdout.replace(TEMP_DIR, "<TEMP_DIR>").trim(),
};
}
}
describe("remix CLI", () => {
describe("the --help flag", () => {
it("prints help info", async () => {
let { stdout } = await execRemix(["--help"]);
expect(stdout.trim()).toMatchInlineSnapshot(`
"R E M I X
Usage:
$ remix create <projectDir> --template <template>
$ remix init [projectDir]
$ remix build [projectDir]
$ remix dev [projectDir]
$ remix routes [projectDir]
$ remix watch [projectDir]
$ remix setup [remixPlatform]
$ remix codemod <codemod> [projectDir]
Options:
--help, -h Print this help message and exit
--version, -v Print the CLI version and exit
--no-color Disable ANSI colors in console output
\`create\` Options:
--template The template to use
--no-install Skip installing dependencies after creation
--no-typescript Convert the template to JavaScript
--remix-version The version of Remix to use
\`build\` Options:
--sourcemap Generate source maps for production
\`dev\` Options:
--debug Attach Node.js inspector
--port, -p Choose the port from which to run your app
\`init\` Options:
--no-delete Skip deleting the \`remix.init\` script
\`routes\` Options:
--json Print the routes as JSON
\`codemod\` Options:
--dry Dry run (no changes are made to files)
--force Bypass Git safety checks
Values:
- projectDir The Remix project directory
- template The project template to use
- remixPlatform \`node\` or \`cloudflare\`
Creating a new project:
Remix projects are created from templates. A template can be:
- a file path to a directory of files
- a file path to a tarball
- the name of a :username/:repo on GitHub
- the URL of a tarball
$ remix create my-app --template /path/to/remix-template
$ remix create my-app --template /path/to/remix-template.tar.gz
$ remix create my-app --template remix-run/grunge-stack
$ remix create my-app --template :username/:repo
$ remix create my-app --template https://github.com/:username/:repo
$ remix create my-app --template https://github.com/:username/:repo/tree/:branch
$ remix create my-app --template https://github.com/:username/:repo/archive/refs/tags/:tag.tar.gz
$ remix create my-app --template https://example.com/remix-template.tar.gz
To create a new project from a template in a private GitHub repo,
pass the \`token\` flag with a personal access token with access to that repo.
Initialize a project::
Remix project templates may contain a \`remix.init\` directory
with a script that initializes the project. This script automatically
runs during \`remix create\`, but if you ever need to run it manually
(e.g. to test it out) you can:
$ remix init
Build your project:
$ remix build
$ remix build --sourcemap
$ remix build my-app
Run your project locally in development:
$ remix dev
$ remix dev my-app
$ remix dev --debug
Start your server separately and watch for changes:
# custom server start command, for example:
$ remix watch
# in a separate tab:
$ node --inspect --require ./node_modules/dotenv/config --require ./mocks ./build/server.js
Show all routes in your app:
$ remix routes
$ remix routes my-app
$ remix routes --json
Reveal the used entry point:
$ remix reveal entry.client
$ remix reveal entry.server
$ remix reveal entry.client --no-typescript
$ remix reveal entry.server --no-typescript"
`);
});
});
describe("the --version flag", () => {
it("prints the current version", async () => {
let { stdout } = await execRemix(["--version"]);
expect(!!semver.valid(stdout.trim())).toBe(true);
});
});
describe("create prompts", () => {
it("allows you to go through the prompts", async () => {
let projectDir = path.join(TEMP_DIR, "my-app");
let proc = childProcess.spawn(
"node",
[
"--require",
require.resolve("esbuild-register"),
"--require",
path.join(__dirname, "./msw.ts"),
path.resolve(__dirname, "../cli.ts"),
"create",
],
{ stdio: [null, null, null] }
);
await interactWithShell(proc, [
{ question: /Where.*create.*app/i, type: [projectDir, ENTER] },
{ question: /What type of app/i, answer: /basics/i },
{ question: /Where.*deploy/i, answer: /express/i },
{ question: /typescript or javascript/i, answer: /typescript/i },
{ question: /install/i, type: ["n", ENTER] },
]);
});
it("allows you to go through the prompts and convert to JS", async () => {
let projectDir = path.join(TEMP_DIR, "my-js-app");
let proc = childProcess.spawn(
"node",
[
"--require",
require.resolve("esbuild-register"),
"--require",
path.join(__dirname, "./msw.ts"),
path.resolve(__dirname, "../cli.ts"),
"create",
],
{ stdio: [null, null, null] }
);
await interactWithShell(proc, [
{ question: /Where.*create.*app/i, type: [projectDir, ENTER] },
{ question: /What type of app/i, answer: /basics/i },
{ question: /Where.*deploy/i, answer: /express/i },
{ question: /typescript or javascript/i, answer: /javascript/i },
{ question: /install/i, type: ["n", ENTER] },
]);
expect(fse.existsSync(path.join(projectDir, "app/root.tsx"))).toBeFalsy();
expect(
fse.existsSync(path.join(projectDir, "app/root.jsx"))
).toBeTruthy();
});
});
});
function defer() {
let resolve: (value: unknown) => void, reject: (reason?: any) => void;
let state: { current: "pending" | "resolved" | "rejected" } = {
current: "pending",
};
let promise = new Promise((res, rej) => {
resolve = (value: unknown) => {
state.current = "resolved";
return res(value);
};
reject = (reason?: any) => {
state.current = "rejected";
return rej(reason);
};
});
return { promise, resolve: resolve!, reject: reject!, state };
}
async function interactWithShell(
proc: childProcess.ChildProcessWithoutNullStreams,
qAndA: Array<
| { question: RegExp; type: Array<string>; answer?: never }
| { question: RegExp; answer: RegExp; type?: never }
>
) {
proc.stdin.setDefaultEncoding("utf-8");
let deferred = defer();
let stepNumber = 0;
let stdout = "";
let stderr = "";
proc.stdout.on("data", (chunk: unknown) => {
if (chunk instanceof Buffer) {
chunk = String(chunk);
}
if (typeof chunk !== "string") {
console.error({ stdoutChunk: chunk });
throw new Error("stdout chunk is not a string");
}
stdout += chunk;
let step = qAndA[stepNumber];
if (!step) return;
let { question, answer, type } = step;
if (question.test(chunk)) {
if (answer) {
let currentSelection = chunk
.split("\n")
.slice(1)
.find((l) => l.includes("❯") || l.includes(">"));
if (currentSelection && answer.test(currentSelection)) {
proc.stdin.write(ENTER);
stepNumber += 1;
} else {
proc.stdin.write(DOWN);
}
} else if (type) {
for (let command of type) {
proc.stdin.write(command);
}
stepNumber += 1;
}
}
if (stepNumber === qAndA.length) {
proc.stdin.end();
}
});
proc.stderr.on("data", (chunk: unknown) => {
if (chunk instanceof Buffer) {
chunk = String(chunk);
}
if (typeof chunk !== "string") {
console.error({ stderrChunk: chunk });
throw new Error("stderr chunk is not a string");
}
stderr += chunk;
});
proc.on("close", (status) => {
if (status === 0) return deferred.resolve(status);
else return deferred.reject({ stdout, stderr });
});
// this ensures that if we do timeout we at least get as much useful
// output as possible.
let timeout = setTimeout(() => {
if (deferred.state.current === "pending") {
proc.kill();
deferred.reject({ status: "timeout", stdout, stderr });
}
}, jestTimeout);
await deferred.promise;
clearTimeout(timeout);
}