-
Notifications
You must be signed in to change notification settings - Fork 384
/
files.ts
479 lines (407 loc) · 16 KB
/
files.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
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
/** ******************************************************************************
* Copyright (C) 2018 Red Hat, Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/
// Some code copied and modified from https://github.com/eclipse-theia/theia/tree/v1.14.0/packages/filesystem/src/common/filesystem.ts
import {
DidFilesChangedParams,
Event,
FileChangeEvent,
IDisposable,
IFileSystemWatcherServer,
URI,
Uri,
WatchOptions,
hasProperty,
isFunction,
isUndefinedOrNull,
} from '@opensumi/ide-core-common';
import { FileStat, FileSystemProvider } from '@opensumi/ide-core-common/lib/types/file';
import type { Range } from 'vscode-languageserver-types';
export {
FileSystemProviderCapabilities,
FileSystemProvider,
FileType,
FileStat,
} from '@opensumi/ide-core-common/lib/types/file';
export * from '@opensumi/ide-core-common/lib/types/file-watch';
export const IDiskFileProvider = Symbol('IDiskFileProvider');
export const IShadowFileProvider = Symbol('IShadowFileProvider');
export const IFileService = Symbol('IFileService');
export interface TextDocumentContentChangeEvent {
/**
* The range of the document that changed.
*/
range?: Range;
/**
* The length of the range that got replaced.
*/
rangeLength?: number;
/**
* The new text of the document.
*/
text: string;
}
export interface IFileService extends IFileSystemWatcherServer {
/**
* Returns the file stat for the given URI.
*
* If the uri points to a folder it will contain one level of unresolved children.
*
* `undefined` if a file for the given URI does not exist.
*/
getFileStat(uri: string): Promise<FileStat | undefined>;
/**
* Resolve the contents of a file identified by the resource.
*/
resolveContent(uri: string, options?: FileSetContentOptions): Promise<{ stat: FileStat; content: string }>;
/**
* Updates the content replacing its previous value.
*/
setContent(file: FileStat, content: string, options?: FileSetContentOptions): Promise<FileStat>;
/**
* Updates the content replacing its previous value.
*/
updateContent(
file: FileStat,
contentChanges: TextDocumentContentChangeEvent[],
options?: FileSetContentOptions,
): Promise<FileStat>;
/**
* Moves the file to a new path identified by the resource.
*
* The optional parameter overwrite can be set to replace an existing file at the location.
*
* | | missing | file | empty dir | dir |
* |-----------|---------|-----------|-----------|-----------|
* | missing | x | x | x | x |
* | file | ✓ | overwrite | x | x |
* | empty dir | ✓ | x | overwrite | overwrite |
* | dir | ✓ | x | overwrite | overwrite |
*/
move(sourceUri: string, targetUri: string, options?: FileMoveOptions): Promise<FileStat>;
/**
* Copies the file to a path identified by the resource.
*
* The optional parameter overwrite can be set to replace an existing file at the location.
*/
copy(sourceUri: string, targetUri: string, options?: FileCopyOptions): Promise<FileStat>;
/**
* Creates a new file with the given path. The returned promise
* will have the stat model object as a result.
*
* The optional parameter content can be used as value to fill into the new file.
*/
createFile(uri: string, options?: { content?: string; encoding?: string }): Promise<FileStat>;
/**
* Creates a new folder with the given path. The returned promise
* will have the stat model object as a result.
*/
createFolder(uri: string): Promise<FileStat>;
/**
* Creates a new empty file if the given path does not exist and otherwise
* will set the mtime and atime of the file to the current date.
*/
// touchFile(uri: string): Promise<FileStat>;
/**
* Deletes the provided file. The optional moveToTrash parameter allows to
* move the file to trash.
*/
delete(uri: string, options?: FileDeleteOptions): Promise<void>;
/**
* Returns the encoding of the given file resource.
*/
getEncoding(uri: string): Promise<string>;
/**
* Returns the encoding info of the given encoding id
*/
// getEncodingInfo(encodingId: string | null): EncodingInfo | null;
/**
* Returns a promise that resolves to a file stat representing the current user's home directory.
*/
getCurrentUserHome(): Promise<FileStat | undefined>;
/**
* Tests a user's permissions for the file or directory specified by URI.
* The mode argument is an optional integer that specifies the accessibility checks to be performed.
* Check `FileAccess.Constants` for possible values of mode.
* It is possible to create a mask consisting of the bitwise `OR` of two or more values (e.g. FileAccess.Constants.W_OK | FileAccess.Constants.R_OK).
* If `mode` is not defined, `FileAccess.Constants.F_OK` will be used instead.
*/
access(uri: string, mode?: number): Promise<boolean>;
/**
* Returns the path of the given file URI, specific to the backend's operating system.
* If the URI is not a file URI, undefined is returned.
*
* USE WITH CAUTION: You should always prefer URIs to paths if possible, as they are
* portable and platform independent. Pathes should only be used in cases you directly
* interact with the OS, e.g. when running a command on the shell.
*/
getFsPath(uri: string): Promise<string | undefined>;
getFileType(uri: string): Promise<string | undefined>;
onFilesChanged: Event<DidFilesChangedParams>;
fireFilesChange(e: FileChangeEvent);
watchFileChanges(uri: string, options?: WatchOptions): Promise<number>;
setWatchFileExcludes(excludes: string[]);
getWatchFileExcludes(): string[];
setFilesExcludes(excludes: string[], roots?: string[]);
getFilesExcludes(): string[];
setWorkspaceRoots(roots: string[]);
registerProvider(scheme: string, provider: FileSystemProvider): IDisposable;
getUri(uri: string | Uri): URI;
dispose(): void;
}
export namespace FileAccess {
export namespace Constants {
/**
* Flag indicating that the file is visible to the calling process.
* This is useful for determining if a file exists, but says nothing about rwx permissions. Default if no mode is specified.
*/
export const F_OK = 0;
/**
* Flag indicating that the file can be read by the calling process.
*/
export const R_OK = 4;
/**
* Flag indicating that the file can be written by the calling process.
*/
export const W_OK = 2;
/**
* Flag indicating that the file can be executed by the calling process.
* This has no effect on Windows (will behave like `FileAccess.F_OK`).
*/
export const X_OK = 1;
}
}
export interface FileMoveOptions {
overwrite?: boolean;
}
export interface FileDeleteOptions {
moveToTrash?: boolean;
}
export interface FileSetContentOptions {
encoding?: string;
}
export interface FileCreateOptions {
content?: string;
encoding?: string;
overwrite?: boolean;
}
export interface FileCopyOptions {
overwrite?: boolean;
}
export enum FileSystemProviderErrorCode {
FileExists = 'EntryExists',
FileNotFound = 'EntryNotFound',
FileNotADirectory = 'EntryNotADirectory',
FileIsADirectory = 'EntryIsADirectory',
FileIsOutOfSync = 'FileIsOutOfSync',
FileExceedsMemoryLimit = 'EntryExceedsMemoryLimit',
FileTooLarge = 'EntryTooLarge',
FileWriteLocked = 'EntryWriteLocked',
NoPermissions = 'NoPermissions',
Unavailable = 'Unavailable',
Unknown = 'Unknown',
}
export interface IFileSystemProviderError extends Error {
readonly name: string;
readonly code: FileSystemProviderErrorCode;
}
export class FileSystemProviderError extends Error implements IFileSystemProviderError {
static declare(code: FileSystemProviderErrorCode, factory: (...args: any[]) => string) {
return Object.assign((...args: any[]) => createFileSystemProviderError(factory(...args), code), {
is: (error: FileSystemProviderError) => error.stack?.startsWith(code),
});
}
constructor(message: string, readonly code: FileSystemProviderErrorCode) {
super(message);
}
is(error: FileSystemProviderError) {
return this.name === error.name;
}
}
export class FileOperationError extends Error {
constructor(message: string, public fileOperationResult: FileOperationResult, public options?: any) {
super(message);
}
static isFileOperationError(obj: unknown): obj is FileOperationError {
return obj instanceof Error && !isUndefinedOrNull((obj as FileOperationError).fileOperationResult);
}
}
export function createFileSystemProviderError(
error: Error | string,
code: FileSystemProviderErrorCode,
): FileSystemProviderError {
const providerError = new FileSystemProviderError(error.toString(), code);
markAsFileSystemProviderError(providerError, code);
return providerError;
}
export function markAsFileSystemProviderError(error: Error, code: FileSystemProviderErrorCode): Error {
error.name = code ? `${code} (FileSystemError)` : 'FileSystemError';
return error;
}
export namespace FileSystemError {
export const FileNotFound = FileSystemProviderError.declare(
FileSystemProviderErrorCode.FileNotFound,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''} '${uri}' is not found.`,
);
export const FileExists = FileSystemProviderError.declare(
FileSystemProviderErrorCode.FileExists,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' already exists.`,
);
export const FileNotADirectory = FileSystemProviderError.declare(
FileSystemProviderErrorCode.FileNotADirectory,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is not a directory.`,
);
export const FileIsADirectory = FileSystemProviderError.declare(
FileSystemProviderErrorCode.FileIsADirectory,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is a directory.`,
);
export const FileIsOutOfSync = FileSystemProviderError.declare(
FileSystemProviderErrorCode.FileIsOutOfSync,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is out of sync.`,
);
export const FileExceedsMemoryLimit = FileSystemProviderError.declare(
FileSystemProviderErrorCode.FileExceedsMemoryLimit,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is exceeds memory limit.`,
);
export const FileTooLarge = FileSystemProviderError.declare(
FileSystemProviderErrorCode.FileTooLarge,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is too large.`,
);
export const FileWriteLocked = FileSystemProviderError.declare(
FileSystemProviderErrorCode.FileWriteLocked,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is locked.`,
);
export const FileIsNoPermissions = FileSystemProviderError.declare(
FileSystemProviderErrorCode.NoPermissions,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is no permissions.`,
);
export const Unavailable = FileSystemProviderError.declare(
FileSystemProviderErrorCode.Unavailable,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is unavailable.`,
);
export const Unknown = FileSystemProviderError.declare(
FileSystemProviderErrorCode.Unknown,
(uri: string, prefix?: string) => `${prefix ? prefix + ' ' : ''}'${uri}' is unkonw.`,
);
}
export const enum FileOperationResult {
FILE_IS_DIRECTORY,
FILE_NOT_FOUND,
FILE_NOT_MODIFIED_SINCE,
FILE_MODIFIED_SINCE,
FILE_MOVE_CONFLICT,
FILE_READ_ONLY,
FILE_PERMISSION_DENIED,
FILE_TOO_LARGE,
FILE_INVALID_PATH,
FILE_EXCEEDS_MEMORY_LIMIT,
FILE_NOT_DIRECTORY,
FILE_OTHER_ERROR,
}
/**
* Copy files or folders. Implementing this function is optional but it will speedup
* the copy operation.
*
* @param source The existing file.
* @param destination The destination location.
* @param options Defines if existing files should be overwritten.
* @throws [`FileNotFound`](#FileSystemProviderError.FileNotFound) when `source` doesn't exist.
* @throws [`FileNotFound`](#FileSystemProviderError.FileNotFound) when parent of `destination` doesn't exist, e.g. no mkdirp-logic required.
* @throws [`FileExists`](#FileSystemProviderError.FileExists) when `destination` exists and when the `overwrite` option is not `true`.
* @throws [`NoPermissions`](#FileSystemProviderError.NoPermissions) when permissions aren't sufficient.
*/
export type FileCopyFn = (
source: Uri,
destination: Uri,
options: { overwrite: boolean },
) => void | Thenable<void | FileStat>;
/**
* @param {(string)} uri
* @returns {Promise<boolean>}
*/
export type FileAccessFn = (uri: Uri, mode: number) => Promise<boolean>;
export type FileGetCurrentUserHomeFn = () => Promise<FileStat | undefined>;
/**
* 返回文件的后缀名,目录则返回 'directory',找不到则返回 undefined
* @param uri string
*/
export type FileGetFileTypeFn = (uri: string) => Promise<string | undefined>;
interface ExtendedFileFns {
copy: FileCopyFn;
access: FileAccessFn;
getCurrentUserHome: FileGetCurrentUserHomeFn;
getFileType: FileGetFileTypeFn;
}
/**
* 判断一个对象是否包含某个方法
* @param obj object
* @param prop string
*/
export function containsExtraFileMethod<X extends {}, Y extends keyof ExtendedFileFns>(
obj: X,
prop: Y,
): obj is X & Record<Y, ExtendedFileFns[Y]> {
return hasProperty<X, Y>(obj, prop) && isFunction<ExtendedFileFns[Y]>(obj[prop]);
}
export interface IDiskFileProvider extends FileSystemProvider {
copy: FileCopyFn;
access: FileAccessFn;
getCurrentUserHome: FileGetCurrentUserHomeFn;
getFileType: FileGetFileTypeFn;
setWatchFileExcludes(excludes: string[]): void | Thenable<void>;
getWatchFileExcludes(): string[] | Thenable<string[]>;
}
export type IShadowFileProvider = FileSystemProvider;
/**
* Inner FileSystemProvider:内部实现的 Provider,可以直接在NODE主进程使用的,用FileSystemProvider标记
* Insert FileSystemProvider: 一般指通过插件API注入进来的 Provider,主进程无法直接使用,用ID来标记,远程调用
*/
export type InnerOrInsertFileSystemProvider = FileSystemProvider | number;
export function notEmpty<T>(value: T | undefined): value is T {
return value !== undefined;
}
export function isErrnoException(error: any | NodeJS.ErrnoException): error is NodeJS.ErrnoException {
return (error as NodeJS.ErrnoException).code !== undefined && (error as NodeJS.ErrnoException).errno !== undefined;
}
export function handleError(error: any | NodeJS.ErrnoException): never {
if (isErrnoException(error)) {
switch (error.code) {
case 'EEXIST':
throw FileSystemError.FileExists(Uri.file(error.path ?? ''));
case 'EPERM':
case 'EACCESS':
throw FileSystemError.FileIsNoPermissions(Uri.file(error.path ?? ''));
case 'ENOENT':
throw FileSystemError.FileNotFound(Uri.file(error.path ?? ''));
case 'ENOTDIR':
throw FileSystemError.FileNotADirectory(Uri.file(error.path ?? ''));
case 'EISDIR':
throw FileSystemError.FileIsADirectory(Uri.file(error.path ?? ''));
}
}
throw error;
}
export interface IFileSystemProviderRegistrationEvent {
added: boolean;
scheme: string;
provider?: FileSystemProvider;
}
export interface IFileSystemProviderCapabilitiesChangeEvent {
provider: FileSystemProvider;
scheme: string;
}
export interface IFileSystemProviderActivationEvent {
readonly scheme: string;
}