Repository navigation
Expand file tree
/
Copy pathnew.ts
More file actions
276 lines (239 loc) · 9.22 KB
/
Copy pathnew.ts
File metadata and controls
276 lines (239 loc) · 9.22 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as fse from "fs-extra";
import * as path from "path";
import { commands, Extension, extensions, languages, QuickPickItem, SnippetString, TextEditor, Uri,
window, workspace, WorkspaceEdit, WorkspaceFolder } from "vscode";
import { sendInfo } from "vscode-extension-telemetry-wrapper";
import { Commands } from "../../extension.bundle";
import { ExtensionName } from "../constants";
import { NodeKind } from "../java/nodeData";
import { DataNode } from "../views/dataNode";
import { resourceRoots } from "../views/packageRootNode";
import { checkJavaQualifiedName } from "./utility";
export async function newJavaClass(node?: DataNode): Promise<void> {
let packageFsPath: string | undefined;
if (!node) {
// from the new file menu entry
sendInfo("", {
triggerNewFileFrom: "menuBar",
});
packageFsPath = await inferPackageFsPath();
} else {
sendInfo("", {
triggerNewFileFrom: "projectExplorer",
});
if (!node?.uri || !canCreateClass(node)) {
return;
}
packageFsPath = await getPackageFsPath(node);
}
if (packageFsPath === undefined) {
// User canceled
return;
} else if (packageFsPath.length === 0) {
return newUntitledJavaFile();
}
const className: string | undefined = await window.showInputBox({
placeHolder: "Input the class name",
ignoreFocusOut: true,
validateInput: async (value: string): Promise<string> => {
const checkMessage: string = checkJavaQualifiedName(value);
if (checkMessage) {
return checkMessage;
}
if (await fse.pathExists(getNewFilePath(packageFsPath!, value))) {
return "Class already exists.";
}
return "";
},
});
if (!className) {
return;
}
// `workspace.applyEdit()` will trigger a workspace file event, and let the
// vscode-java extension to handle the type: class, interface or enum.
const workspaceEdit: WorkspaceEdit = new WorkspaceEdit();
const fsPath: string = getNewFilePath(packageFsPath, className);
workspaceEdit.createFile(Uri.file(fsPath));
workspace.applyEdit(workspaceEdit);
}
async function newUntitledJavaFile(): Promise<void> {
await commands.executeCommand("workbench.action.files.newUntitledFile");
const textEditor: TextEditor | undefined = window.activeTextEditor;
if (!textEditor) {
return;
}
await languages.setTextDocumentLanguage(textEditor.document, "java");
const snippets: string[] = [];
snippets.push(`public \${1|class,interface,enum,abstract class,@interface|} \${2:Main} {`);
snippets.push(`\t\${0}`);
snippets.push("}");
snippets.push("");
textEditor.insertSnippet(new SnippetString(snippets.join("\n")));
}
async function inferPackageFsPath(): Promise<string> {
const javaLanguageSupport: Extension<any> | undefined = extensions.getExtension(ExtensionName.JAVA_LANGUAGE_SUPPORT);
if (!javaLanguageSupport || !javaLanguageSupport.isActive) {
return "";
}
const extensionApi: any = javaLanguageSupport.exports;
if (!extensionApi) {
return "";
}
if (extensionApi.serverMode !== "Standard" || extensionApi.status !== "Started") {
return "";
}
let sourcePaths: string[] | undefined;
try {
const result = await commands.executeCommand<IListCommandResult>(Commands.EXECUTE_WORKSPACE_COMMAND, Commands.LIST_SOURCEPATHS);
if (result && result.data && result.data.length) {
sourcePaths = result.data.map((entry) => entry.path);
}
} catch (e) {
// do nothing
}
if (!window.activeTextEditor) {
if (sourcePaths?.length === 1) {
return sourcePaths[0];
}
return "";
}
const fileUri: Uri = window.activeTextEditor.document.uri;
const workspaceFolder: WorkspaceFolder | undefined = workspace.getWorkspaceFolder(fileUri);
if (!workspaceFolder) {
return "";
}
const filePath: string = window.activeTextEditor.document.uri.fsPath;
if (sourcePaths) {
for (const sourcePath of sourcePaths) {
if (!path.relative(sourcePath, filePath).startsWith("..")) {
return path.dirname(window.activeTextEditor.document.uri.fsPath);
}
}
}
return "";
}
function canCreateClass(node: DataNode): boolean {
if (node.nodeData.kind === NodeKind.Project ||
node.nodeData.kind === NodeKind.PackageRoot ||
node.nodeData.kind === NodeKind.Package ||
node.nodeData.kind === NodeKind.PrimaryType) {
return true;
}
return false;
}
async function getPackageFsPath(node: DataNode): Promise<string | undefined> {
if (node.nodeData.kind === NodeKind.Project) {
const childrenNodes: DataNode[] = await node.getChildren() as DataNode[];
const packageRoots: any[] = childrenNodes.filter((child) => {
return child.nodeData.kind === NodeKind.PackageRoot && !resourceRoots.includes(child.name);
});
if (packageRoots.length < 1) {
// This might happen for an invisible project with "_" as its root
const packageNode: DataNode | undefined = childrenNodes.find((child) => {
return child.nodeData.kind === NodeKind.Package;
});
if (!packageNode && node.uri) {
// This means the .java files are in the default package.
return Uri.parse(node.uri).fsPath;
} else if (packageNode?.uri) {
return getPackageRootPath(Uri.parse(packageNode.uri).fsPath, packageNode.name);
}
return "";
} else if (packageRoots.length === 1) {
return Uri.parse(packageRoots[0].uri).fsPath;
} else {
const options: ISourceRootPickItem[] = packageRoots.map((root) => {
return {
label: root.name,
fsPath: Uri.parse(root.uri).fsPath,
};
});
const choice: ISourceRootPickItem | undefined = await window.showQuickPick(options, {
placeHolder: "Choose a source folder",
ignoreFocusOut: true,
},
);
return choice?.fsPath;
}
} else if (node.nodeData.kind === NodeKind.PrimaryType) {
return node.uri ? path.dirname(Uri.parse(node.uri).fsPath) : "";
}
return node.uri ? Uri.parse(node.uri).fsPath : "";
}
function getNewFilePath(basePath: string, className: string): string {
if (className.endsWith(".java")) {
className = className.substr(0, className.length - ".java".length);
}
return path.join(basePath, ...className.split(".")) + ".java";
}
export async function newPackage(node?: DataNode): Promise<void> {
if (!node?.uri || !canCreatePackage(node)) {
return;
}
let defaultValue: string;
let packageRootPath: string;
const nodeKind = node.nodeData.kind;
if (nodeKind === NodeKind.Project) {
defaultValue = "";
packageRootPath = await getPackageFsPath(node) || "";
} else if (nodeKind === NodeKind.PackageRoot) {
defaultValue = "";
packageRootPath = Uri.parse(node.uri).fsPath;
} else if (nodeKind === NodeKind.Package) {
defaultValue = node.nodeData.name + ".";
packageRootPath = getPackageRootPath(Uri.parse(node.uri).fsPath, node.nodeData.name);
} else {
return;
}
const packageName: string | undefined = await window.showInputBox({
value: defaultValue,
placeHolder: "Input the package name",
valueSelection: [defaultValue.length, defaultValue.length],
ignoreFocusOut: true,
validateInput: async (value: string): Promise<string> => {
const checkMessage: string = checkJavaQualifiedName(value);
if (checkMessage) {
return checkMessage;
}
if (await fse.pathExists(getNewPackagePath(packageRootPath, value))) {
return "Package already exists.";
}
return "";
},
});
if (!packageName) {
return;
}
await fse.ensureDir(getNewPackagePath(packageRootPath, packageName));
}
function canCreatePackage(node: DataNode): boolean {
if (node.nodeData.kind === NodeKind.Project ||
node.nodeData.kind === NodeKind.PackageRoot ||
node.nodeData.kind === NodeKind.Package) {
return true;
}
return false;
}
function getPackageRootPath(packageFsPath: string, packageName: string): string {
const numberOfSegment: number = packageName.split(".").length;
return path.join(packageFsPath, ...Array(numberOfSegment).fill(".."));
}
function getNewPackagePath(packageRootPath: string, packageName: string): string {
return path.join(packageRootPath, ...packageName.split("."));
}
interface ISourceRootPickItem extends QuickPickItem {
fsPath: string;
}
interface IListCommandResult {
status: boolean;
message: string;
data?: ISourcePath[];
}
interface ISourcePath {
path: string;
displayPath: string;
projectName: string;
projectType: string;
}