forked from microsoft/vscode-cosmosdb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabasesFileSystem.ts
More file actions
219 lines (189 loc) · 8.59 KB
/
DatabasesFileSystem.ts
File metadata and controls
219 lines (189 loc) · 8.59 KB
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {
callWithTelemetryAndErrorHandling,
DialogResponses,
UserCancelledError,
type IActionContext,
} from '@microsoft/vscode-azext-utils';
import * as l10n from '@vscode/l10n';
import { parse as parseQuery, stringify as stringifyQuery, type ParsedUrlQuery } from 'querystring';
import * as vscode from 'vscode';
import {
type Disposable,
type Event,
type FileChangeEvent,
type FileChangeType,
type FileStat,
type FileSystemProvider,
type MessageItem,
type TextDocumentShowOptions,
type Uri,
} from 'vscode';
import { ext } from './extensionVariables';
import { SettingsService } from './services/SettingsService';
import { nonNullProp } from './utils/nonNull';
import { getNodeEditorLabel } from './utils/vscodeUtils';
const unsupportedError: Error = new Error(l10n.t('This operation is not supported.'));
export interface EditableFileSystemItem {
id: string;
filePath: string;
cTime: number;
mTime: number;
getFileContent(context: IActionContext): Promise<string>;
writeFileContent(context: IActionContext, data: string): Promise<void>;
refresh?(context: IActionContext): Promise<void>;
}
export class DatabasesFileSystem implements FileSystemProvider {
public static scheme: string = 'azureDatabases';
public scheme: string = DatabasesFileSystem.scheme;
private showSaveConfirmation: boolean = true;
private readonly itemCache = new Map<string, EditableFileSystemItem>();
private readonly eventEmitter = new vscode.EventEmitter<FileChangeEvent[]>();
private readonly bufferedEvents: FileChangeEvent[] = [];
private fireSoonHandle?: NodeJS.Timeout;
// region FileSystemProvider Members
public get onDidChangeFile(): Event<FileChangeEvent[]> {
return this.eventEmitter.event;
}
public watch(): Disposable {
return new vscode.Disposable((): void => {
// Since we're not actually watching "in Azure" (i.e. polling for changes), there's no need to selectively watch based on the UriUri passed in here. Thus, there's nothing to dispose
});
}
public async stat(uri: Uri): Promise<FileStat> {
return (
(await callWithTelemetryAndErrorHandling('stat', async (context) => {
context.telemetry.suppressIfSuccessful = true;
const item = this.lookup(context, uri);
const size = Buffer.byteLength(await item.getFileContent(context));
return { type: vscode.FileType.File, ctime: item.cTime, mtime: item.mTime, size };
})) || { type: vscode.FileType.Unknown, ctime: 0, mtime: 0, size: 0 }
);
}
public readDirectory(): never {
throw unsupportedError;
}
public createDirectory(): never {
throw unsupportedError;
}
public async readFile(uri: Uri): Promise<Uint8Array> {
return (
(await callWithTelemetryAndErrorHandling('readFile', async (context) => {
context.errorHandling.rethrow = true;
context.errorHandling.suppressDisplay = true;
context.telemetry.eventVersion = 2;
const item = this.lookup(context, uri);
return Buffer.from(await item.getFileContent(context));
})) || Buffer.from('')
);
}
public async writeFile(uri: Uri, content: Uint8Array): Promise<void> {
await callWithTelemetryAndErrorHandling('writeFile', async (context) => {
const item = this.lookup(context, uri);
const showSavePromptKey: string = 'showSavePrompt';
// NOTE: Using "cosmosDB" instead of "azureDatabases" here for the sake of backwards compatibility. If/when this file system adds support for non-cosmosdb items, we should consider changing this to "azureDatabases"
const prefix: string = 'cosmosDB';
const nodeEditorLabel: string = getNodeEditorLabel(item);
if (this.showSaveConfirmation && SettingsService.getSetting<boolean>(showSavePromptKey, prefix)) {
const message: string = l10n.t('Saving "{path}" will update the entity "{name}" to the cloud.', {
path: item.filePath,
name: nodeEditorLabel,
});
const result: MessageItem | undefined = await context.ui.showWarningMessage(
message,
{ stepName: 'writeFile' },
DialogResponses.upload,
DialogResponses.alwaysUpload,
DialogResponses.dontUpload,
);
if (result === DialogResponses.alwaysUpload) {
await SettingsService.updateGlobalSetting(showSavePromptKey, false, prefix);
} else if (result === DialogResponses.dontUpload) {
throw new UserCancelledError('dontUpload');
}
}
await item.writeFileContent(context, content.toString());
this.fireChangedEvent(item);
await vscode.commands.executeCommand('azureDatabases.refresh', item);
const updatedMessage: string = l10n.t('Updated entity "{name}".', { name: nodeEditorLabel });
ext.outputChannel.appendLog(updatedMessage);
await item.refresh?.(context);
});
}
public delete(): never {
throw unsupportedError;
}
public rename(): never {
throw unsupportedError;
}
// endregion
// region Public Methods
public async updateWithoutPrompt(uri: Uri): Promise<void> {
const textDoc = await vscode.workspace.openTextDocument(uri);
this.showSaveConfirmation = false;
try {
await textDoc.save();
} finally {
this.showSaveConfirmation = true;
}
}
public async showTextDocument(item: EditableFileSystemItem, options?: TextDocumentShowOptions): Promise<void> {
const uri = this.getUriFromItem(item);
this.itemCache.set(item.id, item);
await vscode.window.showTextDocument(uri, options);
}
// endregion
private fireChangedEvent(item: EditableFileSystemItem): void {
item.mTime = Date.now();
this.fireSoon({ type: vscode.FileChangeType.Changed, item });
}
/**
* Uses a simple buffer to group events that occur within a few milliseconds of each other
* Adapted from https://github.com/microsoft/vscode-extension-samples/blob/master/fsprovider-sample/src/fileSystemProvider.ts
*/
private fireSoon(...events: { type: FileChangeType; item: EditableFileSystemItem }[]): void {
this.bufferedEvents.push(
...events.map((e) => {
return {
type: e.type,
uri: this.getUriFromItem(e.item),
};
}),
);
if (this.fireSoonHandle) {
clearTimeout(this.fireSoonHandle);
}
this.fireSoonHandle = setTimeout(() => {
this.eventEmitter.fire(this.bufferedEvents);
this.bufferedEvents.length = 0; // clear buffer
}, 5);
}
private getUriFromItem(item: EditableFileSystemItem): Uri {
const query: string = stringifyQuery({ id: item.id });
const filePath: string = encodeURIComponent(item.filePath);
return vscode.Uri.parse(`${this.scheme}:///${filePath}?${query}`);
}
private lookup(context: IActionContext, uri: Uri): EditableFileSystemItem | never {
const item = this.itemCache.get(this.getQueryFromUri(uri).id);
if (!item) {
context.telemetry.suppressAll = true;
context.errorHandling.rethrow = true;
context.errorHandling.suppressDisplay = true;
throw vscode.FileSystemError.FileNotFound(uri);
} else {
return item;
}
}
private getQueryFromUri(uri: Uri): { id: string; [key: string]: string | string[] | undefined } {
const query: ParsedUrlQuery = parseQuery(uri.query);
const id: string | string[] = nonNullProp(query, 'id');
if (typeof id === 'string') {
return Object.assign(query, { id }); // Not technically necessary to use `Object.assign`, but it's better than casting which would lose type validation
} else {
throw new Error('Internal Error: Expected "id" to be type string.');
}
}
}