-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathfile-service.ts
1778 lines (1447 loc) · 79.5 KB
/
file-service.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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************************
* Copyright (C) 2020 TypeFox 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
********************************************************************************/
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// based on https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/platform/files/common/fileService.ts
// and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/textfile/browser/textFileService.ts
// and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/textfile/electron-browser/nativeTextFileService.ts
// and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/workingCopy/common/workingCopyFileService.ts
// and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/workingCopy/common/workingCopyFileOperationParticipant.ts
/* eslint-disable max-len */
/* eslint-disable no-shadow */
/* eslint-disable no-null/no-null */
/* eslint-disable @typescript-eslint/tslint/config */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { injectable, inject, named, postConstruct } from 'inversify';
import URI from '@theia/core/lib/common/uri';
import { timeout, Deferred } from '@theia/core/lib/common/promise-util';
import { CancellationToken, CancellationTokenSource } from '@theia/core/lib/common/cancellation';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { WaitUntilEvent, Emitter, AsyncEmitter } from '@theia/core/lib/common/event';
import { ContributionProvider } from '@theia/core/lib/common/contribution-provider';
import { TernarySearchTree } from '@theia/core/lib/common/ternary-search-tree';
import {
ensureFileSystemProviderError, etag, ETAG_DISABLED,
FileChangesEvent,
FileOperation, FileOperationError,
FileOperationEvent, FileOperationResult, FileSystemProviderCapabilities,
FileSystemProviderErrorCode, FileType, hasFileFolderCopyCapability, hasOpenReadWriteCloseCapability, hasReadWriteCapability,
CreateFileOptions, FileContent, FileStat, FileStatWithMetadata,
FileStreamContent, FileSystemProvider,
FileSystemProviderWithFileReadWriteCapability, FileSystemProviderWithOpenReadWriteCloseCapability,
ReadFileOptions, ResolveFileOptions, ResolveMetadataFileOptions,
Stat, WatchOptions, WriteFileOptions,
toFileOperationResult, toFileSystemProviderErrorCode,
ResolveFileResult, ResolveFileResultWithMetadata,
MoveFileOptions, CopyFileOptions, BaseStatWithMetadata, FileDeleteOptions, FileOperationOptions, hasAccessCapability, hasUpdateCapability,
hasFileReadStreamCapability, FileSystemProviderWithFileReadStreamCapability
} from '../common/files';
import { BinaryBuffer, BinaryBufferReadable, BinaryBufferReadableStream, BinaryBufferReadableBufferedStream, BinaryBufferWriteableStream } from '@theia/core/lib/common/buffer';
import { ReadableStream, isReadableStream, isReadableBufferedStream, transform, consumeStream, peekStream, peekReadable, Readable } from '@theia/core/lib/common/stream';
import { LabelProvider } from '@theia/core/lib/browser/label-provider';
import { FileSystemPreferences } from './filesystem-preferences';
import { ProgressService } from '@theia/core/lib/common/progress-service';
import { DelegatingFileSystemProvider } from '../common/delegating-file-system-provider';
import type { TextDocumentContentChangeEvent } from 'vscode-languageserver-protocol';
import { EncodingRegistry } from '@theia/core/lib/browser/encoding-registry';
import { UTF8, UTF8_with_bom } from '@theia/core/lib/common/encodings';
import { EncodingService, ResourceEncoding, DecodeStreamResult } from '@theia/core/lib/common/encoding-service';
import { Mutable } from '@theia/core/lib/common/types';
import { readFileIntoStream } from '../common/io';
import { FileSystemWatcherErrorHandler } from './filesystem-watcher-error-handler';
export interface FileOperationParticipant {
/**
* Participate in a file operation of a working copy. Allows to
* change the working copy before it is being saved to disk.
*/
participate(
target: URI,
source: URI | undefined,
operation: FileOperation,
timeout: number,
token: CancellationToken
): Promise<void>;
}
export interface ReadEncodingOptions {
/**
* The optional encoding parameter allows to specify the desired encoding when resolving
* the contents of the file.
*/
encoding?: string;
/**
* The optional guessEncoding parameter allows to guess encoding from content of the file.
*/
autoGuessEncoding?: boolean;
}
export interface WriteEncodingOptions {
/**
* The encoding to use when updating a file.
*/
encoding?: string;
/**
* If set to true, will enforce the selected encoding and not perform any detection using BOMs.
*/
overwriteEncoding?: boolean;
}
export interface ReadTextFileOptions extends ReadEncodingOptions, ReadFileOptions {
/**
* The optional acceptTextOnly parameter allows to fail this request early if the file
* contents are not textual.
*/
acceptTextOnly?: boolean;
}
interface BaseTextFileContent extends BaseStatWithMetadata {
/**
* The encoding of the content if known.
*/
encoding: string;
}
export interface TextFileContent extends BaseTextFileContent {
/**
* The content of a text file.
*/
value: string;
}
export interface TextFileStreamContent extends BaseTextFileContent {
/**
* The line grouped content of a text file.
*/
value: ReadableStream<string>;
}
export interface CreateTextFileOptions extends WriteEncodingOptions, CreateFileOptions { }
export interface WriteTextFileOptions extends WriteEncodingOptions, WriteFileOptions { }
export interface UpdateTextFileOptions extends WriteEncodingOptions, WriteFileOptions {
readEncoding: string
}
export interface UserFileOperationEvent extends WaitUntilEvent {
/**
* An identifier to correlate the operation through the
* different event types (before, after, error).
*/
readonly correlationId: number;
/**
* The file operation that is taking place.
*/
readonly operation: FileOperation;
/**
* The resource the event is about.
*/
readonly target: URI;
/**
* A property that is defined for move operations.
*/
readonly source?: URI;
}
export const FileServiceContribution = Symbol('FileServiceContribution');
/**
* A {@link FileServiceContribution} can be used to add custom {@link FileSystemProvider}s.
* For this, the contribution has to listen to the {@link FileSystemProviderActivationEvent} and register
* the custom {@link FileSystemProvider}s according to the scheme when this event is fired.
*
* ### Example usage
* ```ts
* export class MyFileServiceContribution implements FileServiceContribution {
* registerFileSystemProviders(service: FileService): void {
* service.onWillActivateFileSystemProvider(event => {
* if (event.scheme === 'mySyncProviderScheme') {
* service.registerProvider('mySyncProviderScheme', this.mySyncProvider);
* }
* if (event.scheme === 'myAsyncProviderScheme') {
* event.waitUntil((async () => {
* const myAsyncProvider = await this.createAsyncProvider();
* service.registerProvider('myAsyncProviderScheme', myAsyncProvider);
* })());
* }
* });
*
* }
*```
*/
export interface FileServiceContribution {
/**
* Register custom file system providers for the given {@link FileService}.
* @param service The file service for which the providers should be registered.
*/
registerFileSystemProviders(service: FileService): void;
}
/**
* Represents the `FileSystemProviderRegistration` event.
* This event is fired by the {@link FileService} if a {@link FileSystemProvider} is
* registered to or unregistered from the service.
*/
export interface FileSystemProviderRegistrationEvent {
/** `True` if a new provider has been registered, `false` if a provider has been unregistered. */
added: boolean;
/** The (uri) scheme for which the provider was (previously) registered */
scheme: string;
/** The affected file system provider for which this event was fired. */
provider?: FileSystemProvider;
}
/**
* Represents the `FileSystemProviderCapabilitiesChange` event.
* This event is fired by the {@link FileService} if the capabilities of one of its managed
* {@link FileSystemProvider}s have changed.
*/
export interface FileSystemProviderCapabilitiesChangeEvent {
/** The affected file system provider for which this event was fired. */
provider: FileSystemProvider;
/** The (uri) scheme for which the provider is registered */
scheme: string;
}
/**
* Represents the `FileSystemProviderActivation` event.
* This event is fired by the {@link FileService} if it wants to activate the
* {@link FileSystemProvider} for a specific scheme.
*/
export interface FileSystemProviderActivationEvent extends WaitUntilEvent {
/** The (uri) scheme for which the provider should be activated */
scheme: string;
}
export const enum TextFileOperationResult {
FILE_IS_BINARY
}
export class TextFileOperationError extends FileOperationError {
constructor(
message: string,
public textFileOperationResult: TextFileOperationResult,
public options?: ReadTextFileOptions & WriteTextFileOptions
) {
super(message, FileOperationResult.FILE_OTHER_ERROR);
Object.setPrototypeOf(this, TextFileOperationError.prototype);
}
}
/**
* The {@link FileService} is the common facade responsible for all interactions with file systems.
* It manages all registered {@link FileSystemProvider}s and
* forwards calls to the responsible {@link FileSystemProvider}, determined by the scheme.
* For additional documentation regarding the provided functions see also {@link FileSystemProvider}.
*/
@injectable()
export class FileService {
private readonly BUFFER_SIZE = 64 * 1024;
@inject(LabelProvider)
protected readonly labelProvider: LabelProvider;
@inject(FileSystemPreferences)
protected readonly preferences: FileSystemPreferences;
@inject(ProgressService)
protected readonly progressService: ProgressService;
@inject(EncodingRegistry)
protected readonly encodingRegistry: EncodingRegistry;
@inject(EncodingService)
protected readonly encodingService: EncodingService;
@inject(ContributionProvider) @named(FileServiceContribution)
protected readonly contributions: ContributionProvider<FileServiceContribution>;
@inject(FileSystemWatcherErrorHandler)
protected readonly watcherErrorHandler: FileSystemWatcherErrorHandler;
@postConstruct()
protected init(): void {
for (const contribution of this.contributions.getContributions()) {
contribution.registerFileSystemProviders(this);
}
}
// #region Events
private correlationIds = 0;
private readonly onWillRunUserOperationEmitter = new AsyncEmitter<UserFileOperationEvent>();
/**
* An event that is emitted when file operation is being performed.
* This event is triggered by user gestures.
*/
readonly onWillRunUserOperation = this.onWillRunUserOperationEmitter.event;
private readonly onDidFailUserOperationEmitter = new AsyncEmitter<UserFileOperationEvent>();
/**
* An event that is emitted when file operation is failed.
* This event is triggered by user gestures.
*/
readonly onDidFailUserOperation = this.onDidFailUserOperationEmitter.event;
private readonly onDidRunUserOperationEmitter = new AsyncEmitter<UserFileOperationEvent>();
/**
* An event that is emitted when file operation is finished.
* This event is triggered by user gestures.
*/
readonly onDidRunUserOperation = this.onDidRunUserOperationEmitter.event;
// #endregion
// #region File System Provider
private onDidChangeFileSystemProviderRegistrationsEmitter = new Emitter<FileSystemProviderRegistrationEvent>();
readonly onDidChangeFileSystemProviderRegistrations = this.onDidChangeFileSystemProviderRegistrationsEmitter.event;
private onWillActivateFileSystemProviderEmitter = new Emitter<FileSystemProviderActivationEvent>();
/**
* See `FileServiceContribution.registerProviders`.
*/
readonly onWillActivateFileSystemProvider = this.onWillActivateFileSystemProviderEmitter.event;
private onDidChangeFileSystemProviderCapabilitiesEmitter = new Emitter<FileSystemProviderCapabilitiesChangeEvent>();
readonly onDidChangeFileSystemProviderCapabilities = this.onDidChangeFileSystemProviderCapabilitiesEmitter.event;
private readonly providers = new Map<string, FileSystemProvider>();
private readonly activations = new Map<string, Promise<FileSystemProvider>>();
/**
* Registers a new {@link FileSystemProvider} for the given scheme.
* @param scheme The (uri) scheme for which the provider should be registered.
* @param provider The file system provider that should be registered.
*
* @returns A `Disposable` that can be invoked to unregister the given provider.
*/
registerProvider(scheme: string, provider: FileSystemProvider): Disposable {
if (this.providers.has(scheme)) {
throw new Error(`A filesystem provider for the scheme '${scheme}' is already registered.`);
}
this.providers.set(scheme, provider);
this.onDidChangeFileSystemProviderRegistrationsEmitter.fire({ added: true, scheme, provider });
const providerDisposables = new DisposableCollection();
providerDisposables.push(provider.onDidChangeFile(changes => this.onDidFilesChangeEmitter.fire(new FileChangesEvent(changes))));
providerDisposables.push(provider.onFileWatchError(() => this.handleFileWatchError()));
providerDisposables.push(provider.onDidChangeCapabilities(() => this.onDidChangeFileSystemProviderCapabilitiesEmitter.fire({ provider, scheme })));
return Disposable.create(() => {
this.onDidChangeFileSystemProviderRegistrationsEmitter.fire({ added: false, scheme, provider });
this.providers.delete(scheme);
providerDisposables.dispose();
});
}
/**
* Try to activate the registered provider for the given scheme
* @param scheme The uri scheme for which the responsible provider should be activated.
*
* @returns A promise of the activated file system provider. Only resolves if a provider is available for this scheme, gets rejected otherwise.
*/
async activateProvider(scheme: string): Promise<FileSystemProvider> {
let provider = this.providers.get(scheme);
if (provider) {
return provider;
}
let activation = this.activations.get(scheme);
if (!activation) {
const deferredActivation = new Deferred<FileSystemProvider>();
this.activations.set(scheme, activation = deferredActivation.promise);
WaitUntilEvent.fire(this.onWillActivateFileSystemProviderEmitter, { scheme }).then(() => {
provider = this.providers.get(scheme);
if (!provider) {
const error = new Error();
error.name = 'ENOPRO';
error.message = `No file system provider found for scheme ${scheme}`;
throw error;
} else {
deferredActivation.resolve(provider);
}
}).catch(e => deferredActivation.reject(e));
}
return activation;
}
/**
* Tests if the service (i.e. any of its registered {@link FileSystemProvider}s) can handle the given resource.
* @param resource `URI` of the resource to test.
*
* @returns `true` if the resource can be handled, `false` otherwise.
*/
canHandleResource(resource: URI): boolean {
return this.providers.has(resource.scheme);
}
/**
* Tests if the service (i.e the {@link FileSystemProvider} registered for the given uri scheme) provides the given capability.
* @param resource `URI` of the resource to test.
* @param capability The required capability.
*
* @returns `true` if the resource can be handled and the required capability can be provided.
*/
hasCapability(resource: URI, capability: FileSystemProviderCapabilities): boolean {
const provider = this.providers.get(resource.scheme);
return !!(provider && (provider.capabilities & capability));
}
protected async withProvider(resource: URI): Promise<FileSystemProvider> {
// Assert path is absolute
if (!resource.path.isAbsolute) {
throw new FileOperationError(`Unable to resolve filesystem provider with relative file path ${this.resourceForError(resource)}`, FileOperationResult.FILE_INVALID_PATH);
}
return this.activateProvider(resource.scheme);
}
private async withReadProvider(resource: URI): Promise<FileSystemProviderWithFileReadWriteCapability | FileSystemProviderWithOpenReadWriteCloseCapability> {
const provider = await this.withProvider(resource);
if (hasOpenReadWriteCloseCapability(provider) || hasReadWriteCapability(provider)) {
return provider;
}
throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite, FileReadStream nor FileOpenReadWriteClose capability which is needed for the read operation.`);
}
private async withWriteProvider(resource: URI): Promise<FileSystemProviderWithFileReadWriteCapability | FileSystemProviderWithOpenReadWriteCloseCapability> {
const provider = await this.withProvider(resource);
if (hasOpenReadWriteCloseCapability(provider) || hasReadWriteCapability(provider)) {
return provider;
}
throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite nor FileOpenReadWriteClose capability which is needed for the write operation.`);
}
// #endregion
private onDidRunOperationEmitter = new Emitter<FileOperationEvent>();
/**
* An event that is emitted when operation is finished.
* This event is triggered by user gestures and programmatically.
*/
readonly onDidRunOperation = this.onDidRunOperationEmitter.event;
/**
* Try to resolve file information and metadata for the given resource.
* @param resource `URI` of the resource that should be resolved.
* @param options Options to customize the resolvement process.
*
* @return A promise that resolves if the resource could be successfully resolved.
*/
resolve(resource: URI, options: ResolveMetadataFileOptions): Promise<FileStatWithMetadata>;
resolve(resource: URI, options?: ResolveFileOptions | undefined): Promise<FileStat>;
async resolve(resource: any, options?: any) {
try {
return await this.doResolveFile(resource, options);
} catch (error) {
// Specially handle file not found case as file operation result
if (toFileSystemProviderErrorCode(error) === FileSystemProviderErrorCode.FileNotFound) {
throw new FileOperationError(`Unable to resolve non-existing file '${this.resourceForError(resource)}'`, FileOperationResult.FILE_NOT_FOUND);
}
// Bubble up any other error as is
throw ensureFileSystemProviderError(error);
}
}
private async doResolveFile(resource: URI, options: ResolveMetadataFileOptions): Promise<FileStatWithMetadata>;
private async doResolveFile(resource: URI, options?: ResolveFileOptions): Promise<FileStat>;
private async doResolveFile(resource: URI, options?: ResolveFileOptions): Promise<FileStat> {
const provider = await this.withProvider(resource);
const resolveTo = options?.resolveTo;
const resolveSingleChildDescendants = options?.resolveSingleChildDescendants;
const resolveMetadata = options?.resolveMetadata;
const stat = await provider.stat(resource);
let trie: TernarySearchTree<URI, boolean> | undefined;
return this.toFileStat(provider, resource, stat, undefined, !!resolveMetadata, (stat, siblings) => {
// lazy trie to check for recursive resolving
if (!trie) {
trie = TernarySearchTree.forUris<true>(!!(provider.capabilities & FileSystemProviderCapabilities.PathCaseSensitive));
trie.set(resource, true);
if (Array.isArray(resolveTo) && resolveTo.length) {
resolveTo.forEach(uri => trie!.set(uri, true));
}
}
// check for recursive resolving
if (Boolean(trie.findSuperstr(stat.resource) || trie.get(stat.resource))) {
return true;
}
// check for resolving single child folders
if (stat.isDirectory && resolveSingleChildDescendants) {
return siblings === 1;
}
return false;
});
}
private async toFileStat(provider: FileSystemProvider, resource: URI, stat: Stat | { type: FileType } & Partial<Stat>, siblings: number | undefined, resolveMetadata: boolean, recurse: (stat: FileStat, siblings?: number) => boolean): Promise<FileStat>;
private async toFileStat(provider: FileSystemProvider, resource: URI, stat: Stat, siblings: number | undefined, resolveMetadata: true, recurse: (stat: FileStat, siblings?: number) => boolean): Promise<FileStatWithMetadata>;
private async toFileStat(provider: FileSystemProvider, resource: URI, stat: Stat | { type: FileType } & Partial<Stat>, siblings: number | undefined, resolveMetadata: boolean, recurse: (stat: FileStat, siblings?: number) => boolean): Promise<FileStat> {
const fileStat = FileStat.fromStat(resource, stat);
// check to recurse for directories
if (fileStat.isDirectory && recurse(fileStat, siblings)) {
try {
const entries = await provider.readdir(resource);
const resolvedEntries = await Promise.all(entries.map(async ([name, type]) => {
try {
const childResource = resource.resolve(name);
const childStat = resolveMetadata ? await provider.stat(childResource) : { type };
return await this.toFileStat(provider, childResource, childStat, entries.length, resolveMetadata, recurse);
} catch (error) {
console.trace(error);
return null; // can happen e.g. due to permission errors
}
}));
// make sure to get rid of null values that signal a failure to resolve a particular entry
fileStat.children = resolvedEntries.filter(e => !!e) as FileStat[];
} catch (error) {
console.trace(error);
fileStat.children = []; // gracefully handle errors, we may not have permissions to read
}
return fileStat;
}
return fileStat;
}
/**
* Try to resolve file information and metadata for all given resource.
* @param toResolve An array of all the resources (and corresponding resolvement options) that should be resolved.
*
* @returns A promise of all resolved resources. The promise is not rejected if any of the given resources cannot be resolved.
* Instead this is reflected with the `success` flag of the corresponding {@link ResolveFileResult}.
*/
async resolveAll(toResolve: { resource: URI, options?: ResolveFileOptions }[]): Promise<ResolveFileResult[]>;
async resolveAll(toResolve: { resource: URI, options: ResolveMetadataFileOptions }[]): Promise<ResolveFileResultWithMetadata[]>;
async resolveAll(toResolve: { resource: URI; options?: ResolveFileOptions; }[]): Promise<ResolveFileResult[]> {
return Promise.all(toResolve.map(async entry => {
try {
return { stat: await this.doResolveFile(entry.resource, entry.options), success: true };
} catch (error) {
console.trace(error);
return { stat: undefined, success: false };
}
}));
}
/**
* Tests if the given resource exists in the filesystem.
* @param resource `URI` of the resource which should be tested.
* @throws Will throw an error if no {@link FileSystemProvider} is registered for the given resource.
*
* @returns A promise that resolves to `true` if the resource exists.
*/
async exists(resource: URI): Promise<boolean> {
const provider = await this.withProvider(resource);
try {
const stat = await provider.stat(resource);
return !!stat;
} catch (error) {
return false;
}
}
/**
* Tests a user's permissions for the given resource.
*/
async access(resource: URI, mode?: number): Promise<boolean> {
const provider = await this.withProvider(resource);
if (!hasAccessCapability(provider)) {
return false;
}
try {
await provider.access(resource, mode);
return true;
} catch (error) {
return false;
}
}
/**
* Resolves the fs path of the given URI.
*
* USE WITH CAUTION: You should always prefer URIs to paths if possible, as they are
* portable and platform independent. Paths should only be used in cases you directly
* interact with the OS, e.g. when running a command on the shell.
*
* If you need to display human readable simple or long names then use `LabelProvider` instead.
* @param resource `URI` of the resource that should be resolved.
* @throws Will throw an error if no {@link FileSystemProvider} is registered for the given resource.
*
* @returns A promise of the resolved fs path.
*/
async fsPath(resource: URI): Promise<string> {
const provider = await this.withProvider(resource);
if (!hasAccessCapability(provider)) {
return resource.path.toString();
}
return provider.fsPath(resource);
}
// #region Text File Reading/Writing
async create(resource: URI, value?: string | Readable<string>, options?: CreateTextFileOptions): Promise<FileStatWithMetadata> {
if (options?.fromUserGesture === false) {
return this.doCreate(resource, value, options);
}
await this.runFileOperationParticipants(resource, undefined, FileOperation.CREATE);
const event = { correlationId: this.correlationIds++, operation: FileOperation.CREATE, target: resource };
await this.onWillRunUserOperationEmitter.fire(event);
let stat: FileStatWithMetadata;
try {
stat = await this.doCreate(resource, value, options);
} catch (error) {
await this.onDidFailUserOperationEmitter.fire(event);
throw error;
}
await this.onDidRunUserOperationEmitter.fire(event);
return stat;
}
protected async doCreate(resource: URI, value?: string | Readable<string>, options?: CreateTextFileOptions): Promise<FileStatWithMetadata> {
const encoding = await this.getWriteEncoding(resource, options);
const encoded = await this.encodingService.encodeStream(value, encoding);
return this.createFile(resource, encoded, options);
}
async write(resource: URI, value: string | Readable<string>, options?: WriteTextFileOptions): Promise<FileStatWithMetadata & { encoding: string }> {
const encoding = await this.getWriteEncoding(resource, options);
const encoded = await this.encodingService.encodeStream(value, encoding);
return Object.assign(await this.writeFile(resource, encoded, options), { encoding: encoding.encoding });
}
async read(resource: URI, options?: ReadTextFileOptions): Promise<TextFileContent> {
const [bufferStream, decoder] = await this.doRead(resource, {
...options,
// optimization: since we know that the caller does not
// care about buffering, we indicate this to the reader.
// this reduces all the overhead the buffered reading
// has (open, read, close) if the provider supports
// unbuffered reading.
preferUnbuffered: true
});
return {
...bufferStream,
encoding: decoder.detected.encoding || UTF8,
value: await consumeStream(decoder.stream, strings => strings.join(''))
};
}
async readStream(resource: URI, options?: ReadTextFileOptions): Promise<TextFileStreamContent> {
const [bufferStream, decoder] = await this.doRead(resource, options);
return {
...bufferStream,
encoding: decoder.detected.encoding || UTF8,
value: decoder.stream
};
}
private async doRead(resource: URI, options?: ReadTextFileOptions & { preferUnbuffered?: boolean }): Promise<[FileStreamContent, DecodeStreamResult]> {
options = this.resolveReadOptions(options);
// read stream raw (either buffered or unbuffered)
let bufferStream: FileStreamContent;
if (options?.preferUnbuffered) {
const content = await this.readFile(resource, options);
bufferStream = {
...content,
value: BinaryBufferReadableStream.fromBuffer(content.value)
};
} else {
bufferStream = await this.readFileStream(resource, options);
}
const decoder = await this.encodingService.decodeStream(bufferStream.value, {
guessEncoding: options.autoGuessEncoding,
overwriteEncoding: detectedEncoding => this.getReadEncoding(resource, options, detectedEncoding)
});
// validate binary
if (options?.acceptTextOnly && decoder.detected.seemsBinary) {
throw new TextFileOperationError('File seems to be binary and cannot be opened as text', TextFileOperationResult.FILE_IS_BINARY, options);
}
return [bufferStream, decoder];
}
protected resolveReadOptions(options?: ReadTextFileOptions): ReadTextFileOptions {
options = {
...options,
autoGuessEncoding: typeof options?.autoGuessEncoding === 'boolean' ? options.autoGuessEncoding : this.preferences['files.autoGuessEncoding']
};
const limits: Mutable<ReadTextFileOptions['limits']> = options.limits = options.limits || {};
if (typeof limits.size !== 'number') {
limits.size = this.preferences['files.maxFileSizeMB'] * 1024 * 1024;
}
return options;
}
async update(resource: URI, changes: TextDocumentContentChangeEvent[], options: UpdateTextFileOptions): Promise<FileStatWithMetadata & { encoding: string }> {
const provider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(resource), resource);
try {
await this.validateWriteFile(provider, resource, options);
if (hasUpdateCapability(provider)) {
const encoding = await this.getEncodingForResource(resource, options ? options.encoding : undefined);;
const stat = await provider.updateFile(resource, changes, {
readEncoding: options.readEncoding,
writeEncoding: encoding,
overwriteEncoding: options.overwriteEncoding || false
});
return Object.assign(FileStat.fromStat(resource, stat), { encoding: stat.encoding });
} else {
throw new Error('incremental file update is not supported');
}
} catch (error) {
this.rethrowAsFileOperationError('Unable to write file', resource, error, options);
}
}
// #endregion
// #region File Reading/Writing
async createFile(resource: URI, bufferOrReadableOrStream: BinaryBuffer | BinaryBufferReadable | BinaryBufferReadableStream = BinaryBuffer.fromString(''), options?: CreateFileOptions): Promise<FileStatWithMetadata> {
// validate overwrite
if (!options?.overwrite && await this.exists(resource)) {
throw new FileOperationError(`Unable to create file '${this.resourceForError(resource)}' that already exists when overwrite flag is not set`, FileOperationResult.FILE_MODIFIED_SINCE, options);
}
// do write into file (this will create it too)
const fileStat = await this.writeFile(resource, bufferOrReadableOrStream);
// events
this.onDidRunOperationEmitter.fire(new FileOperationEvent(resource, FileOperation.CREATE, fileStat));
return fileStat;
}
async writeFile(resource: URI, bufferOrReadableOrStream: BinaryBuffer | BinaryBufferReadable | BinaryBufferReadableStream, options?: WriteFileOptions): Promise<FileStatWithMetadata> {
const provider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(resource), resource);
try {
// validate write
const stat = await this.validateWriteFile(provider, resource, options);
// mkdir recursively as needed
if (!stat) {
await this.mkdirp(provider, resource.parent);
}
// optimization: if the provider has unbuffered write capability and the data
// to write is a Readable, we consume up to 3 chunks and try to write the data
// unbuffered to reduce the overhead. If the Readable has more data to provide
// we continue to write buffered.
let bufferOrReadableOrStreamOrBufferedStream: BinaryBuffer | BinaryBufferReadable | BinaryBufferReadableStream | BinaryBufferReadableBufferedStream;
if (hasReadWriteCapability(provider) && !(bufferOrReadableOrStream instanceof BinaryBuffer)) {
if (isReadableStream(bufferOrReadableOrStream)) {
const bufferedStream = await peekStream(bufferOrReadableOrStream, 3);
if (bufferedStream.ended) {
bufferOrReadableOrStreamOrBufferedStream = BinaryBuffer.concat(bufferedStream.buffer);
} else {
bufferOrReadableOrStreamOrBufferedStream = bufferedStream;
}
} else {
bufferOrReadableOrStreamOrBufferedStream = peekReadable(bufferOrReadableOrStream, data => BinaryBuffer.concat(data), 3);
}
} else {
bufferOrReadableOrStreamOrBufferedStream = bufferOrReadableOrStream;
}
// write file: unbuffered (only if data to write is a buffer, or the provider has no buffered write capability)
if (!hasOpenReadWriteCloseCapability(provider) || (hasReadWriteCapability(provider) && bufferOrReadableOrStreamOrBufferedStream instanceof BinaryBuffer)) {
await this.doWriteUnbuffered(provider, resource, bufferOrReadableOrStreamOrBufferedStream);
}
// write file: buffered
else {
await this.doWriteBuffered(provider, resource, bufferOrReadableOrStreamOrBufferedStream instanceof BinaryBuffer ? BinaryBufferReadable.fromBuffer(bufferOrReadableOrStreamOrBufferedStream) : bufferOrReadableOrStreamOrBufferedStream);
}
} catch (error) {
this.rethrowAsFileOperationError('Unable to write file', resource, error, options);
}
return this.resolve(resource, { resolveMetadata: true });
}
private async validateWriteFile(provider: FileSystemProvider, resource: URI, options?: WriteFileOptions): Promise<Stat | undefined> {
let stat: Stat | undefined = undefined;
try {
stat = await provider.stat(resource);
} catch (error) {
return undefined; // file might not exist
}
// file cannot be directory
if ((stat.type & FileType.Directory) !== 0) {
throw new FileOperationError(`Unable to write file ${this.resourceForError(resource)} that is actually a directory`, FileOperationResult.FILE_IS_DIRECTORY, options);
}
if (this.modifiedSince(stat, options)) {
throw new FileOperationError('File Modified Since', FileOperationResult.FILE_MODIFIED_SINCE, options);
}
return stat;
}
/**
* Dirty write prevention: if the file on disk has been changed and does not match our expected
* mtime and etag, we bail out to prevent dirty writing.
*
* First, we check for a mtime that is in the future before we do more checks. The assumption is
* that only the mtime is an indicator for a file that has changed on disk.
*
* Second, if the mtime has advanced, we compare the size of the file on disk with our previous
* one using the etag() function. Relying only on the mtime check has proven to produce false
* positives due to file system weirdness (especially around remote file systems). As such, the
* check for size is a weaker check because it can return a false negative if the file has changed
* but to the same length. This is a compromise we take to avoid having to produce checksums of
* the file content for comparison which would be much slower to compute.
*/
protected modifiedSince(stat: Stat, options?: WriteFileOptions): boolean {
return !!options && typeof options.mtime === 'number' && typeof options.etag === 'string' && options.etag !== ETAG_DISABLED &&
typeof stat.mtime === 'number' && typeof stat.size === 'number' &&
options.mtime < stat.mtime && options.etag !== etag({ mtime: options.mtime /* not using stat.mtime for a reason, see above */, size: stat.size });
}
async readFile(resource: URI, options?: ReadFileOptions): Promise<FileContent> {
const provider = await this.withReadProvider(resource);
const stream = await this.doReadAsFileStream(provider, resource, {
...options,
// optimization: since we know that the caller does not
// care about buffering, we indicate this to the reader.
// this reduces all the overhead the buffered reading
// has (open, read, close) if the provider supports
// unbuffered reading.
preferUnbuffered: true
});
return {
...stream,
value: await BinaryBufferReadableStream.toBuffer(stream.value)
};
}
async readFileStream(resource: URI, options?: ReadFileOptions): Promise<FileStreamContent> {
const provider = await this.withReadProvider(resource);
return this.doReadAsFileStream(provider, resource, options);
}
private async doReadAsFileStream(provider: FileSystemProviderWithFileReadWriteCapability | FileSystemProviderWithOpenReadWriteCloseCapability, resource: URI, options?: ReadFileOptions & { preferUnbuffered?: boolean }): Promise<FileStreamContent> {
// install a cancellation token that gets cancelled
// when any error occurs. this allows us to resolve
// the content of the file while resolving metadata
// but still cancel the operation in certain cases.
const cancellableSource = new CancellationTokenSource();
// validate read operation
const statPromise = this.validateReadFile(resource, options).then(stat => stat, error => {
cancellableSource.cancel();
throw error;
});
try {
// if the etag is provided, we await the result of the validation
// due to the likelyhood of hitting a NOT_MODIFIED_SINCE result.
// otherwise, we let it run in parallel to the file reading for
// optimal startup performance.
if (options && typeof options.etag === 'string' && options.etag !== ETAG_DISABLED) {
await statPromise;
}
let fileStreamPromise: Promise<BinaryBufferReadableStream>;
// read unbuffered (only if either preferred, or the provider has no buffered read capability)
if (!(hasOpenReadWriteCloseCapability(provider) || hasFileReadStreamCapability(provider)) || (hasReadWriteCapability(provider) && options?.preferUnbuffered)) {
fileStreamPromise = this.readFileUnbuffered(provider, resource, options);
}
// read streamed (always prefer over primitive buffered read)
else if (hasFileReadStreamCapability(provider)) {
fileStreamPromise = Promise.resolve(this.readFileStreamed(provider, resource, cancellableSource.token, options));
}
// read buffered
else {
fileStreamPromise = Promise.resolve(this.readFileBuffered(provider, resource, cancellableSource.token, options));
}
const [fileStat, fileStream] = await Promise.all([statPromise, fileStreamPromise]);
return {
...fileStat,
value: fileStream
};
} catch (error) {
this.rethrowAsFileOperationError('Unable to read file', resource, error, options);
}
}
private readFileStreamed(provider: FileSystemProviderWithFileReadStreamCapability, resource: URI, token: CancellationToken, options: ReadFileOptions = Object.create(null)): BinaryBufferReadableStream {
const fileStream = provider.readFileStream(resource, options, token);
return transform(fileStream, {
data: data => data instanceof BinaryBuffer ? data : BinaryBuffer.wrap(data),
error: error => this.asFileOperationError('Unable to read file', resource, error, options)
}, data => BinaryBuffer.concat(data));
}
private readFileBuffered(provider: FileSystemProviderWithOpenReadWriteCloseCapability, resource: URI, token: CancellationToken, options: ReadFileOptions = Object.create(null)): BinaryBufferReadableStream {
const stream = BinaryBufferWriteableStream.create();
readFileIntoStream(provider, resource, stream, data => data, {
...options,
bufferSize: this.BUFFER_SIZE,
errorTransformer: error => this.asFileOperationError('Unable to read file', resource, error, options)
}, token);
return stream;
}
protected rethrowAsFileOperationError(message: string, resource: URI, error: Error, options?: ReadFileOptions & WriteFileOptions & CreateFileOptions): never {
throw this.asFileOperationError(message, resource, error, options);
}
protected asFileOperationError(message: string, resource: URI, error: Error, options?: ReadFileOptions & WriteFileOptions & CreateFileOptions): FileOperationError {
const fileOperationError = new FileOperationError(`${message} '${this.resourceForError(resource)}' (${ensureFileSystemProviderError(error).toString()})`,
toFileOperationResult(error), options);
fileOperationError.stack = `${fileOperationError.stack}\nCaused by: ${error.stack}`;
return fileOperationError;
}
private async readFileUnbuffered(provider: FileSystemProviderWithFileReadWriteCapability, resource: URI, options?: ReadFileOptions): Promise<BinaryBufferReadableStream> {
let buffer = await provider.readFile(resource);
// respect position option
if (options && typeof options.position === 'number') {
buffer = buffer.slice(options.position);
}
// respect length option
if (options && typeof options.length === 'number') {
buffer = buffer.slice(0, options.length);
}
// Throw if file is too large to load
this.validateReadFileLimits(resource, buffer.byteLength, options);
return BinaryBufferReadableStream.fromBuffer(BinaryBuffer.wrap(buffer));
}