forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mts
More file actions
208 lines (174 loc) · 7.18 KB
/
index.mts
File metadata and controls
208 lines (174 loc) · 7.18 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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {setOutput} from '@actions/core';
import {GitClient, Log, bold, green, yellow} from '@angular/ng-dev';
import {select} from '@inquirer/prompts';
import yargs from 'yargs';
import {collectBenchmarkResults} from './results.mts';
import {
type ResolvedTarget,
findBenchmarkTargets,
getTestlogPath,
resolveTarget,
} from './targets.mts';
import {exec} from './utils.mts';
const benchmarkTestFlags = [
'--cache_test_results=no',
'--color=yes',
'--curses=no',
// We may have RBE set up, but test should run locally on the same machine to
// reduce fluctuation. Output streamed ensures that deps can build with RBE, but
// tests run locally while also providing useful output for debugging.
'--test_output=streamed',
];
await yargs(process.argv.slice(2))
.command(
'run-compare <compare-ref> [bazel-target]',
'Runs a benchmark between two SHAs',
(argv) =>
argv
.positional('compare-ref', {
description: 'Comparison SHA',
type: 'string',
demandOption: true,
})
.positional('bazel-target', {description: 'Bazel target', type: 'string'}),
(args) => runCompare(args.bazelTarget, args.compareRef),
)
.command(
'run [bazel-target]',
'Runs a benchmark',
(argv) => argv.positional('bazel-target', {description: 'Bazel target', type: 'string'}),
(args) => runBenchmarkCmd(args.bazelTarget),
)
.command(
'prepare-for-github-action <comment-body>',
false, // Do not show in help.
(argv) => argv.positional('comment-body', {demandOption: true, type: 'string'}),
(args) => prepareForGitHubAction(args.commentBody),
)
.demandCommand()
.scriptName('$0')
.help()
.strict()
.parseAsync();
/** Prompts for a benchmark target. */
async function promptForBenchmarkTarget(): Promise<string> {
const targets = await findBenchmarkTargets();
return await select({
message: 'Select benchmark target to run:',
choices: targets.map((t) => ({value: t, name: t})),
});
}
/**
* Prepares a benchmark comparison running via GitHub action. This command is
* used by the GitHub action YML workflow and is responsible for extracting
* e.g. command information or fetching/resolving Git refs of the comparison range.
*
* This is a helper used by the GitHub action to perform benchmark
* comparisons. Commands follow the format of: `/benchmark-compare <sha> <target>`.
*/
async function prepareForGitHubAction(commentBody: string): Promise<void> {
const matches = /\/[^ ]+ ([^ ]+) ([^ ]+)/.exec(commentBody);
if (matches === null) {
Log.error('Could not extract information from comment', commentBody);
process.exit(1);
}
const git = await GitClient.get();
const [_, compareRefRaw, benchmarkTarget] = matches;
// We assume the PR is checked out and therefore `HEAD` is the PR head SHA.
const prHeadSha = git.run(['rev-parse', 'HEAD']).stdout.trim();
setOutput('benchmarkTarget', benchmarkTarget);
setOutput('prHeadSha', prHeadSha);
// Attempt to find the compare SHA. The commit may be either part of the
// pull request, or might be a commit unrelated to the PR- but part of the
// upstream repository. We attempt to fetch/resolve the SHA in both remotes.
const compareRefResolve = git.runGraceful(['rev-parse', compareRefRaw]);
let compareRefSha = compareRefResolve.stdout.trim();
if (compareRefSha === '' || compareRefResolve.status !== 0) {
git.run(['fetch', '--depth=1', git.getRepoGitUrl(), compareRefRaw]);
compareRefSha = git.run(['rev-parse', 'FETCH_HEAD']).stdout.trim();
}
setOutput('compareSha', compareRefSha);
}
/** Runs a specified benchmark, or a benchmark selected via prompt. */
async function runBenchmarkCmd(bazelTargetRaw: string | undefined): Promise<void> {
if (bazelTargetRaw === undefined) {
bazelTargetRaw = await promptForBenchmarkTarget();
}
const bazelTarget = await resolveTarget(bazelTargetRaw);
const testlogPath = await getTestlogPath(bazelTarget);
await runBenchmarkTarget(bazelTarget);
const workingDirResults = await collectBenchmarkResults(testlogPath);
Log.info('\n\n\n');
Log.info(bold(green('Results!')));
Log.info(workingDirResults.summaryConsoleText);
}
/** Runs a benchmark Bazel target. */
async function runBenchmarkTarget(bazelTarget: ResolvedTarget): Promise<void> {
await exec('bazel', ['test', bazelTarget, ...benchmarkTestFlags]);
}
/**
* Performs a comparison of benchmark results between the current
* working stage and the comparison Git reference.
*/
async function runCompare(bazelTargetRaw: string | undefined, compareRef: string): Promise<void> {
const git = await GitClient.get();
const currentRef = git.getCurrentBranchOrRevision();
if (git.hasUncommittedChanges()) {
Log.warn(bold('You have uncommitted changes.'));
Log.warn('The script will stash your changes and re-apply them so that');
Log.warn('the comparison ref can be checked out.');
Log.warn('');
}
if (bazelTargetRaw === undefined) {
bazelTargetRaw = await promptForBenchmarkTarget();
}
const bazelTarget = await resolveTarget(bazelTargetRaw);
const testlogPath = await getTestlogPath(bazelTarget);
Log.log(green(`Test log path: ${testlogPath}`));
// Run benchmark with the current working stage.
await runBenchmarkTarget(bazelTarget);
const workingDirResults = await collectBenchmarkResults(testlogPath);
// Stash working directory as we might be in the middle of developing
// and we wouldn't want to discard changes when checking out the compare SHA.
git.run(['stash']);
try {
Log.log(green('Fetching comparison revision.'));
// Note: Not using a shallow fetch here as that would convert the local
// user repository into an incomplete repository.
git.run(['fetch', git.getRepoGitUrl(), compareRef]);
Log.log(green('Checking out comparison revision.'));
git.run(['checkout', 'FETCH_HEAD']);
await exec('yarn');
await runBenchmarkTarget(bazelTarget);
} finally {
restoreWorkingStage(git, currentRef);
}
// Re-install dependencies for `HEAD`.
await exec('yarn');
const comparisonResults = await collectBenchmarkResults(testlogPath);
// If we are running in a GitHub action, expose the benchmark text
// results as outputs. Useful if those are exposed as a GitHub comment then.
if (process.env.GITHUB_ACTION !== undefined) {
setOutput('comparisonResultsText', comparisonResults.summaryMarkdownText);
setOutput('workingStageResultsText', workingDirResults.summaryMarkdownText);
}
Log.info('\n\n\n');
Log.info(bold(green('Results!')));
Log.info(bold(yellow(`Comparison reference (${compareRef}) results:`)), '\n');
Log.info(comparisonResults.summaryConsoleText);
Log.info(bold(yellow(`Working stage (${currentRef}) results:`)), '\n');
Log.info(workingDirResults.summaryConsoleText);
}
function restoreWorkingStage(git: GitClient, initialRef: string) {
Log.log(green('Restoring working stage'));
git.run(['checkout', '-f', initialRef]);
// Stash apply could fail if there were not changes in the working stage.
git.runGraceful(['stash', 'apply']);
}