/
file-resource.ts
361 lines (335 loc) · 15.3 KB
/
file-resource.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
// *****************************************************************************
// Copyright (C) 2018 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-only WITH Classpath-exception-2.0
// *****************************************************************************
import { injectable, inject } from '@theia/core/shared/inversify';
import { Resource, ResourceVersion, ResourceResolver, ResourceError, ResourceSaveOptions } from '@theia/core/lib/common/resource';
import { DisposableCollection } from '@theia/core/lib/common/disposable';
import { Emitter, Event } from '@theia/core/lib/common/event';
import { Readable, ReadableStream } from '@theia/core/lib/common/stream';
import URI from '@theia/core/lib/common/uri';
import { FileOperation, FileOperationError, FileOperationResult, ETAG_DISABLED, FileSystemProviderCapabilities, FileReadStreamOptions, BinarySize } from '../common/files';
import { FileService, TextFileOperationError, TextFileOperationResult } from './file-service';
import { ConfirmDialog, Dialog } from '@theia/core/lib/browser/dialogs';
import { LabelProvider } from '@theia/core/lib/browser/label-provider';
import { GENERAL_MAX_FILE_SIZE_MB } from './filesystem-preferences';
import { FrontendApplicationStateService } from '@theia/core/lib/browser/frontend-application-state';
import { nls } from '@theia/core';
export interface FileResourceVersion extends ResourceVersion {
readonly encoding: string;
readonly mtime: number;
readonly etag: string;
}
export namespace FileResourceVersion {
export function is(version: ResourceVersion | undefined): version is FileResourceVersion {
return !!version && 'encoding' in version && 'mtime' in version && 'etag' in version;
}
}
export interface FileResourceOptions {
isReadonly: boolean
shouldOverwrite: () => Promise<boolean>
shouldOpenAsText: (error: string) => Promise<boolean>
}
export class FileResource implements Resource {
protected acceptTextOnly = true;
protected limits: FileReadStreamOptions['limits'];
protected readonly toDispose = new DisposableCollection();
protected readonly onDidChangeContentsEmitter = new Emitter<void>();
readonly onDidChangeContents: Event<void> = this.onDidChangeContentsEmitter.event;
protected _version: FileResourceVersion | undefined;
get version(): FileResourceVersion | undefined {
return this._version;
}
get encoding(): string | undefined {
return this._version?.encoding;
}
get isReadonly(): boolean {
return this.options.isReadonly || this.fileService.hasCapability(this.uri, FileSystemProviderCapabilities.Readonly);
}
constructor(
readonly uri: URI,
protected readonly fileService: FileService,
protected readonly options: FileResourceOptions
) {
this.toDispose.push(this.onDidChangeContentsEmitter);
this.toDispose.push(this.fileService.onDidFilesChange(event => {
if (event.contains(this.uri)) {
this.sync();
}
}));
this.toDispose.push(this.fileService.onDidRunOperation(e => {
if ((e.isOperation(FileOperation.DELETE) || e.isOperation(FileOperation.MOVE)) && e.resource.isEqualOrParent(this.uri)) {
this.sync();
}
}));
try {
this.toDispose.push(this.fileService.watch(this.uri));
} catch (e) {
console.error(e);
}
this.updateSavingContentChanges();
this.toDispose.push(this.fileService.onDidChangeFileSystemProviderCapabilities(e => {
if (e.scheme === this.uri.scheme) {
this.updateSavingContentChanges();
}
}));
}
dispose(): void {
this.toDispose.dispose();
}
async readContents(options?: { encoding?: string }): Promise<string> {
try {
const encoding = options?.encoding || this.version?.encoding;
const stat = await this.fileService.read(this.uri, {
encoding,
etag: ETAG_DISABLED,
acceptTextOnly: this.acceptTextOnly,
limits: this.limits
});
this._version = {
encoding: stat.encoding,
etag: stat.etag,
mtime: stat.mtime
};
return stat.value;
} catch (e) {
if (e instanceof TextFileOperationError && e.textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY) {
if (await this.shouldOpenAsText(nls.localize('theia/filesystem/fileResource/binaryTitle', 'The file is either binary or uses an unsupported text encoding.'))) {
this.acceptTextOnly = false;
return this.readContents(options);
}
} else if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_TOO_LARGE) {
const stat = await this.fileService.resolve(this.uri, { resolveMetadata: true });
const maxFileSize = GENERAL_MAX_FILE_SIZE_MB * 1024 * 1024;
if (this.limits?.size !== maxFileSize && await this.shouldOpenAsText(nls.localize(
'theia/filesystem/fileResource/largeFileTitle', 'The file is too large ({0}).', BinarySize.formatSize(stat.size)))) {
this.limits = {
size: maxFileSize
};
return this.readContents(options);
}
} else if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
this._version = undefined;
const { message, stack } = e;
throw ResourceError.NotFound({
message, stack,
data: {
uri: this.uri
}
});
}
throw e;
}
}
async readStream(options?: { encoding?: string }): Promise<ReadableStream<string>> {
try {
const encoding = options?.encoding || this.version?.encoding;
const stat = await this.fileService.readStream(this.uri, {
encoding,
etag: ETAG_DISABLED,
acceptTextOnly: this.acceptTextOnly,
limits: this.limits
});
this._version = {
encoding: stat.encoding,
etag: stat.etag,
mtime: stat.mtime
};
return stat.value;
} catch (e) {
if (e instanceof TextFileOperationError && e.textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY) {
if (await this.shouldOpenAsText(nls.localize('theia/filesystem/fileResource/binaryTitle', 'The file is either binary or uses an unsupported text encoding.'))) {
this.acceptTextOnly = false;
return this.readStream(options);
}
} else if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_TOO_LARGE) {
const stat = await this.fileService.resolve(this.uri, { resolveMetadata: true });
const maxFileSize = GENERAL_MAX_FILE_SIZE_MB * 1024 * 1024;
if (this.limits?.size !== maxFileSize && await this.shouldOpenAsText(nls.localize(
'theia/filesystem/fileResource/largeFileTitle', 'The file is too large ({0}).', BinarySize.formatSize(stat.size)))) {
this.limits = {
size: maxFileSize
};
return this.readStream(options);
}
} else if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
this._version = undefined;
const { message, stack } = e;
throw ResourceError.NotFound({
message, stack,
data: {
uri: this.uri
}
});
}
throw e;
}
}
protected doWrite = async (content: string | Readable<string>, options?: ResourceSaveOptions): Promise<void> => {
const version = options?.version || this._version;
const current = FileResourceVersion.is(version) ? version : undefined;
const etag = current?.etag;
try {
const stat = await this.fileService.write(this.uri, content, {
encoding: options?.encoding,
overwriteEncoding: options?.overwriteEncoding,
etag,
mtime: current?.mtime
});
this._version = {
etag: stat.etag,
mtime: stat.mtime,
encoding: stat.encoding
};
} catch (e) {
if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
if (etag !== ETAG_DISABLED && await this.shouldOverwrite()) {
return this.doWrite(content, { ...options, version: { stat: { ...current, etag: ETAG_DISABLED } } });
}
const { message, stack } = e;
throw ResourceError.OutOfSync({ message, stack, data: { uri: this.uri } });
}
throw e;
}
};
saveStream?: Resource['saveStream'];
saveContents?: Resource['saveContents'];
saveContentChanges?: Resource['saveContentChanges'];
protected updateSavingContentChanges(): void {
if (this.isReadonly) {
delete this.saveContentChanges;
delete this.saveContents;
delete this.saveStream;
} else {
this.saveContents = this.doWrite;
this.saveStream = this.doWrite;
if (this.fileService.hasCapability(this.uri, FileSystemProviderCapabilities.Update)) {
this.saveContentChanges = this.doSaveContentChanges;
}
}
}
protected doSaveContentChanges: Resource['saveContentChanges'] = async (changes, options) => {
const version = options?.version || this._version;
const current = FileResourceVersion.is(version) ? version : undefined;
if (!current) {
throw ResourceError.NotFound({ message: 'has not been read yet', data: { uri: this.uri } });
}
const etag = current?.etag;
try {
const stat = await this.fileService.update(this.uri, changes, {
readEncoding: current.encoding,
encoding: options?.encoding,
overwriteEncoding: options?.overwriteEncoding,
etag,
mtime: current?.mtime
});
this._version = {
etag: stat.etag,
mtime: stat.mtime,
encoding: stat.encoding
};
} catch (e) {
if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
const { message, stack } = e;
throw ResourceError.NotFound({ message, stack, data: { uri: this.uri } });
}
if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) {
const { message, stack } = e;
throw ResourceError.OutOfSync({ message, stack, data: { uri: this.uri } });
}
throw e;
}
};
async guessEncoding(): Promise<string> {
// TODO limit size
const content = await this.fileService.read(this.uri, { autoGuessEncoding: true });
return content.encoding;
}
protected async sync(): Promise<void> {
if (await this.isInSync()) {
return;
}
this.onDidChangeContentsEmitter.fire(undefined);
}
protected async isInSync(): Promise<boolean> {
try {
const stat = await this.fileService.resolve(this.uri, { resolveMetadata: true });
return !!this.version && this.version.mtime >= stat.mtime;
} catch {
return !this.version;
}
}
protected async shouldOverwrite(): Promise<boolean> {
return this.options.shouldOverwrite();
}
protected async shouldOpenAsText(error: string): Promise<boolean> {
return this.options.shouldOpenAsText(error);
}
}
@injectable()
export class FileResourceResolver implements ResourceResolver {
@inject(FileService)
protected readonly fileService: FileService;
@inject(LabelProvider)
protected readonly labelProvider: LabelProvider;
@inject(FrontendApplicationStateService)
protected readonly applicationState: FrontendApplicationStateService;
async resolve(uri: URI): Promise<FileResource> {
let stat;
try {
stat = await this.fileService.resolve(uri);
} catch (e) {
if (!(e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND)) {
throw e;
}
}
if (stat && stat.isDirectory) {
throw new Error('The given uri is a directory: ' + this.labelProvider.getLongName(uri));
}
return new FileResource(uri, this.fileService, {
isReadonly: stat?.isReadonly ?? false,
shouldOverwrite: () => this.shouldOverwrite(uri),
shouldOpenAsText: error => this.shouldOpenAsText(uri, error)
});
}
protected async shouldOverwrite(uri: URI): Promise<boolean> {
const dialog = new ConfirmDialog({
title: nls.localize('theia/filesystem/fileResource/overwriteTitle', "The file '{0}' has been changed on the file system.", this.labelProvider.getName(uri)),
msg: nls.localize('theia/fileSystem/fileResource/overWriteBody',
"Do you want to overwrite the changes made to '{0}' on the file system?", this.labelProvider.getLongName(uri)),
ok: Dialog.YES,
cancel: Dialog.NO,
});
return !!await dialog.open();
}
protected async shouldOpenAsText(uri: URI, error: string): Promise<boolean> {
switch (this.applicationState.state) {
case 'init':
case 'started_contributions':
case 'attached_shell':
return true; // We're restoring state - assume that we should open files that were previously open.
default: {
const dialog = new ConfirmDialog({
title: error,
msg: nls.localize('theia/filesystem/fileResource/binaryFileQuery',
"Opening it might take some time and might make the IDE unresponsive. Do you want to open '{0}' anyway?", this.labelProvider.getLongName(uri)
),
ok: Dialog.YES,
cancel: Dialog.NO,
});
return !!await dialog.open();
}
}
}
}