-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
fileExplorer.ts
309 lines (244 loc) · 9.3 KB
/
fileExplorer.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
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
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import * as mkdirp from 'mkdirp';
import * as rimraf from 'rimraf';
//#region Utilities
namespace _ {
function handleResult<T>(resolve: (result: T) => void, reject: (error: Error) => void, error: Error | null | undefined, result: T): void {
if (error) {
reject(massageError(error));
} else {
resolve(result);
}
}
function massageError(error: Error & { code?: string }): Error {
if (error.code === 'ENOENT') {
return vscode.FileSystemError.FileNotFound();
}
if (error.code === 'EISDIR') {
return vscode.FileSystemError.FileIsADirectory();
}
if (error.code === 'EEXIST') {
return vscode.FileSystemError.FileExists();
}
if (error.code === 'EPERM' || error.code === 'EACCES') {
return vscode.FileSystemError.NoPermissions();
}
return error;
}
export function checkCancellation(token: vscode.CancellationToken): void {
if (token.isCancellationRequested) {
throw new Error('Operation cancelled');
}
}
export function normalizeNFC(items: string): string;
export function normalizeNFC(items: string[]): string[];
export function normalizeNFC(items: string | string[]): string | string[] {
if (process.platform !== 'darwin') {
return items;
}
if (Array.isArray(items)) {
return items.map(item => item.normalize('NFC'));
}
return items.normalize('NFC');
}
export function readdir(path: string): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
fs.readdir(path, (error, children) => handleResult(resolve, reject, error, normalizeNFC(children)));
});
}
export function stat(path: string): Promise<fs.Stats> {
return new Promise<fs.Stats>((resolve, reject) => {
fs.stat(path, (error, stat) => handleResult(resolve, reject, error, stat));
});
}
export function readfile(path: string): Promise<Buffer> {
return new Promise<Buffer>((resolve, reject) => {
fs.readFile(path, (error, buffer) => handleResult(resolve, reject, error, buffer));
});
}
export function writefile(path: string, content: Buffer): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.writeFile(path, content, error => handleResult(resolve, reject, error, void 0));
});
}
export function exists(path: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
fs.exists(path, exists => handleResult(resolve, reject, null, exists));
});
}
export function rmrf(path: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
rimraf(path, error => handleResult(resolve, reject, error, void 0));
});
}
export function mkdir(path: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
mkdirp(path, error => handleResult(resolve, reject, error, void 0));
});
}
export function rename(oldPath: string, newPath: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.rename(oldPath, newPath, error => handleResult(resolve, reject, error, void 0));
});
}
export function unlink(path: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.unlink(path, error => handleResult(resolve, reject, error, void 0));
});
}
}
export class FileStat implements vscode.FileStat {
constructor(private fsStat: fs.Stats) { }
get type(): vscode.FileType {
return this.fsStat.isFile() ? vscode.FileType.File : this.fsStat.isDirectory() ? vscode.FileType.Directory : this.fsStat.isSymbolicLink() ? vscode.FileType.SymbolicLink : vscode.FileType.Unknown;
}
get isFile(): boolean | undefined {
return this.fsStat.isFile();
}
get isDirectory(): boolean | undefined {
return this.fsStat.isDirectory();
}
get isSymbolicLink(): boolean | undefined {
return this.fsStat.isSymbolicLink();
}
get size(): number {
return this.fsStat.size;
}
get ctime(): number {
return this.fsStat.ctime.getTime();
}
get mtime(): number {
return this.fsStat.mtime.getTime();
}
}
interface Entry {
uri: vscode.Uri;
type: vscode.FileType;
}
//#endregion
export class FileSystemProvider implements vscode.TreeDataProvider<Entry>, vscode.FileSystemProvider {
private _onDidChangeFile: vscode.EventEmitter<vscode.FileChangeEvent[]>;
constructor() {
this._onDidChangeFile = new vscode.EventEmitter<vscode.FileChangeEvent[]>();
}
get onDidChangeFile(): vscode.Event<vscode.FileChangeEvent[]> {
return this._onDidChangeFile.event;
}
watch(uri: vscode.Uri, options: { recursive: boolean; excludes: string[]; }): vscode.Disposable {
const watcher = fs.watch(uri.fsPath, { recursive: options.recursive }, async (event, filename) => {
if (filename) {
const filepath = path.join(uri.fsPath, _.normalizeNFC(filename.toString()));
// TODO support excludes (using minimatch library?)
this._onDidChangeFile.fire([{
type: event === 'change' ? vscode.FileChangeType.Changed : await _.exists(filepath) ? vscode.FileChangeType.Created : vscode.FileChangeType.Deleted,
uri: uri.with({ path: filepath })
} as vscode.FileChangeEvent]);
}
});
return { dispose: () => watcher.close() };
}
stat(uri: vscode.Uri): vscode.FileStat | Thenable<vscode.FileStat> {
return this._stat(uri.fsPath);
}
async _stat(path: string): Promise<vscode.FileStat> {
return new FileStat(await _.stat(path));
}
readDirectory(uri: vscode.Uri): [string, vscode.FileType][] | Thenable<[string, vscode.FileType][]> {
return this._readDirectory(uri);
}
async _readDirectory(uri: vscode.Uri): Promise<[string, vscode.FileType][]> {
const children = await _.readdir(uri.fsPath);
const result: [string, vscode.FileType][] = [];
for (const child of children) {
const stat = await this._stat(path.join(uri.fsPath, child));
result.push([child, stat.type]);
}
return Promise.resolve(result);
}
createDirectory(uri: vscode.Uri): void | Thenable<void> {
return _.mkdir(uri.fsPath);
}
readFile(uri: vscode.Uri): Uint8Array | Thenable<Uint8Array> {
return _.readfile(uri.fsPath);
}
writeFile(uri: vscode.Uri, content: Uint8Array, options: { create: boolean; overwrite: boolean; }): void | Thenable<void> {
return this._writeFile(uri, content, options);
}
async _writeFile(uri: vscode.Uri, content: Uint8Array, options: { create: boolean; overwrite: boolean; }): Promise<void> {
const exists = await _.exists(uri.fsPath);
if (!exists) {
if (!options.create) {
throw vscode.FileSystemError.FileNotFound();
}
await _.mkdir(path.dirname(uri.fsPath));
} else {
if (!options.overwrite) {
throw vscode.FileSystemError.FileExists();
}
}
return _.writefile(uri.fsPath, content as Buffer);
}
delete(uri: vscode.Uri, options: { recursive: boolean; }): void | Thenable<void> {
if (options.recursive) {
return _.rmrf(uri.fsPath);
}
return _.unlink(uri.fsPath);
}
rename(oldUri: vscode.Uri, newUri: vscode.Uri, options: { overwrite: boolean; }): void | Thenable<void> {
return this._rename(oldUri, newUri, options);
}
async _rename(oldUri: vscode.Uri, newUri: vscode.Uri, options: { overwrite: boolean; }): Promise<void> {
const exists = await _.exists(newUri.fsPath);
if (exists) {
if (!options.overwrite) {
throw vscode.FileSystemError.FileExists();
} else {
await _.rmrf(newUri.fsPath);
}
}
const parentExists = await _.exists(path.dirname(newUri.fsPath));
if (!parentExists) {
await _.mkdir(path.dirname(newUri.fsPath));
}
return _.rename(oldUri.fsPath, newUri.fsPath);
}
// tree data provider
async getChildren(element?: Entry): Promise<Entry[]> {
if (element) {
const children = await this.readDirectory(element.uri);
return children.map(([name, type]) => ({ uri: vscode.Uri.file(path.join(element.uri.fsPath, name)), type }));
}
const workspaceFolder = (vscode.workspace.workspaceFolders ?? []).filter(folder => folder.uri.scheme === 'file')[0];
if (workspaceFolder) {
const children = await this.readDirectory(workspaceFolder.uri);
children.sort((a, b) => {
if (a[1] === b[1]) {
return a[0].localeCompare(b[0]);
}
return a[1] === vscode.FileType.Directory ? -1 : 1;
});
return children.map(([name, type]) => ({ uri: vscode.Uri.file(path.join(workspaceFolder.uri.fsPath, name)), type }));
}
return [];
}
getTreeItem(element: Entry): vscode.TreeItem {
const treeItem = new vscode.TreeItem(element.uri, element.type === vscode.FileType.Directory ? vscode.TreeItemCollapsibleState.Collapsed : vscode.TreeItemCollapsibleState.None);
if (element.type === vscode.FileType.File) {
treeItem.command = { command: 'fileExplorer.openFile', title: "Open File", arguments: [element.uri], };
treeItem.contextValue = 'file';
}
return treeItem;
}
}
export class FileExplorer {
constructor(context: vscode.ExtensionContext) {
const treeDataProvider = new FileSystemProvider();
context.subscriptions.push(vscode.window.createTreeView('fileExplorer', { treeDataProvider }));
vscode.commands.registerCommand('fileExplorer.openFile', (resource) => this.openResource(resource));
}
private openResource(resource: vscode.Uri): void {
vscode.window.showTextDocument(resource);
}
}