@theia/filesystem 1.48.1 → 1.48.3

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