@theia/filesystem 1.48.0 → 1.48.1

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