-
Notifications
You must be signed in to change notification settings - Fork 585
Expand file tree
/
Copy pathcodeAnalysisWebViewController.ts
More file actions
340 lines (320 loc) · 14.1 KB
/
codeAnalysisWebViewController.ts
File metadata and controls
340 lines (320 loc) · 14.1 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from "vscode";
import * as path from "path";
import { ReactWebviewPanelController } from "../controllers/reactWebviewPanelController";
import VscodeWrapper from "../controllers/vscodeWrapper";
import {
CodeAnalysisState,
CodeAnalysisReducers,
SqlCodeAnalysisRule,
CodeAnalysisRuleSeverity,
} from "../sharedInterfaces/codeAnalysis";
import * as constants from "../constants/constants";
import { CodeAnalysis as Loc } from "../constants/locConstants";
import { sendActionEvent, sendErrorEvent } from "../telemetry/telemetry";
import { TelemetryViews, TelemetryActions } from "../sharedInterfaces/telemetry";
import { getErrorMessage, uuid } from "../utils/utils";
import { DacFxService } from "../services/dacFxService";
import { SqlProjectsService } from "../services/sqlProjectsService";
import { DialogMessageSpec } from "../sharedInterfaces/dialogMessage";
import { parseSqlprojRuleOverrides } from "../publishProject/projectUtils";
/**
* Controller for the Code Analysis dialog webview
*/
export class CodeAnalysisWebViewController extends ReactWebviewPanelController<
CodeAnalysisState,
CodeAnalysisReducers
> {
private readonly _operationId: string;
constructor(
context: vscode.ExtensionContext,
vscodeWrapper: VscodeWrapper,
projectFilePath: string,
private dacFxService: DacFxService,
private sqlProjectsService: SqlProjectsService,
) {
const projectName = path.basename(projectFilePath, path.extname(projectFilePath));
super(
context,
vscodeWrapper,
constants.codeAnalysisViewId,
constants.codeAnalysisViewId,
{
projectFilePath,
projectName,
isLoading: true,
rules: [],
dacfxStaticRules: [],
enableCodeAnalysisOnBuild: false,
} as CodeAnalysisState,
{
title: Loc.Title,
viewColumn: vscode.ViewColumn.Active,
iconPath: {
dark: vscode.Uri.joinPath(
context.extensionUri,
"media",
"codeAnalysis_dark.svg",
),
light: vscode.Uri.joinPath(
context.extensionUri,
"media",
"codeAnalysis_light.svg",
),
},
},
);
this._operationId = uuid();
// Send telemetry for dialog opened
sendActionEvent(TelemetryViews.SqlProjects, TelemetryActions.CodeAnalysisDialogOpened, {
operationId: this._operationId,
});
this.registerRpcHandlers();
// Load rules on initialization
void this.loadRules();
}
/**
* Sends a telemetry error event scoped to this dialog's operationId.
*/
private sendError(action: TelemetryActions, error: Error): void {
sendErrorEvent(TelemetryViews.SqlProjects, action, error, false, undefined, undefined, {
operationId: this._operationId,
});
}
private normalizeSeverity(severity: string | undefined): string {
switch (severity?.toLowerCase()) {
case "error":
return CodeAnalysisRuleSeverity.Error;
case "none":
return CodeAnalysisRuleSeverity.Disabled;
default:
return CodeAnalysisRuleSeverity.Warning;
}
}
/**
* Register RPC handlers for webview actions
*/
private registerRpcHandlers(): void {
// Close dialog
this.registerReducer("close", async (state) => {
this.panel.dispose();
return state;
});
// Clear message bar
this.registerReducer("closeMessage", async (state) => {
state.message = undefined;
return state;
});
// Save rule overrides to the .sqlproj
this.registerReducer("saveRules", async (state, payload) => {
try {
const overrides = payload.rules.map((r) => ({
ruleId: r.ruleId,
severity: r.severity,
}));
const result = await this.sqlProjectsService.updateCodeAnalysisRules({
projectUri: state.projectFilePath,
rules: overrides,
runSqlCodeAnalysis: payload.enableCodeAnalysisOnBuild,
});
if (!result.success) {
const errorMsg = result.errorMessage || Loc.failedToSaveRules;
this.logger.error(`Failed to save code analysis rules: ${errorMsg}`);
this.sendError(
TelemetryActions.CodeAnalysisRulesSaveError,
new Error(errorMsg),
);
state.message = { message: errorMsg, intent: "error" } as DialogMessageSpec;
return state;
}
const additionalProps: Record<string, string> = {
operationId: this._operationId,
ruleCount: overrides.length.toString(),
};
// Only include rule IDs when code analysis is enabled on build —
// Sent as a semicolon-separated string and query the enabled rules
if (payload.enableCodeAnalysisOnBuild) {
additionalProps.enabledRuleIds = payload.rules
.filter((r) => r.severity !== CodeAnalysisRuleSeverity.Disabled)
.map((r) => r.shortRuleId)
.join(";");
}
sendActionEvent(
TelemetryViews.SqlProjects,
TelemetryActions.CodeAnalysisRulesSaved,
additionalProps,
);
if (payload.enableCodeAnalysisOnBuild !== state.enableCodeAnalysisOnBuild) {
sendActionEvent(
TelemetryViews.SqlProjects,
payload.enableCodeAnalysisOnBuild
? TelemetryActions.CodeAnalysisEnabledOnBuild
: TelemetryActions.CodeAnalysisDisabledOnBuild,
{ operationId: this._operationId },
);
}
if (payload.closeAfterSave) {
this.vscodeWrapper.logToOutputChannel(Loc.rulesSaved);
this.panel.dispose();
}
// Update the baseline rules so the component's useEffect resets isDirty
state.rules = payload.rules;
state.enableCodeAnalysisOnBuild = payload.enableCodeAnalysisOnBuild;
state.message = payload.closeAfterSave
? undefined
: ({ message: Loc.rulesSaved, intent: "success" } as DialogMessageSpec);
return state;
} catch (error) {
this.logger.error(`Failed to save code analysis rules: ${getErrorMessage(error)}`);
this.sendError(
TelemetryActions.CodeAnalysisRulesSaveError,
error instanceof Error ? error : new Error(getErrorMessage(error)),
);
state.message = {
message: getErrorMessage(error),
intent: "error",
} as DialogMessageSpec;
return state;
}
});
}
/**
* Reads saved overrides from the .sqlproj and merges them into the provided DacFx rules.
* Returns the resolved rules and an optional warning message.
* Never throws — on failure falls back to dacfxStaticRules so the dialog remains usable.
*/
private async applyProjectOverrides(dacfxStaticRules: SqlCodeAnalysisRule[]): Promise<{
rules: SqlCodeAnalysisRule[];
message?: DialogMessageSpec;
enableCodeAnalysisOnBuild: boolean;
}> {
try {
const projectProps = await this.sqlProjectsService.getProjectProperties(
this.state.projectFilePath,
);
if (projectProps?.success && projectProps.sqlCodeAnalysisRules) {
const overrides = parseSqlprojRuleOverrides(projectProps.sqlCodeAnalysisRules);
return {
rules: dacfxStaticRules.map((rule) => {
const overrideSeverity = overrides.get(rule.shortRuleId);
if (overrideSeverity === undefined) {
return rule;
}
return {
...rule,
severity: overrideSeverity,
enabled: overrideSeverity !== CodeAnalysisRuleSeverity.Disabled,
};
}),
enableCodeAnalysisOnBuild: projectProps.runSqlCodeAnalysis ?? false,
};
} else if (projectProps?.success === false) {
// Retrieval failed — fall back to DacFx defaults and surface a warning
// so the user understands why their saved overrides weren't applied.
const detail = projectProps.errorMessage;
this.sendError(
TelemetryActions.CodeAnalysisRulesLoadError,
new Error(detail ?? Loc.failedToLoadOverrides),
);
return {
rules: dacfxStaticRules,
enableCodeAnalysisOnBuild: false,
message: {
message: detail
? `${Loc.failedToLoadOverrides}: ${detail}`
: Loc.failedToLoadOverrides,
intent: "warning",
} as DialogMessageSpec,
};
} else {
// success: true but no sqlCodeAnalysisRules — no overrides saved, use DacFx defaults.
return {
rules: dacfxStaticRules,
enableCodeAnalysisOnBuild: projectProps?.runSqlCodeAnalysis ?? false,
};
}
} catch (propsError) {
// Fall back to DacFx defaults and show a non-blocking warning so the
// dialog is still usable even if the .sqlproj can't be read.
this.sendError(
TelemetryActions.CodeAnalysisRulesLoadError,
propsError instanceof Error ? propsError : new Error(getErrorMessage(propsError)),
);
return {
rules: dacfxStaticRules,
enableCodeAnalysisOnBuild: false,
message: {
message: `${Loc.failedToLoadOverrides}: ${getErrorMessage(propsError)}`,
intent: "warning",
} as DialogMessageSpec,
};
}
}
/**
* Fetches rules from the DacFx service and maps them to the UI view model.
* Throws on service failure or mapping errors — caught by loadRules.
*/
private async fetchRulesFromDacFx(): Promise<SqlCodeAnalysisRule[]> {
const rulesResult = await this.dacFxService.getCodeAnalysisRules();
if (!rulesResult.success) {
const detail = rulesResult.errorMessage;
throw new Error(detail ? `${Loc.failedToLoadRules}: ${detail}` : Loc.failedToLoadRules);
}
return (rulesResult.rules ?? []).map((rule) => {
const severity = this.normalizeSeverity(rule.severity);
return {
ruleId: rule.ruleId,
shortRuleId: rule.shortRuleId,
displayName: rule.displayName,
severity,
enabled: severity !== CodeAnalysisRuleSeverity.Disabled,
category: rule.category,
description: rule.description,
ruleScope: rule.ruleScope,
};
});
}
/**
* Load code analysis rules from the DacFx service
*/
private async loadRules(): Promise<void> {
try {
this.state.isLoading = true;
this.state.message = undefined;
this.updateState();
// Get the static code analysis rules from dacfx
const dacfxStaticRules = await this.fetchRulesFromDacFx();
// Load saved overrides from the .sqlproj and apply them.
// Isolated in its own method so a failure here doesn't discard the DacFx rules.
const overrideResult = await this.applyProjectOverrides(dacfxStaticRules);
this.state.rules = overrideResult.rules;
this.state.dacfxStaticRules = dacfxStaticRules;
this.state.enableCodeAnalysisOnBuild = overrideResult.enableCodeAnalysisOnBuild;
this.state.message = overrideResult.message;
this.state.isLoading = false;
this.updateState();
sendActionEvent(TelemetryViews.SqlProjects, TelemetryActions.CodeAnalysisRulesLoaded, {
operationId: this._operationId,
ruleCount: dacfxStaticRules.length.toString(),
categoryCount: new Set(
dacfxStaticRules.filter((rule) => rule.category).map((rule) => rule.category),
).size.toString(),
});
} catch (error) {
this.state.isLoading = false;
this.logger.error(`Failed to load code analysis rules: ${getErrorMessage(error)}`);
this.state.message = {
message: getErrorMessage(error),
intent: "error",
} as DialogMessageSpec;
this.updateState();
this.sendError(
TelemetryActions.CodeAnalysisRulesLoadError,
error instanceof Error ? error : new Error(getErrorMessage(error)),
);
}
}
}