-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathextension-pack-picker.ts
More file actions
284 lines (247 loc) · 7.91 KB
/
extension-pack-picker.ts
File metadata and controls
284 lines (247 loc) · 7.91 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
import { join } from "path";
import { outputFile, pathExists, readFile } from "fs-extra";
import { dump as dumpYaml, load as loadYaml } from "js-yaml";
import type { CancellationToken } from "vscode";
import Ajv from "ajv";
import type { CodeQLCliServer } from "../codeql-cli/cli";
import { getOnDiskWorkspaceFolders } from "../common/vscode/workspace-folders";
import type { ProgressCallback } from "../common/vscode/progress";
import { UserCancellationException } from "../common/vscode/progress";
import type { DatabaseItem } from "../databases/local-databases";
import { getQlPackFilePath, QLPACK_FILENAMES } from "../common/ql";
import { getErrorMessage } from "../common/helpers-pure";
import type { ExtensionPack } from "./shared/extension-pack";
import type { NotificationLogger } from "../common/logging";
import { showAndLogErrorMessage } from "../common/logging";
import type { ModelConfig, ModelConfigPackVariables } from "../config";
import type { ExtensionPackName } from "./extension-pack-name";
import {
validatePackName,
sanitizePackName,
formatPackName,
} from "./extension-pack-name";
import {
ensurePackLocationIsInWorkspaceFolder,
packLocationToAbsolute,
} from "./extensions-workspace-folder";
import type { ExtensionPackMetadata } from "./extension-pack-metadata";
import extensionPackMetadataSchemaJson from "./extension-pack-metadata.schema.json";
const ajv = new Ajv({ allErrors: true });
const extensionPackValidate = ajv.compile(extensionPackMetadataSchemaJson);
export async function pickExtensionPack(
cliServer: Pick<CodeQLCliServer, "resolveQlpacks">,
databaseItem: Pick<DatabaseItem, "name" | "language" | "origin">,
modelConfig: ModelConfig,
logger: NotificationLogger,
progress: ProgressCallback,
token: CancellationToken,
maxStep: number,
): Promise<ExtensionPack | undefined> {
progress({
message: "Resolving extension packs...",
step: 1,
maxStep,
});
// Get all existing extension packs in the workspace
const additionalPacks = getOnDiskWorkspaceFolders();
// the CLI doesn't check packs in the .github folder, so we need to add it manually
if (additionalPacks.length === 1) {
additionalPacks.push(`${additionalPacks[0]}/.github`);
}
const extensionPacksInfo = await cliServer.resolveQlpacks(
additionalPacks,
true,
);
if (token.isCancellationRequested) {
throw new UserCancellationException(
"Open Model editor action cancelled.",
true,
);
}
progress({
message: "Creating extension pack...",
step: 2,
maxStep,
});
// The default is .github/codeql/extensions/${name}-${language}
const packPath = await packLocationToAbsolute(
modelConfig.getPackLocation(
databaseItem.language,
getModelConfigPackVariables(databaseItem),
),
logger,
);
if (!packPath) {
return undefined;
}
await ensurePackLocationIsInWorkspaceFolder(packPath, modelConfig, logger);
const userPackName = modelConfig.getPackName(
databaseItem.language,
getModelConfigPackVariables(databaseItem),
);
// Generate the name of the extension pack
const packName = sanitizePackName(userPackName);
// Validate that the name isn't too long etc.
const packNameError = validatePackName(formatPackName(packName));
if (packNameError) {
void showAndLogErrorMessage(
logger,
`Invalid model pack name '${formatPackName(packName)}' for database ${databaseItem.name}: ${packNameError}`,
);
return undefined;
}
// Find any existing locations of this extension pack
const existingExtensionPackPaths =
extensionPacksInfo[formatPackName(packName)];
// If there is already an extension pack with this name, use it if it is valid
if (existingExtensionPackPaths?.length === 1) {
let extensionPack: ExtensionPack;
try {
extensionPack = await readExtensionPack(
existingExtensionPackPaths[0],
databaseItem.language,
);
} catch (e) {
void showAndLogErrorMessage(
logger,
`Could not read extension pack ${formatPackName(packName)}`,
{
fullMessage: `Could not read extension pack ${formatPackName(
packName,
)} at ${existingExtensionPackPaths[0]}: ${getErrorMessage(e)}`,
},
);
return undefined;
}
return extensionPack;
}
// If there is already an existing extension pack with this name, but it resolves
// to multiple paths, then we can't use it
if (existingExtensionPackPaths?.length > 1) {
void showAndLogErrorMessage(
logger,
`Extension pack ${formatPackName(packName)} resolves to multiple paths`,
{
fullMessage: `Extension pack ${formatPackName(
packName,
)} resolves to multiple paths: ${existingExtensionPackPaths.join(
", ",
)}`,
},
);
return undefined;
}
if (await pathExists(packPath)) {
void showAndLogErrorMessage(
logger,
`Directory ${packPath} already exists for extension pack ${formatPackName(
packName,
)}, but wasn't returned by codeql resolve qlpacks --kind extension --no-recursive`,
);
return undefined;
}
return writeExtensionPack(packPath, packName, databaseItem.language);
}
function getModelConfigPackVariables(
databaseItem: Pick<DatabaseItem, "name" | "language" | "origin">,
): ModelConfigPackVariables {
const database = databaseItem.name;
const language = databaseItem.language;
let name = databaseItem.name;
let owner = "";
if (databaseItem.origin?.type === "github") {
[owner, name] = databaseItem.origin.repository.split("/");
}
return {
database,
language,
name,
owner,
};
}
async function writeExtensionPack(
packPath: string,
packName: ExtensionPackName,
language: string,
): Promise<ExtensionPack> {
const packYamlPath = join(packPath, "codeql-pack.yml");
const extensionPack: ExtensionPack = {
path: packPath,
yamlPath: packYamlPath,
name: formatPackName(packName),
version: "0.0.0",
language,
extensionTargets: {
[`codeql/${language}-all`]: "*",
},
dataExtensions: ["models/**/*.yml"],
};
await outputFile(
packYamlPath,
dumpYaml({
name: extensionPack.name,
version: extensionPack.version,
library: true,
extensionTargets: extensionPack.extensionTargets,
dataExtensions: extensionPack.dataExtensions,
}),
);
return extensionPack;
}
function validateExtensionPack(
extensionPack: unknown,
): extensionPack is ExtensionPackMetadata {
extensionPackValidate(extensionPack);
if (extensionPackValidate.errors) {
throw new Error(
`Invalid extension pack YAML: ${extensionPackValidate.errors
.map((error) => `${error.instancePath} ${error.message}`)
.join(", ")}`,
);
}
return true;
}
async function readExtensionPack(
path: string,
language: string,
): Promise<ExtensionPack> {
const qlpackPath = await getQlPackFilePath(path);
if (!qlpackPath) {
throw new Error(
`Could not find any of ${QLPACK_FILENAMES.join(", ")} in ${path}`,
);
}
const qlpack = await loadYaml(await readFile(qlpackPath, "utf8"), {
filename: qlpackPath,
});
if (typeof qlpack !== "object" || qlpack === null) {
throw new Error(`Could not parse ${qlpackPath}`);
}
if (!validateExtensionPack(qlpack)) {
throw new Error(`Could not validate ${qlpackPath}`);
}
const dataExtensionValue = qlpack.dataExtensions;
if (
!(
Array.isArray(dataExtensionValue) ||
typeof dataExtensionValue === "string"
)
) {
throw new Error(
`Expected 'dataExtensions' to be a string or an array in ${qlpackPath}`,
);
}
// The YAML allows either a string or an array of strings
const dataExtensions = Array.isArray(dataExtensionValue)
? dataExtensionValue
: [dataExtensionValue];
return {
path,
yamlPath: qlpackPath,
name: qlpack.name,
version: qlpack.version,
language,
extensionTargets: qlpack.extensionTargets,
dataExtensions,
};
}