-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathupload-sarif-action.ts
More file actions
228 lines (204 loc) · 6.59 KB
/
upload-sarif-action.ts
File metadata and controls
228 lines (204 loc) · 6.59 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
import * as core from "@actions/core";
import * as actionsUtil from "./actions-util";
import { getActionVersion, getTemporaryDirectory } from "./actions-util";
import * as analyses from "./analyses";
import { getGitHubVersion } from "./api-client";
import { CodeQL, getCodeQL } from "./codeql";
import { Config, getConfig } from "./config-utils";
import { FeatureEnablement, initFeatures } from "./feature-flags";
import { Logger, getActionsLogger } from "./logging";
import { getRepositoryNwo } from "./repository";
import {
createStatusReportBase,
sendStatusReport,
sendUnhandledErrorStatusReport,
StatusReportBase,
getActionsStatus,
ActionName,
isThirdPartyAnalysis,
} from "./status-report";
import * as upload_lib from "./upload-lib";
import { postProcessAndUploadSarif } from "./upload-sarif";
import {
ConfigurationError,
GitHubVersion,
checkActionVersion,
checkDiskUsage,
getErrorMessage,
initializeEnvironment,
shouldSkipSarifUpload,
wrapError,
} from "./util";
interface UploadSarifStatusReport
extends StatusReportBase,
upload_lib.UploadStatusReport {}
async function sendSuccessStatusReport(
startedAt: Date,
uploadStats: upload_lib.UploadStatusReport,
logger: Logger,
) {
const statusReportBase = await createStatusReportBase(
ActionName.UploadSarif,
"success",
startedAt,
undefined,
await checkDiskUsage(logger),
logger,
);
if (statusReportBase !== undefined) {
const statusReport: UploadSarifStatusReport = {
...statusReportBase,
...uploadStats,
};
await sendStatusReport(statusReport);
}
}
/** The cached `CodeQL` instance, if any. */
let codeql: CodeQL | undefined;
/** Get or initialise a `CodeQL` instance for use by the `upload-sarif` action. */
async function getOrInitCodeQL(
logger: Logger,
gitHubVersion: GitHubVersion,
features: FeatureEnablement,
config: Config | undefined,
): Promise<CodeQL> {
// Return the cached instance, if we have one.
if (codeql !== undefined) return codeql;
// If we have been able to load a `Config` from an earlier CodeQL Action step in the job,
// then use the CodeQL executable that we have used previously. Otherwise, initialise the
// CLI specifically for `upload-sarif`. Either way, we cache the instance.
if (config !== undefined) {
codeql = await getCodeQL(config.codeQLCmd);
} else {
codeql = await upload_lib.minimalInitCodeQL(
logger,
gitHubVersion,
features,
);
}
return codeql;
}
async function run(startedAt: Date) {
// To capture errors appropriately, keep as much code within the try-catch as
// possible, and only use safe functions outside.
const logger = getActionsLogger();
try {
initializeEnvironment(getActionVersion());
const gitHubVersion = await getGitHubVersion();
checkActionVersion(getActionVersion(), gitHubVersion);
// Make inputs accessible in the `post` step.
actionsUtil.persistInputs();
const repositoryNwo = getRepositoryNwo();
const features = initFeatures(
gitHubVersion,
repositoryNwo,
getTemporaryDirectory(),
logger,
);
const startingStatusReportBase = await createStatusReportBase(
ActionName.UploadSarif,
"starting",
startedAt,
undefined,
await checkDiskUsage(logger),
logger,
);
if (startingStatusReportBase !== undefined) {
await sendStatusReport(startingStatusReportBase);
}
// `sarifPath` can either be a path to a single file, or a path to a directory.
const sarifPath = actionsUtil.getRequiredInput("sarif_file");
const checkoutPath = actionsUtil.getRequiredInput("checkout_path");
const category = actionsUtil.getOptionalInput("category");
// Determine the temporary directory to use. If we are able to read a `Config` from a previous CodeQL Action
// step in the job, then use the temporary directory configured there. Otherwise, use our default.
let tempDir: string = actionsUtil.getTemporaryDirectory();
const config = await getConfig(tempDir, logger);
if (config !== undefined) {
tempDir = config.tempDir;
}
const uploadResults = await postProcessAndUploadSarif(
logger,
tempDir,
features,
() => getOrInitCodeQL(logger, gitHubVersion, features, config),
"always",
checkoutPath,
sarifPath,
category,
);
// Fail if we didn't upload anything.
if (Object.keys(uploadResults).length === 0) {
throw new ConfigurationError(
`No SARIF files found to upload in "${sarifPath}".`,
);
}
const codeScanningResult =
uploadResults[analyses.AnalysisKind.CodeScanning];
if (codeScanningResult !== undefined) {
core.setOutput("sarif-id", codeScanningResult.sarifID);
}
core.setOutput("sarif-ids", JSON.stringify(uploadResults));
// We don't upload results in test mode, so don't wait for processing
if (shouldSkipSarifUpload()) {
core.debug(
"SARIF upload disabled by an environment variable. Waiting for processing is disabled.",
);
} else if (actionsUtil.getRequiredInput("wait-for-processing") === "true") {
if (codeScanningResult !== undefined) {
await upload_lib.waitForProcessing(
getRepositoryNwo(),
codeScanningResult.sarifID,
logger,
);
}
// The code quality service does not currently have an endpoint to wait for SARIF processing,
// so we can't wait for that here.
}
await sendSuccessStatusReport(
startedAt,
codeScanningResult?.statusReport || {},
logger,
);
} catch (unwrappedError) {
const error =
isThirdPartyAnalysis(ActionName.UploadSarif) &&
unwrappedError instanceof upload_lib.InvalidSarifUploadError
? new ConfigurationError(unwrappedError.message)
: wrapError(unwrappedError);
const message = error.message;
core.setFailed(message);
const errorStatusReportBase = await createStatusReportBase(
ActionName.UploadSarif,
getActionsStatus(error),
startedAt,
undefined,
await checkDiskUsage(logger),
logger,
message,
error.stack,
);
if (errorStatusReportBase !== undefined) {
await sendStatusReport(errorStatusReportBase);
}
return;
}
}
async function runWrapper() {
const startedAt = new Date();
const logger = getActionsLogger();
try {
await run(startedAt);
} catch (error) {
core.setFailed(
`codeql/upload-sarif action failed: ${getErrorMessage(error)}`,
);
await sendUnhandledErrorStatusReport(
ActionName.UploadSarif,
startedAt,
error,
logger,
);
}
}
void runWrapper();