-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathexport-results.ts
More file actions
391 lines (351 loc) · 10.8 KB
/
export-results.ts
File metadata and controls
391 lines (351 loc) · 10.8 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
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
import { join } from "path";
import { ensureDir, writeFile } from "fs-extra";
import {
CancellationToken,
commands,
Uri,
ViewColumn,
window,
workspace,
} from "vscode";
import {
ProgressCallback,
UserCancellationException,
withProgress,
} from "../commandRunner";
import { showInformationMessageWithAction } from "../helpers";
import { extLogger } from "../common";
import { QueryHistoryManager } from "../query-history/query-history-manager";
import { createGist } from "./gh-api/gh-api-client";
import {
generateVariantAnalysisMarkdown,
MarkdownFile,
RepositorySummary,
} from "./markdown-generation";
import { pluralize } from "../pure/word";
import { VariantAnalysisManager } from "./variant-analysis-manager";
import {
VariantAnalysis,
VariantAnalysisScannedRepository,
VariantAnalysisScannedRepositoryDownloadStatus,
VariantAnalysisScannedRepositoryResult,
} from "./shared/variant-analysis";
import {
filterAndSortRepositoriesWithResults,
RepositoriesFilterSortStateWithIds,
} from "../pure/variant-analysis-filter-sort";
import { Credentials } from "../common/authentication";
/**
* Exports the results of the currently-selected variant analysis.
*/
export async function exportSelectedVariantAnalysisResults(
variantAnalysisManager: VariantAnalysisManager,
queryHistoryManager: QueryHistoryManager,
): Promise<void> {
const queryHistoryItem = queryHistoryManager.getCurrentQueryHistoryItem();
if (!queryHistoryItem || queryHistoryItem.t !== "variant-analysis") {
throw new Error(
"No variant analysis results currently open. To open results, click an item in the query history view.",
);
}
await variantAnalysisManager.exportResults(
queryHistoryItem.variantAnalysis.id,
);
}
const MAX_VARIANT_ANALYSIS_EXPORT_PROGRESS_STEPS = 2;
/**
* Exports the results of the given or currently-selected variant analysis.
* The user is prompted to select the export format.
*/
export async function exportVariantAnalysisResults(
variantAnalysisManager: VariantAnalysisManager,
variantAnalysisId: number,
filterSort: RepositoriesFilterSortStateWithIds | undefined,
credentials: Credentials,
): Promise<void> {
await withProgress(
async (progress: ProgressCallback, token: CancellationToken) => {
const variantAnalysis = await variantAnalysisManager.getVariantAnalysis(
variantAnalysisId,
);
if (!variantAnalysis) {
void extLogger.log(
`Could not find variant analysis with id ${variantAnalysisId}`,
);
throw new Error(
"There was an error when trying to retrieve variant analysis information",
);
}
if (token.isCancellationRequested) {
throw new UserCancellationException("Cancelled");
}
const repoStates = await variantAnalysisManager.getRepoStates(
variantAnalysisId,
);
void extLogger.log(
`Exporting variant analysis results for variant analysis with id ${variantAnalysis.id}`,
);
progress({
maxStep: MAX_VARIANT_ANALYSIS_EXPORT_PROGRESS_STEPS,
step: 0,
message: "Determining export format",
});
const exportFormat = await determineExportFormat();
if (!exportFormat) {
return;
}
if (token.isCancellationRequested) {
throw new UserCancellationException("Cancelled");
}
const repositories = filterAndSortRepositoriesWithResults(
variantAnalysis.scannedRepos,
filterSort,
)?.filter(
(repo) =>
repo.resultCount &&
repoStates.find((r) => r.repositoryId === repo.repository.id)
?.downloadStatus ===
VariantAnalysisScannedRepositoryDownloadStatus.Succeeded,
);
async function* getAnalysesResults(): AsyncGenerator<
[
VariantAnalysisScannedRepository,
VariantAnalysisScannedRepositoryResult,
]
> {
if (!variantAnalysis) {
return;
}
if (!repositories) {
return;
}
for (const repo of repositories) {
const result = await variantAnalysisManager.loadResults(
variantAnalysis.id,
repo.repository.fullName,
{
skipCacheStore: true,
},
);
yield [repo, result];
}
}
const exportDirectory =
variantAnalysisManager.getVariantAnalysisStorageLocation(
variantAnalysis.id,
);
// The date will be formatted like the following: 20221115T123456Z. The time is in UTC.
const formattedDate = new Date()
.toISOString()
.replace(/[-:]/g, "")
.replace(/\.\d+Z$/, "Z");
const exportedResultsDirectory = join(
exportDirectory,
"exported-results",
`results_${formattedDate}`,
);
await exportVariantAnalysisAnalysisResults(
exportedResultsDirectory,
variantAnalysis,
getAnalysesResults(),
repositories?.length ?? 0,
exportFormat,
credentials,
progress,
token,
);
},
{
title: "Exporting variant analysis results",
cancellable: true,
},
);
}
export async function exportVariantAnalysisAnalysisResults(
exportedResultsPath: string,
variantAnalysis: VariantAnalysis,
analysesResults: AsyncIterable<
[VariantAnalysisScannedRepository, VariantAnalysisScannedRepositoryResult]
>,
expectedAnalysesResultsCount: number,
exportFormat: "gist" | "local",
credentials: Credentials,
progress: ProgressCallback,
token: CancellationToken,
) {
if (token.isCancellationRequested) {
throw new UserCancellationException("Cancelled");
}
progress({
maxStep: MAX_VARIANT_ANALYSIS_EXPORT_PROGRESS_STEPS,
step: 1,
message: "Generating Markdown files",
});
const { markdownFiles, summaries } = await generateVariantAnalysisMarkdown(
variantAnalysis,
analysesResults,
expectedAnalysesResultsCount,
exportFormat,
);
const description = buildVariantAnalysisGistDescription(
variantAnalysis,
summaries,
);
await exportResults(
exportedResultsPath,
description,
markdownFiles,
exportFormat,
credentials,
progress,
token,
);
}
/**
* Determines the format in which to export the results, from the given export options.
*/
async function determineExportFormat(): Promise<"gist" | "local" | undefined> {
const gistOption = {
label: "$(ports-open-browser-icon) Create Gist (GitHub)",
};
const localMarkdownOption = {
label: "$(markdown) Save as markdown",
};
const exportFormat = await window.showQuickPick(
[gistOption, localMarkdownOption],
{
placeHolder: "Select export format",
canPickMany: false,
ignoreFocusOut: true,
},
);
if (!exportFormat || !exportFormat.label) {
throw new UserCancellationException("No export format selected", true);
}
if (exportFormat === gistOption) {
return "gist";
}
if (exportFormat === localMarkdownOption) {
return "local";
}
return undefined;
}
export async function exportResults(
exportedResultsPath: string,
description: string,
markdownFiles: MarkdownFile[],
exportFormat: "gist" | "local",
credentials: Credentials,
progress?: ProgressCallback,
token?: CancellationToken,
) {
if (token?.isCancellationRequested) {
throw new UserCancellationException("Cancelled");
}
if (exportFormat === "gist") {
await exportToGist(
description,
markdownFiles,
credentials,
progress,
token,
);
} else if (exportFormat === "local") {
await exportToLocalMarkdown(
exportedResultsPath,
markdownFiles,
progress,
token,
);
}
}
export async function exportToGist(
description: string,
markdownFiles: MarkdownFile[],
credentials: Credentials,
progress?: ProgressCallback,
token?: CancellationToken,
) {
progress?.({
maxStep: MAX_VARIANT_ANALYSIS_EXPORT_PROGRESS_STEPS,
step: 2,
message: "Creating Gist",
});
if (token?.isCancellationRequested) {
throw new UserCancellationException("Cancelled");
}
// Convert markdownFiles to the appropriate format for uploading to gist
const gistFiles = markdownFiles.reduce((acc, cur) => {
acc[`${cur.fileName}.md`] = { content: cur.content.join("\n") };
return acc;
}, {} as { [key: string]: { content: string } });
const gistUrl = await createGist(credentials, description, gistFiles);
if (gistUrl) {
// This needs to use .then to ensure we aren't keeping the progress notification open. We shouldn't await the
// "Open gist" button click.
void showInformationMessageWithAction(
"Variant analysis results exported to gist.",
"Open gist",
).then((shouldOpenGist) => {
if (!shouldOpenGist) {
return;
}
return commands.executeCommand("vscode.open", Uri.parse(gistUrl));
});
}
}
/**
* Builds Gist description
* Ex: Empty Block (Go) x results (y repositories)
*/
const buildVariantAnalysisGistDescription = (
variantAnalysis: VariantAnalysis,
summaries: RepositorySummary[],
) => {
const resultCount = summaries.reduce(
(acc, summary) => acc + (summary.resultCount ?? 0),
0,
);
const resultLabel = pluralize(resultCount, "result", "results");
const repositoryLabel = summaries.length
? `(${pluralize(summaries.length, "repository", "repositories")})`
: "";
return `${variantAnalysis.query.name} (${variantAnalysis.query.language}) ${resultLabel} ${repositoryLabel}`;
};
/**
* Saves the results of an exported query to local markdown files.
*/
async function exportToLocalMarkdown(
exportedResultsPath: string,
markdownFiles: MarkdownFile[],
progress?: ProgressCallback,
token?: CancellationToken,
) {
if (token?.isCancellationRequested) {
throw new UserCancellationException("Cancelled");
}
progress?.({
maxStep: MAX_VARIANT_ANALYSIS_EXPORT_PROGRESS_STEPS,
step: 2,
message: "Creating local Markdown files",
});
await ensureDir(exportedResultsPath);
for (const markdownFile of markdownFiles) {
const filePath = join(exportedResultsPath, `${markdownFile.fileName}.md`);
await writeFile(filePath, markdownFile.content.join("\n"), "utf8");
}
// This needs to use .then to ensure we aren't keeping the progress notification open. We shouldn't await the
// "Open exported results" button click.
void showInformationMessageWithAction(
`Variant analysis results exported to \"${exportedResultsPath}\".`,
"Open exported results",
).then(async (shouldOpenExportedResults) => {
if (!shouldOpenExportedResults) {
return;
}
const summaryFilePath = join(exportedResultsPath, "_summary.md");
const summaryFile = await workspace.openTextDocument(summaryFilePath);
await window.showTextDocument(summaryFile, ViewColumn.One);
await commands.executeCommand("revealFileInOS", Uri.file(summaryFilePath));
});
}