@theia/filesystem 1.34.3 → 1.34.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/LICENSE +641 -641
  2. package/README.md +30 -30
  3. package/lib/browser/breadcrumbs/filepath-breadcrumb.d.ts +15 -15
  4. package/lib/browser/breadcrumbs/filepath-breadcrumb.js +41 -41
  5. package/lib/browser/breadcrumbs/filepath-breadcrumbs-container.d.ts +13 -13
  6. package/lib/browser/breadcrumbs/filepath-breadcrumbs-container.js +78 -78
  7. package/lib/browser/breadcrumbs/filepath-breadcrumbs-contribution.d.ts +27 -27
  8. package/lib/browser/breadcrumbs/filepath-breadcrumbs-contribution.js +126 -126
  9. package/lib/browser/download/file-download-command-contribution.d.ts +18 -18
  10. package/lib/browser/download/file-download-command-contribution.js +83 -83
  11. package/lib/browser/download/file-download-frontend-module.d.ts +3 -3
  12. package/lib/browser/download/file-download-frontend-module.js +25 -25
  13. package/lib/browser/download/file-download-service.d.ts +28 -28
  14. package/lib/browser/download/file-download-service.js +175 -175
  15. package/lib/browser/file-dialog/file-dialog-container.d.ts +5 -5
  16. package/lib/browser/file-dialog/file-dialog-container.js +52 -52
  17. package/lib/browser/file-dialog/file-dialog-model.d.ts +25 -25
  18. package/lib/browser/file-dialog/file-dialog-model.js +108 -108
  19. package/lib/browser/file-dialog/file-dialog-module.d.ts +3 -3
  20. package/lib/browser/file-dialog/file-dialog-module.js +37 -37
  21. package/lib/browser/file-dialog/file-dialog-service.d.ts +32 -32
  22. package/lib/browser/file-dialog/file-dialog-service.js +107 -107
  23. package/lib/browser/file-dialog/file-dialog-tree-filters-renderer.d.ts +39 -39
  24. package/lib/browser/file-dialog/file-dialog-tree-filters-renderer.js +92 -92
  25. package/lib/browser/file-dialog/file-dialog-tree.d.ts +22 -22
  26. package/lib/browser/file-dialog/file-dialog-tree.js +71 -71
  27. package/lib/browser/file-dialog/file-dialog-widget.d.ts +15 -15
  28. package/lib/browser/file-dialog/file-dialog-widget.js +86 -86
  29. package/lib/browser/file-dialog/file-dialog.d.ts +126 -126
  30. package/lib/browser/file-dialog/file-dialog.js +355 -355
  31. package/lib/browser/file-dialog/index.d.ts +4 -4
  32. package/lib/browser/file-dialog/index.js +31 -31
  33. package/lib/browser/file-resource.d.ts +63 -63
  34. package/lib/browser/file-resource.js +352 -352
  35. package/lib/browser/file-selection.d.ts +14 -14
  36. package/lib/browser/file-selection.js +36 -36
  37. package/lib/browser/file-service.d.ts +412 -412
  38. package/lib/browser/file-service.js +1330 -1330
  39. package/lib/browser/file-tree/file-tree-container.d.ts +3 -3
  40. package/lib/browser/file-tree/file-tree-container.js +35 -35
  41. package/lib/browser/file-tree/file-tree-decorator-adapter.d.ts +30 -30
  42. package/lib/browser/file-tree/file-tree-decorator-adapter.js +174 -174
  43. package/lib/browser/file-tree/file-tree-label-provider.d.ts +12 -12
  44. package/lib/browser/file-tree/file-tree-label-provider.js +62 -62
  45. package/lib/browser/file-tree/file-tree-model.d.ts +37 -37
  46. package/lib/browser/file-tree/file-tree-model.js +225 -225
  47. package/lib/browser/file-tree/file-tree-widget.d.ts +44 -44
  48. package/lib/browser/file-tree/file-tree-widget.js +315 -315
  49. package/lib/browser/file-tree/file-tree.d.ts +46 -46
  50. package/lib/browser/file-tree/file-tree.js +184 -184
  51. package/lib/browser/file-tree/index.d.ts +6 -6
  52. package/lib/browser/file-tree/index.js +33 -33
  53. package/lib/browser/file-upload-service.d.ts +98 -98
  54. package/lib/browser/file-upload-service.js +428 -428
  55. package/lib/browser/filesystem-frontend-contribution.d.ts +63 -63
  56. package/lib/browser/filesystem-frontend-contribution.js +324 -324
  57. package/lib/browser/filesystem-frontend-module.d.ts +5 -5
  58. package/lib/browser/filesystem-frontend-module.js +64 -64
  59. package/lib/browser/filesystem-preferences.d.ts +29 -29
  60. package/lib/browser/filesystem-preferences.js +108 -108
  61. package/lib/browser/filesystem-save-resource-service.d.ts +29 -29
  62. package/lib/browser/filesystem-save-resource-service.js +142 -142
  63. package/lib/browser/filesystem-watcher-error-handler.d.ts +10 -10
  64. package/lib/browser/filesystem-watcher-error-handler.js +69 -69
  65. package/lib/browser/index.d.ts +5 -5
  66. package/lib/browser/index.js +32 -32
  67. package/lib/browser/location/index.d.ts +2 -2
  68. package/lib/browser/location/index.js +29 -29
  69. package/lib/browser/location/location-renderer.d.ts +99 -99
  70. package/lib/browser/location/location-renderer.js +351 -351
  71. package/lib/browser/location/location-service.d.ts +5 -5
  72. package/lib/browser/location/location-service.js +17 -17
  73. package/lib/browser/remote-file-service-contribution.d.ts +6 -6
  74. package/lib/browser/remote-file-service-contribution.js +47 -47
  75. package/lib/common/delegating-file-system-provider.d.ts +76 -76
  76. package/lib/common/delegating-file-system-provider.js +168 -168
  77. package/lib/common/download/file-download-data.d.ts +6 -6
  78. package/lib/common/download/file-download-data.js +26 -26
  79. package/lib/common/file-upload.d.ts +1 -1
  80. package/lib/common/file-upload.js +19 -19
  81. package/lib/common/files.d.ts +651 -651
  82. package/lib/common/files.js +347 -347
  83. package/lib/common/files.spec.d.ts +1 -1
  84. package/lib/common/files.spec.js +51 -51
  85. package/lib/common/filesystem-utils.d.ts +14 -14
  86. package/lib/common/filesystem-utils.js +63 -63
  87. package/lib/common/filesystem-utils.spec.d.ts +1 -1
  88. package/lib/common/filesystem-utils.spec.js +378 -378
  89. package/lib/common/filesystem-watcher-protocol.d.ts +71 -71
  90. package/lib/common/filesystem-watcher-protocol.js +20 -20
  91. package/lib/common/filesystem.d.ts +22 -22
  92. package/lib/common/filesystem.js +42 -42
  93. package/lib/common/index.d.ts +2 -2
  94. package/lib/common/index.js +29 -29
  95. package/lib/common/io.d.ts +19 -19
  96. package/lib/common/io.js +110 -110
  97. package/lib/common/remote-file-system-provider.d.ts +164 -164
  98. package/lib/common/remote-file-system-provider.js +413 -413
  99. package/lib/electron-browser/file-dialog/electron-file-dialog-module.d.ts +3 -3
  100. package/lib/electron-browser/file-dialog/electron-file-dialog-module.js +24 -24
  101. package/lib/electron-browser/file-dialog/electron-file-dialog-service.d.ts +58 -58
  102. package/lib/electron-browser/file-dialog/electron-file-dialog-service.js +194 -194
  103. package/lib/node/disk-file-system-provider.d.ts +72 -72
  104. package/lib/node/disk-file-system-provider.js +783 -783
  105. package/lib/node/download/directory-archiver.d.ts +9 -9
  106. package/lib/node/download/directory-archiver.js +132 -132
  107. package/lib/node/download/directory-archiver.spec.d.ts +1 -1
  108. package/lib/node/download/directory-archiver.spec.js +97 -97
  109. package/lib/node/download/file-download-backend-module.d.ts +3 -3
  110. package/lib/node/download/file-download-backend-module.js +32 -32
  111. package/lib/node/download/file-download-cache.d.ts +21 -21
  112. package/lib/node/download/file-download-cache.js +90 -90
  113. package/lib/node/download/file-download-endpoint.d.ts +11 -11
  114. package/lib/node/download/file-download-endpoint.js +75 -75
  115. package/lib/node/download/file-download-handler.d.ts +50 -50
  116. package/lib/node/download/file-download-handler.js +315 -315
  117. package/lib/node/download/test/mock-directory-archiver.d.ts +7 -7
  118. package/lib/node/download/test/mock-directory-archiver.js +29 -29
  119. package/lib/node/file-change-collection.d.ts +22 -22
  120. package/lib/node/file-change-collection.js +77 -77
  121. package/lib/node/file-change-collection.spec.d.ts +1 -1
  122. package/lib/node/file-change-collection.spec.js +90 -90
  123. package/lib/node/filesystem-backend-module.d.ts +26 -26
  124. package/lib/node/filesystem-backend-module.js +120 -120
  125. package/lib/node/filesystem-watcher-client.d.ts +23 -23
  126. package/lib/node/filesystem-watcher-client.js +83 -83
  127. package/lib/node/filesystem-watcher-dispatcher.d.ts +23 -23
  128. package/lib/node/filesystem-watcher-dispatcher.js +85 -85
  129. package/lib/node/node-file-upload-service.d.ts +15 -15
  130. package/lib/node/node-file-upload-service.js +76 -76
  131. package/lib/node/nsfw-watcher/index.d.ts +3 -3
  132. package/lib/node/nsfw-watcher/index.js +39 -39
  133. package/lib/node/nsfw-watcher/nsfw-filesystem-service.d.ts +191 -191
  134. package/lib/node/nsfw-watcher/nsfw-filesystem-service.js +389 -389
  135. package/lib/node/nsfw-watcher/nsfw-filesystem-watcher.spec.d.ts +1 -1
  136. package/lib/node/nsfw-watcher/nsfw-filesystem-watcher.spec.js +151 -151
  137. package/lib/node/nsfw-watcher/nsfw-options.d.ts +6 -6
  138. package/lib/node/nsfw-watcher/nsfw-options.js +22 -22
  139. package/package.json +4 -4
  140. package/src/browser/breadcrumbs/filepath-breadcrumb.ts +43 -43
  141. package/src/browser/breadcrumbs/filepath-breadcrumbs-container.ts +65 -65
  142. package/src/browser/breadcrumbs/filepath-breadcrumbs-contribution.ts +129 -129
  143. package/src/browser/download/file-download-command-contribution.ts +83 -83
  144. package/src/browser/download/file-download-frontend-module.ts +25 -25
  145. package/src/browser/download/file-download-service.ts +179 -179
  146. package/src/browser/file-dialog/file-dialog-container.ts +67 -67
  147. package/src/browser/file-dialog/file-dialog-model.ts +96 -96
  148. package/src/browser/file-dialog/file-dialog-module.ts +36 -36
  149. package/src/browser/file-dialog/file-dialog-service.ts +97 -97
  150. package/src/browser/file-dialog/file-dialog-tree-filters-renderer.tsx +100 -100
  151. package/src/browser/file-dialog/file-dialog-tree.ts +71 -71
  152. package/src/browser/file-dialog/file-dialog-widget.ts +75 -75
  153. package/src/browser/file-dialog/file-dialog.ts +428 -428
  154. package/src/browser/file-dialog/index.ts +20 -20
  155. package/src/browser/file-resource.ts +361 -361
  156. package/src/browser/file-selection.ts +44 -44
  157. package/src/browser/file-service.ts +1814 -1814
  158. package/src/browser/file-tree/file-tree-container.ts +36 -36
  159. package/src/browser/file-tree/file-tree-decorator-adapter.ts +159 -159
  160. package/src/browser/file-tree/file-tree-label-provider.ts +53 -53
  161. package/src/browser/file-tree/file-tree-model.ts +212 -212
  162. package/src/browser/file-tree/file-tree-widget.tsx +327 -327
  163. package/src/browser/file-tree/file-tree.ts +183 -183
  164. package/src/browser/file-tree/index.ts +22 -22
  165. package/src/browser/file-upload-service.ts +513 -513
  166. package/src/browser/filesystem-frontend-contribution.ts +338 -338
  167. package/src/browser/filesystem-frontend-module.ts +77 -77
  168. package/src/browser/filesystem-preferences.ts +138 -138
  169. package/src/browser/filesystem-save-resource-service.ts +124 -124
  170. package/src/browser/filesystem-watcher-error-handler.ts +60 -60
  171. package/src/browser/index.ts +21 -21
  172. package/src/browser/location/index.ts +18 -18
  173. package/src/browser/location/location-renderer.tsx +400 -400
  174. package/src/browser/location/location-service.ts +22 -22
  175. package/src/browser/remote-file-service-contribution.ts +38 -38
  176. package/src/browser/style/file-dialog.css +204 -204
  177. package/src/browser/style/file-icons.css +64 -64
  178. package/src/browser/style/filepath-breadcrumbs.css +20 -20
  179. package/src/browser/style/index.css +36 -36
  180. package/src/common/delegating-file-system-provider.ts +226 -226
  181. package/src/common/download/README.md +30 -30
  182. package/src/common/download/file-download-data.ts +27 -27
  183. package/src/common/file-upload.ts +17 -17
  184. package/src/common/files.spec.ts +51 -51
  185. package/src/common/files.ts +983 -983
  186. package/src/common/filesystem-utils.spec.ts +411 -411
  187. package/src/common/filesystem-utils.ts +64 -64
  188. package/src/common/filesystem-watcher-protocol.ts +96 -96
  189. package/src/common/filesystem.ts +43 -43
  190. package/src/common/index.ts +18 -18
  191. package/src/common/io.ts +150 -150
  192. package/src/common/remote-file-system-provider.ts +511 -511
  193. package/src/electron-browser/file-dialog/electron-file-dialog-module.ts +24 -24
  194. package/src/electron-browser/file-dialog/electron-file-dialog-service.ts +229 -229
  195. package/src/node/disk-file-system-provider.ts +908 -908
  196. package/src/node/download/directory-archiver.spec.ts +104 -104
  197. package/src/node/download/directory-archiver.ts +126 -126
  198. package/src/node/download/file-download-backend-module.ts +32 -32
  199. package/src/node/download/file-download-cache.ts +88 -88
  200. package/src/node/download/file-download-endpoint.ts +63 -63
  201. package/src/node/download/file-download-handler.ts +304 -304
  202. package/src/node/download/test/mock-directory-archiver.ts +30 -30
  203. package/src/node/file-change-collection.spec.ts +110 -110
  204. package/src/node/file-change-collection.ts +78 -78
  205. package/src/node/filesystem-backend-module.ts +140 -140
  206. package/src/node/filesystem-watcher-client.ts +72 -72
  207. package/src/node/filesystem-watcher-dispatcher.ts +82 -82
  208. package/src/node/node-file-upload-service.ts +73 -73
  209. package/src/node/nsfw-watcher/index.ts +45 -45
  210. package/src/node/nsfw-watcher/nsfw-filesystem-service.ts +476 -476
  211. package/src/node/nsfw-watcher/nsfw-filesystem-watcher.spec.ts +182 -182
  212. package/src/node/nsfw-watcher/nsfw-options.ts +23 -23
  213. package/src/typings/dom.webkit.d.ts +77 -77
  214. package/src/typings/mv/index.d.ts +21 -21
  215. package/src/typings/nsfw/index.d.ts +18 -18
  216. package/src/typings/trash/index.d.ts +20 -20
@@ -1,908 +1,908 @@
1
- // *****************************************************************************
2
- // Copyright (C) 2020 TypeFox and others.
3
- //
4
- // This program and the accompanying materials are made available under the
5
- // terms of the Eclipse Public License v. 2.0 which is available at
6
- // http://www.eclipse.org/legal/epl-2.0.
7
- //
8
- // This Source Code may also be made available under the following Secondary
9
- // Licenses when the conditions for such availability set forth in the Eclipse
10
- // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
- // with the GNU Classpath Exception which is available at
12
- // https://www.gnu.org/software/classpath/license.html.
13
- //
14
- // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15
- // *****************************************************************************
16
- /*---------------------------------------------------------------------------------------------
17
- * Copyright (c) Microsoft Corporation. All rights reserved.
18
- * Licensed under the MIT License. See License.txt in the project root for license information.
19
- *--------------------------------------------------------------------------------------------*/
20
- // based on https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/platform/files/node/diskFileSystemProvider.ts
21
-
22
- /* eslint-disable no-null/no-null */
23
- /* eslint-disable @typescript-eslint/no-shadow */
24
-
25
- import { injectable, inject, postConstruct } from '@theia/core/shared/inversify';
26
- import { basename, dirname, normalize, join } from 'path';
27
- import { v4 } from 'uuid';
28
- import * as os from 'os';
29
- import * as fs from 'fs';
30
- import {
31
- mkdir, open, close, read, write, fdatasync, Stats,
32
- lstat, stat, readdir, readFile, exists, chmod,
33
- rmdir, unlink, rename, futimes, truncate
34
- } from 'fs';
35
- import { promisify } from 'util';
36
- import URI from '@theia/core/lib/common/uri';
37
- import { Path } from '@theia/core/lib/common/path';
38
- import { FileUri } from '@theia/core/lib/node/file-uri';
39
- import { Event, Emitter } from '@theia/core/lib/common/event';
40
- import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
41
- import { OS, isWindows } from '@theia/core/lib/common/os';
42
- import { retry } from '@theia/core/lib/common/promise-util';
43
- import {
44
- FileSystemProviderWithFileReadWriteCapability, FileSystemProviderWithOpenReadWriteCloseCapability, FileSystemProviderWithFileFolderCopyCapability,
45
- FileSystemProviderCapabilities,
46
- Stat,
47
- FileType,
48
- FileWriteOptions,
49
- createFileSystemProviderError,
50
- FileSystemProviderErrorCode,
51
- FileOpenOptions,
52
- FileDeleteOptions,
53
- FileOverwriteOptions,
54
- FileSystemProviderError,
55
- FileChange,
56
- WatchOptions,
57
- FileUpdateOptions, FileUpdateResult, FileReadStreamOptions
58
- } from '../common/files';
59
- import { FileSystemWatcherServer } from '../common/filesystem-watcher-protocol';
60
- import trash = require('trash');
61
- import { TextDocumentContentChangeEvent } from '@theia/core/shared/vscode-languageserver-protocol';
62
- import { TextDocument } from 'vscode-languageserver-textdocument';
63
- import { EncodingService } from '@theia/core/lib/common/encoding-service';
64
- import { BinaryBuffer } from '@theia/core/lib/common/buffer';
65
- import { ReadableStreamEvents, newWriteableStream } from '@theia/core/lib/common/stream';
66
- import { CancellationToken } from '@theia/core/lib/common/cancellation';
67
- import { readFileIntoStream } from '../common/io';
68
-
69
- export namespace DiskFileSystemProvider {
70
- export interface StatAndLink {
71
-
72
- // The stats of the file. If the file is a symbolic
73
- // link, the stats will be of that target file and
74
- // not the link itself.
75
- // If the file is a symbolic link pointing to a non
76
- // existing file, the stat will be of the link and
77
- // the `dangling` flag will indicate this.
78
- stat: fs.Stats;
79
-
80
- // Will be provided if the resource is a symbolic link
81
- // on disk. Use the `dangling` flag to find out if it
82
- // points to a resource that does not exist on disk.
83
- symbolicLink?: { dangling: boolean };
84
- }
85
- }
86
-
87
- @injectable()
88
- export class DiskFileSystemProvider implements Disposable,
89
- FileSystemProviderWithFileReadWriteCapability,
90
- FileSystemProviderWithOpenReadWriteCloseCapability,
91
- FileSystemProviderWithFileFolderCopyCapability {
92
-
93
- private readonly BUFFER_SIZE = 64 * 1024;
94
-
95
- private readonly onDidChangeFileEmitter = new Emitter<readonly FileChange[]>();
96
- readonly onDidChangeFile = this.onDidChangeFileEmitter.event;
97
-
98
- private readonly onFileWatchErrorEmitter = new Emitter<void>();
99
- readonly onFileWatchError = this.onFileWatchErrorEmitter.event;
100
-
101
- protected readonly toDispose = new DisposableCollection(
102
- this.onDidChangeFileEmitter
103
- );
104
-
105
- @inject(FileSystemWatcherServer)
106
- protected readonly watcher: FileSystemWatcherServer;
107
-
108
- @inject(EncodingService)
109
- protected readonly encodingService: EncodingService;
110
-
111
- @postConstruct()
112
- protected init(): void {
113
- this.toDispose.push(this.watcher);
114
- this.watcher.setClient({
115
- onDidFilesChanged: params => this.onDidChangeFileEmitter.fire(params.changes.map(({ uri, type }) => ({
116
- resource: new URI(uri),
117
- type
118
- }))),
119
- onError: () => this.onFileWatchErrorEmitter.fire()
120
- });
121
- }
122
-
123
- // #region File Capabilities
124
-
125
- readonly onDidChangeCapabilities = Event.None;
126
-
127
- protected _capabilities: FileSystemProviderCapabilities | undefined;
128
- get capabilities(): FileSystemProviderCapabilities {
129
- if (!this._capabilities) {
130
- this._capabilities =
131
- FileSystemProviderCapabilities.FileReadWrite |
132
- FileSystemProviderCapabilities.FileOpenReadWriteClose |
133
- FileSystemProviderCapabilities.FileReadStream |
134
- FileSystemProviderCapabilities.FileFolderCopy |
135
- FileSystemProviderCapabilities.Access |
136
- FileSystemProviderCapabilities.Trash |
137
- FileSystemProviderCapabilities.Update;
138
-
139
- if (OS.type() === OS.Type.Linux) {
140
- this._capabilities |= FileSystemProviderCapabilities.PathCaseSensitive;
141
- }
142
- }
143
-
144
- return this._capabilities;
145
- }
146
-
147
- // #endregion
148
-
149
- // #region File Metadata Resolving
150
-
151
- async stat(resource: URI): Promise<Stat> {
152
- try {
153
- const { stat, symbolicLink } = await this.statLink(this.toFilePath(resource)); // cannot use fs.stat() here to support links properly
154
-
155
- return {
156
- type: this.toType(stat, symbolicLink),
157
- ctime: stat.birthtime.getTime(), // intentionally not using ctime here, we want the creation time
158
- mtime: stat.mtime.getTime(),
159
- size: stat.size
160
- };
161
- } catch (error) {
162
- throw this.toFileSystemProviderError(error);
163
- }
164
- }
165
-
166
- async access(resource: URI, mode?: number): Promise<void> {
167
- try {
168
- await promisify(fs.access)(this.toFilePath(resource), mode);
169
- } catch (error) {
170
- throw this.toFileSystemProviderError(error);
171
- }
172
- }
173
-
174
- async fsPath(resource: URI): Promise<string> {
175
- return FileUri.fsPath(resource);
176
- }
177
-
178
- protected async statLink(path: string): Promise<DiskFileSystemProvider.StatAndLink> {
179
-
180
- // First stat the link
181
- let lstats: Stats | undefined;
182
- try {
183
- lstats = await promisify(lstat)(path);
184
-
185
- // Return early if the stat is not a symbolic link at all
186
- if (!lstats.isSymbolicLink()) {
187
- return { stat: lstats };
188
- }
189
- } catch (error) {
190
- /* ignore - use stat() instead */
191
- }
192
-
193
- // If the stat is a symbolic link or failed to stat, use fs.stat()
194
- // which for symbolic links will stat the target they point to
195
- try {
196
- const stats = await promisify(stat)(path);
197
-
198
- return { stat: stats, symbolicLink: lstats?.isSymbolicLink() ? { dangling: false } : undefined };
199
- } catch (error) {
200
-
201
- // If the link points to a non-existing file we still want
202
- // to return it as result while setting dangling: true flag
203
- if (error.code === 'ENOENT' && lstats) {
204
- return { stat: lstats, symbolicLink: { dangling: true } };
205
- }
206
-
207
- throw error;
208
- }
209
- }
210
-
211
- async readdir(resource: URI): Promise<[string, FileType][]> {
212
- try {
213
- const children = await promisify(fs.readdir)(this.toFilePath(resource));
214
-
215
- const result: [string, FileType][] = [];
216
- await Promise.all(children.map(async child => {
217
- try {
218
- const stat = await this.stat(resource.resolve(child));
219
- result.push([child, stat.type]);
220
- } catch (error) {
221
- console.trace(error); // ignore errors for individual entries that can arise from permission denied
222
- }
223
- }));
224
-
225
- return result;
226
- } catch (error) {
227
- throw this.toFileSystemProviderError(error);
228
- }
229
- }
230
-
231
- private toType(entry: Stats, symbolicLink?: { dangling: boolean }): FileType {
232
- // Signal file type by checking for file / directory, except:
233
- // - symbolic links pointing to non-existing files are FileType.Unknown
234
- // - files that are neither file nor directory are FileType.Unknown
235
- let type: FileType;
236
- if (symbolicLink?.dangling) {
237
- type = FileType.Unknown;
238
- } else if (entry.isFile()) {
239
- type = FileType.File;
240
- } else if (entry.isDirectory()) {
241
- type = FileType.Directory;
242
- } else {
243
- type = FileType.Unknown;
244
- }
245
-
246
- // Always signal symbolic link as file type additionally
247
- if (symbolicLink) {
248
- type |= FileType.SymbolicLink;
249
- }
250
-
251
- return type;
252
- }
253
-
254
- // #endregion
255
-
256
- // #region File Reading/Writing
257
-
258
- async readFile(resource: URI): Promise<Uint8Array> {
259
- try {
260
- const filePath = this.toFilePath(resource);
261
-
262
- return await promisify(readFile)(filePath);
263
- } catch (error) {
264
- throw this.toFileSystemProviderError(error);
265
- }
266
- }
267
-
268
- readFileStream(resource: URI, opts: FileReadStreamOptions, token: CancellationToken): ReadableStreamEvents<Uint8Array> {
269
- const stream = newWriteableStream<Uint8Array>(data => BinaryBuffer.concat(data.map(data => BinaryBuffer.wrap(data))).buffer);
270
-
271
- readFileIntoStream(this, resource, stream, data => data.buffer, {
272
- ...opts,
273
- bufferSize: this.BUFFER_SIZE
274
- }, token);
275
-
276
- return stream;
277
- }
278
-
279
- async writeFile(resource: URI, content: Uint8Array, opts: FileWriteOptions): Promise<void> {
280
- let handle: number | undefined = undefined;
281
- try {
282
- const filePath = this.toFilePath(resource);
283
-
284
- // Validate target unless { create: true, overwrite: true }
285
- if (!opts.create || !opts.overwrite) {
286
- const fileExists = await promisify(exists)(filePath);
287
- if (fileExists) {
288
- if (!opts.overwrite) {
289
- throw createFileSystemProviderError('File already exists', FileSystemProviderErrorCode.FileExists);
290
- }
291
- } else {
292
- if (!opts.create) {
293
- throw createFileSystemProviderError('File does not exist', FileSystemProviderErrorCode.FileNotFound);
294
- }
295
- }
296
- }
297
-
298
- // Open
299
- handle = await this.open(resource, { create: true });
300
-
301
- // Write content at once
302
- await this.write(handle, 0, content, 0, content.byteLength);
303
- } catch (error) {
304
- throw this.toFileSystemProviderError(error);
305
- } finally {
306
- if (typeof handle === 'number') {
307
- await this.close(handle);
308
- }
309
- }
310
- }
311
-
312
- private mapHandleToPos: Map<number, number> = new Map();
313
-
314
- private writeHandles: Set<number> = new Set();
315
- private canFlush: boolean = true;
316
-
317
- async open(resource: URI, opts: FileOpenOptions): Promise<number> {
318
- try {
319
- const filePath = this.toFilePath(resource);
320
-
321
- let flags: string | undefined = undefined;
322
- if (opts.create) {
323
- if (isWindows && await promisify(exists)(filePath)) {
324
- try {
325
- // On Windows and if the file exists, we use a different strategy of saving the file
326
- // by first truncating the file and then writing with r+ flag. This helps to save hidden files on Windows
327
- // (see https://github.com/Microsoft/vscode/issues/931) and prevent removing alternate data streams
328
- // (see https://github.com/Microsoft/vscode/issues/6363)
329
- await promisify(truncate)(filePath, 0);
330
-
331
- // After a successful truncate() the flag can be set to 'r+' which will not truncate.
332
- flags = 'r+';
333
- } catch (error) {
334
- console.trace(error);
335
- }
336
- }
337
-
338
- // we take opts.create as a hint that the file is opened for writing
339
- // as such we use 'w' to truncate an existing or create the
340
- // file otherwise. we do not allow reading.
341
- if (!flags) {
342
- flags = 'w';
343
- }
344
- } else {
345
- // otherwise we assume the file is opened for reading
346
- // as such we use 'r' to neither truncate, nor create
347
- // the file.
348
- flags = 'r';
349
- }
350
-
351
- const handle = await promisify(open)(filePath, flags);
352
-
353
- // remember this handle to track file position of the handle
354
- // we init the position to 0 since the file descriptor was
355
- // just created and the position was not moved so far (see
356
- // also http://man7.org/linux/man-pages/man2/open.2.html -
357
- // "The file offset is set to the beginning of the file.")
358
- this.mapHandleToPos.set(handle, 0);
359
-
360
- // remember that this handle was used for writing
361
- if (opts.create) {
362
- this.writeHandles.add(handle);
363
- }
364
-
365
- return handle;
366
- } catch (error) {
367
- throw this.toFileSystemProviderError(error);
368
- }
369
- }
370
-
371
- async close(fd: number): Promise<void> {
372
- try {
373
-
374
- // remove this handle from map of positions
375
- this.mapHandleToPos.delete(fd);
376
-
377
- // if a handle is closed that was used for writing, ensure
378
- // to flush the contents to disk if possible.
379
- if (this.writeHandles.delete(fd) && this.canFlush) {
380
- try {
381
- await promisify(fdatasync)(fd);
382
- } catch (error) {
383
- // In some exotic setups it is well possible that node fails to sync
384
- // In that case we disable flushing and log the error to our logger
385
- this.canFlush = false;
386
- console.error(error);
387
- }
388
- }
389
-
390
- return await promisify(close)(fd);
391
- } catch (error) {
392
- throw this.toFileSystemProviderError(error);
393
- }
394
- }
395
-
396
- async read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
397
- const normalizedPos = this.normalizePos(fd, pos);
398
-
399
- let bytesRead: number | null = null;
400
- try {
401
- const result = await promisify(read)(fd, data, offset, length, normalizedPos);
402
-
403
- if (typeof result === 'number') {
404
- bytesRead = result; // node.d.ts fail
405
- } else {
406
- bytesRead = result.bytesRead;
407
- }
408
-
409
- return bytesRead;
410
- } catch (error) {
411
- throw this.toFileSystemProviderError(error);
412
- } finally {
413
- this.updatePos(fd, normalizedPos, bytesRead);
414
- }
415
- }
416
-
417
- private normalizePos(fd: number, pos: number): number | null {
418
-
419
- // when calling fs.read/write we try to avoid passing in the "pos" argument and
420
- // rather prefer to pass in "null" because this avoids an extra seek(pos)
421
- // call that in some cases can even fail (e.g. when opening a file over FTP -
422
- // see https://github.com/microsoft/vscode/issues/73884).
423
- //
424
- // as such, we compare the passed in position argument with our last known
425
- // position for the file descriptor and use "null" if they match.
426
- if (pos === this.mapHandleToPos.get(fd)) {
427
- return null;
428
- }
429
-
430
- return pos;
431
- }
432
-
433
- private updatePos(fd: number, pos: number | null, bytesLength: number | null): void {
434
- const lastKnownPos = this.mapHandleToPos.get(fd);
435
- if (typeof lastKnownPos === 'number') {
436
-
437
- // pos !== null signals that previously a position was used that is
438
- // not null. node.js documentation explains, that in this case
439
- // the internal file pointer is not moving and as such we do not move
440
- // our position pointer.
441
- //
442
- // Docs: "If position is null, data will be read from the current file position,
443
- // and the file position will be updated. If position is an integer, the file position
444
- // will remain unchanged."
445
- if (typeof pos === 'number') {
446
- // do not modify the position
447
- } else if (typeof bytesLength === 'number') {
448
- this.mapHandleToPos.set(fd, lastKnownPos + bytesLength);
449
- } else {
450
- this.mapHandleToPos.delete(fd);
451
- }
452
- }
453
- }
454
-
455
- async write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
456
- // we know at this point that the file to write to is truncated and thus empty
457
- // if the write now fails, the file remains empty. as such we really try hard
458
- // to ensure the write succeeds by retrying up to three times.
459
- return retry(() => this.doWrite(fd, pos, data, offset, length), 100 /* ms delay */, 3 /* retries */);
460
- }
461
-
462
- private async doWrite(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
463
- const normalizedPos = this.normalizePos(fd, pos);
464
-
465
- let bytesWritten: number | null = null;
466
- try {
467
- const result = await promisify(write)(fd, data, offset, length, normalizedPos);
468
-
469
- if (typeof result === 'number') {
470
- bytesWritten = result; // node.d.ts fail
471
- } else {
472
- bytesWritten = result.bytesWritten;
473
- }
474
-
475
- return bytesWritten;
476
- } catch (error) {
477
- throw this.toFileSystemProviderError(error);
478
- } finally {
479
- this.updatePos(fd, normalizedPos, bytesWritten);
480
- }
481
- }
482
-
483
- // #endregion
484
-
485
- // #region Move/Copy/Delete/Create Folder
486
-
487
- async mkdir(resource: URI): Promise<void> {
488
- try {
489
- await promisify(mkdir)(this.toFilePath(resource));
490
- } catch (error) {
491
- throw this.toFileSystemProviderError(error);
492
- }
493
- }
494
-
495
- async delete(resource: URI, opts: FileDeleteOptions): Promise<void> {
496
- try {
497
- const filePath = this.toFilePath(resource);
498
-
499
- await this.doDelete(filePath, opts);
500
- } catch (error) {
501
- throw this.toFileSystemProviderError(error);
502
- }
503
- }
504
-
505
- protected async doDelete(filePath: string, opts: FileDeleteOptions): Promise<void> {
506
- if (!opts.useTrash) {
507
- if (opts.recursive) {
508
- await this.rimraf(filePath);
509
- } else {
510
- await promisify(unlink)(filePath);
511
- }
512
- } else {
513
- await trash(filePath);
514
- }
515
- }
516
-
517
- protected rimraf(path: string): Promise<void> {
518
- if (new Path(path).isRoot) {
519
- throw new Error('rimraf - will refuse to recursively delete root');
520
- }
521
- return this.rimrafMove(path);
522
- }
523
-
524
- protected async rimrafMove(path: string): Promise<void> {
525
- try {
526
- const pathInTemp = join(os.tmpdir(), v4());
527
- try {
528
- await promisify(rename)(path, pathInTemp);
529
- } catch (error) {
530
- return this.rimrafUnlink(path); // if rename fails, delete without tmp dir
531
- }
532
-
533
- // Delete but do not return as promise
534
- this.rimrafUnlink(pathInTemp);
535
- } catch (error) {
536
- if (error.code !== 'ENOENT') {
537
- throw error;
538
- }
539
- }
540
- }
541
-
542
- protected async rimrafUnlink(path: string): Promise<void> {
543
- try {
544
- const stat = await promisify(lstat)(path);
545
-
546
- // Folder delete (recursive) - NOT for symbolic links though!
547
- if (stat.isDirectory() && !stat.isSymbolicLink()) {
548
-
549
- // Children
550
- const children = await promisify(readdir)(path);
551
- await Promise.all(children.map(child => this.rimrafUnlink(join(path, child))));
552
-
553
- // Folder
554
- await promisify(rmdir)(path);
555
- } else {
556
-
557
- // chmod as needed to allow for unlink
558
- const mode = stat.mode;
559
- if (!(mode & 128)) { // 128 === 0200
560
- await promisify(chmod)(path, mode | 128);
561
- }
562
-
563
- return promisify(unlink)(path);
564
- }
565
- } catch (error) {
566
- if (error.code !== 'ENOENT') {
567
- throw error;
568
- }
569
- }
570
- }
571
-
572
- async rename(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> {
573
- const fromFilePath = this.toFilePath(from);
574
- const toFilePath = this.toFilePath(to);
575
-
576
- if (fromFilePath === toFilePath) {
577
- return; // simulate node.js behaviour here and do a no-op if paths match
578
- }
579
-
580
- try {
581
-
582
- // Ensure target does not exist
583
- await this.validateTargetDeleted(from, to, 'move', opts.overwrite);
584
-
585
- // Move
586
- await this.move(fromFilePath, toFilePath);
587
- } catch (error) {
588
-
589
- // rewrite some typical errors that can happen especially around symlinks
590
- // to something the user can better understand
591
- if (error.code === 'EINVAL' || error.code === 'EBUSY' || error.code === 'ENAMETOOLONG') {
592
- error = new Error(`Unable to move '${basename(fromFilePath)}' into '${basename(dirname(toFilePath))}' (${error.toString()}).`);
593
- }
594
-
595
- throw this.toFileSystemProviderError(error);
596
- }
597
- }
598
-
599
- protected async move(source: string, target: string): Promise<void> {
600
- if (source === target) {
601
- return Promise.resolve();
602
- }
603
-
604
- async function updateMtime(path: string): Promise<void> {
605
- const stat = await promisify(lstat)(path);
606
- if (stat.isDirectory() || stat.isSymbolicLink()) {
607
- return Promise.resolve(); // only for files
608
- }
609
-
610
- const fd = await promisify(open)(path, 'a');
611
- try {
612
- await promisify(futimes)(fd, stat.atime, new Date());
613
- } catch (error) {
614
- // ignore
615
- }
616
-
617
- return promisify(close)(fd);
618
- }
619
-
620
- try {
621
- await promisify(rename)(source, target);
622
- await updateMtime(target);
623
- } catch (error) {
624
-
625
- // In two cases we fallback to classic copy and delete:
626
- //
627
- // 1.) The EXDEV error indicates that source and target are on different devices
628
- // In this case, fallback to using a copy() operation as there is no way to
629
- // rename() between different devices.
630
- //
631
- // 2.) The user tries to rename a file/folder that ends with a dot. This is not
632
- // really possible to move then, at least on UNC devices.
633
- if (source.toLowerCase() !== target.toLowerCase() && error.code === 'EXDEV' || source.endsWith('.')) {
634
- await this.doCopy(source, target);
635
- await this.rimraf(source);
636
- await updateMtime(target);
637
- } else {
638
- throw error;
639
- }
640
- }
641
- }
642
-
643
- async copy(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> {
644
- const fromFilePath = this.toFilePath(from);
645
- const toFilePath = this.toFilePath(to);
646
-
647
- if (fromFilePath === toFilePath) {
648
- return; // simulate node.js behaviour here and do a no-op if paths match
649
- }
650
-
651
- try {
652
-
653
- // Ensure target does not exist
654
- await this.validateTargetDeleted(from, to, 'copy', opts.overwrite);
655
-
656
- // Copy
657
- await this.doCopy(fromFilePath, toFilePath);
658
- } catch (error) {
659
-
660
- // rewrite some typical errors that can happen especially around symlinks
661
- // to something the user can better understand
662
- if (error.code === 'EINVAL' || error.code === 'EBUSY' || error.code === 'ENAMETOOLONG') {
663
- error = new Error(`Unable to copy '${basename(fromFilePath)}' into '${basename(dirname(toFilePath))}' (${error.toString()}).`);
664
- }
665
-
666
- throw this.toFileSystemProviderError(error);
667
- }
668
- }
669
-
670
- private async validateTargetDeleted(from: URI, to: URI, mode: 'move' | 'copy', overwrite?: boolean): Promise<void> {
671
- const isPathCaseSensitive = !!(this.capabilities & FileSystemProviderCapabilities.PathCaseSensitive);
672
-
673
- const fromFilePath = this.toFilePath(from);
674
- const toFilePath = this.toFilePath(to);
675
-
676
- let isSameResourceWithDifferentPathCase = false;
677
- if (!isPathCaseSensitive) {
678
- isSameResourceWithDifferentPathCase = fromFilePath.toLowerCase() === toFilePath.toLowerCase();
679
- }
680
-
681
- if (isSameResourceWithDifferentPathCase && mode === 'copy') {
682
- throw createFileSystemProviderError("'File cannot be copied to same path with different path case", FileSystemProviderErrorCode.FileExists);
683
- }
684
-
685
- // handle existing target (unless this is a case change)
686
- if (!isSameResourceWithDifferentPathCase && await promisify(exists)(toFilePath)) {
687
- if (!overwrite) {
688
- throw createFileSystemProviderError('File at target already exists', FileSystemProviderErrorCode.FileExists);
689
- }
690
-
691
- // Delete target
692
- await this.delete(to, { recursive: true, useTrash: false });
693
- }
694
- }
695
-
696
- protected async doCopy(source: string, target: string, copiedSourcesIn?: { [path: string]: boolean }): Promise<void> {
697
- const copiedSources = copiedSourcesIn ? copiedSourcesIn : Object.create(null);
698
-
699
- const fileStat = await promisify(stat)(source);
700
- if (!fileStat.isDirectory()) {
701
- return this.doCopyFile(source, target, fileStat.mode & 511);
702
- }
703
-
704
- if (copiedSources[source]) {
705
- return Promise.resolve(); // escape when there are cycles (can happen with symlinks)
706
- }
707
-
708
- copiedSources[source] = true; // remember as copied
709
-
710
- // Create folder
711
- await this.mkdirp(target, fileStat.mode & 511);
712
-
713
- // Copy each file recursively
714
- const files = await promisify(readdir)(source);
715
- for (let i = 0; i < files.length; i++) {
716
- const file = files[i];
717
- await this.doCopy(join(source, file), join(target, file), copiedSources);
718
- }
719
- }
720
-
721
- protected async mkdirp(path: string, mode?: number): Promise<void> {
722
- const mkdir = async () => {
723
- try {
724
- await promisify(fs.mkdir)(path, mode);
725
- } catch (error) {
726
-
727
- // ENOENT: a parent folder does not exist yet
728
- if (error.code === 'ENOENT') {
729
- throw error;
730
- }
731
-
732
- // Any other error: check if folder exists and
733
- // return normally in that case if its a folder
734
- let targetIsFile = false;
735
- try {
736
- const fileStat = await promisify(fs.stat)(path);
737
- targetIsFile = !fileStat.isDirectory();
738
- } catch (statError) {
739
- throw error; // rethrow original error if stat fails
740
- }
741
-
742
- if (targetIsFile) {
743
- throw new Error(`'${path}' exists and is not a directory.`);
744
- }
745
- }
746
- };
747
-
748
- // stop at root
749
- if (path === dirname(path)) {
750
- return;
751
- }
752
-
753
- try {
754
- await mkdir();
755
- } catch (error) {
756
-
757
- // ENOENT: a parent folder does not exist yet, continue
758
- // to create the parent folder and then try again.
759
- if (error.code === 'ENOENT') {
760
- await this.mkdirp(dirname(path), mode);
761
-
762
- return mkdir();
763
- }
764
-
765
- // Any other error
766
- throw error;
767
- }
768
- }
769
-
770
- protected doCopyFile(source: string, target: string, mode: number): Promise<void> {
771
- return new Promise((resolve, reject) => {
772
- const reader = fs.createReadStream(source);
773
- const writer = fs.createWriteStream(target, { mode });
774
-
775
- let finished = false;
776
- const finish = (error?: Error) => {
777
- if (!finished) {
778
- finished = true;
779
-
780
- // in error cases, pass to callback
781
- if (error) {
782
- return reject(error);
783
- }
784
-
785
- // we need to explicitly chmod because of https://github.com/nodejs/node/issues/1104
786
- fs.chmod(target, mode, error => error ? reject(error) : resolve());
787
- }
788
- };
789
-
790
- // handle errors properly
791
- reader.once('error', error => finish(error));
792
- writer.once('error', error => finish(error));
793
-
794
- // we are done (underlying fd has been closed)
795
- writer.once('close', () => finish());
796
-
797
- // start piping
798
- reader.pipe(writer);
799
- });
800
- }
801
-
802
- // #endregion
803
-
804
- // #region File Watching
805
-
806
- watch(resource: URI, opts: WatchOptions): Disposable {
807
- const watcherService = this.watcher;
808
- /**
809
- * Disposable handle. Can be disposed early (before the watcher is allocated.)
810
- */
811
- const handle = {
812
- disposed: false,
813
- watcherId: undefined as number | undefined,
814
- dispose(): void {
815
- if (this.disposed) {
816
- return;
817
- }
818
- if (this.watcherId !== undefined) {
819
- watcherService.unwatchFileChanges(this.watcherId);
820
- }
821
- this.disposed = true;
822
- },
823
- };
824
- watcherService.watchFileChanges(resource.toString(), {
825
- // Convert from `files.WatchOptions` to internal `watcher-protocol.WatchOptions`:
826
- ignored: opts.excludes
827
- }).then(watcherId => {
828
- if (handle.disposed) {
829
- watcherService.unwatchFileChanges(watcherId);
830
- } else {
831
- handle.watcherId = watcherId;
832
- }
833
- });
834
- this.toDispose.push(handle);
835
- return handle;
836
- }
837
-
838
- // #endregion
839
-
840
- async updateFile(resource: URI, changes: TextDocumentContentChangeEvent[], opts: FileUpdateOptions): Promise<FileUpdateResult> {
841
- try {
842
- const content = await this.readFile(resource);
843
- const decoded = this.encodingService.decode(BinaryBuffer.wrap(content), opts.readEncoding);
844
- const newContent = TextDocument.update(TextDocument.create('', '', 1, decoded), changes, 2).getText();
845
- const encoding = await this.encodingService.toResourceEncoding(opts.writeEncoding, {
846
- overwriteEncoding: opts.overwriteEncoding,
847
- read: async length => {
848
- const fd = await this.open(resource, { create: false });
849
- try {
850
- const data = new Uint8Array(length);
851
- await this.read(fd, 0, data, 0, length);
852
- return data;
853
- } finally {
854
- await this.close(fd);
855
- }
856
- }
857
- });
858
- const encoded = this.encodingService.encode(newContent, encoding);
859
- await this.writeFile(resource, encoded.buffer, { create: false, overwrite: true });
860
- const stat = await this.stat(resource);
861
- return Object.assign(stat, { encoding: encoding.encoding });
862
- } catch (error) {
863
- throw this.toFileSystemProviderError(error);
864
- }
865
- }
866
-
867
- // #region Helpers
868
-
869
- protected toFilePath(resource: URI): string {
870
- return normalize(FileUri.fsPath(resource));
871
- }
872
-
873
- private toFileSystemProviderError(error: NodeJS.ErrnoException): FileSystemProviderError {
874
- if (error instanceof FileSystemProviderError) {
875
- return error; // avoid double conversion
876
- }
877
-
878
- let code: FileSystemProviderErrorCode;
879
- switch (error.code) {
880
- case 'ENOENT':
881
- code = FileSystemProviderErrorCode.FileNotFound;
882
- break;
883
- case 'EISDIR':
884
- code = FileSystemProviderErrorCode.FileIsADirectory;
885
- break;
886
- case 'ENOTDIR':
887
- code = FileSystemProviderErrorCode.FileNotADirectory;
888
- break;
889
- case 'EEXIST':
890
- code = FileSystemProviderErrorCode.FileExists;
891
- break;
892
- case 'EPERM':
893
- case 'EACCES':
894
- code = FileSystemProviderErrorCode.NoPermissions;
895
- break;
896
- default:
897
- code = FileSystemProviderErrorCode.Unknown;
898
- }
899
-
900
- return createFileSystemProviderError(error, code);
901
- }
902
-
903
- // #endregion
904
-
905
- dispose(): void {
906
- this.toDispose.dispose();
907
- }
908
- }
1
+ // *****************************************************************************
2
+ // Copyright (C) 2020 TypeFox and others.
3
+ //
4
+ // This program and the accompanying materials are made available under the
5
+ // terms of the Eclipse Public License v. 2.0 which is available at
6
+ // http://www.eclipse.org/legal/epl-2.0.
7
+ //
8
+ // This Source Code may also be made available under the following Secondary
9
+ // Licenses when the conditions for such availability set forth in the Eclipse
10
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
+ // with the GNU Classpath Exception which is available at
12
+ // https://www.gnu.org/software/classpath/license.html.
13
+ //
14
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15
+ // *****************************************************************************
16
+ /*---------------------------------------------------------------------------------------------
17
+ * Copyright (c) Microsoft Corporation. All rights reserved.
18
+ * Licensed under the MIT License. See License.txt in the project root for license information.
19
+ *--------------------------------------------------------------------------------------------*/
20
+ // based on https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/platform/files/node/diskFileSystemProvider.ts
21
+
22
+ /* eslint-disable no-null/no-null */
23
+ /* eslint-disable @typescript-eslint/no-shadow */
24
+
25
+ import { injectable, inject, postConstruct } from '@theia/core/shared/inversify';
26
+ import { basename, dirname, normalize, join } from 'path';
27
+ import { v4 } from 'uuid';
28
+ import * as os from 'os';
29
+ import * as fs from 'fs';
30
+ import {
31
+ mkdir, open, close, read, write, fdatasync, Stats,
32
+ lstat, stat, readdir, readFile, exists, chmod,
33
+ rmdir, unlink, rename, futimes, truncate
34
+ } from 'fs';
35
+ import { promisify } from 'util';
36
+ import URI from '@theia/core/lib/common/uri';
37
+ import { Path } from '@theia/core/lib/common/path';
38
+ import { FileUri } from '@theia/core/lib/node/file-uri';
39
+ import { Event, Emitter } from '@theia/core/lib/common/event';
40
+ import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
41
+ import { OS, isWindows } from '@theia/core/lib/common/os';
42
+ import { retry } from '@theia/core/lib/common/promise-util';
43
+ import {
44
+ FileSystemProviderWithFileReadWriteCapability, FileSystemProviderWithOpenReadWriteCloseCapability, FileSystemProviderWithFileFolderCopyCapability,
45
+ FileSystemProviderCapabilities,
46
+ Stat,
47
+ FileType,
48
+ FileWriteOptions,
49
+ createFileSystemProviderError,
50
+ FileSystemProviderErrorCode,
51
+ FileOpenOptions,
52
+ FileDeleteOptions,
53
+ FileOverwriteOptions,
54
+ FileSystemProviderError,
55
+ FileChange,
56
+ WatchOptions,
57
+ FileUpdateOptions, FileUpdateResult, FileReadStreamOptions
58
+ } from '../common/files';
59
+ import { FileSystemWatcherServer } from '../common/filesystem-watcher-protocol';
60
+ import trash = require('trash');
61
+ import { TextDocumentContentChangeEvent } from '@theia/core/shared/vscode-languageserver-protocol';
62
+ import { TextDocument } from 'vscode-languageserver-textdocument';
63
+ import { EncodingService } from '@theia/core/lib/common/encoding-service';
64
+ import { BinaryBuffer } from '@theia/core/lib/common/buffer';
65
+ import { ReadableStreamEvents, newWriteableStream } from '@theia/core/lib/common/stream';
66
+ import { CancellationToken } from '@theia/core/lib/common/cancellation';
67
+ import { readFileIntoStream } from '../common/io';
68
+
69
+ export namespace DiskFileSystemProvider {
70
+ export interface StatAndLink {
71
+
72
+ // The stats of the file. If the file is a symbolic
73
+ // link, the stats will be of that target file and
74
+ // not the link itself.
75
+ // If the file is a symbolic link pointing to a non
76
+ // existing file, the stat will be of the link and
77
+ // the `dangling` flag will indicate this.
78
+ stat: fs.Stats;
79
+
80
+ // Will be provided if the resource is a symbolic link
81
+ // on disk. Use the `dangling` flag to find out if it
82
+ // points to a resource that does not exist on disk.
83
+ symbolicLink?: { dangling: boolean };
84
+ }
85
+ }
86
+
87
+ @injectable()
88
+ export class DiskFileSystemProvider implements Disposable,
89
+ FileSystemProviderWithFileReadWriteCapability,
90
+ FileSystemProviderWithOpenReadWriteCloseCapability,
91
+ FileSystemProviderWithFileFolderCopyCapability {
92
+
93
+ private readonly BUFFER_SIZE = 64 * 1024;
94
+
95
+ private readonly onDidChangeFileEmitter = new Emitter<readonly FileChange[]>();
96
+ readonly onDidChangeFile = this.onDidChangeFileEmitter.event;
97
+
98
+ private readonly onFileWatchErrorEmitter = new Emitter<void>();
99
+ readonly onFileWatchError = this.onFileWatchErrorEmitter.event;
100
+
101
+ protected readonly toDispose = new DisposableCollection(
102
+ this.onDidChangeFileEmitter
103
+ );
104
+
105
+ @inject(FileSystemWatcherServer)
106
+ protected readonly watcher: FileSystemWatcherServer;
107
+
108
+ @inject(EncodingService)
109
+ protected readonly encodingService: EncodingService;
110
+
111
+ @postConstruct()
112
+ protected init(): void {
113
+ this.toDispose.push(this.watcher);
114
+ this.watcher.setClient({
115
+ onDidFilesChanged: params => this.onDidChangeFileEmitter.fire(params.changes.map(({ uri, type }) => ({
116
+ resource: new URI(uri),
117
+ type
118
+ }))),
119
+ onError: () => this.onFileWatchErrorEmitter.fire()
120
+ });
121
+ }
122
+
123
+ // #region File Capabilities
124
+
125
+ readonly onDidChangeCapabilities = Event.None;
126
+
127
+ protected _capabilities: FileSystemProviderCapabilities | undefined;
128
+ get capabilities(): FileSystemProviderCapabilities {
129
+ if (!this._capabilities) {
130
+ this._capabilities =
131
+ FileSystemProviderCapabilities.FileReadWrite |
132
+ FileSystemProviderCapabilities.FileOpenReadWriteClose |
133
+ FileSystemProviderCapabilities.FileReadStream |
134
+ FileSystemProviderCapabilities.FileFolderCopy |
135
+ FileSystemProviderCapabilities.Access |
136
+ FileSystemProviderCapabilities.Trash |
137
+ FileSystemProviderCapabilities.Update;
138
+
139
+ if (OS.type() === OS.Type.Linux) {
140
+ this._capabilities |= FileSystemProviderCapabilities.PathCaseSensitive;
141
+ }
142
+ }
143
+
144
+ return this._capabilities;
145
+ }
146
+
147
+ // #endregion
148
+
149
+ // #region File Metadata Resolving
150
+
151
+ async stat(resource: URI): Promise<Stat> {
152
+ try {
153
+ const { stat, symbolicLink } = await this.statLink(this.toFilePath(resource)); // cannot use fs.stat() here to support links properly
154
+
155
+ return {
156
+ type: this.toType(stat, symbolicLink),
157
+ ctime: stat.birthtime.getTime(), // intentionally not using ctime here, we want the creation time
158
+ mtime: stat.mtime.getTime(),
159
+ size: stat.size
160
+ };
161
+ } catch (error) {
162
+ throw this.toFileSystemProviderError(error);
163
+ }
164
+ }
165
+
166
+ async access(resource: URI, mode?: number): Promise<void> {
167
+ try {
168
+ await promisify(fs.access)(this.toFilePath(resource), mode);
169
+ } catch (error) {
170
+ throw this.toFileSystemProviderError(error);
171
+ }
172
+ }
173
+
174
+ async fsPath(resource: URI): Promise<string> {
175
+ return FileUri.fsPath(resource);
176
+ }
177
+
178
+ protected async statLink(path: string): Promise<DiskFileSystemProvider.StatAndLink> {
179
+
180
+ // First stat the link
181
+ let lstats: Stats | undefined;
182
+ try {
183
+ lstats = await promisify(lstat)(path);
184
+
185
+ // Return early if the stat is not a symbolic link at all
186
+ if (!lstats.isSymbolicLink()) {
187
+ return { stat: lstats };
188
+ }
189
+ } catch (error) {
190
+ /* ignore - use stat() instead */
191
+ }
192
+
193
+ // If the stat is a symbolic link or failed to stat, use fs.stat()
194
+ // which for symbolic links will stat the target they point to
195
+ try {
196
+ const stats = await promisify(stat)(path);
197
+
198
+ return { stat: stats, symbolicLink: lstats?.isSymbolicLink() ? { dangling: false } : undefined };
199
+ } catch (error) {
200
+
201
+ // If the link points to a non-existing file we still want
202
+ // to return it as result while setting dangling: true flag
203
+ if (error.code === 'ENOENT' && lstats) {
204
+ return { stat: lstats, symbolicLink: { dangling: true } };
205
+ }
206
+
207
+ throw error;
208
+ }
209
+ }
210
+
211
+ async readdir(resource: URI): Promise<[string, FileType][]> {
212
+ try {
213
+ const children = await promisify(fs.readdir)(this.toFilePath(resource));
214
+
215
+ const result: [string, FileType][] = [];
216
+ await Promise.all(children.map(async child => {
217
+ try {
218
+ const stat = await this.stat(resource.resolve(child));
219
+ result.push([child, stat.type]);
220
+ } catch (error) {
221
+ console.trace(error); // ignore errors for individual entries that can arise from permission denied
222
+ }
223
+ }));
224
+
225
+ return result;
226
+ } catch (error) {
227
+ throw this.toFileSystemProviderError(error);
228
+ }
229
+ }
230
+
231
+ private toType(entry: Stats, symbolicLink?: { dangling: boolean }): FileType {
232
+ // Signal file type by checking for file / directory, except:
233
+ // - symbolic links pointing to non-existing files are FileType.Unknown
234
+ // - files that are neither file nor directory are FileType.Unknown
235
+ let type: FileType;
236
+ if (symbolicLink?.dangling) {
237
+ type = FileType.Unknown;
238
+ } else if (entry.isFile()) {
239
+ type = FileType.File;
240
+ } else if (entry.isDirectory()) {
241
+ type = FileType.Directory;
242
+ } else {
243
+ type = FileType.Unknown;
244
+ }
245
+
246
+ // Always signal symbolic link as file type additionally
247
+ if (symbolicLink) {
248
+ type |= FileType.SymbolicLink;
249
+ }
250
+
251
+ return type;
252
+ }
253
+
254
+ // #endregion
255
+
256
+ // #region File Reading/Writing
257
+
258
+ async readFile(resource: URI): Promise<Uint8Array> {
259
+ try {
260
+ const filePath = this.toFilePath(resource);
261
+
262
+ return await promisify(readFile)(filePath);
263
+ } catch (error) {
264
+ throw this.toFileSystemProviderError(error);
265
+ }
266
+ }
267
+
268
+ readFileStream(resource: URI, opts: FileReadStreamOptions, token: CancellationToken): ReadableStreamEvents<Uint8Array> {
269
+ const stream = newWriteableStream<Uint8Array>(data => BinaryBuffer.concat(data.map(data => BinaryBuffer.wrap(data))).buffer);
270
+
271
+ readFileIntoStream(this, resource, stream, data => data.buffer, {
272
+ ...opts,
273
+ bufferSize: this.BUFFER_SIZE
274
+ }, token);
275
+
276
+ return stream;
277
+ }
278
+
279
+ async writeFile(resource: URI, content: Uint8Array, opts: FileWriteOptions): Promise<void> {
280
+ let handle: number | undefined = undefined;
281
+ try {
282
+ const filePath = this.toFilePath(resource);
283
+
284
+ // Validate target unless { create: true, overwrite: true }
285
+ if (!opts.create || !opts.overwrite) {
286
+ const fileExists = await promisify(exists)(filePath);
287
+ if (fileExists) {
288
+ if (!opts.overwrite) {
289
+ throw createFileSystemProviderError('File already exists', FileSystemProviderErrorCode.FileExists);
290
+ }
291
+ } else {
292
+ if (!opts.create) {
293
+ throw createFileSystemProviderError('File does not exist', FileSystemProviderErrorCode.FileNotFound);
294
+ }
295
+ }
296
+ }
297
+
298
+ // Open
299
+ handle = await this.open(resource, { create: true });
300
+
301
+ // Write content at once
302
+ await this.write(handle, 0, content, 0, content.byteLength);
303
+ } catch (error) {
304
+ throw this.toFileSystemProviderError(error);
305
+ } finally {
306
+ if (typeof handle === 'number') {
307
+ await this.close(handle);
308
+ }
309
+ }
310
+ }
311
+
312
+ private mapHandleToPos: Map<number, number> = new Map();
313
+
314
+ private writeHandles: Set<number> = new Set();
315
+ private canFlush: boolean = true;
316
+
317
+ async open(resource: URI, opts: FileOpenOptions): Promise<number> {
318
+ try {
319
+ const filePath = this.toFilePath(resource);
320
+
321
+ let flags: string | undefined = undefined;
322
+ if (opts.create) {
323
+ if (isWindows && await promisify(exists)(filePath)) {
324
+ try {
325
+ // On Windows and if the file exists, we use a different strategy of saving the file
326
+ // by first truncating the file and then writing with r+ flag. This helps to save hidden files on Windows
327
+ // (see https://github.com/Microsoft/vscode/issues/931) and prevent removing alternate data streams
328
+ // (see https://github.com/Microsoft/vscode/issues/6363)
329
+ await promisify(truncate)(filePath, 0);
330
+
331
+ // After a successful truncate() the flag can be set to 'r+' which will not truncate.
332
+ flags = 'r+';
333
+ } catch (error) {
334
+ console.trace(error);
335
+ }
336
+ }
337
+
338
+ // we take opts.create as a hint that the file is opened for writing
339
+ // as such we use 'w' to truncate an existing or create the
340
+ // file otherwise. we do not allow reading.
341
+ if (!flags) {
342
+ flags = 'w';
343
+ }
344
+ } else {
345
+ // otherwise we assume the file is opened for reading
346
+ // as such we use 'r' to neither truncate, nor create
347
+ // the file.
348
+ flags = 'r';
349
+ }
350
+
351
+ const handle = await promisify(open)(filePath, flags);
352
+
353
+ // remember this handle to track file position of the handle
354
+ // we init the position to 0 since the file descriptor was
355
+ // just created and the position was not moved so far (see
356
+ // also http://man7.org/linux/man-pages/man2/open.2.html -
357
+ // "The file offset is set to the beginning of the file.")
358
+ this.mapHandleToPos.set(handle, 0);
359
+
360
+ // remember that this handle was used for writing
361
+ if (opts.create) {
362
+ this.writeHandles.add(handle);
363
+ }
364
+
365
+ return handle;
366
+ } catch (error) {
367
+ throw this.toFileSystemProviderError(error);
368
+ }
369
+ }
370
+
371
+ async close(fd: number): Promise<void> {
372
+ try {
373
+
374
+ // remove this handle from map of positions
375
+ this.mapHandleToPos.delete(fd);
376
+
377
+ // if a handle is closed that was used for writing, ensure
378
+ // to flush the contents to disk if possible.
379
+ if (this.writeHandles.delete(fd) && this.canFlush) {
380
+ try {
381
+ await promisify(fdatasync)(fd);
382
+ } catch (error) {
383
+ // In some exotic setups it is well possible that node fails to sync
384
+ // In that case we disable flushing and log the error to our logger
385
+ this.canFlush = false;
386
+ console.error(error);
387
+ }
388
+ }
389
+
390
+ return await promisify(close)(fd);
391
+ } catch (error) {
392
+ throw this.toFileSystemProviderError(error);
393
+ }
394
+ }
395
+
396
+ async read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
397
+ const normalizedPos = this.normalizePos(fd, pos);
398
+
399
+ let bytesRead: number | null = null;
400
+ try {
401
+ const result = await promisify(read)(fd, data, offset, length, normalizedPos);
402
+
403
+ if (typeof result === 'number') {
404
+ bytesRead = result; // node.d.ts fail
405
+ } else {
406
+ bytesRead = result.bytesRead;
407
+ }
408
+
409
+ return bytesRead;
410
+ } catch (error) {
411
+ throw this.toFileSystemProviderError(error);
412
+ } finally {
413
+ this.updatePos(fd, normalizedPos, bytesRead);
414
+ }
415
+ }
416
+
417
+ private normalizePos(fd: number, pos: number): number | null {
418
+
419
+ // when calling fs.read/write we try to avoid passing in the "pos" argument and
420
+ // rather prefer to pass in "null" because this avoids an extra seek(pos)
421
+ // call that in some cases can even fail (e.g. when opening a file over FTP -
422
+ // see https://github.com/microsoft/vscode/issues/73884).
423
+ //
424
+ // as such, we compare the passed in position argument with our last known
425
+ // position for the file descriptor and use "null" if they match.
426
+ if (pos === this.mapHandleToPos.get(fd)) {
427
+ return null;
428
+ }
429
+
430
+ return pos;
431
+ }
432
+
433
+ private updatePos(fd: number, pos: number | null, bytesLength: number | null): void {
434
+ const lastKnownPos = this.mapHandleToPos.get(fd);
435
+ if (typeof lastKnownPos === 'number') {
436
+
437
+ // pos !== null signals that previously a position was used that is
438
+ // not null. node.js documentation explains, that in this case
439
+ // the internal file pointer is not moving and as such we do not move
440
+ // our position pointer.
441
+ //
442
+ // Docs: "If position is null, data will be read from the current file position,
443
+ // and the file position will be updated. If position is an integer, the file position
444
+ // will remain unchanged."
445
+ if (typeof pos === 'number') {
446
+ // do not modify the position
447
+ } else if (typeof bytesLength === 'number') {
448
+ this.mapHandleToPos.set(fd, lastKnownPos + bytesLength);
449
+ } else {
450
+ this.mapHandleToPos.delete(fd);
451
+ }
452
+ }
453
+ }
454
+
455
+ async write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
456
+ // we know at this point that the file to write to is truncated and thus empty
457
+ // if the write now fails, the file remains empty. as such we really try hard
458
+ // to ensure the write succeeds by retrying up to three times.
459
+ return retry(() => this.doWrite(fd, pos, data, offset, length), 100 /* ms delay */, 3 /* retries */);
460
+ }
461
+
462
+ private async doWrite(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
463
+ const normalizedPos = this.normalizePos(fd, pos);
464
+
465
+ let bytesWritten: number | null = null;
466
+ try {
467
+ const result = await promisify(write)(fd, data, offset, length, normalizedPos);
468
+
469
+ if (typeof result === 'number') {
470
+ bytesWritten = result; // node.d.ts fail
471
+ } else {
472
+ bytesWritten = result.bytesWritten;
473
+ }
474
+
475
+ return bytesWritten;
476
+ } catch (error) {
477
+ throw this.toFileSystemProviderError(error);
478
+ } finally {
479
+ this.updatePos(fd, normalizedPos, bytesWritten);
480
+ }
481
+ }
482
+
483
+ // #endregion
484
+
485
+ // #region Move/Copy/Delete/Create Folder
486
+
487
+ async mkdir(resource: URI): Promise<void> {
488
+ try {
489
+ await promisify(mkdir)(this.toFilePath(resource));
490
+ } catch (error) {
491
+ throw this.toFileSystemProviderError(error);
492
+ }
493
+ }
494
+
495
+ async delete(resource: URI, opts: FileDeleteOptions): Promise<void> {
496
+ try {
497
+ const filePath = this.toFilePath(resource);
498
+
499
+ await this.doDelete(filePath, opts);
500
+ } catch (error) {
501
+ throw this.toFileSystemProviderError(error);
502
+ }
503
+ }
504
+
505
+ protected async doDelete(filePath: string, opts: FileDeleteOptions): Promise<void> {
506
+ if (!opts.useTrash) {
507
+ if (opts.recursive) {
508
+ await this.rimraf(filePath);
509
+ } else {
510
+ await promisify(unlink)(filePath);
511
+ }
512
+ } else {
513
+ await trash(filePath);
514
+ }
515
+ }
516
+
517
+ protected rimraf(path: string): Promise<void> {
518
+ if (new Path(path).isRoot) {
519
+ throw new Error('rimraf - will refuse to recursively delete root');
520
+ }
521
+ return this.rimrafMove(path);
522
+ }
523
+
524
+ protected async rimrafMove(path: string): Promise<void> {
525
+ try {
526
+ const pathInTemp = join(os.tmpdir(), v4());
527
+ try {
528
+ await promisify(rename)(path, pathInTemp);
529
+ } catch (error) {
530
+ return this.rimrafUnlink(path); // if rename fails, delete without tmp dir
531
+ }
532
+
533
+ // Delete but do not return as promise
534
+ this.rimrafUnlink(pathInTemp);
535
+ } catch (error) {
536
+ if (error.code !== 'ENOENT') {
537
+ throw error;
538
+ }
539
+ }
540
+ }
541
+
542
+ protected async rimrafUnlink(path: string): Promise<void> {
543
+ try {
544
+ const stat = await promisify(lstat)(path);
545
+
546
+ // Folder delete (recursive) - NOT for symbolic links though!
547
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
548
+
549
+ // Children
550
+ const children = await promisify(readdir)(path);
551
+ await Promise.all(children.map(child => this.rimrafUnlink(join(path, child))));
552
+
553
+ // Folder
554
+ await promisify(rmdir)(path);
555
+ } else {
556
+
557
+ // chmod as needed to allow for unlink
558
+ const mode = stat.mode;
559
+ if (!(mode & 128)) { // 128 === 0200
560
+ await promisify(chmod)(path, mode | 128);
561
+ }
562
+
563
+ return promisify(unlink)(path);
564
+ }
565
+ } catch (error) {
566
+ if (error.code !== 'ENOENT') {
567
+ throw error;
568
+ }
569
+ }
570
+ }
571
+
572
+ async rename(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> {
573
+ const fromFilePath = this.toFilePath(from);
574
+ const toFilePath = this.toFilePath(to);
575
+
576
+ if (fromFilePath === toFilePath) {
577
+ return; // simulate node.js behaviour here and do a no-op if paths match
578
+ }
579
+
580
+ try {
581
+
582
+ // Ensure target does not exist
583
+ await this.validateTargetDeleted(from, to, 'move', opts.overwrite);
584
+
585
+ // Move
586
+ await this.move(fromFilePath, toFilePath);
587
+ } catch (error) {
588
+
589
+ // rewrite some typical errors that can happen especially around symlinks
590
+ // to something the user can better understand
591
+ if (error.code === 'EINVAL' || error.code === 'EBUSY' || error.code === 'ENAMETOOLONG') {
592
+ error = new Error(`Unable to move '${basename(fromFilePath)}' into '${basename(dirname(toFilePath))}' (${error.toString()}).`);
593
+ }
594
+
595
+ throw this.toFileSystemProviderError(error);
596
+ }
597
+ }
598
+
599
+ protected async move(source: string, target: string): Promise<void> {
600
+ if (source === target) {
601
+ return Promise.resolve();
602
+ }
603
+
604
+ async function updateMtime(path: string): Promise<void> {
605
+ const stat = await promisify(lstat)(path);
606
+ if (stat.isDirectory() || stat.isSymbolicLink()) {
607
+ return Promise.resolve(); // only for files
608
+ }
609
+
610
+ const fd = await promisify(open)(path, 'a');
611
+ try {
612
+ await promisify(futimes)(fd, stat.atime, new Date());
613
+ } catch (error) {
614
+ // ignore
615
+ }
616
+
617
+ return promisify(close)(fd);
618
+ }
619
+
620
+ try {
621
+ await promisify(rename)(source, target);
622
+ await updateMtime(target);
623
+ } catch (error) {
624
+
625
+ // In two cases we fallback to classic copy and delete:
626
+ //
627
+ // 1.) The EXDEV error indicates that source and target are on different devices
628
+ // In this case, fallback to using a copy() operation as there is no way to
629
+ // rename() between different devices.
630
+ //
631
+ // 2.) The user tries to rename a file/folder that ends with a dot. This is not
632
+ // really possible to move then, at least on UNC devices.
633
+ if (source.toLowerCase() !== target.toLowerCase() && error.code === 'EXDEV' || source.endsWith('.')) {
634
+ await this.doCopy(source, target);
635
+ await this.rimraf(source);
636
+ await updateMtime(target);
637
+ } else {
638
+ throw error;
639
+ }
640
+ }
641
+ }
642
+
643
+ async copy(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> {
644
+ const fromFilePath = this.toFilePath(from);
645
+ const toFilePath = this.toFilePath(to);
646
+
647
+ if (fromFilePath === toFilePath) {
648
+ return; // simulate node.js behaviour here and do a no-op if paths match
649
+ }
650
+
651
+ try {
652
+
653
+ // Ensure target does not exist
654
+ await this.validateTargetDeleted(from, to, 'copy', opts.overwrite);
655
+
656
+ // Copy
657
+ await this.doCopy(fromFilePath, toFilePath);
658
+ } catch (error) {
659
+
660
+ // rewrite some typical errors that can happen especially around symlinks
661
+ // to something the user can better understand
662
+ if (error.code === 'EINVAL' || error.code === 'EBUSY' || error.code === 'ENAMETOOLONG') {
663
+ error = new Error(`Unable to copy '${basename(fromFilePath)}' into '${basename(dirname(toFilePath))}' (${error.toString()}).`);
664
+ }
665
+
666
+ throw this.toFileSystemProviderError(error);
667
+ }
668
+ }
669
+
670
+ private async validateTargetDeleted(from: URI, to: URI, mode: 'move' | 'copy', overwrite?: boolean): Promise<void> {
671
+ const isPathCaseSensitive = !!(this.capabilities & FileSystemProviderCapabilities.PathCaseSensitive);
672
+
673
+ const fromFilePath = this.toFilePath(from);
674
+ const toFilePath = this.toFilePath(to);
675
+
676
+ let isSameResourceWithDifferentPathCase = false;
677
+ if (!isPathCaseSensitive) {
678
+ isSameResourceWithDifferentPathCase = fromFilePath.toLowerCase() === toFilePath.toLowerCase();
679
+ }
680
+
681
+ if (isSameResourceWithDifferentPathCase && mode === 'copy') {
682
+ throw createFileSystemProviderError("'File cannot be copied to same path with different path case", FileSystemProviderErrorCode.FileExists);
683
+ }
684
+
685
+ // handle existing target (unless this is a case change)
686
+ if (!isSameResourceWithDifferentPathCase && await promisify(exists)(toFilePath)) {
687
+ if (!overwrite) {
688
+ throw createFileSystemProviderError('File at target already exists', FileSystemProviderErrorCode.FileExists);
689
+ }
690
+
691
+ // Delete target
692
+ await this.delete(to, { recursive: true, useTrash: false });
693
+ }
694
+ }
695
+
696
+ protected async doCopy(source: string, target: string, copiedSourcesIn?: { [path: string]: boolean }): Promise<void> {
697
+ const copiedSources = copiedSourcesIn ? copiedSourcesIn : Object.create(null);
698
+
699
+ const fileStat = await promisify(stat)(source);
700
+ if (!fileStat.isDirectory()) {
701
+ return this.doCopyFile(source, target, fileStat.mode & 511);
702
+ }
703
+
704
+ if (copiedSources[source]) {
705
+ return Promise.resolve(); // escape when there are cycles (can happen with symlinks)
706
+ }
707
+
708
+ copiedSources[source] = true; // remember as copied
709
+
710
+ // Create folder
711
+ await this.mkdirp(target, fileStat.mode & 511);
712
+
713
+ // Copy each file recursively
714
+ const files = await promisify(readdir)(source);
715
+ for (let i = 0; i < files.length; i++) {
716
+ const file = files[i];
717
+ await this.doCopy(join(source, file), join(target, file), copiedSources);
718
+ }
719
+ }
720
+
721
+ protected async mkdirp(path: string, mode?: number): Promise<void> {
722
+ const mkdir = async () => {
723
+ try {
724
+ await promisify(fs.mkdir)(path, mode);
725
+ } catch (error) {
726
+
727
+ // ENOENT: a parent folder does not exist yet
728
+ if (error.code === 'ENOENT') {
729
+ throw error;
730
+ }
731
+
732
+ // Any other error: check if folder exists and
733
+ // return normally in that case if its a folder
734
+ let targetIsFile = false;
735
+ try {
736
+ const fileStat = await promisify(fs.stat)(path);
737
+ targetIsFile = !fileStat.isDirectory();
738
+ } catch (statError) {
739
+ throw error; // rethrow original error if stat fails
740
+ }
741
+
742
+ if (targetIsFile) {
743
+ throw new Error(`'${path}' exists and is not a directory.`);
744
+ }
745
+ }
746
+ };
747
+
748
+ // stop at root
749
+ if (path === dirname(path)) {
750
+ return;
751
+ }
752
+
753
+ try {
754
+ await mkdir();
755
+ } catch (error) {
756
+
757
+ // ENOENT: a parent folder does not exist yet, continue
758
+ // to create the parent folder and then try again.
759
+ if (error.code === 'ENOENT') {
760
+ await this.mkdirp(dirname(path), mode);
761
+
762
+ return mkdir();
763
+ }
764
+
765
+ // Any other error
766
+ throw error;
767
+ }
768
+ }
769
+
770
+ protected doCopyFile(source: string, target: string, mode: number): Promise<void> {
771
+ return new Promise((resolve, reject) => {
772
+ const reader = fs.createReadStream(source);
773
+ const writer = fs.createWriteStream(target, { mode });
774
+
775
+ let finished = false;
776
+ const finish = (error?: Error) => {
777
+ if (!finished) {
778
+ finished = true;
779
+
780
+ // in error cases, pass to callback
781
+ if (error) {
782
+ return reject(error);
783
+ }
784
+
785
+ // we need to explicitly chmod because of https://github.com/nodejs/node/issues/1104
786
+ fs.chmod(target, mode, error => error ? reject(error) : resolve());
787
+ }
788
+ };
789
+
790
+ // handle errors properly
791
+ reader.once('error', error => finish(error));
792
+ writer.once('error', error => finish(error));
793
+
794
+ // we are done (underlying fd has been closed)
795
+ writer.once('close', () => finish());
796
+
797
+ // start piping
798
+ reader.pipe(writer);
799
+ });
800
+ }
801
+
802
+ // #endregion
803
+
804
+ // #region File Watching
805
+
806
+ watch(resource: URI, opts: WatchOptions): Disposable {
807
+ const watcherService = this.watcher;
808
+ /**
809
+ * Disposable handle. Can be disposed early (before the watcher is allocated.)
810
+ */
811
+ const handle = {
812
+ disposed: false,
813
+ watcherId: undefined as number | undefined,
814
+ dispose(): void {
815
+ if (this.disposed) {
816
+ return;
817
+ }
818
+ if (this.watcherId !== undefined) {
819
+ watcherService.unwatchFileChanges(this.watcherId);
820
+ }
821
+ this.disposed = true;
822
+ },
823
+ };
824
+ watcherService.watchFileChanges(resource.toString(), {
825
+ // Convert from `files.WatchOptions` to internal `watcher-protocol.WatchOptions`:
826
+ ignored: opts.excludes
827
+ }).then(watcherId => {
828
+ if (handle.disposed) {
829
+ watcherService.unwatchFileChanges(watcherId);
830
+ } else {
831
+ handle.watcherId = watcherId;
832
+ }
833
+ });
834
+ this.toDispose.push(handle);
835
+ return handle;
836
+ }
837
+
838
+ // #endregion
839
+
840
+ async updateFile(resource: URI, changes: TextDocumentContentChangeEvent[], opts: FileUpdateOptions): Promise<FileUpdateResult> {
841
+ try {
842
+ const content = await this.readFile(resource);
843
+ const decoded = this.encodingService.decode(BinaryBuffer.wrap(content), opts.readEncoding);
844
+ const newContent = TextDocument.update(TextDocument.create('', '', 1, decoded), changes, 2).getText();
845
+ const encoding = await this.encodingService.toResourceEncoding(opts.writeEncoding, {
846
+ overwriteEncoding: opts.overwriteEncoding,
847
+ read: async length => {
848
+ const fd = await this.open(resource, { create: false });
849
+ try {
850
+ const data = new Uint8Array(length);
851
+ await this.read(fd, 0, data, 0, length);
852
+ return data;
853
+ } finally {
854
+ await this.close(fd);
855
+ }
856
+ }
857
+ });
858
+ const encoded = this.encodingService.encode(newContent, encoding);
859
+ await this.writeFile(resource, encoded.buffer, { create: false, overwrite: true });
860
+ const stat = await this.stat(resource);
861
+ return Object.assign(stat, { encoding: encoding.encoding });
862
+ } catch (error) {
863
+ throw this.toFileSystemProviderError(error);
864
+ }
865
+ }
866
+
867
+ // #region Helpers
868
+
869
+ protected toFilePath(resource: URI): string {
870
+ return normalize(FileUri.fsPath(resource));
871
+ }
872
+
873
+ private toFileSystemProviderError(error: NodeJS.ErrnoException): FileSystemProviderError {
874
+ if (error instanceof FileSystemProviderError) {
875
+ return error; // avoid double conversion
876
+ }
877
+
878
+ let code: FileSystemProviderErrorCode;
879
+ switch (error.code) {
880
+ case 'ENOENT':
881
+ code = FileSystemProviderErrorCode.FileNotFound;
882
+ break;
883
+ case 'EISDIR':
884
+ code = FileSystemProviderErrorCode.FileIsADirectory;
885
+ break;
886
+ case 'ENOTDIR':
887
+ code = FileSystemProviderErrorCode.FileNotADirectory;
888
+ break;
889
+ case 'EEXIST':
890
+ code = FileSystemProviderErrorCode.FileExists;
891
+ break;
892
+ case 'EPERM':
893
+ case 'EACCES':
894
+ code = FileSystemProviderErrorCode.NoPermissions;
895
+ break;
896
+ default:
897
+ code = FileSystemProviderErrorCode.Unknown;
898
+ }
899
+
900
+ return createFileSystemProviderError(error, code);
901
+ }
902
+
903
+ // #endregion
904
+
905
+ dispose(): void {
906
+ this.toDispose.dispose();
907
+ }
908
+ }