-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathrename.ts
90 lines (75 loc) · 2.73 KB
/
rename.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as fse from "fs-extra";
import * as path from "path";
import { Uri, window, workspace, WorkspaceEdit } from "vscode";
import { NodeKind } from "../java/nodeData";
import { DataNode } from "../views/dataNode";
import { checkJavaQualifiedName, isMutable } from "./utility";
export async function renameFile(node?: DataNode): Promise<void> {
if (!node?.uri || !isMutable(node)) {
return;
}
const oldFsPath = Uri.parse(node.uri).fsPath;
const newName: string | undefined = await window.showInputBox({
placeHolder: "Input new file name",
value: getPrefillValue(node),
ignoreFocusOut: true,
valueSelection: getValueSelection(node.uri),
validateInput: async (value: string): Promise<string> => {
const checkMessage = CheckQualifiedInputName(value, node.nodeData.kind);
if (checkMessage) {
return checkMessage;
}
const inputFsPath = getRenamedFsPath(oldFsPath, value);
if (await fse.pathExists(inputFsPath)) {
return `File path: ${inputFsPath} already exists.`;
}
return "";
},
});
if (!newName) {
return;
}
const newFsPath = getRenamedFsPath(oldFsPath, newName);
const workspaceEdit: WorkspaceEdit = new WorkspaceEdit();
workspaceEdit.renameFile(Uri.file(oldFsPath), Uri.file(newFsPath));
workspace.applyEdit(workspaceEdit);
}
function getRenamedFsPath(oldUri: string, newName: string): string {
// preserve default file extension if not provided
if (!path.extname(newName)) {
newName += path.extname(oldUri);
}
const dirname = path.dirname(oldUri);
return path.join(dirname, newName);
}
function getPrefillValue(node: DataNode): string {
const nodeKind = node.nodeData.kind;
if (nodeKind === NodeKind.PrimaryType) {
return node.name;
}
return path.basename(node.uri!);
}
function getValueSelection(uri: string): [number, number] | undefined {
const pos = path.basename(uri).lastIndexOf(".");
if (pos !== -1) {
return [0, pos];
}
return undefined;
}
function CheckQualifiedInputName(value: string, nodeKind: NodeKind): string {
if (nodeKind === NodeKind.Folder || nodeKind === NodeKind.File) {
return "";
}
const javaValidateMessage = checkJavaQualifiedName(value);
if (javaValidateMessage) {
return javaValidateMessage;
}
if (nodeKind === NodeKind.Package || nodeKind === NodeKind.PackageRoot) {
if (value.indexOf(".") !== -1) {
return "Rename is only applicable to innermost package.";
}
}
return "";
}