-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathextension-pack-picker.ts
258 lines (224 loc) · 7.08 KB
/
extension-pack-picker.ts
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
import { join } from "path";
import { outputFile, pathExists, readFile } from "fs-extra";
import { dump as dumpYaml, load as loadYaml } from "js-yaml";
import { CancellationToken, Uri } from "vscode";
import Ajv from "ajv";
import { CodeQLCliServer } from "../codeql-cli/cli";
import { getOnDiskWorkspaceFolders } from "../common/vscode/workspace-folders";
import {
ProgressCallback,
UserCancellationException,
} from "../common/vscode/progress";
import { DatabaseItem } from "../databases/local-databases";
import { getQlPackPath, QLPACK_FILENAMES } from "../common/ql";
import { getErrorMessage } from "../common/helpers-pure";
import { ExtensionPack } from "./shared/extension-pack";
import { NotificationLogger, showAndLogErrorMessage } from "../common/logging";
import { ModelConfig } from "../config";
import {
autoNameExtensionPack,
ExtensionPackName,
formatPackName,
} from "./extension-pack-name";
import { autoPickExtensionsDirectory } from "./extensions-workspace-folder";
import { ExtensionPackMetadata } from "./extension-pack-metadata";
import * as 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">,
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,
});
// Get the `codeQL.model.extensionsDirectory` setting for the language
const userExtensionsDirectory = modelConfig.getExtensionsDirectory(
databaseItem.language,
);
// If the setting is not set, automatically pick a suitable directory
const extensionsDirectory = userExtensionsDirectory
? Uri.file(userExtensionsDirectory)
: await autoPickExtensionsDirectory(logger);
if (!extensionsDirectory) {
return undefined;
}
// Generate the name of the extension pack
const packName = autoNameExtensionPack(
databaseItem.name,
databaseItem.language,
);
if (!packName) {
void showAndLogErrorMessage(
logger,
`Could not automatically name extension pack for database ${databaseItem.name}`,
);
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: unknown) {
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;
}
const packPath = join(extensionsDirectory.fsPath, packName.name);
if (await pathExists(packPath)) {
void showAndLogErrorMessage(
logger,
`Directory ${packPath} already exists for extension pack ${formatPackName(
packName,
)}`,
);
return undefined;
}
return writeExtensionPack(packPath, packName, databaseItem.language);
}
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 getQlPackPath(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,
};
}