-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.ts
More file actions
501 lines (482 loc) · 20.4 KB
/
extension.ts
File metadata and controls
501 lines (482 loc) · 20.4 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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// Entry point for the Pipeline-Check VS Code extension.
//
// All this client does is spawn `python -m pipeline_check.lsp` over stdio
// and bridge it to VS Code's LanguageClient. Every rule decision, every
// hover prose string, and every diagnostic comes from the Python server
// — the TypeScript side stays a thin transport adapter so the editor
// findings match `pipeline_check --output json` byte-for-byte (modulo
// position translation).
//
// The server itself lives upstream in `dmartinochoa/pipeline-check`
// under `pipeline_check/lsp/`; install via `pip install
// "pipeline-check[lsp]"`.
import * as vscode from "vscode";
import {
LanguageClient,
LanguageClientOptions,
ServerOptions,
State,
TransportKind,
} from "vscode-languageclient/node";
import { FindingsCodeLensProvider } from "./codeLens";
import { FindingsTreeProvider, GroupMode } from "./findingsView";
import {
copyInstallCommandToClipboard,
installInTerminal,
} from "./install";
import * as clientLog from "./log";
import { startWithTimeout } from "./lspStart";
import { setLspReady } from "./lspState";
import { transformDiagnostics } from "./middleware";
import { goToFinding } from "./navigate";
import {
providerForPath,
TRIGGER_DOCUMENT_SELECTOR,
} from "./providers";
import { createScanOnSaveHandler } from "./scanOnSave";
import { registerStatusBar } from "./statusBar";
import { scanWorkspace } from "./workspaceScan";
import { showWhatsNewIfUpgraded } from "./whatsNew";
// Group-mode options offered by the Findings panel's "Change
// Grouping" button. Labels are user-facing; descriptions are the
// muted secondary text in the Quick Pick row. The order matches the
// title-bar history of the radio buttons that this Quick Pick
// replaces, so muscle memory carries over.
const GROUPING_PICKS: readonly {
readonly mode: GroupMode;
readonly label: string;
readonly description: string;
}[] = [
{
mode: "severity",
label: "Severity",
description: "Critical, High, Medium, Low, Info",
},
{
mode: "file",
label: "File",
description: "One bucket per file, ordered by path",
},
{
mode: "rule",
label: "Rule",
description: "One bucket per check ID (GHA-001, etc.)",
},
];
async function changeGrouping(
provider: FindingsTreeProvider,
): Promise<void> {
const current = provider.getGroupMode();
type Pick = vscode.QuickPickItem & { mode: GroupMode };
const items: Pick[] = GROUPING_PICKS.map((p) => ({
// ``$(check)`` prefix marks the active mode. The Quick Pick has
// no native "selected option" affordance for show-only-callback
// pickers, so we draw the check ourselves — same pattern VS Code
// uses for its "Change Language Mode" picker.
label: p.mode === current ? `$(check) ${p.label}` : ` ${p.label}`,
description: p.description,
mode: p.mode,
}));
const choice = await vscode.window.showQuickPick(items, {
title: "Group findings by",
placeHolder: "Choose how the panel should bucket findings",
});
if (choice) {
provider.setGroupMode(choice.mode);
}
}
const LANGUAGE_ID = "pipelineCheck";
const LANGUAGE_NAME = "Pipeline-Check";
const OUTPUT_CHANNEL = "Pipeline-Check";
// `setStatusBarMessage` TTL for transient confirmations (clipboard
// writes, etc.). Two seconds is long enough to be readable and short
// enough that a stream of copies doesn't pile up.
const CONFIRM_TTL_MS = 2000;
// Structural shape of a Findings-tree leaf node, used by the
// context-menu commands. The real LeafNode lives in findingsView.ts;
// duplicating just the fields the commands read keeps extension.ts
// independent of the tree's internal type definitions.
type LeafLike = {
readonly finding?: {
readonly ruleId?: string;
readonly docsUrl?: string;
readonly uri?: vscode.Uri;
readonly diagnostic?: { readonly range?: vscode.Range };
};
};
let client: LanguageClient | undefined;
// Disposable for the onDidChangeState listener registered against the
// current `client`. We hang on to it so `stopClient` can dispose it
// before the next `startClient` builds a fresh listener — otherwise a
// crash on the previous client would still fire into our handler and
// flip `lspReady` against the live client.
let clientStateChangeDisposable: vscode.Disposable | undefined;
// Hard ceiling on how long `client.start()` is allowed to run before
// we treat the LSP as broken. Without this, a `serverArgs: []`
// (configured Python interpreter drops into the REPL waiting on
// stdin), or any Python interpreter that hangs during module import,
// leaves `activate()` pending forever — the install-prompt welcome
// panel stays up and the user has no way to know the difference
// between "LSP is slow" and "LSP will never come up". 30 s is well
// above the cold-start budget on Windows (where pyc compilation can
// add several seconds the first time pipeline_check.lsp imports).
const START_TIMEOUT_MS = 30_000;
function buildClient(): LanguageClient {
const config = vscode.workspace.getConfiguration("pipelineCheck");
const command = config.get<string>("serverCommand", "python");
const args = config.get<string[]>("serverArgs", ["-m", "pipeline_check.lsp"]);
const serverOptions: ServerOptions = {
run: { command, args, transport: TransportKind.stdio },
debug: { command, args, transport: TransportKind.stdio },
};
// Match by path glob instead of language ID. Language-based selectors
// would let unrelated YAML files (mkdocs.yml, Helm `values.yaml`,
// package.json, etc.) reach the LSP and rely on the server's
// content-and-path filter to bounce them. Path-based selectors keep
// that filter as a backstop but hand the server only candidate files
// in the first place — smaller cross-section, no dependency on whether
// the user has the official GitHub Actions extension installed
// (which would otherwise hijack the `github-actions-workflow`
// language ID for `.github/workflows/*.yml`). The pattern list itself
// lives in providers.ts so the documentSelector, activationEvents,
// and the workspace-scan command can't drift apart.
const clientOptions: LanguageClientOptions = {
documentSelector: [...TRIGGER_DOCUMENT_SELECTOR],
synchronize: {
configurationSection: "pipelineCheck",
},
outputChannelName: OUTPUT_CHANNEL,
middleware: {
// Two-stage filter (composition lives in middleware.ts): drop
// every diagnostic for a URI whose provider the user has
// silenced via `disabledProviders`, otherwise drop those below
// the configured `severityThreshold`. Re-reads the config on
// each publish so a settings change takes effect on the next
// scan without a server restart.
handleDiagnostics: (uri, diagnostics, next) => {
const config = vscode.workspace.getConfiguration("pipelineCheck");
next(
uri,
transformDiagnostics(uri, diagnostics, {
disabledProviders: config.get<string[]>("disabledProviders", []),
severityThreshold: config.get<string>("severityThreshold", "low"),
}),
);
},
},
};
return new LanguageClient(
LANGUAGE_ID,
LANGUAGE_NAME,
serverOptions,
clientOptions,
);
}
async function startClient(): Promise<void> {
if (client) {
// Bail without restart-loops if someone double-fires the activation
// event. The restart command goes through stopClient first, so
// this guard is the genuinely-duplicate case.
return;
}
client = buildClient();
// The output channel is created by LanguageClient as a side effect of
// construction, so it is always present here. Capture it before we
// drop the broken client on failure (the "Open server log" action
// below still needs to focus it to surface the server's traceback).
const outputChannel: vscode.OutputChannel = client.outputChannel;
// Point the client-side logger at the same channel the LSP server
// writes to, so [client] and [server] lines interleave with shared
// timestamps — much easier to read when triaging a bug report.
clientLog.setLogChannel(outputChannel);
try {
clientLog.info("language server: starting");
await startWithTimeout(client, START_TIMEOUT_MS);
clientLog.info("language server: started");
setLspReady(true);
// Watch the post-start lifecycle so a mid-session crash (server
// process exits, LanguageClient's auto-restart exhausts) flips the
// welcome panel back to the install-prompt state. Without this,
// `lspReady` only ever transitions back to false on an explicit
// stop/restart — a crashed server would leave the panel saying
// "Scan workspace" even though clicking it produces no findings.
// The listener lives in module scope so stopClient can tear it
// down before a restart builds a new one against the new client.
clientStateChangeDisposable = client.onDidChangeState((event) => {
if (event.newState === State.Stopped) {
clientLog.warn("language server: state transitioned to stopped");
setLspReady(false);
} else if (event.newState === State.Running) {
setLspReady(true);
}
});
} catch (err) {
// The most common cause is `python -m pipeline_check.lsp` failing:
// either Python is not on PATH or the [lsp] extra is not installed.
// Surface the install command and the server log as two distinct
// actions so the user can act on either without re-reading the
// notification body. The notification chrome already shows the
// extension name, so the message body doesn't repeat it.
//
// The notification is fire-and-forget: `showErrorMessage` resolves
// only when the user clicks a button or closes the toast, and
// `activate()` already awaits this path. Awaiting here would block
// activation indefinitely whenever nobody is around to click
// (CI, automation, headless extension host). Detaching keeps the
// user's buttons live while letting startClient return.
const message = err instanceof Error ? err.message : String(err);
clientLog.error(`language server: failed to start — ${message}`);
void vscode.window
.showErrorMessage(
`Language server failed to start (${message}).`,
"Install in terminal",
"Open server log",
)
.then((choice) => {
if (choice === "Install in terminal") {
installInTerminal();
} else if (choice === "Open server log") {
outputChannel.show();
}
});
// Drop the broken client so a subsequent restart starts fresh
// rather than trying to recover from a half-initialised state.
client = undefined;
setLspReady(false);
}
}
// Hard ceiling on how long deactivate / restart waits for the LSP
// child to shut down cleanly. A deadlocked server would otherwise
// hold the deactivate path indefinitely and VS Code reports "Window
// not responding".
const STOP_TIMEOUT_MS = 2000;
async function stopClient(): Promise<void> {
if (!client) {
return;
}
const local = client;
client = undefined;
setLspReady(false);
// Drop the state-change listener BEFORE awaiting stop(). Otherwise
// the Stopped transition that stop() triggers re-fires our handler
// against the now-detached client and calls setLspReady(false) a
// second time. Cheap, but the second flip is misleading in the log.
if (clientStateChangeDisposable) {
clientStateChangeDisposable.dispose();
clientStateChangeDisposable = undefined;
}
let timer: NodeJS.Timeout | undefined;
try {
await Promise.race([
local.stop(),
new Promise<void>((resolve) => {
timer = setTimeout(resolve, STOP_TIMEOUT_MS);
}),
]);
} finally {
if (timer) {
clearTimeout(timer);
}
// If stop() didn't win the race the client is stranded; dispose
// explicitly so its subscriptions don't outlive us.
local.dispose?.();
}
}
export async function activate(
context: vscode.ExtensionContext,
): Promise<void> {
// The Findings tree reads from already-published diagnostics, so we
// wire it up before starting the client. That way, if the server
// takes a moment to come up (or fails outright), the panel is still
// visible and surfaces findings the moment the first publish lands.
// Seed the welcome-panel context key before any UI renders so the
// install-prompt is what shows up on the very first frame; flipped
// to true by startClient on a successful connection.
setLspReady(false);
const findingsProvider = new FindingsTreeProvider(context);
const findingsView = vscode.window.createTreeView("pipelineCheck.findings", {
treeDataProvider: findingsProvider,
showCollapseAll: true,
});
// Two-phase wiring: the view needs the provider at construction
// time, but the provider needs the view to drive its activity-bar
// badge. Handing the view back closes the loop and triggers an
// initial badge update.
findingsProvider.setTreeView(findingsView);
// Status bar item lives at the bottom-left and shows the per-
// severity tally. Click reveals the Findings panel. registerStatusBar
// pushes the item onto context.subscriptions internally.
registerStatusBar(context);
// CodeLens summary at the top of every scanned file. Reads from the
// same diagnostic stream the tree does; click navigates to the
// Findings panel for drill-down.
context.subscriptions.push(
vscode.languages.registerCodeLensProvider(
[...TRIGGER_DOCUMENT_SELECTOR],
new FindingsCodeLensProvider(context),
),
);
context.subscriptions.push(
findingsView,
// Workspace scan: open every candidate file so the LSP runs its
// didOpen pipeline on each. Findings panel updates as the server
// publishes; no extra state to manage.
vscode.commands.registerCommand("pipelineCheck.scanWorkspace", () =>
scanWorkspace(),
),
// "Refresh Findings" was historically a tree-only re-render. Now
// that we have a real scan command, refresh runs an actual scan so
// the button matches the user's mental model — clicking "refresh"
// should fetch fresh data, not re-paint stale data. The tree
// updates automatically as scan publishes arrive (R10).
vscode.commands.registerCommand("pipelineCheck.findings.refresh", () =>
scanWorkspace(),
),
vscode.commands.registerCommand(
"pipelineCheck.findings.changeGrouping",
() => changeGrouping(findingsProvider),
),
// Context-menu entries on a Findings tree leaf. VS Code passes the
// TreeNode as the first argument; we read the `finding` shape off
// it. Both commands are gated behind `viewItem == pipelineCheck.finding`
// in package.json so the node is always a leaf when these fire.
vscode.commands.registerCommand(
"pipelineCheck.findings.copyRuleId",
async (node: LeafLike | undefined) => {
const id = node?.finding?.ruleId?.trim();
if (!id) {
void vscode.window.showInformationMessage(
"Pipeline-Check: this finding has no rule ID.",
);
return;
}
await vscode.env.clipboard.writeText(id);
// Status-bar message instead of a modal toast — the copy
// succeeded silently 95% of the time anyway; this is a
// ~2-second confirmation that doesn't steal focus.
vscode.window.setStatusBarMessage(`Copied ${id}`, CONFIRM_TTL_MS);
},
),
vscode.commands.registerCommand(
"pipelineCheck.findings.openRuleDocs",
async (node: LeafLike | undefined) => {
const url = node?.finding?.docsUrl?.trim();
if (!url) {
void vscode.window.showInformationMessage(
"Pipeline-Check: no documentation URL was published for this rule.",
);
return;
}
await vscode.env.openExternal(vscode.Uri.parse(url));
},
),
// Open a finding without using the editor's preview-tab slot.
// Same target as the default click-to-reveal, but `preview: false`
// pins each opened file as a permanent tab — useful when the user
// is opening several findings side-by-side. Lives only in the
// leaf context menu; the single-click path stays preview-style so
// the common "click through findings to triage" flow doesn't
// create tab clutter.
vscode.commands.registerCommand(
"pipelineCheck.findings.openNonPreview",
async (node: LeafLike | undefined) => {
const uri = node?.finding?.uri;
const range = node?.finding?.diagnostic?.range;
if (!uri) return;
await vscode.commands.executeCommand("vscode.open", uri, {
selection: range,
preserveFocus: false,
preview: false,
});
},
),
// Filter the Findings tree by a substring. Matches against rule
// ID, message body, and fsPath case-insensitively. Re-invoking
// the command pre-fills the current filter so users can edit or
// clear it (empty string clears).
vscode.commands.registerCommand(
"pipelineCheck.findings.filter",
async () => {
const current = findingsProvider.getFilter();
const next = await vscode.window.showInputBox({
title: "Filter Pipeline-Check findings",
prompt:
"Match rule ID, message text, or file path. Empty to clear.",
value: current,
placeHolder: "e.g. GHA-001 or release.yml",
});
if (next === undefined) return; // user cancelled
findingsProvider.setFilter(next);
},
),
// Install commands. installInTerminal is the primary CTA from the
// welcome panel — it opens a terminal with the pip command typed
// but not executed, so the user reviews / activates their venv
// first. copyInstallCommand stays registered as a fallback for
// users in headless / non-terminal flows. Both bodies live in
// install.ts so the welcome-panel CTAs and the LSP-failure toast
// share one code path.
vscode.commands.registerCommand(
"pipelineCheck.installInTerminal",
installInTerminal,
),
vscode.commands.registerCommand(
"pipelineCheck.copyInstallCommand",
copyInstallCommandToClipboard,
),
vscode.commands.registerCommand("pipelineCheck.goToNextFinding", () =>
goToFinding("next"),
),
vscode.commands.registerCommand("pipelineCheck.goToPreviousFinding", () =>
goToFinding("previous"),
),
vscode.commands.registerCommand("pipelineCheck.restart", async () => {
await stopClient();
await startClient();
// Only confirm success when startClient left a live client behind.
// If start failed it surfaced its own error toast; we'd otherwise
// show "failed to start" and "restarted" at the same time.
if (client) {
vscode.window.showInformationMessage("Language server restarted.");
}
}),
vscode.commands.registerCommand("pipelineCheck.showLog", () => {
if (client?.outputChannel) {
client.outputChannel.show();
} else {
vscode.window.showInformationMessage(
"The language server is not running yet. Open a supported file " +
"or run 'Pipeline-Check: Restart language server'.",
);
}
}),
);
await startClient();
// Scan-on-save: when the user saves a CI/CD config file and has the
// setting enabled, re-scan the whole workspace (quietly). The LSP
// already re-publishes diagnostics for the saved file itself on
// `didSave`, so this is purely about picking up cross-file effects in
// *other* CI files (a Jenkinsfile that includes the just-edited
// library, a GHA workflow that calls the just-edited composite
// action). Busy-guard semantics + the gate logic live in
// src/scanOnSave.ts so they're unit-testable without a real save
// event source; this wiring just plumbs VS Code's dependencies in.
const onSave = createScanOnSaveHandler({
isEnabled: () =>
vscode.workspace
.getConfiguration("pipelineCheck")
.get<boolean>("scanOnSave", false),
isPipelineFile: (fsPath) => providerForPath(fsPath) !== undefined,
scan: () => scanWorkspace({ quiet: true }),
});
context.subscriptions.push(vscode.workspace.onDidSaveTextDocument(onSave));
// Fire-and-forget the one-time "what's new" toast for users who
// just upgraded. Detached so a not-yet-dismissed notification never
// blocks activation (same lesson as the LSP-failure toast). The
// function persists the seen-version before showing, so a missed
// notification doesn't repeat next launch.
void showWhatsNewIfUpgraded(context, context.extension.packageJSON.version);
}
export async function deactivate(): Promise<void> {
await stopClient();
}