-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathdependencyDataProvider.ts
More file actions
300 lines (270 loc) · 13.1 KB
/
dependencyDataProvider.ts
File metadata and controls
300 lines (270 loc) · 13.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as _ from "lodash";
import {
commands, Event, EventEmitter, ExtensionContext, ProviderResult,
RelativePattern, TreeDataProvider, TreeItem, Uri, window, workspace,
} from "vscode";
import { instrumentOperationAsVsCodeCommand, sendError } from "vscode-extension-telemetry-wrapper";
import { ContainerNode, contextManager } from "../../extension.bundle";
import { Commands } from "../commands";
import { Context } from "../constants";
import { appendOutput, executeExportJarTask } from "../tasks/buildArtifact/BuildArtifactTaskProvider";
import { Jdtls } from "../java/jdtls";
import { INodeData, NodeKind } from "../java/nodeData";
import { languageServerApiManager } from "../languageServerApi/languageServerApiManager";
import { Settings } from "../settings";
import { explorerLock } from "../utils/Lock";
import { DataNode } from "./dataNode";
import { ExplorerNode } from "./explorerNode";
import { explorerNodeCache } from "./nodeCache/explorerNodeCache";
import { ProjectNode } from "./projectNode";
import { WorkspaceNode } from "./workspaceNode";
export class DependencyDataProvider implements TreeDataProvider<ExplorerNode> {
private _onDidChangeTreeData: EventEmitter<ExplorerNode | null | undefined> = new EventEmitter<ExplorerNode | null | undefined>();
// tslint:disable-next-line:member-ordering
public onDidChangeTreeData: Event<ExplorerNode | null | undefined> = this._onDidChangeTreeData.event;
private _rootItems: ExplorerNode[] | undefined = undefined;
private _refreshDelayTrigger: _.DebouncedFunc<((element?: ExplorerNode) => void)>;
/**
* The element which is pending to be refreshed.
* `undefined` denotes to root node.
* `null` means no node is pending.
*/
private pendingRefreshElement: ExplorerNode | undefined | null;
/** Resolved when the first batch of progressive items arrives. */
private _progressiveItemsReady: Promise<void> | undefined;
private _resolveProgressiveItems: (() => void) | undefined;
constructor(public readonly context: ExtensionContext) {
// commands that do not send back telemetry
context.subscriptions.push(commands.registerCommand(Commands.VIEW_PACKAGE_INTERNAL_REFRESH, (debounce?: boolean, element?: ExplorerNode) =>
this.refresh(debounce, element)));
context.subscriptions.push(commands.registerCommand(Commands.VIEW_PACKAGE_INTERNAL_ADD_PROJECTS, (projectUris: string[]) =>
this.addProgressiveProjects(projectUris)));
context.subscriptions.push(commands.registerCommand(Commands.EXPORT_JAR_REPORT, (terminalId: string, message: string) => {
appendOutput(terminalId, message);
}));
// normal commands
context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.VIEW_PACKAGE_REFRESH, (debounce?: boolean, element?: ExplorerNode) =>
this.refresh(debounce, element)));
context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.VIEW_PACKAGE_EXPORT_JAR, async (node: INodeData) => {
executeExportJarTask(node);
}));
context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.VIEW_PACKAGE_OUTLINE, (uri, range) =>
window.showTextDocument(Uri.parse(uri), { selection: range })));
context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.JAVA_PROJECT_BUILD_WORKSPACE, () =>
commands.executeCommand(Commands.JAVA_BUILD_WORKSPACE, true /*fullCompile*/)));
context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.JAVA_PROJECT_CLEAN_WORKSPACE, () =>
commands.executeCommand(Commands.JAVA_CLEAN_WORKSPACE)));
context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.JAVA_PROJECT_UPDATE, async (node: INodeData) => {
if (!node.uri) {
sendError(new Error("Uri not available when reloading project"));
window.showErrorMessage("The URI of the project is not available, you can try to trigger the command 'Java: Reload Project' from Command Palette.");
return;
}
const pattern: RelativePattern = new RelativePattern(Uri.parse(node.uri).fsPath?.replace(/[\\\/]+$/, ""), "{pom.xml,*.gradle}");
const uris: Uri[] = await workspace.findFiles(pattern, null /*exclude*/, 1 /*maxResults*/);
if (uris.length >= 1) {
commands.executeCommand(Commands.JAVA_PROJECT_CONFIGURATION_UPDATE, uris[0]);
}
}));
context.subscriptions.push(instrumentOperationAsVsCodeCommand(Commands.JAVA_PROJECT_REBUILD, async (node: INodeData) => {
if (!node.uri) {
sendError(new Error("Uri not available when building project"));
window.showErrorMessage("The URI of the project is not available, you can try to trigger the command 'Java: Rebuild Projects' from Command Palette.");
return;
}
commands.executeCommand(Commands.BUILD_PROJECT, Uri.parse(node.uri), true);
}));
this.setRefreshDebounceFunc();
}
public refresh(debounce = false, element?: ExplorerNode) {
if (element === undefined || this.pendingRefreshElement === undefined) {
this._refreshDelayTrigger(undefined);
this.pendingRefreshElement = undefined;
} else if (this.pendingRefreshElement === null
|| element.isItselfOrAncestorOf(this.pendingRefreshElement)) {
this._refreshDelayTrigger(element);
this.pendingRefreshElement = element;
} else if (this.pendingRefreshElement.isItselfOrAncestorOf(element)) {
this._refreshDelayTrigger(this.pendingRefreshElement);
} else {
this._refreshDelayTrigger.flush();
this._refreshDelayTrigger(element);
this.pendingRefreshElement = element;
}
if (!debounce) { // Immediately refresh
this._refreshDelayTrigger.flush();
}
}
public setRefreshDebounceFunc(wait?: number) {
if (!wait) {
wait = Settings.refreshDelay();
}
if (this._refreshDelayTrigger) {
this._refreshDelayTrigger.cancel();
}
this._refreshDelayTrigger = _.debounce(this.doRefresh, wait);
}
public getTreeItem(element: ExplorerNode): TreeItem | Promise<TreeItem> {
return element.getTreeItem();
}
public async getChildren(element?: ExplorerNode): Promise<ExplorerNode[] | undefined | null> {
// Fast path: if root items are already populated by progressive loading
// (addProgressiveProjects), return them directly without querying the
// server, which may be blocked during long-running imports.
if (!element && this._rootItems && this._rootItems.length > 0) {
explorerNodeCache.saveNodes(this._rootItems);
return this._rootItems;
}
if (!await languageServerApiManager.ready()) {
return [];
}
// During progressive loading (server running but not fully ready after
// a clean workspace), don't enter getRootNodes() — its server queries
// will block for the entire import duration. Instead, keep the TreeView
// progress spinner visible by awaiting until the first progressive
// notification delivers items.
if (!element && !languageServerApiManager.isFullyReady()) {
if (!this._rootItems || this._rootItems.length === 0) {
if (!this._progressiveItemsReady) {
this._progressiveItemsReady = new Promise<void>((resolve) => {
this._resolveProgressiveItems = resolve;
});
}
await this._progressiveItemsReady;
}
return this._rootItems || [];
}
const children = (!this._rootItems || !element) ?
await this.getRootNodes() : await element.getChildren();
if (children && element instanceof ContainerNode) {
if (element.isMavenType()) {
children.sort((a, b) => {
return a.getDisplayName().localeCompare(b.getDisplayName());
});
}
}
explorerNodeCache.saveNodes(children || []);
return children;
}
public getParent(element: ExplorerNode): ProviderResult<ExplorerNode> {
return element.getParent();
}
public async revealPaths(paths: INodeData[]): Promise<DataNode | undefined> {
const projectNodeData = paths.shift();
const projects = await this.getRootProjects();
const project = projects ? <DataNode>projects.find((node: DataNode) =>
node.path === projectNodeData?.path && node.nodeData.name === projectNodeData?.name) : undefined;
return project?.revealPaths(paths);
}
public async getRootProjects(): Promise<ExplorerNode[]> {
const rootElements = await this.getRootNodes();
if (rootElements[0] instanceof ProjectNode) {
return rootElements;
} else {
let result: ExplorerNode[] = [];
for (const rootWorkspace of rootElements) {
const projects = await rootWorkspace.getChildren();
if (projects) {
result = result.concat(projects);
}
}
return result;
}
}
private doRefresh(element?: ExplorerNode): void {
if (!element) {
this._rootItems = undefined;
// Resolve any pending progressive await so getChildren() doesn't hang
if (this._resolveProgressiveItems) {
this._resolveProgressiveItems();
this._resolveProgressiveItems = undefined;
this._progressiveItemsReady = undefined;
}
}
explorerNodeCache.removeNodeChildren(element);
this._onDidChangeTreeData.fire(element);
this.pendingRefreshElement = null;
}
/**
* Add projects progressively from ProjectsImported notifications.
* This directly creates ProjectNode items from URIs without querying
* the JDTLS server, which may be blocked during long-running imports.
*/
public addProgressiveProjects(projectUris: string[]): void {
const folders = workspace.workspaceFolders;
if (!folders || !folders.length) {
return;
}
if (!this._rootItems) {
this._rootItems = [];
}
const existingUris = new Set(
this._rootItems
.filter((n): n is ProjectNode => n instanceof ProjectNode)
.map((n) => n.uri)
);
let added = false;
for (const uriStr of projectUris) {
if (existingUris.has(uriStr)) {
continue;
}
// Extract project name from URI (last non-empty path segment)
const name = uriStr.replace(/\/+$/, "").split("/").pop() || "unknown";
const nodeData: INodeData = {
name,
uri: uriStr,
kind: NodeKind.Project,
};
this._rootItems.push(new ProjectNode(nodeData, undefined));
existingUris.add(uriStr);
added = true;
}
if (added) {
// Resolve the pending getChildren() promise so the TreeView
// spinner stops and items appear.
if (this._resolveProgressiveItems) {
this._resolveProgressiveItems();
this._resolveProgressiveItems = undefined;
this._progressiveItemsReady = undefined;
}
this._onDidChangeTreeData.fire(undefined);
}
}
private async getRootNodes(): Promise<ExplorerNode[]> {
try {
await explorerLock.acquireAsync();
if (this._rootItems) {
return this._rootItems;
}
const hasJavaError: boolean = await Jdtls.checkImportStatus();
if (hasJavaError) {
contextManager.setContextValue(Context.IMPORT_FAILED, true);
return [];
}
const rootItems: ExplorerNode[] = [];
const folders = workspace.workspaceFolders;
if (folders && folders.length) {
if (folders.length > 1) {
folders.forEach((folder) => rootItems.push(new WorkspaceNode({
name: folder.name,
uri: folder.uri.toString(),
kind: NodeKind.Workspace,
}, undefined)));
this._rootItems = rootItems;
} else {
const result: INodeData[] = await Jdtls.getProjects(folders[0].uri.toString());
result.forEach((project) => {
rootItems.push(new ProjectNode(project, undefined));
});
this._rootItems = rootItems;
}
}
contextManager.setContextValue(Context.NO_JAVA_PROJECT, _.isEmpty(rootItems));
return rootItems;
} finally {
explorerLock.release();
}
}
}