-
-
Notifications
You must be signed in to change notification settings - Fork 9.9k
Expand file tree
/
Copy pathget-template.ts
More file actions
220 lines (187 loc) · 7.15 KB
/
get-template.ts
File metadata and controls
220 lines (187 loc) · 7.15 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
import { program } from 'commander';
// eslint-disable-next-line depend/ban-dependencies
import { pathExists, readFile } from 'fs-extra';
import { readdir } from 'fs/promises';
import picocolors from 'picocolors';
import { dedent } from 'ts-dedent';
import yaml from 'yaml';
import {
type Cadence,
type SkippableTask,
type Template as TTemplate,
allTemplates,
templatesByCadence,
} from '../code/lib/cli-storybook/src/sandbox-templates';
import { SANDBOX_DIRECTORY } from './utils/constants';
import { esMain } from './utils/esmain';
const sandboxDir = process.env.SANDBOX_ROOT || SANDBOX_DIRECTORY;
type Template = Pick<TTemplate, 'inDevelopment' | 'skipTasks'>;
export type TemplateKey = keyof typeof allTemplates;
export type Templates = Record<TemplateKey, Template>;
async function getDirectories(source: string) {
return (await readdir(source, { withFileTypes: true }))
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
}
export async function getTemplate(
cadence: Cadence,
scriptName: string,
{ index, total }: { index: number; total: number }
) {
let potentialTemplateKeys: TemplateKey[] = [];
if (await pathExists(sandboxDir)) {
const sandboxes = await getDirectories(sandboxDir);
potentialTemplateKeys = sandboxes
.map((dirName) => {
return Object.keys(allTemplates).find(
(templateKey) => templateKey.replace('/', '-') === dirName
);
})
.filter(Boolean) as TemplateKey[];
}
if (potentialTemplateKeys.length === 0) {
const cadenceTemplates = Object.entries(allTemplates).filter(([key]) =>
templatesByCadence[cadence].includes(key as TemplateKey)
);
potentialTemplateKeys = cadenceTemplates.map(([k]) => k) as TemplateKey[];
}
potentialTemplateKeys = potentialTemplateKeys.filter((t) => {
const currentTemplate = allTemplates[t] as Template;
return (
currentTemplate.inDevelopment !== true &&
!currentTemplate.skipTasks?.includes(scriptName as SkippableTask)
);
});
if (potentialTemplateKeys.length !== total) {
throw new Error(dedent`Circle parallelism set incorrectly.
Parallelism is set to ${total}, but there are ${
potentialTemplateKeys.length
} templates to run for the "${scriptName}" task:
${potentialTemplateKeys.map((v) => `- ${v}`).join('\n')}
${await checkParallelism(cadence)}
`);
}
return potentialTemplateKeys[index];
}
const tasksMap = {
sandbox: 'create-sandboxes',
build: 'build-sandboxes',
chromatic: 'chromatic-sandboxes',
'e2e-tests': 'e2e-production',
'e2e-tests-dev': 'e2e-dev',
'test-runner': 'test-runner-production',
// 'test-runner-dev', TODO: bring this back when the task is enabled again
bench: 'bench',
'vitest-integration': 'vitest-integration',
} as const;
type TaskKey = keyof typeof tasksMap;
const tasks = Object.keys(tasksMap) as TaskKey[];
const CONFIG_YML_FILE = '../.circleci/config.yml';
async function checkParallelism(cadence?: Cadence, scriptName?: TaskKey) {
const configYml = await readFile(CONFIG_YML_FILE, 'utf-8');
const data = yaml.parse(configYml);
let potentialTemplateKeys: TemplateKey[] = [];
const cadences = cadence ? [cadence] : (Object.keys(templatesByCadence) as Cadence[]);
const scripts = scriptName ? [scriptName] : tasks;
const summary = [];
let isIncorrect = false;
cadences.forEach((cad) => {
summary.push(`\n${picocolors.bold(cad)}`);
const cadenceTemplates = Object.entries(allTemplates).filter(([key]) =>
templatesByCadence[cad].includes(key as TemplateKey)
);
potentialTemplateKeys = cadenceTemplates.map(([k]) => k) as TemplateKey[];
scripts.forEach((script) => {
const templateKeysPerScript = potentialTemplateKeys.filter((t) => {
const currentTemplate = allTemplates[t] as Template;
return (
currentTemplate.inDevelopment !== true &&
!currentTemplate.skipTasks?.includes(script as SkippableTask)
);
});
const workflowJobsRaw: (string | { [key: string]: any })[] = data.workflows[cad].jobs;
const workflowJobs = workflowJobsRaw
.filter((item) => typeof item === 'object' && item !== null)
.reduce((result, item) => Object.assign(result, item), {}) as Record<string, any>;
if (templateKeysPerScript.length > 0 && workflowJobs[tasksMap[script]]) {
const currentParallelism = workflowJobs[tasksMap[script]].parallelism || 2;
const newParallelism = templateKeysPerScript.length;
if (newParallelism !== currentParallelism) {
summary.push(
`-- ❌ ${tasksMap[script]} - parallelism: ${currentParallelism} ${picocolors.bgRed(
`(should be ${newParallelism})`
)}`
);
isIncorrect = true;
} else {
summary.push(
`-- ✅ ${tasksMap[script]} - parallelism: ${templateKeysPerScript.length}${
templateKeysPerScript.length === 2 ? ' (default)' : ''
}`
);
}
} else {
summary.push(`-- ${script} - this script is fully skipped for this cadence.`);
}
});
});
if (isIncorrect) {
summary.unshift(
'The parellism count is incorrect for some jobs in .circleci/config.yml, you have to update them:'
);
throw new Error(summary.concat('\n').join('\n'));
} else {
summary.unshift('✅ The parallelism count is correct for all jobs in .circleci/config.yml:');
console.log(summary.concat('\n').join('\n'));
}
const inDevelopmentTemplates = Object.entries(allTemplates)
.filter(([_, t]) => t.inDevelopment)
.map(([k]) => k);
if (inDevelopmentTemplates.length > 0) {
console.log(
`👇 Some templates were skipped as they are flagged to be in development. Please review if they should still contain this flag:\n${inDevelopmentTemplates
.map((k) => `- ${k}`)
.join('\n')}`
);
}
}
type RunOptions = { cadence?: Cadence; task?: TaskKey; check: boolean };
async function run({ cadence, task, check }: RunOptions) {
if (check) {
if (task && !tasks.includes(task)) {
throw new Error(
dedent`The "${task}" task you provided is not valid. Valid tasks (found in .circleci/config.yml) are:
${tasks.map((v) => `- ${v}`).join('\n')}`
);
}
await checkParallelism(cadence as Cadence, task);
return;
}
if (!cadence) {
throw new Error('Need to supply cadence to get template script');
}
const { CIRCLE_NODE_INDEX = 0, CIRCLE_NODE_TOTAL = 1 } = process.env;
console.log(
await getTemplate(cadence as Cadence, task, {
index: +CIRCLE_NODE_INDEX,
total: +CIRCLE_NODE_TOTAL,
})
);
}
if (esMain(import.meta.url)) {
program
.description('Retrieve the template to run for a given cadence and task')
.option('--cadence <cadence>', 'Which cadence you want to run the script for')
.option('--task <task>', 'Which task you want to run the script for')
.option(
'--check',
'Throws an error when the parallelism counts for tasks are incorrect',
false
);
program.parse(process.argv);
const options = program.opts() as RunOptions;
run(options).catch((err) => {
console.error(err);
process.exit(1);
});
}