forked from storybookjs/storybook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask.ts
539 lines (480 loc) · 17 KB
/
task.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// eslint-disable-next-line depend/ban-dependencies
import { outputFile, pathExists, readFile } from 'fs-extra';
import type { TestCase } from 'junit-xml';
import { getJunitXml } from 'junit-xml';
import { join, resolve } from 'path';
import { prompt } from 'prompts';
import invariant from 'tiny-invariant';
import { dedent } from 'ts-dedent';
import {
allTemplates as TEMPLATES,
type Template,
type TemplateKey,
} from '../code/lib/cli-storybook/src/sandbox-templates';
import { version } from '../code/package.json';
import { bench } from './tasks/bench';
import { build } from './tasks/build';
import { check } from './tasks/check';
import { chromatic } from './tasks/chromatic';
import { compile } from './tasks/compile';
import { dev } from './tasks/dev';
import { e2eTestsBuild } from './tasks/e2e-tests-build';
import { e2eTestsDev } from './tasks/e2e-tests-dev';
import { generate } from './tasks/generate';
import { install } from './tasks/install';
import { publish } from './tasks/publish';
import { runRegistryTask } from './tasks/run-registry';
import { sandbox } from './tasks/sandbox';
import { serve } from './tasks/serve';
import { smokeTest } from './tasks/smoke-test';
import { syncDocs } from './tasks/sync-docs';
import { testRunnerBuild } from './tasks/test-runner-build';
import { testRunnerDev } from './tasks/test-runner-dev';
import { vitestTests } from './tasks/vitest-test';
import { CODE_DIRECTORY, JUNIT_DIRECTORY, SANDBOX_DIRECTORY } from './utils/constants';
import type { OptionValues } from './utils/options';
import { createOptions, getCommand, getOptionsOrPrompt } from './utils/options';
const sandboxDir = process.env.SANDBOX_ROOT || SANDBOX_DIRECTORY;
export const extraAddons = ['a11y', 'storysource'];
export type Path = string;
export type TemplateDetails = {
key: TemplateKey;
selectedTask: TaskKey;
template: Template;
codeDir: Path;
sandboxDir: Path;
builtSandboxDir: Path;
junitFilename: Path;
};
type MaybePromise<T> = T | Promise<T>;
export type Task = {
/** A description of the task for a prompt */
description: string;
/**
* Does this task represent a service for another task?
*
* Unlink other tasks, if a service is not ready, it doesn't mean the subsequent tasks must be out
* of date. As such, services will never be reset back to, although they will be started if
* dependent tasks are.
*/
service?: boolean;
/** Which tasks must be ready before this task can run */
dependsOn?: TaskKey[] | ((details: TemplateDetails, options: PassedOptionValues) => TaskKey[]);
/** Is this task already "ready", and potentially not required? */
ready: (details: TemplateDetails, options?: PassedOptionValues) => MaybePromise<boolean>;
/** Run the task */
run: (
details: TemplateDetails,
options: PassedOptionValues
) => MaybePromise<void | AbortController>;
/** Does this task handle its own junit results? */
junit?: boolean;
};
export const tasks = {
// These tasks pertain to the whole monorepo, rather than an
// individual template/sandbox
install,
compile,
check,
publish,
'sync-docs': syncDocs,
'run-registry': runRegistryTask,
// These tasks pertain to a single sandbox in the ../sandboxes dir
generate,
sandbox,
dev,
'smoke-test': smokeTest,
build,
serve,
'test-runner': testRunnerBuild,
'test-runner-dev': testRunnerDev,
chromatic,
'e2e-tests': e2eTestsBuild,
'e2e-tests-dev': e2eTestsDev,
bench,
'vitest-integration': vitestTests,
};
type TaskKey = keyof typeof tasks;
function isSandboxTask(taskKey: TaskKey) {
return !['install', 'compile', 'publish', 'run-registry', 'check', 'sync-docs'].includes(taskKey);
}
export const options = createOptions({
task: {
type: 'string',
description: 'Which task would you like to run?',
values: Object.keys(tasks) as TaskKey[],
valueDescriptions: Object.values(tasks).map((t) => `${t.description} (${getTaskKey(t)})`),
required: true,
},
startFrom: {
type: 'string',
description: 'Which task should we start execution from?',
values: [...(Object.keys(tasks) as TaskKey[]), 'never', 'auto'] as const,
// This is prompted later based on information about what's ready
promptType: false,
},
template: {
type: 'string',
description: 'What template would you like to make a sandbox for?',
values: Object.keys(TEMPLATES) as TemplateKey[],
required: ({ task }) => !task || isSandboxTask(task),
promptType: (_, { task }) => isSandboxTask(task),
},
// // TODO -- feature flags
// sandboxDir: {
// type: 'string',
// description: 'What is the name of the directory the sandbox runs in?',
// promptType: false,
// },
addon: {
type: 'string[]',
description: 'Which extra addons (beyond the CLI defaults) would you like installed?',
values: extraAddons,
promptType: (_, { task }) => isSandboxTask(task),
},
link: {
type: 'boolean',
description: 'Build code and link for local development?',
inverse: true,
promptType: false,
},
prod: {
type: 'boolean',
description: 'Build code for production',
promptType: false,
},
dryRun: {
type: 'boolean',
description: "Don't execute commands, just list them (dry run)?",
promptType: false,
},
debug: {
type: 'boolean',
description: 'Print all the logs to the console',
promptType: false,
},
junit: {
type: 'boolean',
description: 'Store results in junit format?',
promptType: false,
},
skipTemplateStories: {
type: 'boolean',
description: 'Do not include template stories and their addons',
promptType: false,
},
disableDocs: {
type: 'boolean',
description: 'Disable addon-docs from essentials',
promptType: false,
},
});
export type PassedOptionValues = Omit<OptionValues<typeof options>, 'task' | 'startFrom' | 'junit'>;
const logger = console;
function getJunitFilename(taskKey: TaskKey) {
return join(JUNIT_DIRECTORY, `${taskKey}.xml`);
}
async function writeJunitXml(
taskKey: TaskKey,
templateKey: TemplateKey,
startTime: Date,
err?: Error,
systemError?: boolean
) {
let errorData = {};
if (err) {
// we want to distinguish whether the error comes from the tests we are running or from arbitrary code
errorData = systemError ? { errors: [{ message: err.stack }] } : { errors: [err] };
}
const name = `${taskKey} - ${templateKey}`;
const time = (Date.now() - +startTime) / 1000;
const testCase = { name, assertions: 1, time, ...errorData };
// We store the metadata as a system-err.
// Which is a bit unfortunate but it seems that one can't store extra data when the task is successful.
// system-err won't turn the whole test suite as failing, which makes it a reasonable candidate
const metadata: TestCase = {
name: `${name} - metadata`,
systemErr: [JSON.stringify({ ...TEMPLATES[templateKey], id: templateKey, version })],
};
const suite = { name, timestamp: startTime, time, testCases: [testCase, metadata] };
const junitXml = getJunitXml({ time, name, suites: [suite] });
const path = getJunitFilename(taskKey);
await outputFile(path, junitXml);
logger.log(`Test results written to ${resolve(path)}`);
}
function getTaskKey(task: Task): TaskKey {
return (Object.entries(tasks) as [TaskKey, Task][]).find(([_, t]) => t === task)[0];
}
/** Get a list of tasks that need to be (possibly) run, in order, to be able to run `finalTask`. */
function getTaskList(finalTask: Task, details: TemplateDetails, optionValues: PassedOptionValues) {
const taskDeps = new Map<Task, Task[]>();
// Which tasks depend on a given task
const tasksThatDepend = new Map<Task, Task[]>();
const addTask = (task: Task, dependent?: Task) => {
if (tasksThatDepend.has(task)) {
if (!dependent) {
throw new Error('Unexpected task without dependent seen a second time');
}
tasksThatDepend.set(task, tasksThatDepend.get(task).concat(dependent));
return;
}
// This is the first time we've seen this task
tasksThatDepend.set(task, dependent ? [dependent] : []);
const dependedTaskNames =
typeof task.dependsOn === 'function'
? task.dependsOn(details, optionValues)
: task.dependsOn || [];
const dependedTasks = dependedTaskNames.map((n) => tasks[n]);
taskDeps.set(task, dependedTasks);
dependedTasks.forEach((t) => addTask(t, task));
};
addTask(finalTask);
// We need to sort the tasks topologically so we run each task before the tasks that
// depend on it. This is Kahn's algorithm :shrug:
const sortedTasks = [] as Task[];
const tasksWithoutDependencies = [finalTask];
while (taskDeps.size !== sortedTasks.length) {
const task = tasksWithoutDependencies.pop();
if (!task) {
throw new Error('Topological sort failed, is there a cyclic task dependency?');
}
sortedTasks.unshift(task);
taskDeps.get(task).forEach((depTask) => {
const remainingTasksThatDepend = tasksThatDepend
.get(depTask)
.filter((t) => !sortedTasks.includes(t));
if (remainingTasksThatDepend.length === 0) {
tasksWithoutDependencies.push(depTask);
}
});
}
return { sortedTasks, tasksThatDepend };
}
type TaskStatus =
| 'ready'
| 'unready'
| 'running'
| 'complete'
| 'failed'
| 'serving'
| 'notserving';
const statusToEmoji: Record<TaskStatus, string> = {
ready: '🟢',
unready: '🟡',
running: '🔄',
complete: '✅',
failed: '❌',
serving: '🔊',
notserving: '🔇',
};
function writeTaskList(statusMap: Map<Task, TaskStatus>) {
logger.info(
[...statusMap.entries()]
.map(([task, status]) => `${statusToEmoji[status]} ${getTaskKey(task)}`)
.join(' > ')
);
logger.info();
}
async function runTask(task: Task, details: TemplateDetails, optionValues: PassedOptionValues) {
const { junitFilename } = details;
const startTime = new Date();
try {
let updatedOptions = optionValues;
if (details.template?.modifications?.skipTemplateStories) {
updatedOptions = { ...updatedOptions, skipTemplateStories: true };
}
if (details.template?.modifications?.disableDocs) {
updatedOptions = { ...updatedOptions, disableDocs: true };
}
const controller = await task.run(details, updatedOptions);
if (junitFilename && !task.junit) {
await writeJunitXml(getTaskKey(task), details.key, startTime);
}
return controller;
} catch (err) {
invariant(err instanceof Error);
const hasJunitFile = await pathExists(junitFilename);
// If there's a non-test related error (junit report has not been reported already), we report the general failure in a junit report
if (junitFilename && !hasJunitFile) {
await writeJunitXml(getTaskKey(task), details.key, startTime, err, true);
}
throw err;
} finally {
if (await pathExists(junitFilename)) {
const junitXml = await (await readFile(junitFilename)).toString();
const prefixedXml = junitXml.replace(/classname="(.*)"/g, `classname="${details.key} $1"`);
await outputFile(junitFilename, prefixedXml);
}
}
}
const controllers: AbortController[] = [];
async function run() {
// useful for other scripts to know whether they're running in the creation of a sandbox in the monorepo
process.env.IN_STORYBOOK_SANDBOX = 'true';
const allOptionValues = await getOptionsOrPrompt('yarn task', options);
const { task: taskKey, startFrom, junit, ...optionValues } = allOptionValues;
const finalTask = tasks[taskKey];
const { template: templateKey } = optionValues;
const template = TEMPLATES[templateKey];
const templateSandboxDir = templateKey && join(sandboxDir, templateKey.replace('/', '-'));
const details: TemplateDetails = {
key: templateKey,
template,
codeDir: CODE_DIRECTORY,
selectedTask: taskKey,
sandboxDir: templateSandboxDir,
builtSandboxDir: templateKey && join(templateSandboxDir, 'storybook-static'),
junitFilename: junit && getJunitFilename(taskKey),
};
const { sortedTasks, tasksThatDepend } = getTaskList(finalTask, details, optionValues);
const sortedTasksReady = await Promise.all(
sortedTasks.map((t) => t.ready(details, optionValues))
);
if (templateKey) {
logger.info(`👉 Selected sandbox: ${templateKey}`);
logger.info();
}
logger.info(`Task readiness up to ${taskKey}`);
const initialTaskStatus = (task: Task, ready: boolean) => {
if (task.service) {
return ready ? 'serving' : 'notserving';
}
return ready ? 'ready' : 'unready';
};
const statuses = new Map<Task, TaskStatus>(
sortedTasks.map((task, index) => [task, initialTaskStatus(task, sortedTasksReady[index])])
);
writeTaskList(statuses);
function setUnready(task: Task) {
// If the task is a service we don't need to set it unready but we still need to do so for
// it's dependencies
// If the task is a service we don't need to set it unready but we still need to do so for
// it's dependencies
if (!task.service) {
statuses.set(task, 'unready');
}
tasksThatDepend
.get(task)
.filter((t) => !t.service)
.forEach(setUnready);
}
// NOTE: we don't include services in the first unready task. We only need to rewind back to a
// service if the user explicitly asks. It's expected that a service is no longer running.
const firstUnready = sortedTasks.find((task) => statuses.get(task) === 'unready');
if (startFrom === 'auto') {
// Don't reset anything!
} else if (startFrom === 'never') {
if (!firstUnready) {
throw new Error(`Task ${taskKey} is ready`);
}
if (firstUnready !== finalTask) {
throw new Error(`Task ${getTaskKey(firstUnready)} was not ready`);
}
} else if (startFrom) {
// set to reset back to a specific task
if (firstUnready && sortedTasks.indexOf(tasks[startFrom]) > sortedTasks.indexOf(firstUnready)) {
throw new Error(
`Task ${getTaskKey(firstUnready)} was not ready, earlier than your request ${startFrom}.`
);
}
setUnready(tasks[startFrom]);
} else if (firstUnready === sortedTasks[0]) {
// We need to do everything, no need to change anything
} else if (sortedTasks.length === 1) {
setUnready(sortedTasks[0]);
} else {
// We don't know what to do! Let's ask
const { startFromTask } = await prompt(
{
type: 'select',
message: firstUnready
? `We need to run all tasks from ${getTaskKey(
firstUnready
)} onwards, would you like to start from an earlier task?`
: `Which task would you like to start from?`,
name: 'startFromTask',
choices: sortedTasks
.slice(0, firstUnready && sortedTasks.indexOf(firstUnready) + 1)
.reverse()
.map((t) => ({
title: `${t.description} (${getTaskKey(t)})`,
value: t,
})),
},
{
onCancel: () => {
logger.log('Command cancelled by the user. Exiting...');
process.exit(1);
},
}
);
setUnready(startFromTask);
}
for (let i = 0; i < sortedTasks.length; i += 1) {
const task = sortedTasks[i];
const status = statuses.get(task);
let shouldRun = status === 'unready';
if (status === 'notserving') {
shouldRun =
finalTask === task ||
!!tasksThatDepend.get(task).find((t) => statuses.get(t) === 'unready');
}
if (shouldRun) {
statuses.set(task, 'running');
writeTaskList(statuses);
try {
const controller = await runTask(task, details, {
...optionValues,
// Always debug the final task so we can see it's output fully
debug: task === finalTask ? true : optionValues.debug,
});
if (controller) {
controllers.push(controller);
}
} catch (err) {
invariant(err instanceof Error);
logger.error(`Error running task ${getTaskKey(task)}:`);
logger.error(JSON.stringify(err, null, 2));
if (process.env.CI) {
logger.error(
dedent`
To reproduce this error locally, run:
${getCommand('yarn task', options, {
...allOptionValues,
link: true,
startFrom: 'auto',
})}
Note this uses locally linking which in rare cases behaves differently to CI. For a closer match, run:
${getCommand('yarn task', options, {
...allOptionValues,
startFrom: 'auto',
})}`
);
}
controllers.forEach((controller) => {
controller.abort();
});
throw err;
}
statuses.set(task, task.service ? 'serving' : 'complete');
// If the task is a service, we want to stay open until we are ctrl-ced
if (sortedTasks[i] === finalTask && finalTask.service) {
await new Promise(() => {});
}
}
}
return 0;
}
process.on('exit', () => {
// Make sure to kill any running tasks 🎉
controllers.forEach((controller) => {
controller.abort();
});
});
run()
.then((status) => process.exit(status))
.catch((err) => {
logger.error();
logger.error(err);
process.exit(1);
});